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 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611
|
#include "graphingwindow.h"
#include "ui_graphingwindow.h"
#include "newgraphdialog.h"
#include "mainwindow.h"
#include "helpwindow.h"
#include "utility.h"
#include <QDebug>
#include <algorithm>
#include <limits>
GraphingWindow::GraphingWindow(const QVector<CANFrame> *frames, QWidget *parent) :
QDialog(parent),
ui(new Ui::GraphingWindow)
{
ui->setupUi(this);
setWindowFlags(Qt::Window);
readSettings();
modelFrames = frames;
dbcHandler = DBCHandler::getReference();
ui->graphingView->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectAxes |
QCP::iSelectLegend | QCP::iSelectPlottables);
ui->graphingView->xAxis->setRange(0, 8);
ui->graphingView->yAxis->setRange(0, 255);
ui->graphingView->axisRect()->setupFullAxesBox();
//ui->graphingView->plotLayout()->insertRow(0);
//ui->graphingView->plotLayout()->addElement(0, 0, new QCPPlotTitle(ui->graphingView, "Data Graphing"));
ui->graphingView->xAxis->setLabel("Time Axis");
ui->graphingView->yAxis->setLabel("Value Axis");
ui->graphingView->xAxis->setNumberFormat("f");
if (Utility::timeStyle == TS_SECONDS) ui->graphingView->xAxis->setNumberPrecision(6);
else ui->graphingView->xAxis->setNumberPrecision(0);
if (Utility::timeStyle == TS_CLOCK)
{
QSharedPointer timeTicker = QSharedPointer<QCPAxisTickerTime>::create();
timeTicker->setTimeFormat("%h:%m:%s.%z");
ui->graphingView->xAxis->setTicker(timeTicker);
}
ui->graphingView->legend->setVisible(true);
QFont legendFont = font();
legendFont.setPointSize(10);
QFont legendSelectedFont = font();
legendSelectedFont.setPointSize(12);
legendSelectedFont.setBold(true);
ui->graphingView->legend->setFont(legendFont);
ui->graphingView->legend->setSelectedFont(legendSelectedFont);
ui->graphingView->legend->setSelectableParts(QCPLegend::spItems); // legend box shall not be selectable, only legend items
locationText = new QCPItemText(ui->graphingView);
locationText->position->setType(QCPItemPosition::ptAxisRectRatio);
locationText->position->setCoords(QPointF(0.16, 0.03));
locationText->setText("X: 0 Y: 0");
locationText->setFont(legendSelectedFont);
itemTracer = new QCPItemTracer(ui->graphingView);
itemTracer->setInterpolating(true);
itemTracer->setVisible(false); //no graph selected yet
itemTracer->setStyle(QCPItemTracer::tsCircle);
itemTracer->setSize(20);
// connect slot that ties some axis selections together (especially opposite axes):
connect(ui->graphingView, SIGNAL(selectionChangedByUser()), this, SLOT(selectionChanged()));
//connect up the mouse controls
connect(ui->graphingView, SIGNAL(plottableDoubleClick(QCPAbstractPlottable*,int,QMouseEvent*)), this, SLOT(plottableDoubleClick(QCPAbstractPlottable*,int,QMouseEvent*)));
connect(ui->graphingView, SIGNAL(plottableClick(QCPAbstractPlottable*,int,QMouseEvent*)), this, SLOT(plottableClick(QCPAbstractPlottable*,int,QMouseEvent*)));
connect(ui->graphingView, SIGNAL(mousePress(QMouseEvent*)), this, SLOT(mousePress()));
connect(ui->graphingView, SIGNAL(mouseWheel(QWheelEvent*)), this, SLOT(mouseWheel()));
// make bottom and left axes transfer their ranges to top and right axes:
connect(ui->graphingView->xAxis, SIGNAL(rangeChanged(QCPRange)), ui->graphingView->xAxis2, SLOT(setRange(QCPRange)));
connect(ui->graphingView->yAxis, SIGNAL(rangeChanged(QCPRange)), ui->graphingView->yAxis2, SLOT(setRange(QCPRange)));
//connect(ui->graphingView, SIGNAL(titleDoubleClick(QMouseEvent*,QCPTextElement*)), this, SLOT(titleDoubleClick(QMouseEvent*,QCPTextElement*)));
connect(ui->graphingView, SIGNAL(axisDoubleClick(QCPAxis*,QCPAxis::SelectablePart,QMouseEvent*)), this, SLOT(axisDoubleClick(QCPAxis*,QCPAxis::SelectablePart)));
connect(ui->graphingView, SIGNAL(legendDoubleClick(QCPLegend*,QCPAbstractLegendItem*,QMouseEvent*)), this, SLOT(legendDoubleClick(QCPLegend*,QCPAbstractLegendItem*)));
connect(ui->graphingView, SIGNAL(legendClick(QCPLegend*,QCPAbstractLegendItem*,QMouseEvent*)), this, SLOT(legendSingleClick(QCPLegend*,QCPAbstractLegendItem*)));
connect(MainWindow::getReference(), SIGNAL(framesUpdated(int)), this, SLOT(updatedFrames(int)));
// setup policy and connect slot for context menu popup:
ui->graphingView->setContextMenuPolicy(Qt::CustomContextMenu);
connect(ui->graphingView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextMenuRequest(QPoint)));
selectedPen.setWidth(3);
selectedPen.setStyle(Qt::DashLine);
selectedPen.setColor(Qt::blue);
//ui->graphingView->setAttribute(Qt::WA_AcceptTouchEvents);
if (useOpenGL)
{
//Fix the device pixel ratio for openGL so the graph doesn't render double sized
ui->graphingView->setBufferDevicePixelRatio(1);
ui->graphingView->setAntialiasedElements(QCP::aeAll);
//ui->graphingView->setNoAntialiasingOnDrag(true);
ui->graphingView->setOpenGl(true);
}
else
{
ui->graphingView->setOpenGl(false);
ui->graphingView->setAntialiasedElements(QCP::aeNone);
}
needScaleSetup = true;
followGraphEnd = false;
}
GraphingWindow::~GraphingWindow()
{
delete ui;
}
void GraphingWindow::showEvent(QShowEvent* event)
{
QDialog::showEvent(event);
installEventFilter(this);
readSettings();
ui->graphingView->replot();
}
void GraphingWindow::closeEvent(QCloseEvent *event)
{
Q_UNUSED(event);
removeEventFilter(this);
writeSettings();
}
void GraphingWindow::changeEvent(QEvent *event)
{
QWidget::changeEvent(event);
if (event->type() == QEvent::ActivationChange)
{
if(this->isActiveWindow())
{
setWindowOpacity(1);
ui->graphingView->repaint();
qDebug() << "Show";
}
else
{
//setWindowOpacity(0.25);
// widget is now inactive
qDebug() << "Hide";
}
}
}
void GraphingWindow::readSettings()
{
QSettings settings;
if (settings.value("Main/SaveRestorePositions", false).toBool())
{
resize(settings.value("Graphing/WindowSize", QSize(800, 600)).toSize());
move(Utility::constrainedWindowPos(settings.value("Graphing/WindowPos", QPoint(50, 50)).toPoint()));
}
useOpenGL = settings.value("Main/UseOpenGL", false).toBool();
}
void GraphingWindow::writeSettings()
{
QSettings settings;
if (settings.value("Main/SaveRestorePositions", false).toBool())
{
settings.setValue("Graphing/WindowSize", size());
settings.setValue("Graphing/WindowPos", pos());
}
}
void GraphingWindow::updatedFrames(int numFrames)
{
CANFrame thisFrame;
QVector<double> x, y;
bool appendedToGraph = false;
bool needReplot = false;
if (numFrames == -1) //all frames deleted. Kill the display
{
//removeAllGraphs();
//now instead of removing the graphs regenerate them which will blank them out but leave them there in case
//more traffic that matches comes in or someone otherwise loads more data
ui->graphingView->clearGraphs(); //temporarily remove the graphs from the graph view
for (int i = 0; i < graphParams.count(); i++)
{
createGraph(graphParams[i], false); //regenerate each one
}
ui->graphingView->replot(); //now, redisplay them all
}
else if (numFrames == -2) //all new set of frames. Reset
{
//there shouldn't be any need to actually remove the graphs.
//regenerate them instead
ui->graphingView->clearGraphs(); //temporarily remove the graphs from the graph view
//needScaleSetup = true;
for (int i = 0; i < graphParams.count(); i++)
{
createGraph(graphParams[i], false); //regenerate each one
}
ui->graphingView->replot(); //now, redisplay them all
}
else //just got some new frames. See if they are relevant.
{
if (numFrames > modelFrames->count()) return;
for (int j = 0; j < graphParams.count(); j++)
{
appendedToGraph = false;
x.clear();
y.clear();
for (int i = modelFrames->count() - numFrames; i < modelFrames->count(); i++)
{
thisFrame = modelFrames->at(i);
if ( graphParams[j].ID == thisFrame.frameId() && ( (graphParams[j].bus == -1) || (graphParams[j].bus == thisFrame.bus) ) )
{
appendToGraph(graphParams[j], thisFrame, x, y);
appendedToGraph = true;
}
}
if (appendedToGraph)
{
graphParams[j].ref->addData(x, y);
needReplot = true;
}
}
if (needReplot)
{
if (followGraphEnd)
{
//find the current X span and maintain that span but move the end of it over to match the new end
//of the actual graph. This causes the view to move with the data to always show the end
QCPRange range = ui->graphingView->xAxis->range();
double size = range.size();
bool foundRange;
QCPRange keyRange = ui->graphingView->graph()->getKeyRange(foundRange);
if (foundRange)
{
double end, start;
end = keyRange.upper;
start = end - size;
ui->graphingView->xAxis->setRange(start, end);
}
}
ui->graphingView->replot();
}
}
}
void GraphingWindow::plottableClick(QCPAbstractPlottable* plottable, int dataIdx, QMouseEvent* event)
{
Q_UNUSED(dataIdx);
qDebug() << "plottableClick";
double x, y;
QCPGraph *graph = reinterpret_cast<QCPGraph *>(plottable);
graph->pixelsToCoords(event->position(), x, y);
locationText->setText("X: " + QString::number(x, 'f', 3) + " Y: " + QString::number(y, 'f', 3));
}
void GraphingWindow::plottableDoubleClick(QCPAbstractPlottable* plottable, int dataIdx, QMouseEvent* event)
{
Q_UNUSED(dataIdx);
qDebug() << "plottableDoubleClick";
int id = 0;
//apply transforms to get the X axis value where we double clicked
double coord = plottable->keyAxis()->pixelToCoord(event->position().x());
id = plottable->property("id").toInt();
if (Utility::timeStyle == TS_SECONDS) emit sendCenterTimeID(id, coord);
else emit sendCenterTimeID(id, coord / 1000000.0);
double x, y;
QCPGraph *graph = reinterpret_cast<QCPGraph *>(plottable);
graph->pixelsToCoords(event->position(), x, y);
x = ui->graphingView->xAxis->pixelToCoord(event->position().x());
itemTracer->setGraph(graph);
itemTracer->setVisible(true);
itemTracer->setInterpolating(true);
itemTracer->setGraphKey(x);
itemTracer->updatePosition();
qDebug() << "val " << itemTracer->position->value();
locationText->setText("X: " + QString::number(x) + " Y: " + QString::number(itemTracer->position->value()));
}
void GraphingWindow::gotCenterTimeID(uint32_t ID, double timestamp)
{
Q_UNUSED(ID)
//its problematic to try to highlight a graph since we get the ID
//and timestamp not the signal in question so there is no real way
//to know which graph. But, if that changes here is a stub
//for (int i = 0; i < graphParams.count(); i++)
//{
//}
qDebug() << "Trying to center graph on timestamp: " << timestamp;
QCPRange range = ui->graphingView->xAxis->range();
double offset = range.size() / 2.0;
if (Utility::timeStyle != TS_SECONDS) timestamp *= 1000000.0; //timestamp is always in seconds when being passed so convert if necessary
ui->graphingView->xAxis->setRange(timestamp - offset, timestamp + offset);
ui->graphingView->replot();
}
void GraphingWindow::titleDoubleClick(QMouseEvent* event, QCPTextElement* title)
{
Q_UNUSED(event)
Q_UNUSED(title)
qDebug() << "title Double Click";
// Set the plot title by double clicking on it
/*
bool ok;
QString newTitle = QInputDialog::getText(this, "SavvyCAN Graphing", "New plot title:", QLineEdit::Normal, title->text(), &ok);
if (ok)
{
title->setText(newTitle);
ui->graphingView->replot();
} */
editSelectedGraph();
}
void GraphingWindow::axisDoubleClick(QCPAxis *axis, QCPAxis::SelectablePart part)
{
qDebug() << "axisDoubleClick";
if (part == QCPAxis::spAxisLabel) // Set an axis label by double clicking on it
{
bool ok;
QString newLabel = QInputDialog::getText(this, "SavvyCAN Graphing", "New axis label:", QLineEdit::Normal, axis->label(), &ok);
if (ok)
{
axis->setLabel(newLabel);
ui->graphingView->replot();
}
} else if (part == QCPAxis::spAxis) // Resize an axis to fit by double clicking it
{
this->rescaleAxis(axis);
ui->graphingView->replot();
}
}
void GraphingWindow::legendSingleClick(QCPLegend *legend, QCPAbstractLegendItem *item)
{
// select a graph by clicking on the legend
qDebug() << "Legend Single Click " << item;
Q_UNUSED(legend)
if (item) // only react if item was clicked (user could have clicked on border padding of legend where there is no item, then item is 0)
{
QCPPlottableLegendItem *plItem = qobject_cast<QCPPlottableLegendItem*>(item);
QCPGraph *pGraph = qobject_cast<QCPGraph *>(plItem->plottable());
QCPDataSelection sel;
QCPDataRange rang;
rang.setBegin(0);
rang.setEnd(pGraph->dataCount());
sel.addDataRange(rang);
pGraph->setSelection(sel);
}
}
void GraphingWindow::legendDoubleClick(QCPLegend *legend, QCPAbstractLegendItem *item)
{
// edit a graph by double clicking on its legend item
qDebug() << "Legend Double Click " << item;
Q_UNUSED(legend)
if (item) // only react if item was clicked (user could have clicked on border padding of legend where there is no item, then item is 0)
{
QCPPlottableLegendItem *plItem = qobject_cast<QCPPlottableLegendItem*>(item);
QCPGraph *pGraph = qobject_cast<QCPGraph *>(plItem->plottable());
QCPDataSelection sel;
QCPDataRange rang;
rang.setBegin(0);
rang.setEnd(pGraph->dataCount());
sel.addDataRange(rang);
pGraph->setSelection(sel);
editSelectedGraph();
}
}
void GraphingWindow::selectionChanged()
{
/*
normally, axis base line, axis tick labels and axis labels are selectable separately, but we want
the user only to be able to select the axis as a whole, so we tie the selected states of the tick labels
and the axis base line together. However, the axis label shall be selectable individually.
The selection state of the left and right axes shall be synchronized as well as the state of the
bottom and top axes.
Further, we want to synchronize the selection of the graphs with the selection state of the respective
legend item belonging to that graph. So the user can select a graph by either clicking on the graph itself
or on its legend item.
*/
qDebug() << "SelectionChanged";
// make top and bottom axes be selected synchronously, and handle axis and tick labels as one selectable object:
if (ui->graphingView->xAxis->selectedParts().testFlag(QCPAxis::spAxis) || ui->graphingView->xAxis->selectedParts().testFlag(QCPAxis::spTickLabels) ||
ui->graphingView->xAxis2->selectedParts().testFlag(QCPAxis::spAxis) || ui->graphingView->xAxis2->selectedParts().testFlag(QCPAxis::spTickLabels))
{
ui->graphingView->xAxis2->setSelectedParts(QCPAxis::spAxis|QCPAxis::spTickLabels);
ui->graphingView->xAxis->setSelectedParts(QCPAxis::spAxis|QCPAxis::spTickLabels);
}
// make left and right axes be selected synchronously, and handle axis and tick labels as one selectable object:
if (ui->graphingView->yAxis->selectedParts().testFlag(QCPAxis::spAxis) || ui->graphingView->yAxis->selectedParts().testFlag(QCPAxis::spTickLabels) ||
ui->graphingView->yAxis2->selectedParts().testFlag(QCPAxis::spAxis) || ui->graphingView->yAxis2->selectedParts().testFlag(QCPAxis::spTickLabels))
{
ui->graphingView->yAxis2->setSelectedParts(QCPAxis::spAxis|QCPAxis::spTickLabels);
ui->graphingView->yAxis->setSelectedParts(QCPAxis::spAxis|QCPAxis::spTickLabels);
}
// synchronize selection of graphs with selection of corresponding legend items:
for (int i=0; i<ui->graphingView->graphCount(); ++i)
{
QCPGraph *graph = ui->graphingView->graph(i);
QCPPlottableLegendItem *item = ui->graphingView->legend->itemWithPlottable(graph);
if (item->selected() || graph->selected())
{
item->setSelected(true);
//select graph too.
QCPDataSelection sel;
QCPDataRange rang;
rang.setBegin(0);
rang.setEnd(graph->dataCount());
sel.addDataRange(rang);
graph->setSelection(sel);
}
}
}
void GraphingWindow::mousePress()
{
// if an axis is selected, only allow the direction of that axis to be dragged
// if no axis is selected, both directions may be dragged
if (ui->graphingView->xAxis->selectedParts().testFlag(QCPAxis::spAxis))
ui->graphingView->axisRect()->setRangeDrag(ui->graphingView->xAxis->orientation());
else if (ui->graphingView->yAxis->selectedParts().testFlag(QCPAxis::spAxis))
ui->graphingView->axisRect()->setRangeDrag(ui->graphingView->yAxis->orientation());
else
ui->graphingView->axisRect()->setRangeDrag(Qt::Horizontal|Qt::Vertical);
}
void GraphingWindow::mouseWheel()
{
// if an axis is selected, only allow the direction of that axis to be zoomed
// if no axis is selected, both directions may be zoomed
if (ui->graphingView->xAxis->selectedParts().testFlag(QCPAxis::spAxis))
ui->graphingView->axisRect()->setRangeZoom(ui->graphingView->xAxis->orientation());
else if (ui->graphingView->yAxis->selectedParts().testFlag(QCPAxis::spAxis))
ui->graphingView->axisRect()->setRangeZoom(ui->graphingView->yAxis->orientation());
else
ui->graphingView->axisRect()->setRangeZoom(Qt::Horizontal|Qt::Vertical);
}
bool GraphingWindow::eventFilter(QObject *obj, QEvent *event)
{
if (event->type() == QEvent::KeyRelease) {
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
switch (keyEvent->key())
{
case Qt::Key_Plus:
zoomIn();
break;
case Qt::Key_Minus:
zoomOut();
break;
case Qt::Key_F1:
HelpWindow::getRef()->showHelp("graphwindow.md");
break;
}
return true;
} else if (event->type() == QEvent::TouchBegin)
{
qDebug() << "Touch begin";
} else if (event->type() == QEvent::TouchCancel)
{
qDebug() << "Touch cancel";
} else if (event->type() == QEvent::TouchEnd)
{
qDebug() << "Touch End";
} else if (event->type() == QEvent::TouchUpdate)
{
qDebug() << "Touch Update";
} else {
// standard event processing
return QObject::eventFilter(obj, event);
}
return false;
}
void GraphingWindow::resetView()
{
double yminval=10000000.0, ymaxval = -1000000.0;
double xminval=100000000000, xmaxval = -10000000000.0;
for (int i = 0; i < graphParams.count(); i++)
{
for (int j = 0; j < graphParams[i].x.count(); j++)
{
if (graphParams[i].x[j] < xminval) xminval = graphParams[i].x[j];
if (graphParams[i].x[j] > xmaxval) xmaxval = graphParams[i].x[j];
if (graphParams[i].y[j] < yminval) yminval = graphParams[i].y[j];
if (graphParams[i].y[j] > ymaxval) ymaxval = graphParams[i].y[j];
}
}
ui->graphingView->xAxis->setRange(xminval, xmaxval);
ui->graphingView->yAxis->setRange(yminval, ymaxval);
ui->graphingView->axisRect()->setupFullAxesBox();
ui->graphingView->replot();
}
void GraphingWindow::zoomIn()
{
QCPRange xrange = ui->graphingView->xAxis->range();
QCPRange yrange = ui->graphingView->yAxis->range();
if (ui->graphingView->xAxis->selectedParts().testFlag(QCPAxis::spAxis))
{
ui->graphingView->xAxis->scaleRange(0.666, xrange.center());
}
else if (ui->graphingView->yAxis->selectedParts().testFlag(QCPAxis::spAxis))
{
ui->graphingView->yAxis->scaleRange(0.666, yrange.center());
}
else
{
ui->graphingView->xAxis->scaleRange(0.666, xrange.center());
ui->graphingView->yAxis->scaleRange(0.666, yrange.center());
}
ui->graphingView->replot();
}
void GraphingWindow::zoomOut()
{
QCPRange xrange = ui->graphingView->xAxis->range();
QCPRange yrange = ui->graphingView->yAxis->range();
if (ui->graphingView->xAxis->selectedParts().testFlag(QCPAxis::spAxis))
{
ui->graphingView->xAxis->scaleRange(1.5, xrange.center());
}
else if (ui->graphingView->yAxis->selectedParts().testFlag(QCPAxis::spAxis))
{
ui->graphingView->yAxis->scaleRange(1.5, yrange.center());
}
else
{
ui->graphingView->xAxis->scaleRange(1.5, xrange.center());
ui->graphingView->yAxis->scaleRange(1.5, yrange.center());
}
ui->graphingView->replot();
}
void GraphingWindow::removeSelectedGraph()
{
if (ui->graphingView->selectedGraphs().size() > 0)
{
int idx = -1;
for (int i = 0; i < graphParams.count(); i++)
{
if (graphParams[i].ref == ui->graphingView->selectedGraphs().constFirst())
{
idx = i;
break;
}
}
foreach (QCPItemBracket* brk, graphParams[idx].brackets)
{
ui->graphingView->removeItem(brk);
}
foreach (QCPItemText* txt, graphParams[idx].bracketTexts)
{
ui->graphingView->removeItem(txt);
}
graphParams.removeAt(idx);
ui->graphingView->removeGraph(ui->graphingView->selectedGraphs().constFirst());
if (graphParams.count() == 0) needScaleSetup = true;
ui->graphingView->replot();
}
}
void GraphingWindow::editSelectedGraph()
{
if (ui->graphingView->selectedGraphs().size() > 0)
{
int idx = -1;
for (int i = 0; i < graphParams.count(); i++)
{
if (graphParams[i].ref == ui->graphingView->selectedGraphs().constFirst())
{
idx = i;
break;
}
}
qDebug() << "Selected index for editing: " << idx;
showParamsDialog(idx);
//ui->graphingView->replot();
}
}
void GraphingWindow::removeAllGraphs()
{
QMessageBox::StandardButton confirmDialog;
confirmDialog = QMessageBox::question(this, "Really?", "Remove all graphs?",
QMessageBox::Yes|QMessageBox::No);
if (confirmDialog == QMessageBox::Yes)
{
ui->graphingView->clearGraphs();
ui->graphingView->clearItems();
graphParams.clear();
needScaleSetup = true;
ui->graphingView->replot();
}
}
void GraphingWindow::rescaleAxis(QCPAxis *axis)
{
axis->rescale(true);
}
void GraphingWindow::rescaleToData()
{
this->rescaleAxis(ui->graphingView->xAxis);
this->rescaleAxis(ui->graphingView->yAxis);
ui->graphingView->replot();
}
void GraphingWindow::toggleFollowMode()
{
followGraphEnd = !followGraphEnd;
}
void GraphingWindow::contextMenuRequest(QPoint pos)
{
QMenu *menu = new QMenu(this);
menu->setAttribute(Qt::WA_DeleteOnClose);
if (ui->graphingView->legend->selectTest(pos, false) >= 0) // context menu on legend requested
{
menu->addAction(tr("Move to top left"), this, SLOT(moveLegend()))->setData((int)(Qt::AlignTop|Qt::AlignLeft));
menu->addAction(tr("Move to top center"), this, SLOT(moveLegend()))->setData((int)(Qt::AlignTop|Qt::AlignHCenter));
menu->addAction(tr("Move to top right"), this, SLOT(moveLegend()))->setData((int)(Qt::AlignTop|Qt::AlignRight));
menu->addAction(tr("Move to bottom right"), this, SLOT(moveLegend()))->setData((int)(Qt::AlignBottom|Qt::AlignRight));
menu->addAction(tr("Move to bottom left"), this, SLOT(moveLegend()))->setData((int)(Qt::AlignBottom|Qt::AlignLeft));
}
else // general context menu on graphs requested
{
menu->addAction(tr("Save graph image to file"), this, SLOT(saveGraphs()));
menu->addAction(tr("Save graph definitions to file"), this, SLOT(saveDefinitions()));
menu->addAction(tr("Load graph definitions from file"), this, SLOT(loadDefinitions()));
menu->addAction(tr("Save spreadsheet of data"), this, SLOT(saveSpreadsheet()));
QAction *act = menu->addAction(tr("Follow end of graph"), this, SLOT(toggleFollowMode()));
act->setCheckable(true);
act->setChecked(followGraphEnd);
menu->addAction(tr("Add new graph"), this, SLOT(addNewGraph()));
if (ui->graphingView->selectedGraphs().size() > 0)
{
menu->addSeparator();
menu->addAction(tr("Edit selected graph"), this, SLOT(editSelectedGraph()));
menu->addAction(tr("Remove selected graph"), this, SLOT(removeSelectedGraph()));
}
if (ui->graphingView->graphCount() > 0)
{
menu->addSeparator();
menu->addAction(tr("Remove all graphs"), this, SLOT(removeAllGraphs()));
}
menu->addSeparator();
menu->addAction(tr("Reset View"), this, SLOT(resetView()));
if (ui->graphingView->graphCount() > 0)
{
menu->addAction(tr("Rescale to data"), this, SLOT(rescaleToData()));
}
menu->addAction(tr("Zoom In"), this, SLOT(zoomIn()));
menu->addAction(tr("Zoom Out"), this, SLOT(zoomOut()));
}
menu->popup(ui->graphingView->mapToGlobal(pos));
}
void GraphingWindow::saveGraphs()
{
QFileDialog dialog(this);
QSettings settings;
QStringList filters;
filters.append(QString(tr("PDF Files (*.pdf)")));
filters.append(QString(tr("PNG Files (*.png)")));
filters.append(QString(tr("JPEG Files (*.jpg)")));
dialog.setFileMode(QFileDialog::AnyFile);
dialog.setNameFilters(filters);
dialog.setViewMode(QFileDialog::Detail);
dialog.setAcceptMode(QFileDialog::AcceptSave);
dialog.setDirectory(settings.value("Graphing/LoadSaveDirectory", dialog.directory().path()).toString());
if (dialog.exec() == QDialog::Accepted)
{
QString filename = dialog.selectedFiles().constFirst();
settings.setValue("Graphing/LoadSaveDirectory", dialog.directory().path());
if (dialog.selectedNameFilter() == filters[0])
{
if (!filename.contains('.')) filename += ".pdf";
ui->graphingView->savePdf(filename, 0, 0);
}
if (dialog.selectedNameFilter() == filters[1])
{
if (!filename.contains('.')) filename += ".png";
ui->graphingView->savePng(filename, 0, 0);
}
if (dialog.selectedNameFilter() == filters[2])
{
if (!filename.contains('.')) filename += ".jpg";
ui->graphingView->saveJpg(filename, 0, 0);
}
}
}
void GraphingWindow::saveSpreadsheet()
{
QFileDialog dialog(this);
QSettings settings;
QStringList filters;
filters.append(QString(tr("Spreadsheet (*.csv)")));
dialog.setFileMode(QFileDialog::AnyFile);
dialog.setNameFilters(filters);
dialog.setViewMode(QFileDialog::Detail);
dialog.setAcceptMode(QFileDialog::AcceptSave);
dialog.setDirectory(settings.value("Graphing/LoadSaveDirectory", dialog.directory().path()).toString());
if (dialog.exec() == QDialog::Accepted)
{
QString filename = dialog.selectedFiles().constFirst();
settings.setValue("Graphing/LoadSaveDirectory", dialog.directory().path());
if (!filename.contains('.')) filename += ".csv";
QFile outFile(filename);
if (!outFile.open(QIODevice::WriteOnly | QIODevice::Text))
return;
/*
* save some data
* The problem here is that we've got X number of graphs that all have different
* timestamps but a spreadsheet would be best if each graph were taken at the same slice
* such that you have a list of slices with the value of each graph at that slice.
*
* But, for now export each graph in turn with the proper timestamp for each piece of data
* and a reference for which graph it came from. This is better than nothing.
*/
QList<GraphParams>::iterator iter;
double xMin = std::numeric_limits<double>::max(),
xMax = std::numeric_limits<double>::min();
int maxCount = 0;
int numGraphs = graphParams.length();
for (auto && graph : graphParams) {
xMin = std::min(xMin, graph.x[0]);
xMax = std::max(xMax, graph.x[graph.x.count() - 1]);
maxCount = std::max((qsizetype)maxCount, graph.x.count());
}
qDebug() << "xMin: " << xMin;
qDebug() << "xMax: " << xMax;
qDebug() << "MaxCount: " << maxCount;
//The idea now is to iterate from xMin to xMax slicing all graphs up into MaxCount slices.
//But, actually, don't visit actual xMin or xMax, inset from there by one slice. Then, if
//a given graph doesn't exist there use the value from the nearest place that does exist.
double xSize = xMax - xMin;
double sliceSize = xSize / ((double)maxCount);
double equivValue = sliceSize / 100.0;
QList<int> indices;
indices.reserve(numGraphs);
outFile.write("TimeStamp");
for (auto && graph : graphParams) {
indices.append(0);
outFile.putChar(',');
outFile.write(graph.graphName.toUtf8());
}
outFile.write("\n");
for (int j = 1; j < (maxCount - 1); j++)
{
double currentX = xMin + (j * sliceSize);
qDebug() << "X: " << currentX;
outFile.write(QString::number(currentX, 'f').toUtf8());
for (int k = 0; k < numGraphs; k++)
{
double value = 0.0;
// move cursor to last sample before currentX
while (graphParams[k].x[indices[k]+1] < currentX)
{
indices[k]++;
}
//five possibilities.
//1: we're at the beginning for this graph but the slice is before this graph even starts
if (indices[k] == 0 && graphParams[k].x[indices[k]] > currentX)
{
value = graphParams[k].y[indices[k]];
}
//2: The opposite, we're at the end of this graph but the slices keep going
else if (indices[k] == (graphParams[k].x.count() - 1) && graphParams[k].x[indices[k]] < currentX)
{
value = graphParams[k].y[indices[k]];
}
//3: the slice is right near the current value we're at for this graph
else if (fabs(graphParams[k].x[indices[k]] - currentX) < equivValue)
{
value = graphParams[k].y[indices[k]];
}
//4: the slice is right next to the next value for this graph
else if (fabs(graphParams[k].x[indices[k] + 1] - currentX) < equivValue)
{
value = graphParams[k].y[indices[k] + 1];
}
//5: it's somewhere in between two values for this graph
//the two values will be indices[k] and indices[k] + 1
else
{
// find index, where x >= currentX
int cursor = indices[k];
double span = graphParams[k].x[cursor+1] - graphParams[k].x[cursor];
double progress = (currentX - graphParams[k].x[cursor]) / span;
Q_ASSERT(progress >= 0.0 && progress <= 1.0);
value = Utility::Lerp(graphParams[k].y[cursor], graphParams[k].y[cursor+1], progress);
qDebug() << "Span: " << span << " Prog: " << progress << " Value: " << value;
}
outFile.putChar(',');
outFile.write(QString::number(value).toUtf8());
}
outFile.write("\n");
}
outFile.close();
}
}
void GraphingWindow::saveDefinitions()
{
QFileDialog dialog(this);
QSettings settings;
QStringList filters;
filters.append(QString(tr("Graph definition (*.gdf)")));
dialog.setFileMode(QFileDialog::AnyFile);
dialog.setNameFilters(filters);
dialog.setViewMode(QFileDialog::Detail);
dialog.setAcceptMode(QFileDialog::AcceptSave);
dialog.setDirectory(settings.value("Graphing/LoadSaveDirectory", dialog.directory().path()).toString());
if (dialog.exec() == QDialog::Accepted)
{
QString filename = dialog.selectedFiles().constFirst();
settings.setValue("Graphing/LoadSaveDirectory", dialog.directory().path());
if (!filename.contains('.')) filename += ".gdf";
QFile outFile(filename);
if (!outFile.open(QIODevice::WriteOnly | QIODevice::Text))
return;
QList<GraphParams>::iterator iter;
for (iter = graphParams.begin(); iter != graphParams.end(); ++iter)
{
outFile.write("Z,");
outFile.write(QString::number(iter->ID, 16).toUtf8());
outFile.putChar(',');
outFile.write(QString::number(iter->mask, 16).toUtf8());
outFile.putChar(',');
if (iter->intelFormat) outFile.write(QString::number(iter->startBit).toUtf8());
else outFile.write(QString::number(iter->startBit * -1).toUtf8());
outFile.putChar(',');
outFile.write(QString::number(iter->numBits).toUtf8());
outFile.putChar(',');
if (iter->isSigned) outFile.putChar('Y');
else outFile.putChar('N');
outFile.putChar(',');
outFile.write(QString::number(iter->bias).toUtf8());
outFile.putChar(',');
outFile.write(QString::number(iter->scale).toUtf8());
outFile.putChar(',');
outFile.write(QString::number(iter->stride).toUtf8());
outFile.putChar(',');
outFile.write(QString::number(iter->bus).toUtf8());
outFile.putChar(',');
outFile.write(QString::number(iter->lineColor.red()).toUtf8());
outFile.putChar(',');
outFile.write(QString::number(iter->lineColor.green()).toUtf8());
outFile.putChar(',');
outFile.write(QString::number(iter->lineColor.blue()).toUtf8());
outFile.putChar(',');
outFile.write(iter->graphName.toUtf8());
outFile.putChar(',');
outFile.write(QString::number(iter->fillColor.red()).toUtf8());
outFile.putChar(',');
outFile.write(QString::number(iter->fillColor.green()).toUtf8());
outFile.putChar(',');
outFile.write(QString::number(iter->fillColor.blue()).toUtf8());
outFile.putChar(',');
outFile.write(QString::number(iter->fillColor.alpha()).toUtf8());
outFile.putChar(',');
if (iter->drawOnlyPoints) outFile.putChar('Y');
else outFile.putChar('N');
outFile.putChar(',');
outFile.write(QString::number(iter->pointType).toUtf8());
outFile.putChar(',');
outFile.write(QString::number(iter->lineWidth).toUtf8());
if (iter->associatedSignal)
{
outFile.putChar(',');
outFile.write(iter->associatedSignal->parentMessage->name.toUtf8());
outFile.putChar(',');
outFile.write(iter->associatedSignal->name.toUtf8());
}
outFile.write("\n");
}
outFile.close();
}
}
void GraphingWindow::loadDefinitions()
{
QFileDialog dialog;
QSettings settings;
QStringList filters;
filters.append(QString(tr("Graph definition (*.gdf)")));
if (dbcHandler == nullptr) return;
if (dbcHandler->getFileCount() == 0) dbcHandler->createBlankFile();
dialog.setFileMode(QFileDialog::ExistingFile);
dialog.setNameFilters(filters);
dialog.setViewMode(QFileDialog::Detail);
dialog.setDirectory(settings.value("Graphing/LoadSaveDirectory", dialog.directory().path()).toString());
if (dialog.exec() == QDialog::Accepted)
{
QString filename = dialog.selectedFiles().constFirst();
settings.setValue("Graphing/LoadSaveDirectory", dialog.directory().path());
QFile inFile(filename);
QByteArray line;
if (!inFile.open(QIODevice::ReadOnly | QIODevice::Text))
return;
while (!inFile.atEnd()) {
line = inFile.readLine().simplified();
if (line.length() > 2)
{
GraphParams gp;
QList<QByteArray> tokens = line.split(',');
gp.associatedSignal = nullptr; //might not be saved in the graph definition so default it to nothing
//should probably do better at merging all the code that is the same between all these formats instead of duplication...
if (tokens[0] == "Z") //very newest format, adds ability to set bus number
{
gp.ID = tokens[1].toUInt(nullptr, 16);
gp.mask = tokens[2].toULongLong(nullptr, 16);
gp.startBit = tokens[3].toInt();
if (gp.startBit < 0) {
gp.intelFormat = false;
gp.startBit *= -1;
}
else gp.intelFormat = true;
gp.numBits = tokens[4].toInt();
if (tokens[5] == "Y") gp.isSigned = true;
else gp.isSigned = false;
gp.bias = tokens[6].toFloat();
gp.scale = tokens[7].toFloat();
gp.stride = tokens[8].toInt();
gp.bus = tokens[9].toInt();
gp.lineColor.setRed( tokens[10].toInt() );
gp.lineColor.setGreen( tokens[11].toInt() );
gp.lineColor.setBlue( tokens[12].toInt() );
if (tokens.length() > 13)
gp.graphName = tokens[13];
else
gp.graphName = QString();
if (tokens.length() > 20) //even newer format with extra graph formatting options
{
gp.fillColor.setRed( tokens[14].toInt() );
gp.fillColor.setGreen( tokens[15].toInt() );
gp.fillColor.setBlue( tokens[16].toInt() );
gp.fillColor.setAlpha( tokens[17].toInt() );
if (tokens[18] == "Y") gp.drawOnlyPoints = true;
else gp.drawOnlyPoints = false;
gp.pointType = tokens[19].toInt();
gp.lineWidth = tokens[20].toInt();
}
if (tokens.length() > 22)
{
DBC_MESSAGE *msg = dbcHandler->findMessage(gp.ID);
if (msg)
{
gp.associatedSignal = msg->sigHandler->findSignalByName(tokens[22]);
}
else qDebug() << "Couldn't find the message by name! " << tokens[21] << " " << tokens[22];
}
createGraph(gp, true);
}
else if (tokens[0] == "X") //second newest format based around signals
{
gp.ID = tokens[1].toUInt(nullptr, 16);
gp.mask = tokens[2].toULongLong(nullptr, 16);
gp.startBit = tokens[3].toInt();
if (gp.startBit < 0) {
gp.intelFormat = false;
gp.startBit *= -1;
}
else gp.intelFormat = true;
gp.numBits = tokens[4].toInt();
if (tokens[5] == "Y") gp.isSigned = true;
else gp.isSigned = false;
gp.bias = tokens[6].toFloat();
gp.scale = tokens[7].toFloat();
gp.stride = tokens[8].toInt();
gp.bus = -1;
gp.lineColor.setRed( tokens[9].toInt() );
gp.lineColor.setGreen( tokens[10].toInt() );
gp.lineColor.setBlue( tokens[11].toInt() );
if (tokens.length() > 12)
gp.graphName = tokens[12];
else
gp.graphName = QString();
if (tokens.length() > 19) //even newer format with extra graph formatting options
{
gp.fillColor.setRed( tokens[13].toInt() );
gp.fillColor.setGreen( tokens[14].toInt() );
gp.fillColor.setBlue( tokens[15].toInt() );
gp.fillColor.setAlpha( tokens[16].toInt() );
if (tokens[17] == "Y") gp.drawOnlyPoints = true;
else gp.drawOnlyPoints = false;
gp.pointType = tokens[18].toInt();
gp.lineWidth = tokens[19].toInt();
}
if (tokens.length() > 21)
{
DBC_MESSAGE *msg = dbcHandler->findMessage(gp.ID);
if (msg)
{
gp.associatedSignal = msg->sigHandler->findSignalByName(tokens[21]);
}
else qDebug() << "Couldn't find the message by name! " << tokens[20] << " " << tokens[21];
}
createGraph(gp, true);
}
else //one of the two older formats then
{
gp.ID = tokens[0].toUInt(nullptr, 16);
gp.bus = -1;
if (tokens[1] == "S") //old signal based graph definition
{
//tokens[2] is the signal name. Need to use the message ID and this name to look it up
DBC_MESSAGE *msg = dbcHandler->getFileByIdx(0)->messageHandler->findMsgByID(gp.ID);
if (msg != nullptr)
{
DBC_SIGNAL *sig = msg->sigHandler->findSignalByName(tokens[2]);
if (sig)
{
gp.mask = 0xFFFFFFFF;
gp.bias = (float)sig->bias;
gp.lineColor.setRed(tokens[3].toInt());
gp.lineColor.setGreen(tokens[4].toInt());
gp.lineColor.setBlue(tokens[5].toInt());
gp.graphName = sig->name;
gp.intelFormat = sig->intelByteOrder;
if (sig->valType == SIGNED_INT) gp.isSigned = true;
else gp.isSigned = false;
gp.numBits = sig->signalSize;
gp.scale = (float)sig->factor;
gp.startBit = sig->startBit;
gp.stride = 1;
createGraph(gp, true);
}
}
}
else //old standard graph definition
{
//hard part - this all changed drastically
//the difference between intel and motorola format is whether
//start is larger than end byte or not.
uint64_t oldMask = tokens[1].toULongLong(nullptr, 16);
int oldStart = tokens[2].toInt();
int oldEnd = tokens[3].toInt();
if (oldEnd > oldStart) //motorola / big endian - hell...
{
gp.intelFormat = false;
//for now just naively use the entire bytes called for.
gp.startBit = 8 * oldStart + 7;
gp.numBits = (oldEnd - oldStart + 1) * 8;
}
else if (oldStart > oldEnd) //intel / little endian - easiest of multi-byte types
{
//have to find both ends. start bit is somewhere in oldEnd and last bit is somewhere in
//oldStart.
gp.intelFormat = true;
//start by setting a safe default if nothing else pans out.
gp.startBit = 8 * oldEnd;
int numBytes = oldStart - oldEnd + 1;
gp.numBits = numBytes * 8;
for (int b = 0; b < 8; b++)
{
if (oldMask & (1ull << b))
{
gp.startBit = (8 * oldEnd) + b;
break;
}
}
for (int c = 7; c >= 0; c--)
{
if ( oldMask & (1ull << (((numBytes - 1) * 8) + c)) )
{
gp.numBits -= (7-c);
break;
}
}
}
else //within a single byte - easier than the above two by a bit - always use intel format for this
{
gp.intelFormat = true;
oldMask = oldMask & 0xFF; //only this part matters
//for intel format we give startbit as the lowest bit number in the signal
//we can find that by going backward from bit 0 to 7 and picking the first bit that is 1.
//that's our start bit (+ 8*oldStart)
//set default first in case the rest falls through
gp.startBit = 8 * oldStart;
gp.numBits = 8;
for (int b = 0; b < 8; b++)
{
if (oldMask & (1ull << b))
{
gp.startBit = 8 * oldStart + b;
gp.numBits = 8 - b;
break;
}
}
}
//the rest is easy stuff
if (tokens[4] == "Y") gp.isSigned = true;
else gp.isSigned = false;
gp.bias = tokens[5].toFloat();
gp.scale = tokens[6].toFloat();
gp.stride = tokens[7].toInt();
gp.lineColor.setRed(tokens[8].toInt());
gp.lineColor.setGreen(tokens[9].toInt());
gp.lineColor.setBlue(tokens[10].toInt());
if (tokens.length() > 11)
gp.graphName = tokens[11];
else
gp.graphName = QString();
createGraph(gp, true);
}
}
}
}
inFile.close();
}
}
void GraphingWindow::showParamsDialog(int idx = -1)
{
dbcHandler = DBCHandler::getReference();
NewGraphDialog *thisDialog = new NewGraphDialog(dbcHandler, this);
if (idx > -1)
{
thisDialog->setParams(graphParams[idx]);
}
else thisDialog->clearParams();
if (thisDialog->exec() == QDialog::Accepted)
{
if (idx > -1) //if there was an existing graph then delete it
{
graphParams.removeAt(idx);
ui->graphingView->removeGraph(idx);
}
//create a new graph with the returned parameters.
GraphParams params;
thisDialog->getParams(params);
createGraph(params);
}
delete thisDialog;
}
void GraphingWindow::addNewGraph()
{
showParamsDialog(-1);
}
void GraphingWindow::appendToGraph(GraphParams ¶ms, CANFrame &frame, QVector<double> &x, QVector<double> &y)
{
params.strideSoFar++;
if (params.strideSoFar >= params.stride)
{
params.strideSoFar = 0;
int64_t tempVal; //64 bit temp value.
tempVal = Utility::processIntegerSignal(frame.payload(), params.startBit, params.numBits, params.intelFormat, params.isSigned); //& params.mask;
double xVal, yVal;
if (Utility::timeStyle == TS_SECONDS)
{
xVal = ((double)(frame.timeStamp().microSeconds()) / 1000000.0 - params.xbias);
}
else if (Utility::timeStyle == TS_CLOCK)
{
QDateTime dt = QDateTime::fromMSecsSinceEpoch((frame.timeStamp().microSeconds() / 1000) - params.xbias);
xVal = (dt.time().msec()/1000.0 + dt.time().second() + dt.time().minute() * 60 + dt.time().hour() * 3600);
}
else
{
xVal = (frame.timeStamp().microSeconds() - params.xbias);
}
//there really is no way to set a graphable item as being stored as a float unless it was an actual DBC signal
//So, if we have a DBC signal associated then use that, otherwise try to turn the above integer calculation into
//a final output by using the scale and bias.
if (params.associatedSignal)
{
//if for some reason the processAsDouble fails we'll fall back on manual approach
if (!params.associatedSignal->processAsDouble(frame, yVal)) yVal = (tempVal * params.scale) + params.bias;
}
else yVal = (tempVal * params.scale) + params.bias;
params.x.append(xVal);
params.y.append(yVal);
x.append(xVal);
y.append(yVal);
//now see if we've got to do anything with the brackets and labels for value table stuff
QString tempStr;
if (params.associatedSignal)
{
bool isValid = params.associatedSignal->getValueString(tempVal, tempStr);
if (isValid)
{
//we have a graph with associated signal and we could interpret it. So, see what we need to do
if (tempStr == params.prevValStr) //still same value, update bracket only
{
params.lastBracket->right->setCoords(xVal, params.prevValLocation.y());
}
else //changed. See if this is the first value or if we're merely starting another one
{
//a quick check for whether this is the first value or not.
if (params.prevValLocation == QPointF(0,0))
{
params.prevValLocation = QPointF(xVal, yVal);
//params.prevValStr = tempStr;
//params.prevValTable = tempVal;
}
else //wasn't the same so complete the previous span and start a new one.
{
params.prevValTable = tempVal;
params.prevValLocation = QPointF(xVal, yVal);
params.prevValStr = tempStr;
QCPItemBracket *bracket = new QCPItemBracket(ui->graphingView);
bracket->left->setCoords(params.prevValLocation);
bracket->right->setCoords(params.prevValLocation);
bracket->setLength(12);
params.lastBracket = bracket;
params.brackets.append(bracket);
// add text label for this value table entry
QCPItemText *valueText = new QCPItemText(ui->graphingView);
valueText->position->setParentAnchor(bracket->center);
valueText->position->setCoords(0, -10.0); // move 10 pixels to the top from bracket center anchor
valueText->setPositionAlignment(Qt::AlignBottom|Qt::AlignHCenter);
valueText->setText(tempStr);
qDebug() << "JiggaWatts: " << tempStr;
valueText->setFont(QFont(font().family(), 10));
params.bracketTexts.append(valueText);
}
}
}
}
}
}
void GraphingWindow::createGraph(GraphParams ¶ms, bool createGraphParam)
{
int64_t tempVal; //64 bit temp value.
double yminval=10000000.0, ymaxval = -1000000.0;
double xminval=10000000000.0, xmaxval = -10000000000.0;
GraphParams *refParam = ¶ms;
QString tempStr;
double x{}, y{};
qDebug() << "New Graph ID: " << params.ID;
qDebug() << "Start bit: " << params.startBit;
qDebug() << "Data length: " << params.numBits;
qDebug() << "Intel Mode: " << params.intelFormat;
qDebug() << "Signed: " << params.isSigned;
qDebug() << "Mask: " << params.mask;
frameCache.clear();
for (int i = 0; i < modelFrames->count(); i++)
{
CANFrame thisFrame = modelFrames->at(i);
if ( (thisFrame.frameId() == params.ID) && (thisFrame.frameType() == QCanBusFrame::DataFrame)
&& ( ( params.bus == -1) || (params.bus == thisFrame.bus) ) ) frameCache.append(thisFrame);
}
//to fix weirdness where a graph that has no data won't be able to be edited, selected, or deleted properly
//we'll check for the condition that there is nothing to graph and add a single dummy frame to the cache
//that has all data bytes = 0. This allows the graph to be edited and deleted. No idea why you can't otherwise.
if (frameCache.count() == 0)
{
CANFrame dummy;
dummy.setFrameId(params.ID);
dummy.bus = 0;
dummy.setPayload(QByteArray(8, 0));
dummy.setFrameType(QCanBusFrame::DataFrame);
frameCache.append(dummy);
}
int numEntries = frameCache.count() / params.stride;
if (numEntries < 1) numEntries = 1; //could happen if stride is larger than frame count
params.x.clear();
params.y.clear();
params.x.reserve(numEntries);
params.y.reserve(numEntries);
//params.x.fill(0, numEntries);
//params.y.fill(0, numEntries);
int sBit = params.startBit;
int bits = params.numBits;
bool intelFormat = params.intelFormat;
bool isSigned = params.isSigned;
for (int j = 0; j < numEntries; j++)
{
int k = j * params.stride;
if (params.associatedSignal)
{
//skip all the rest of the stuff in this loop and don't add this to the graph if this signal isn't in this frame
if (!params.associatedSignal->isSignalInMessage(frameCache[k]))
{
qDebug() << "Signal was not in this frame";
continue;
}
else qDebug() << "Signal in the frame!";
}
tempVal = Utility::processIntegerSignal(frameCache[k].payload(), sBit, bits, intelFormat, isSigned); //& params.mask;
//qDebug() << tempVal;
if (params.associatedSignal)
{
//if for some reason the processAsDouble fails we'll fall back on manual approach
if (!params.associatedSignal->processAsDouble(frameCache[k], y))
y = (tempVal * params.scale) + params.bias;
}
else y = (tempVal * params.scale) + params.bias;
params.y.append( y );
if (Utility::timeStyle == TS_SECONDS)
{
x = (frameCache[k].timeStamp().microSeconds()) / 1000000.0;
}
else if (Utility::timeStyle == TS_CLOCK)
{
QDateTime dt = QDateTime::fromMSecsSinceEpoch((frameCache[k].timeStamp().microSeconds() / 1000) - params.xbias);
x = (dt.time().msecsSinceStartOfDay() / 1000.0);
}
else
{
x = frameCache[k].timeStamp().microSeconds();
}
params.x.append( x );
if (params.associatedSignal && numEntries > 1)
{
bool isValid = params.associatedSignal->getValueString(tempVal, tempStr);
if (isValid)
{
if (params.prevValLocation == QPointF(0,0)) {
params.prevValLocation = QPointF(x, y);
params.prevValStr = tempStr;
params.prevValTable = 0;
}
if (tempVal != params.prevValTable)
{
qDebug() << "New Value: " << tempStr;
//Adding a bracket is a neat idea but you can't do that unless:
//1. you wait until the value changes again so you can put the bracket where it belongs or
//2. you constantly update the bracket in size then relocate the text too to match.
//since this code runs at the beginning of a graph operation it could center the bracket
//but supporting this all in realtime updating code is a bit more complicated.
// add the bracket at the top:
QCPItemBracket *bracket = new QCPItemBracket(ui->graphingView);
bracket->left->setCoords(params.prevValLocation);
bracket->right->setCoords(x, params.prevValLocation.y());
bracket->setLength(12);
params.brackets.append(bracket);
// add text label for this value table entry
QCPItemText *valueText = new QCPItemText(ui->graphingView);
valueText->position->setParentAnchor(bracket->center);
valueText->position->setCoords(0, -10.0); // move 10 pixels to the top from bracket center anchor
valueText->setPositionAlignment(Qt::AlignBottom|Qt::AlignHCenter);
valueText->setText(params.prevValStr);
valueText->setFont(QFont(font().family(), 10));
params.bracketTexts.append(valueText);
params.prevValLocation = QPointF(x, y);
params.prevValStr = tempStr;
params.lastBracket = bracket;
}
params.prevValTable = tempVal;
}
}
if (y < yminval) yminval = y;
if (y > ymaxval) ymaxval = y;
if (x < xminval) xminval = x;
if (x > xmaxval) xmaxval = x;
}
if (params.prevValLocation != QPointF(0,0))
{
QCPItemBracket *bracket = new QCPItemBracket(ui->graphingView);
bracket->left->setCoords(params.prevValLocation);
bracket->right->setCoords(x, params.prevValLocation.y());
bracket->setLength(12);
// add text label for this value table entry
QCPItemText *valueText = new QCPItemText(ui->graphingView);
valueText->position->setParentAnchor(bracket->center);
valueText->position->setCoords(0, -10.0); // move 10 pixels to the top from bracket center anchor
valueText->setPositionAlignment(Qt::AlignBottom|Qt::AlignHCenter);
valueText->setText(params.prevValStr);
valueText->setFont(QFont(font().family(), 10));
params.prevValLocation = QPointF(x, y);
params.prevValStr = tempStr;
params.prevValTable = tempVal;
params.lastBracket = bracket;
}
if (numEntries == 0)
{
yminval = -128.0;
ymaxval = 128.0;
xminval = 0;
xmaxval = 100;
}
params.xbias = 0;
ui->graphingView->addGraph();
params.ref = ui->graphingView->graph();
if (createGraphParam)
{
graphParams.append(params);
refParam = &graphParams.last();
}
selDecorator = new QCPSelectionDecorator(); //this has to be a pointer as it is freed internally to qcustomplot classes
selDecorator->setBrush(Qt::NoBrush);
selDecorator->setPen(selectedPen);
ui->graphingView->graph()->setSelectionDecorator(selDecorator);
if (params.graphName == nullptr || params.graphName.length() == 0)
{
params.graphName = QString("0x") + QString::number(params.ID, 16) + ":" + QString::number(params.startBit);
params.graphName += "-" + QString::number(params.numBits);
}
ui->graphingView->graph()->setName(params.graphName);
ui->graphingView->graph()->setProperty("id", params.ID);
ui->graphingView->graph()->setData(refParam->x,refParam->y);
ui->graphingView->graph()->setScatterStyle(QCPScatterStyle((QCPScatterStyle::ScatterShape)params.pointType));
if (params.drawOnlyPoints) ui->graphingView->graph()->setLineStyle(QCPGraph::lsNone); //Draw only the points, no connections, no fills
else
{
ui->graphingView->graph()->setLineStyle(QCPGraph::lsLine); //connect points with lines
}
QPen graphPen;
graphPen.setColor(params.lineColor);
graphPen.setWidth(params.lineWidth);
ui->graphingView->graph()->setPen(graphPen);
if (params.fillColor.alpha() > 0) //only if there is some opacity will we set up a fill brush
{
qDebug() << "Drawing filled graph";
QBrush fillBrush;
fillBrush.setColor(params.fillColor);
fillBrush.setStyle(Qt::SolidPattern);
ui->graphingView->graph()->setBrush(fillBrush);
}
double xRange = (xmaxval - xminval);
double yRange = (ymaxval - yminval);
double xMid = xminval + (xRange / 2.0);
double yMid = yminval + (yRange / 2.0);
//creates a slightly larger view than the actual boundary values to give some padding
xminval = xMid - (xRange / 1.95);
xmaxval = xMid + (xRange / 1.95);
yminval = yMid - (yRange / 1.8);
ymaxval = yMid + (yRange / 1.80);
qDebug() << "xmin: " << xminval;
qDebug() << "xmax: " << xmaxval;
qDebug() << "ymin: " << yminval;
qDebug() << "ymax: " << ymaxval;
if (needScaleSetup)
{
needScaleSetup = false;
ui->graphingView->xAxis->setRange(xminval, xmaxval);
ui->graphingView->axisRect()->setupFullAxesBox();
}
//always recalculate Y range so that new graphs actually show up in view
ui->graphingView->yAxis->setRange(yminval, ymaxval);
ui->graphingView->replot();
}
void GraphingWindow::moveLegend()
{
qDebug() << "moveLegend";
if (QAction* contextAction = qobject_cast<QAction*>(sender())) // make sure this slot is really called by a context menu action, so it carries the data we need
{
bool ok;
int dataInt = contextAction->data().toInt(&ok);
if (ok)
{
ui->graphingView->axisRect()->insetLayout()->setInsetAlignment(0, (Qt::Alignment)dataInt);
ui->graphingView->replot();
}
}
}
GraphParams::GraphParams()
{
ID = 0;
startBit = 1;
numBits = 1;
intelFormat = false;
isSigned = false;
mask = 0xFFFFFFFFFFFFFFFFULL;
bias = 0;
scale = 1;
stride = 1;
strideSoFar = 1;
bus = -1;
lineColor = QColor(0,0,0);
fillColor = QColor(255,255,255,0);
lineWidth = 1;
drawOnlyPoints = false;
pointType = 0;
ref = nullptr;
associatedSignal = nullptr;
graphName = "default";
xbias = 0;
prevValTable = 9999999999;
prevValLocation = QPointF(0,0);
prevValStr = "";
lastBracket = nullptr;
}
|