-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathqcpl_io_json.cpp
790 lines (701 loc) · 28.8 KB
/
qcpl_io_json.cpp
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
#include "qcpl_io_json.h"
#include "qcpl_plot.h"
#include "qcpl_utils.h"
#include "core/OriResult.h"
#include "tools/OriSettings.h"
#define MIME_TYPE "application/x-orion-project-org;value=plot-format"
#define CURRENT_LEGEND_VERSION 1
#define CURRENT_TITLE_VERSION 1
#define CURRENT_AXIS_VERSION 1
#define CURRENT_GRAPH_VERSION 1
#define SECTION_INI "DefaultPlotFormat"
#define KEY_TITLE "title"
#define KEY_LEGEND "legend"
#define KEY_AXIS "axis"
#define KEY_AXIS_X "axis_x"
#define KEY_AXIS_Y "axis_y"
#define KEY_GRAPH "graph"
namespace QCPL {
namespace {
QJsonValue colorToJson(const QColor& color)
{
return color.name();
}
QColor jsonToColor(const QJsonValue& val, const QColor& def)
{
QColor color(val.toString());
return color.isValid() ? color : def;
}
QJsonObject writeFont(const QFont& font)
{
return QJsonObject({
{ "family", font.family() },
{ "size", font.pointSize() },
{ "bold", font.bold() },
{ "italic", font.italic() },
{ "underline", font.underline() },
{ "strikeout", font.strikeOut() },
});
}
QFont readFont(const QJsonObject& obj, const QFont& def)
{
QFont f(def);
f.setFamily(obj["family"].toString(def.family()));
f.setPointSize(obj["size"].toInt(def.pointSize()));
f.setBold(obj["bold"].toBool(def.bold()));
f.setItalic(obj["italic"].toBool(def.italic()));
f.setUnderline(obj["underline"].toBool(def.underline()));
f.setStrikeOut(obj["strikeout"].toBool(def.strikeOut()));
return f;
}
QJsonObject writeSize(const QSize& size)
{
return QJsonObject({
{ "width", size.width() },
{ "height", size.height() },
});
}
QSize readSize(const QJsonObject& obj, const QSize& def)
{
return QSize(
obj["width"].toInt(def.width()),
obj["height"].toInt(def.height())
);
}
QJsonObject writeMargins(const QMargins& margins)
{
return QJsonObject({
{ "left", margins.left() },
{ "top", margins.top() },
{ "right", margins.right() },
{ "bottom", margins.bottom() },
});
}
QMargins readMargins(const QJsonObject& obj, const QMargins& def)
{
return QMargins(
obj["left"].toInt(def.left()),
obj["top"].toInt(def.top()),
obj["right"].toInt(def.right()),
obj["bottom"].toInt(def.bottom())
);
}
QJsonObject writeGradient(const QCPColorGradient& grad)
{
auto obj = QJsonObject({
{ "level_count", grad.levelCount() },
{ "color_interpolation", int(grad.colorInterpolation()) },
{ "nan_handling", int(grad.nanHandling()) },
{ "nan_color", colorToJson(grad.nanColor()) },
{ "periodic", grad.periodic() },
});
QJsonArray jsonStops;
auto stops = grad.colorStops();
for (auto it = stops.constBegin(); it != stops.constEnd(); it++)
{
jsonStops.append(QJsonObject({
{ "stop", it.key() },
{ "color", colorToJson(it.value()) },
}));
}
obj["color_stops"] = jsonStops;
return obj;
}
QCPColorGradient readGradient(const QJsonObject& obj, const QCPColorGradient& def)
{
QCPColorGradient grad;
grad.setLevelCount(obj["level_count"].toInt(def.levelCount()));
grad.setColorInterpolation(QCPColorGradient::ColorInterpolation(obj["color_interpolation"].toInt(int(def.colorInterpolation()))));
grad.setNanHandling(QCPColorGradient::NanHandling(obj["nan_handling"].toInt(int(def.nanHandling()))));
grad.setNanColor(jsonToColor(obj["nan_color"], def.nanColor()));
grad.setPeriodic(obj["periodic"].toBool(def.periodic()));
grad.clearColorStops();
QJsonArray jsonStops = obj["color_stops"].toArray();
for (auto it = jsonStops.constBegin(); it != jsonStops.constEnd(); it++)
{
auto jsonStop = (*it).toObject();
QColor color(jsonStop["color"].toString());
if (color.isValid())
grad.setColorStopAt(jsonStop["stop"].toDouble(), color);
}
return grad;
}
} // namespace
QJsonObject writePen(const QPen& pen)
{
return QJsonObject({
{ "color", pen.color().name() },
{ "style", int(pen.style()) },
{ "width", pen.width() },
});
}
QPen readPen(const QJsonObject& obj, const QPen& def)
{
QPen p(def);
QColor c(obj["color"].toString());
if (c.isValid())
p.setColor(c);
p.setStyle(Qt::PenStyle(obj["style"].toInt(def.style())));
p.setWidth(obj["width"].toInt(def.width()));
return p;
}
//------------------------------------------------------------------------------
// Write to JSON
static QString makeAxisKey(const QString base, int index) {
return index == 0 ? base : QString("%1_%2").arg(base).arg(index);
}
QJsonObject writePlot(Plot* plot, const WritePlotOptions &opts)
{
QJsonObject root({
{ KEY_LEGEND, writeLegend(plot->legend) },
{ KEY_TITLE, writeTitle(plot->title()) },
});
auto axes = plot->axisRect()->axes(QCPAxis::atBottom);
for (int i = 0; i < axes.size(); i++) {
root[makeAxisKey("axis_x", i)] = writeAxis(axes.at(i));
if (opts.onlyPrimaryAxes) break;
}
axes = plot->axisRect()->axes(QCPAxis::atLeft);
for (int i = 0; i < axes.size(); i++) {
root[makeAxisKey("axis_y", i)] = writeAxis(axes.at(i));
if (opts.onlyPrimaryAxes) break;
}
if (!opts.onlyPrimaryAxes) {
axes = plot->axisRect()->axes(QCPAxis::atTop);
for (int i = 0; i < axes.size(); i++)
root[makeAxisKey("axis_x2", i)] = writeAxis(axes.at(i));
axes = plot->axisRect()->axes(QCPAxis::atRight);
for (int i = 0; i < axes.size(); i++)
root[makeAxisKey("axis_y2", i)] = writeAxis(axes.at(i));
}
for (auto it = plot->additionalParts.constBegin(); it != plot->additionalParts.constEnd(); it++)
{
if (auto colorScale = qobject_cast<QCPColorScale*>(it.key()); colorScale)
{
root[it.value()] = writeColorScale(colorScale);
continue;
}
qWarning() << "writePlot: Unknown how lo write object to key" << it.value();
}
return root;
}
QJsonObject writeLegend(QCPLegend* legend)
{
return QJsonObject({
{ "version", CURRENT_LEGEND_VERSION },
{ "visible", legend->visible() },
{ "back_color", legend->brush().color().name() },
{ "text_color", legend->textColor().name() },
{ "font", writeFont(legend->font()) },
{ "icon_size", writeSize(legend->iconSize()) },
{ "icon_margin", legend->iconTextPadding() },
{ "border", writePen(legend->borderPen()) },
{ "paddings", writeMargins(legend->margins()) },
{ "margins", writeMargins(legendMargins(legend)) },
{ "location", int(legendLocation(legend)) }
});
}
QJsonObject writeTitle(QCPTextElement* title)
{
auto obj = QJsonObject({
{ "version", CURRENT_TITLE_VERSION },
{ "visible", title->visible() },
{ "font", writeFont(title->font()) },
{ "text_color", colorToJson(title->textColor()) },
{ "text_flags", title->textFlags() },
{ "margins", writeMargins(title->margins()) },
});
return obj;
}
QJsonObject writeAxis(QCPAxis *axis)
{
auto grid = axis->grid();
auto ticker = axis->ticker();
auto obj = QJsonObject({
{ "version", CURRENT_AXIS_VERSION },
{ "visible", axis->visible() },
{ "title_font", writeFont(axis->labelFont()) },
{ "title_color", colorToJson(axis->labelColor()) },
{ "title_margin_in", axis->labelPadding() },
{ "title_margin_out", axis->padding() },
{ "offset", axis->offset() },
{ "scale_log", axis->scaleType() == QCPAxis::stLogarithmic },
{ "reversed", axis->rangeReversed() },
{ "labels_visible", axis->tickLabels() },
{ "labels_inside", axis->tickLabelSide() == QCPAxis::lsInside },
{ "labels_rotation", axis->tickLabelRotation() },
{ "labels_margin", axis->tickLabelPadding() },
{ "labels_color", colorToJson(axis->tickLabelColor()) },
{ "labels_font", writeFont(axis->tickLabelFont()) },
{ "number_format", axis->numberFormat() },
{ "number_precision", axis->numberPrecision() },
{ "pen", writePen(axis->basePen()) },
{ "tick_visible", axis->ticks() },
{ "tick_pen", writePen(axis->tickPen()) },
{ "tick_len_in", axis->tickLengthIn() },
{ "tick_len_out", axis->tickLengthOut() },
{ "subtick_visible", axis->subTicks() },
{ "subtick_pen", writePen(axis->subTickPen()) },
{ "subtick_len_in", axis->subTickLengthIn() },
{ "subtick_len_out", axis->subTickLengthOut() },
{ "grid_visible", grid->visible() },
{ "grid_pen", writePen(grid->pen()) },
{ "zero_pen", writePen(grid->zeroLinePen()) },
{ "subgrid_visible", grid->subGridVisible() },
{ "subgrid_pen", writePen(grid->subGridPen()) },
{ "tick_strategy", int(ticker->tickStepStrategy()) },
{ "tick_count", ticker->tickCount() },
{ "tick_offset", ticker->tickOrigin() },
});
return obj;
}
QJsonObject writeColorScale(QCPColorScale *scale)
{
auto obj = writeAxis(scale->axis());
obj["color_bar_width"] = scale->barWidth();
obj["color_bar_gradient"] = writeGradient(scale->gradient());
obj["color_bar_margins"] = writeMargins(scale->margins());
return obj;
}
QJsonObject writeGraph(QCPGraph * graph)
{
auto scatter = graph->scatterStyle();
return QJsonObject({
{ "version", CURRENT_GRAPH_VERSION },
{ "line_pen", writePen(graph->pen()) },
{ "scatter_pen", writePen(scatter.pen()) },
{ "scatter_color", colorToJson(scatter.brush().color()) },
{ "scatter_shape", int(scatter.shape()) },
{ "scatter_size", scatter.size() },
{ "scatter_skip", graph->scatterSkip() },
});
}
//------------------------------------------------------------------------------
// Read from JSON
void readPlot(const QJsonObject& root, Plot *plot, JsonReport *report, const ReadPlotOptions& opts)
{
if (auto err = readLegend(root[KEY_LEGEND].toObject(), plot->legend); !err.ok() and report)
report->append(err);
if (auto err = readTitle(root[KEY_TITLE].toObject(), plot->title()); !err.ok() and report)
report->append(err);
const QLatin1String axisKeyPrefix("axis_");
QList<QPair<int, QString>> bottomAxisKeys, leftAxisKeys, topAxisKeys, rightAxisKeys;
foreach (const auto& key, root.keys())
{
if (!key.startsWith(axisKeyPrefix)) continue;
auto s = QStringView(key).right(key.size() - axisKeyPrefix.size());
QList<QPair<int, QString>> *keys;
int indexOffset;
if (s.startsWith(QLatin1String("y2"))) keys = &rightAxisKeys, indexOffset = 2;
else if (s.startsWith(QLatin1String("x2"))) keys = &topAxisKeys, indexOffset = 2;
else if (s.startsWith('y')) keys = &leftAxisKeys, indexOffset = 1;
else if (s.startsWith('x')) keys = &bottomAxisKeys, indexOffset = 1;
else continue;
s = s.right(s.size() - indexOffset);
int index = s.startsWith('_') ? s.right(s.size()-1).toInt() : 0;
keys->append({index, key});
}
auto readAxes = [root, plot, report, opts](QList<QPair<int, QString>>& keys, QCPAxis::AxisType axisType) {
std::sort(keys.begin(), keys.end(), [](const QPair<int, QString>& a, const QPair<int, QString>&b){
return a.first < b.first;
});
auto axes = plot->axisRect()->axes(axisType);
for (int i = 0; i < keys.size(); i++)
{
auto key = keys.at(i).second;
if (i < axes.size()) {
// pass
} else if (opts.autoCreateAxes) {
axes << plot->addAxis(axisType);
} else break;
if (auto err = readAxis(root[key].toObject(), axes.at(i)); !err.ok() and report)
report->append(err);
}
};
readAxes(bottomAxisKeys, QCPAxis::atBottom);
readAxes(leftAxisKeys, QCPAxis::atLeft);
readAxes(topAxisKeys, QCPAxis::atTop);
readAxes(rightAxisKeys, QCPAxis::atRight);
for (auto it = plot->additionalParts.constBegin(); it != plot->additionalParts.constEnd(); it++)
{
if (auto colorScale = qobject_cast<QCPColorScale*>(it.key()); colorScale)
{
if (auto err = readColorScale(root[it.value()].toObject(), colorScale); !err.ok() and report)
report->append(err);
continue;
}
qWarning() << "readPlot: Unknown how to read object from key" << it.value();
}
plot->updateTitleVisibility();
}
JsonError readLegend(const QJsonObject& obj, QCPLegend* legend)
{
if (obj.isEmpty())
return { JsonError::NoData, "Legend object is empty" };
auto ver = obj["version"].toInt();
if (ver != CURRENT_LEGEND_VERSION)
return {
JsonError::BadVersion,
QString("Unsupported legend version %1, expected %2").arg(ver, CURRENT_LEGEND_VERSION) };
legend->setVisible(obj["visible"].toBool(legend->visible()));
legend->setBrush(jsonToColor(obj["back_color"], legend->brush().color()));
legend->setTextColor(jsonToColor(obj["text_color"], legend->textColor()));
legend->setFont(readFont(obj["font"].toObject(), legend->font()));
legend->setSelectedFont(legend->font());
legend->setIconSize(readSize(obj["icon_size"].toObject(), legend->iconSize()));
legend->setIconTextPadding(obj["icon_margin"].toInt(legend->iconTextPadding()));
legend->setBorderPen(readPen(obj["border"].toObject(), legend->borderPen()));
legend->setMargins(readMargins(obj["paddings"].toObject(), legend->margins()));
setLegendMargins(legend, readMargins(obj["margins"].toObject(), legendMargins(legend)));
setLegendLocation(legend, Qt::Alignment(obj["location"].toInt(legendLocation(legend))));
return {};
}
JsonError readTitle(const QJsonObject &obj, QCPTextElement* title)
{
if (obj.isEmpty())
return { JsonError::NoData, "Title object is empty" };
auto ver = obj["version"].toInt();
if (ver != CURRENT_TITLE_VERSION)
return {
JsonError::BadVersion,
QString("Unsupported title version %1, expected %2").arg(ver, CURRENT_TITLE_VERSION) };
title->setVisible(obj["visible"].toBool(title->visible()));
title->setFont(readFont(obj["font"].toObject(), title->font()));
title->setSelectedFont(title->font());
title->setTextColor(jsonToColor(obj["text_color"], title->textColor()));
title->setTextFlags(obj["text_flags"].toInt(title->textFlags()));
title->setMargins(readMargins(obj["margins"].toObject(), title->margins()));
return {};
}
JsonError readAxis(const QJsonObject &obj, QCPAxis* axis)
{
if (obj.isEmpty())
return { JsonError::NoData, "Axis object is empty" };
auto ver = obj["version"].toInt();
if (ver != CURRENT_AXIS_VERSION)
return {
JsonError::BadVersion,
QString("Unsupported axis version %1, expected %2").arg(ver, CURRENT_AXIS_VERSION) };
axis->setVisible(obj["visible"].toBool(axis->visible()));
axis->setLabelFont(readFont(obj["title_font"].toObject(), axis->labelFont()));
axis->setSelectedLabelFont(axis->labelFont());
axis->setLabelColor(jsonToColor(obj["title_color"], axis->labelColor()));
axis->setLabelPadding(obj["title_margin_in"].toInt(axis->labelPadding()));
axis->setPadding(obj["title_margin_out"].toInt(axis->padding()));
axis->setOffset(obj["offset"].toInt(axis->offset()));
axis->setScaleType(obj["scale_log"].toBool(axis->scaleType() == QCPAxis::stLogarithmic) ? QCPAxis::stLogarithmic : QCPAxis::stLinear);
axis->setRangeReversed(obj["reversed"].toBool(axis->rangeReversed()));
axis->setTickLabels(obj["labels_visible"].toBool(axis->tickLabels()));
axis->setTickLabelSide(obj["labels_inside"].toBool(axis->tickLabelSide() == QCPAxis::lsInside) ? QCPAxis::lsInside : QCPAxis::lsOutside);
axis->setTickLabelRotation(obj["labels_rotation"].toDouble(axis->tickLabelRotation()));
axis->setTickLabelPadding(obj["labels_margin"].toInt(axis->tickLabelPadding()));
axis->setTickLabelColor(jsonToColor(obj["labels_color"], axis->tickLabelColor()));
axis->setTickLabelFont(readFont(obj["labels_font"].toObject(), axis->tickLabelFont()));
axis->setSelectedTickLabelFont(axis->tickLabelFont());
axis->setNumberFormat(obj["number_format"].toString(axis->numberFormat()));
axis->setNumberPrecision(obj["number_precision"].toInt(axis->numberPrecision()));
axis->setBasePen(readPen(obj["pen"].toObject(), axis->basePen()));
axis->setTicks(obj["tick_visible"].toBool(axis->ticks()));
axis->setTickPen(readPen(obj["tick_pen"].toObject(), axis->tickPen()));
axis->setTickLengthIn(obj["tick_len_in"].toInt(axis->tickLengthIn()));
axis->setTickLengthOut(obj["tick_len_out"].toInt(axis->tickLengthOut()));
axis->setSubTicks(obj["subtick_visible"].toInt(axis->subTicks()));
axis->setSubTickPen(readPen(obj["subtick_pen"].toObject(), axis->subTickPen()));
axis->setSubTickLengthIn(obj["subtick_len_in"].toInt(axis->subTickLengthIn()));
axis->setSubTickLengthOut(obj["subtick_len_out"].toInt(axis->subTickLengthOut()));
auto grid = axis->grid();
grid->setVisible(obj["grid_visible"].toBool(grid->visible()));
grid->setPen(readPen(obj["grid_pen"].toObject(), grid->pen()));
grid->setZeroLinePen(readPen(obj["zero_pen"].toObject(), grid->zeroLinePen()));
grid->setSubGridVisible(obj["subgrid_visible"].toBool(grid->subGridVisible()));
grid->setSubGridPen(readPen(obj["subgrid_pen"].toObject(), grid->subGridPen()));
auto ticker = axis->ticker();
ticker->setTickStepStrategy(QCPAxisTicker::TickStepStrategy(obj["tick_strategy"].toInt(int(ticker->tickStepStrategy()))));
ticker->setTickCount(obj["tick_count"].toInt(ticker->tickCount()));
ticker->setTickOrigin(obj["tick_offset"].toDouble(ticker->tickOrigin()));
updateAxisTicker(axis);
return {};
}
JsonError readColorScale(const QJsonObject &obj, QCPColorScale *scale)
{
auto err = readAxis(obj, scale->axis());
if (!err.ok())
return err;
scale->setBarWidth(obj["color_bar_width"].toInt(scale->barWidth()));
scale->setGradient(readGradient(obj["color_bar_gradient"].toObject(), scale->gradient()));
scale->setMargins(readMargins(obj["color_bar_margins"].toObject(), scale->margins()));
return {};
}
JsonError readGraph(const QJsonObject &obj, QCPGraph * graph)
{
if (obj.isEmpty())
return { JsonError::NoData, "Line format object is empty" };
auto ver = obj["version"].toInt();
if (ver != CURRENT_GRAPH_VERSION)
return {
JsonError::BadVersion,
QString("Unsupported line format version %1, expected %2").arg(ver, CURRENT_GRAPH_VERSION) };
graph->setPen(readPen(obj["line_pen"].toObject(), graph->pen()));
QCPScatterStyle scatter = graph->scatterStyle();
scatter.setPen(readPen(obj["scatter_pen"].toObject(), scatter.pen()));
scatter.setBrush(jsonToColor(obj["scatter_color"], scatter.brush().color()));
scatter.setShape(QCPScatterStyle::ScatterShape(obj["scatter_shape"].toInt(int(scatter.shape()))));
scatter.setSize(obj["scatter_size"].toDouble(scatter.size()));
graph->setScatterStyle(scatter);
graph->setScatterSkip(obj["scatter_skip"].toInt(graph->scatterSkip()));
return {};
}
//------------------------------------------------------------------------------
// QCPL::FormatStorageIni
//------------------------------------------------------------------------------
QString findStorageKey(const char* func, QCPLayerable* obj)
{
auto plot = qobject_cast<Plot*>(obj->parentPlot());
if (!plot || !plot->additionalParts.contains(obj))
{
qWarning() << func << "Object is not registerd in parent plot as storable object";
return {};
}
return plot->additionalParts[obj];
}
static QJsonObject varToJson(const QVariant& data)
{
QString str = data.toString();
if (str.isEmpty()) return QJsonObject();
QJsonDocument doc = QJsonDocument::fromJson(str.toUtf8());
return doc.isNull() ? QJsonObject() : doc.object();
}
static QVariant jsonToVar(const QJsonObject& obj)
{
return QJsonDocument(obj).toJson(QJsonDocument::Compact);
}
static void savePlotFormatIni(const QString& key, const QJsonObject& obj)
{
Ori::Settings s;
s.beginGroup(SECTION_INI);
s.setValue(key, jsonToVar(obj));
}
void FormatStorageIni::save(Plot* plot)
{
Ori::Settings s;
s.beginGroup(SECTION_INI);
s.setValue(KEY_TITLE, jsonToVar(writeTitle(plot->title())));
s.setValue(KEY_LEGEND, jsonToVar(writeLegend(plot->legend)));
s.setValue(KEY_AXIS_X, jsonToVar(writeAxis(plot->xAxis)));
s.setValue(KEY_AXIS_Y, jsonToVar(writeAxis(plot->yAxis)));
for (auto it = plot->additionalParts.constBegin(); it != plot->additionalParts.constEnd(); it++)
{
if (auto colorScale = qobject_cast<QCPColorScale*>(it.key()); colorScale)
{
s.setValue(it.value(), jsonToVar(writeColorScale(colorScale)));
continue;
}
qWarning() << "FormatStorageIni::save: Unknown how to save object with key" << it.value();
}
}
void FormatStorageIni::load(Plot *plot, JsonReport* report)
{
Ori::Settings s;
s.beginGroup(SECTION_INI);
// Non existent settings keys can be safely read too, they result in empty json objects
// and read functons should skip empty objects without substituting default values for every prop.
if (auto err = readLegend(varToJson(s.value(KEY_LEGEND)), plot->legend); !err.ok() and report)
report->append(err);
if (auto err = readTitle(varToJson(s.value(KEY_TITLE)), plot->title()); !err.ok() and report)
report->append(err);
if (auto err = readAxis(varToJson(s.value(KEY_AXIS_X)), plot->xAxis); !err.ok() and report)
report->append(err);
if (auto err = readAxis(varToJson(s.value(KEY_AXIS_Y)), plot->yAxis); !err.ok() and report)
report->append(err);
for (auto it = plot->additionalParts.constBegin(); it != plot->additionalParts.constEnd(); it++)
{
if (auto colorScale = qobject_cast<QCPColorScale*>(it.key()); colorScale)
{
if (auto err = readColorScale(varToJson(s.value(it.value())), colorScale); !err.ok() and report)
report->append(err);
continue;
}
qWarning() << "FormatStorageIni::load: Unknown how to read object from key" << it.value();
}
plot->updateTitleVisibility();
}
void FormatStorageIni::saveLegend(QCPLegend* legend)
{
savePlotFormatIni(KEY_LEGEND, writeLegend(legend));
}
void FormatStorageIni::saveTitle(QCPTextElement* title)
{
savePlotFormatIni(KEY_TITLE, writeTitle(title));
}
void FormatStorageIni::saveAxis(QCPAxis* axis)
{
auto plot = axis->parentPlot();
QString key = (axis == plot->xAxis) ? KEY_AXIS_X :
((axis == plot->yAxis) ? KEY_AXIS_Y : KEY_AXIS);
savePlotFormatIni(key, writeAxis(axis));
}
void FormatStorageIni::saveColorScale(QCPColorScale* scale)
{
if (auto key = findStorageKey("FormatStorageIni::saveColorScale", scale); !key.isEmpty())
savePlotFormatIni(key, writeColorScale(scale));
}
//------------------------------------------------------------------------------
// Load / Save
//------------------------------------------------------------------------------
QString loadFormatFromFile(const QString& fileName, Plot* plot, JsonReport *report, const ReadPlotOptions& opts)
{
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return "Unable to open file for reading: " + file.errorString();
QJsonParseError error;
QJsonDocument doc = QJsonDocument::fromJson(file.readAll(), &error);
if (doc.isNull())
return "Unable to parse json file: " + error.errorString();
readPlot(doc.object(), plot, report, opts);
return {};
}
QString saveFormatToFile(const QString& fileName, Plot* plot, const WritePlotOptions& opts)
{
QFile file(fileName);
if (!file.open(QFile::WriteOnly | QFile::Text))
return "Unable to open file for writing: " + file.errorString();
QTextStream(&file) << QJsonDocument(writePlot(plot, opts)).toJson();
return QString();
}
//------------------------------------------------------------------------------
// Copy / Paste
//------------------------------------------------------------------------------
static void setClipboardData(const QJsonObject& value, const QString& dataType)
{
QJsonObject root({{ dataType, value }});
auto mimeData = new QMimeData;
mimeData->setData(MIME_TYPE, QJsonDocument(root).toJson());
qApp->clipboard()->setMimeData(mimeData);
}
using JsonResult = Ori::Result<QJsonObject>;
static JsonResult getClipboradData(const QString& dataType)
{
auto mimeData = qApp->clipboard()->mimeData();
if (!mimeData)
return JsonResult::fail("Clipboard is empty");
auto data = mimeData->data(MIME_TYPE);
if (data.isNull())
return JsonResult::fail("Clipboard doesn't contain data in supported format");
QJsonParseError error;
QJsonDocument doc = QJsonDocument::fromJson(data, &error);
if (doc.isNull())
return JsonResult::fail("Clipboard text is not a valid JSON text: " + error.errorString());
QJsonObject root = doc.object();
if (!root.contains(dataType))
return JsonResult::fail("There is no data of appropriate type in Clipboard");
return JsonResult::ok(root[dataType].toObject());
}
void copyPlotFormat(Plot* plot)
{
setClipboardData(writePlot(plot), "plot");
}
void copyLegendFormat(QCPLegend* legend)
{
setClipboardData(writeLegend(legend), KEY_LEGEND);
}
void copyTitleFormat(QCPTextElement* title)
{
setClipboardData(writeTitle(title), KEY_TITLE);
}
void copyAxisFormat(QCPAxis* axis)
{
setClipboardData(writeAxis(axis), KEY_AXIS);
}
void copyColorScaleFormat(QCPColorScale* scale)
{
if (auto key = findStorageKey("copyColorScaleFormat", scale); !key.isEmpty())
setClipboardData(writeColorScale(scale), key);
}
void copyGraphFormat(QCPGraph* graph)
{
setClipboardData(writeGraph(graph), KEY_GRAPH);
}
QString pastePlotFormat(Plot* plot)
{
auto res = getClipboradData("plot");
if (!res.ok()) return res.error();
auto root = res.result();
// This is mostly for context menu commands and hence should be invoked on visible elements.
// It's not expected that element gets hidden when its format pasted, so the function doesn't
// change visibility
QHash<QCPLayerable*, bool> oldVisibility {
{ plot->title(), plot->title()->visible() },
{ plot->legend, plot->legend->visible() },
{ plot->xAxis, plot->xAxis->visible() },
{ plot->yAxis, plot->yAxis->visible() },
};
for (auto it = plot->additionalParts.constBegin(); it != plot->additionalParts.constEnd(); it++)
oldVisibility[it.key()] = it.key()->visible();
JsonReport report;
readPlot(root, plot, &report);
QStringList strReport;
for (auto& err : report)
if (!err.ok() && err.code != JsonError::NoData)
strReport << err.message;
for (auto it = oldVisibility.constBegin(); it != oldVisibility.constEnd(); it++)
it.key()->setVisible(it.value());
plot->updateTitleVisibility();
return strReport.join('\n');
}
QString pasteLegendFormat(QCPLegend* legend)
{
auto res = getClipboradData(KEY_LEGEND);
if (!res.ok()) return res.error();
bool oldVisible = legend->visible();
auto err = readLegend(res.result(), legend);
if (err.code == JsonError::BadVersion)
return err.message;
legend->setVisible(oldVisible);
return {};
}
QString pasteTitleFormat(QCPTextElement* title)
{
auto res = getClipboradData(KEY_TITLE);
if (!res.ok()) return res.error();
bool oldVisible = title->visible();
auto err = readTitle(res.result(), title);
if (err.code == JsonError::BadVersion)
return err.message;
title->setVisible(oldVisible);
return {};
}
QString pasteAxisFormat(QCPAxis* axis)
{
auto res = getClipboradData(KEY_AXIS);
if (!res.ok()) return res.error();
bool oldVisible = axis->visible();
auto err = readAxis(res.result(), axis);
if (err.code == JsonError::BadVersion)
return err.message;
axis->setVisible(oldVisible);
return {};
}
QString pasteColorScaleFormat(QCPColorScale* scale)
{
auto key = findStorageKey("copyColorScaleFormat", scale);
if (key.isEmpty())
return "Operation is not supported";
auto res = getClipboradData(key);
if (!res.ok()) return res.error();
bool oldVisible = scale->visible();
auto err = readColorScale(res.result(), scale);
if (err.code == JsonError::BadVersion)
return err.message;
scale->setVisible(oldVisible);
return {};
}
QString pasteGraphFormat(QCPGraph* graph)
{
auto res = getClipboradData(KEY_GRAPH);
if (!res.ok()) return res.error();
auto err = readGraph(res.result(), graph);
if (err.code == JsonError::BadVersion)
return err.message;
return {};
}
} // namespace QCPL