aboutsummaryrefslogtreecommitdiff
path: root/core/client.cpp
blob: a5cf6d6eb048fe31bbbd1bb8c1b3acaba1ea61e5 (plain)
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
#include <arpa/inet.h>
#include <GLFW/glfw3.h>
#include <imgui_impl_glfw.h>
#include <imgui_impl_opengl3.h>
#include <implot.h>
#include <implot_internal.h>
#include <json-c/json.h>
#include <signal.h>
#include <threads.h>

#include <algorithm>
#include <array>
#include <map>
#include <vector>

#include "logger.c"

// ----------------------------------------------------------------------------
// Defines
// ----------------------------------------------------------------------------
#define COLOR_BLACK ImVec4(0.f, 0.f, 0.f, 1.f)
#define FONT_SIZE 12.f
#define FONT_SOURCE "/usr/share/fonts/droid/DroidSansMono.ttf"
#define GLSL_VERSION "#version 130"
#define PLOT_MIN_COLS 1
#define PLOT_MAX_COLS 8
#define PLOT_MIN_HEIGHT 100.f
#define PLOT_MAX_HEIGHT 800.f
#define PLOT_HEIGHT_INTERVAL 50.f
#define PLOT_SCROLL_MARGIN 28.f
#define HM_SCALE_POW_MIN -1.f
#define HM_SCALE_POW_MAX 64.f
#define HM_SCALE_POW_INTERVAL 1.f
#define HM_COLORSCALE_WIDTH 80.f

#define IMGUI_WINDOW_FLAGS ( \
    ImGuiWindowFlags_NoBackground | \
    ImGuiWindowFlags_NoDecoration | \
    ImGuiWindowFlags_NoMove | \
    ImGuiWindowFlags_NoSavedSettings \
)

#define DATA_FETCH_INTERVAL 10
#define DATA_FETCH_INTERVAL_SUBDIV 1000

#define DEFVAL_ENTRIES 0x800l
#define DEFVAL_NTH 1l
#define DEFVAL_X_AXIS 0
#define DEFVAL_X_LOW 0l
#define DEFVAL_X_HIGH INT64_MAX
#define DEFVAL_HM_LEFT 0l
#define DEFVAL_HM_PIXEL_COUNT 0x400l // must equal HM_PIXEL_COUNT in server.c

// ----------------------------------------------------------------------------
// State declaration
// ----------------------------------------------------------------------------
enum Status {
    STATUS_STOPPED,
    STATUS_RUNNING,
    STATUS_STOPPING,
};

// ----------------------------------------------------------------------------
// Trace declarations
// ----------------------------------------------------------------------------
template <class T>
class Trace {
public:
    Trace();
    virtual ~Trace();
    virtual size_t start_offset() const;
    virtual void trim();
#if !defined(NDEBUG)
    virtual void validate() const;
#endif

    size_t size() const;
    T &back();
    T &operator[](size_t n);
    T *start();
    T max() const;
    T operator[](size_t n) const;
    void clear();
    void push_back(T);

protected:
    void trim_spec(int mult = 1);

    std::vector<T> m_data;
    size_t m_max_index;
};

template <class T>
class TraceNamed : public Trace<T> {
public:
    TraceNamed(const char *name, const char *name_fmt);

    const char *m_name;
    const char *m_name_fmt;
};

template <class T>
class TraceHeatmap : public TraceNamed<T> {
public:
    TraceHeatmap(const char *name, const char *name_fmt);

    size_t start_offset() const;
    void trim();
#if !defined(NDEBUG)
    void validate() const;
#endif
};

// ----------------------------------------------------------------------------
// Plot declarations
// ----------------------------------------------------------------------------
typedef int (*AxisFormatter)(double value, char *buff, int size, void *data);

class Plot {
public:
    Plot(const char *name, const char *section);
    virtual ~Plot();
    void render(ImVec2 frame_size);

    const char *m_name;
    const char *m_section;

private:
    static int hex_axis_formatter(double value, char *buff, int size, void *data);
    virtual AxisFormatter x_axis_formatter();
    virtual AxisFormatter y_axis_formatter();
    virtual float frame_right_margin();
    virtual int plot_flags();
    virtual void render_internal() = 0;
    virtual void render_post(ImVec2 frame_size);
};

class PlotLines : public Plot {
public:
    PlotLines(const char *name, const char *section, std::vector<const char *> trace_keys);
    std::vector<const char *> m_trace_keys;

private:
    void render_internal();
};

class PlotStacked : public Plot {
public:
    PlotStacked(const char *name, const char *section, std::vector<const char *> trace_keys);

    std::vector<ImS64> m_totals;
    std::vector<double> m_old_trace;
    std::vector<double> m_new_trace;
    std::vector<const char *> m_trace_keys;

private:
    AxisFormatter y_axis_formatter();
    static int percent_axis_formatter(double value, char *buff, int size, void *data);
    void render_internal();
};

class PlotHeatmap : public Plot  {
public:
    PlotHeatmap(const char *name, const char *section, const char *trace_key);
    const char *m_trace_key;

private:
    float frame_right_margin();
    int plot_flags();
    void render_internal();
    void render_post(ImVec2 frame_size);
};

// ----------------------------------------------------------------------------
// Plots
// ----------------------------------------------------------------------------
#include "arch_plots.cpp"

std::array g_core_traces = std::to_array<TraceNamed<ImS64>>({
    {"rowid", "rowid"},
    {"step", "step"},
#define FOR_CORE(i) \
    {"cycl_" #i, "cycl_" #i}, \
    {"mall_" #i, "mall_" #i}, \
    {"pnum_" #i, "pnum_" #i}, \
    {"pfst_" #i, "pfst_" #i}, \
    {"plst_" #i, "plst_" #i}, \
    {"amb0_" #i, "amb0_" #i}, \
    {"amb1_" #i, "amb1_" #i}, \
    {"emb0_" #i, "emb0_" #i}, \
    {"emb1_" #i, "emb1_" #i}, \
    {"eliv_" #i, "eliv_" #i}, \
    {"edea_" #i, "edea_" #i},
    FOR_CORES
#undef FOR_CORE
});

std::array g_core_traces_heatmaps = std::to_array<TraceHeatmap<ImS64>>({
#define FOR_CORE(i) \
    {"aev_" #i, "aev_" #i}, \
    {"eev_" #i, "eev_" #i}, \
    {"bev_" #i, "bev_" #i},
    FOR_CORES
#undef FOR_CORE
});

std::array g_core_plots = std::to_array<PlotLines>({
    {"cycl", "general", {
#define FOR_CORE(i) "cycl_" #i,
        FOR_CORES
#undef FOR_CORE
    }},
    {"mall", "general", {
#define FOR_CORE(i) "mall_" #i,
        FOR_CORES
#undef FOR_CORE
    }},
    {"pnum", "general", {
#define FOR_CORE(i) "pnum_" #i,
        FOR_CORES
#undef FOR_CORE
    }},
    {"ppop", "general", {
#define FOR_CORE(i) "pfst_" #i, "plst_" #i,
        FOR_CORES
#undef FOR_CORE
    }},
    {"ambs", "general", {
#define FOR_CORE(i) "amb0_" #i, "amb1_" #i,
        FOR_CORES
#undef FOR_CORE
    }},
    {"eevs", "general", {
#define FOR_CORE(i) "emb0_" #i, "emb1_" #i, "eliv_" #i, "edea_" #i,
        FOR_CORES
#undef FOR_CORE
    }},
});

std::array g_core_plots_heatmaps = std::to_array<PlotHeatmap>({
#define FOR_CORE(i) \
    {"aev_" #i, "heatmaps", "aev_" #i},
    FOR_CORES
#undef FOR_CORE
#define FOR_CORE(i) \
    {"eev_" #i, "heatmaps", "eev_" #i},
    FOR_CORES
#undef FOR_CORE
#define FOR_CORE(i) \
    {"bev_" #i, "heatmaps", "bev_" #i},
    FOR_CORES
#undef FOR_CORE
});

// ----------------------------------------------------------------------------
// Heatmap colormap
// ----------------------------------------------------------------------------
std::array g_hm_colormap_cols = std::to_array<ImVec4>({
    {0.000f, 0.000f, 0.016f, 1.f},
    {0.106f, 0.047f, 0.255f, 1.f},
    {0.290f, 0.047f, 0.420f, 1.f},
    {0.471f, 0.110f, 0.427f, 1.f},
    {0.647f, 0.173f, 0.376f, 1.f},
    {0.812f, 0.267f, 0.275f, 1.f},
    {0.929f, 0.412f, 0.145f, 1.f},
    {0.984f, 0.608f, 0.024f, 1.f},
    {0.969f, 0.820f, 0.239f, 1.f},
    {0.988f, 1.000f, 0.643f, 1.f},
});

// ----------------------------------------------------------------------------
// Globals
// ----------------------------------------------------------------------------
GLFWwindow *g_window;
ImGuiIO *g_imgui_io;
ImGuiStyle *g_imgui_style;
ImPlotStyle *g_implot_style;

// Data
std::array g_x_axes = std::to_array<const char *>({
    "rowid",
    "step",
#define FOR_CORE(i) "cycl_" #i,
    FOR_CORES
#undef FOR_CORE
});

int g_status;
int g_x_axis = DEFVAL_X_AXIS;
int64_t g_entries = DEFVAL_ENTRIES;
int64_t g_nth = DEFVAL_NTH;
int64_t g_x_low = DEFVAL_X_LOW;
int64_t g_x_high = DEFVAL_X_HIGH;
int64_t g_hm_left = DEFVAL_HM_LEFT;
int64_t g_hm_pixel_count = DEFVAL_HM_PIXEL_COUNT;
int64_t g_hm_pixel_pow; // calculate on init
int64_t g_x_current = -1l;

int g_trace_len;
int g_trace_offset;

thrd_t g_fetching_thread;
mtx_t g_fetching_mutex;

// Layout
bool g_data_col_visible = true;
bool g_plot_maximized;
bool g_plot_scroll;
float g_plot_scroll_current;
float g_plot_scroll_to;
float g_data_col_width;
std::vector<Plot *> g_plot_cells;
std::vector<float> g_plot_cells_top;
std::vector<float> g_plot_cells_bottom;
std::vector<bool> g_plots_covered;
Plot *g_plot_selected;
Plot *g_plot_hovered;
int g_plot_cols = 2;
int g_plot_col_selected;
int g_plot_row_selected;
float g_plot_height = 300.f;
float g_hm_scale_pow = HM_SCALE_POW_MIN;
ImPlotColormap g_hm_colormap;

// Plots
struct CompStr {
   bool operator()(const char *a, const char *b) const {
      return strcmp(a, b) < 0;
   }
};

std::map<const char *, TraceNamed<ImS64> *, CompStr> g_trace_map;
std::vector<TraceNamed<ImS64> *> g_traces;
std::vector<Plot *> g_plots;
Trace<double> g_x_axis_normal;

// ----------------------------------------------------------------------------
// Trace definitions
// ----------------------------------------------------------------------------
template <class T>
Trace<T>::Trace() : m_data({}), m_max_index(0) {}

template <class T>
Trace<T>::~Trace() {}

template <class T>
size_t Trace<T>::start_offset() const {
    return g_trace_offset;
}

template <class T>
void Trace<T>::trim() {
    trim_spec(1);
}

#if !defined(NDEBUG)
template <class T>
void Trace<T>::validate() const {
    assert(size() == g_traces[0]->size());
}
#endif

template <class T>
size_t Trace<T>::size() const {
    return m_data.size();
}

template <class T>
T &Trace<T>::back() {
    return m_data.back();
}

template <class T>
T &Trace<T>::operator[](size_t n) {
#if !defined(NDEBUG)
    return m_data.at(n);
#else
    return m_data[n];
#endif
}

template <class T>
T *Trace<T>::start() {
    return size() ? &operator[](start_offset()) : nullptr;
}

template <class T>
T Trace<T>::max() const {
    return size() ? operator[](m_max_index) : 0;
}

template <class T>
T Trace<T>::operator[](size_t n) const {
#if !defined(NDEBUG)
    return m_data.at(n);
#else
    return m_data[n];
#endif
}

template <class T>
void Trace<T>::clear() {
    m_data.clear();
    m_max_index = 0;
}

template <class T>
void Trace<T>::push_back(T value) {
    m_data.push_back(value);

    if (value > operator[](m_max_index)) {
        m_max_index = size() - 1;
    }
}

template <class T>
void Trace<T>::trim_spec(int mult) {
    assert((int64_t)size() >= g_entries * mult * 2);
    m_data.erase(m_data.begin(), m_data.end() - (g_entries * mult));

    for (size_t i = 0; i < size(); i++) {
        m_max_index = std::max(operator[](m_max_index), operator[](i));
    }
}

// ----------------------------------------------------------------------------
// TraceNamed definitions
// ----------------------------------------------------------------------------
template <class T>
TraceNamed<T>::TraceNamed(const char *name, const char *name_fmt) : m_name(name), m_name_fmt(name_fmt) {}

// ----------------------------------------------------------------------------
// TraceHeatmap definitions
// ----------------------------------------------------------------------------
template <class T>
TraceHeatmap<T>::TraceHeatmap(const char *name, const char *name_fmt) : TraceNamed<T>(name, name_fmt) {}

template <class T>
size_t TraceHeatmap<T>::start_offset() const {
    return g_trace_offset * g_hm_pixel_count;
}

template <class T>
void TraceHeatmap<T>::trim() {
    this->trim_spec(g_hm_pixel_count);
}

#if !defined(NDEBUG)
template <class T>
void TraceHeatmap<T>::validate() const {
    assert(this->size() == g_traces[0]->size() * g_hm_pixel_count);
}
#endif

// ----------------------------------------------------------------------------
// Plot definitions
// ----------------------------------------------------------------------------
Plot::Plot(const char *name, const char *section) : m_name(name), m_section(section) {}

Plot::~Plot() {}

void Plot::render(ImVec2 frame_size) {
    if (ImPlot::BeginPlot(m_name, ImVec2(frame_size.x - frame_right_margin(), frame_size.y), plot_flags())) {
        int axis_flags = ImPlotAxisFlags_Foreground | (g_status != STATUS_STOPPED ? ImPlotAxisFlags_AutoFit : 0);
        ImPlot::SetupAxes(nullptr, nullptr, axis_flags, axis_flags);
        ImPlot::SetupAxisFormat(ImAxis_X1, x_axis_formatter());
        ImPlot::SetupAxisFormat(ImAxis_Y1, y_axis_formatter());
        if (ImPlot::IsPlotHovered()) g_plot_hovered = this;
        render_internal();
        ImPlot::EndPlot();
    }

    render_post(frame_size);
}

int Plot::hex_axis_formatter(double value, char *buff, int size, void *data) {
    (void)data;
    snprintf(buff, size, "%s%#lx", value < 0. ? "-" : "", abs((int64_t)value));
    return 0;
}

AxisFormatter Plot::x_axis_formatter() {
    return Plot::hex_axis_formatter;
}

AxisFormatter Plot::y_axis_formatter() {
    return Plot::hex_axis_formatter;
}

float Plot::frame_right_margin() {
    return 0.f;
}

int Plot::plot_flags() {
    return 0;
}

void Plot::render_post(ImVec2 frame_size) {
    (void)frame_size;
}

// ----------------------------------------------------------------------------
// PlotLines definitions
// ----------------------------------------------------------------------------
PlotLines::PlotLines(const char *name, const char *section, std::vector<const char *> trace_keys) : Plot(name, section), m_trace_keys(trace_keys) {}

void PlotLines::render_internal() {
    ImS64 *x = g_trace_map[g_x_axes[g_x_axis]]->start();

    for (auto &trace : m_trace_keys) {
        TraceNamed<ImS64> *trace_obj = g_trace_map[trace];
        ImS64 *y = trace_obj->start();
        ImPlot::PlotLine(trace_obj->m_name_fmt, x, y, g_trace_len);
    }
}

// ----------------------------------------------------------------------------
// PlotStacked definitions
// ----------------------------------------------------------------------------
PlotStacked::PlotStacked(const char *name, const char *section, std::vector<const char *> trace_keys) : Plot(name, section), m_trace_keys(trace_keys) {}

AxisFormatter PlotStacked::y_axis_formatter() {
    return PlotStacked::percent_axis_formatter;
}

int PlotStacked::percent_axis_formatter(double value, char *buff, int size, void *data) {
    (void)data;
    snprintf(buff, size, "%3.0f%%", value * 100.);
    return 0;
}

void PlotStacked::render_internal() {
    m_totals.resize(g_trace_len);
    m_old_trace.resize(g_trace_len);
    m_new_trace.resize(g_trace_len);

    for (size_t i = 0; i < m_trace_keys.size(); i++) {
        ImPlot::PlotDummy(g_trace_map[m_trace_keys[i]]->m_name_fmt);
    }

    for (int i = 0; i < (int)m_trace_keys.size(); i++) {
        if (GImPlot->CurrentPlot->Items.GetLegendItem(i)->Show) {
            for (int j = 0; j < g_trace_len; j++) {
                m_totals[j] += g_trace_map[m_trace_keys[i]]->start()[j];
            }
        }
    }

    for (int i = 0; i < (int)m_trace_keys.size(); i++) {
        if (GImPlot->CurrentPlot->Items.GetLegendItem(i)->Show) {
            ImPlotSpec spec = ImPlotSpec(ImPlotProp_FillAlpha, GImPlot->CurrentPlot->Items.GetLegendItem(i)->LegendHovered ? 1.f : 0.9f);
            TraceNamed<ImS64> *trace = g_trace_map[m_trace_keys[i]];
            const char *trace_name = trace->m_name_fmt;

            for (int j = 0; j < g_trace_len; j++) {
                m_new_trace[j] = m_totals[j] ? (m_old_trace[j] + (double)trace->start()[j] / (double)m_totals[j]) : 0.;
            }

            ImPlot::PlotShaded(trace_name, g_x_axis_normal.start(), m_old_trace.data(), m_new_trace.data(), g_trace_len, spec);
            ImPlot::PlotLine(trace_name, g_x_axis_normal.start(), m_old_trace.data(), g_trace_len);
            ImPlot::PlotLine(trace_name, g_x_axis_normal.start(), m_new_trace.data(), g_trace_len);
            std::swap(m_old_trace, m_new_trace);
        }
    }

    m_totals.clear();
    m_old_trace.clear();
    m_new_trace.clear();
}

// ----------------------------------------------------------------------------
// PlotHeatmap definitions
// ----------------------------------------------------------------------------
PlotHeatmap::PlotHeatmap(const char *name, const char *section, const char *trace_key) : Plot(name, section), m_trace_key(trace_key) {}

float PlotHeatmap::frame_right_margin() {
    return HM_COLORSCALE_WIDTH;
}

int PlotHeatmap::plot_flags() {
    return ImPlotFlags_NoLegend;
}

void PlotHeatmap::render_internal() {
    TraceNamed<ImS64> *trace = g_trace_map[m_trace_key];
    ImPlot::PushColormap(g_hm_colormap);
    double scale_max = g_hm_scale_pow == HM_SCALE_POW_MIN ? 0. : pow(2., (double)g_hm_scale_pow);
    ImPlot::PlotHeatmap(trace->m_name_fmt, trace->start(), g_trace_len, g_hm_pixel_count, 0., scale_max, nullptr, ImPlotPoint(0, g_x_current), ImPlotPoint(MVEC_SIZE, 0));
    ImPlot::PopColormap();
}

void PlotHeatmap::render_post(ImVec2 frame_size) {
    ImGui::SameLine();
    ImPlot::PushColormap(g_hm_colormap);
    double scale_max = g_hm_scale_pow == HM_SCALE_POW_MIN ? (double)g_trace_map[m_trace_key]->max() : pow(2., (double)g_hm_scale_pow);
    ImPlot::ColormapScale("##hm-scale", 0., scale_max, ImVec2(HM_COLORSCALE_WIDTH, frame_size.y), "%.1e");
    ImPlot::PopColormap();
}

// ----------------------------------------------------------------------------
// Data functions
// ----------------------------------------------------------------------------
int64_t data_max_hm_pixel_pow(void) {
    return (int64_t)floor(log2((double)(MVEC_SIZE - g_hm_left) / (double)g_hm_pixel_count));
}

void data_on_field_change(void) {
    g_entries = std::clamp(g_entries, 1l, DEFVAL_ENTRIES);
    g_nth = std::clamp(g_nth, DEFVAL_NTH, INT64_MAX);
    g_x_low = std::clamp(g_x_low, DEFVAL_X_LOW, INT64_MAX);
    g_x_high = std::clamp(g_x_high, g_x_low + 1l, DEFVAL_X_HIGH);
#if !defined(MVEC_LOOP)
    g_hm_left = std::clamp(g_hm_left, DEFVAL_HM_LEFT, (int64_t)MVEC_SIZE);
#endif
    g_hm_pixel_count = std::clamp(g_hm_pixel_count, 1l, DEFVAL_HM_PIXEL_COUNT);
    g_hm_pixel_pow = std::clamp(g_hm_pixel_pow, 0l, data_max_hm_pixel_pow());
    g_x_current = -1l;

    g_trace_len = 0;
    g_trace_offset = 0;

    for (auto &trace : g_traces) trace->clear();
    g_x_axis_normal.clear();
}

void data_reset_fields(void) {
    g_entries = DEFVAL_ENTRIES;
    g_nth = DEFVAL_NTH;
    g_x_axis = DEFVAL_X_AXIS;
    g_x_low = DEFVAL_X_LOW;
    g_x_high = DEFVAL_X_HIGH;
    g_hm_left = DEFVAL_HM_LEFT;
    g_hm_pixel_count = DEFVAL_HM_PIXEL_COUNT;
    g_hm_pixel_pow = data_max_hm_pixel_pow();

    data_on_field_change();
}

void data_reset_plot_cells(void) {
    std::fill(g_plot_cells.begin(), g_plot_cells.end(), nullptr);
    std::fill(g_plot_cells_top.begin(), g_plot_cells_top.end(), 0.f);
    std::fill(g_plot_cells_bottom.begin(), g_plot_cells_bottom.end(), 0.f);
}

void data_fetch(void) {
    json_object *request = json_object_new_object();
    json_object_object_add(request, "request", json_object_new_string("data"));
    json_object_object_add(request, "entries", json_object_new_int64(g_entries));
    json_object_object_add(request, "nth", json_object_new_int64(g_nth));
    json_object_object_add(request, "x-axis", json_object_new_string(g_x_axes[g_x_axis]));
    json_object_object_add(request, "x-low", json_object_new_int64(g_x_low));
    json_object_object_add(request, "x-high", json_object_new_int64(g_x_high));
    json_object_object_add(request, "hm-left", json_object_new_int64(g_hm_left));
    json_object_object_add(request, "hm-pixel-count", json_object_new_int64(g_hm_pixel_count));
    json_object_object_add(request, "hm-pixel-pow", json_object_new_int64(g_hm_pixel_pow));
    json_object_object_add(request, "x-current", json_object_new_int64(g_x_current));
    const char *request_str = json_object_to_json_string(request);

    log_info("Sending request to server: %s", request_str);
    int socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    sockaddr_in socket_addr;
    memset(&socket_addr, 0, sizeof(sockaddr_in));
    socket_addr.sin_family = AF_INET;
    socket_addr.sin_port = htons(PORT);
    inet_pton(AF_INET, IP, &socket_addr.sin_addr);
    if (connect(socket_fd, (sockaddr *)&socket_addr, sizeof(sockaddr_in))) assert(false);
    json_object_to_fd(socket_fd, request, 0);
    shutdown(socket_fd, SHUT_WR);

    json_object *response = json_object_from_fd(socket_fd);

    mtx_lock(&g_fetching_mutex);

    json_object_object_foreach(response, key, value) {
        size_t new_rows = json_object_array_length(value);

        if (!strcmp(key, g_x_axes[g_x_axis])) {
            log_info("Received %lu rows of data from server", new_rows);

            for (size_t i = 0; i < new_rows; i++) {
                ImS64 point = json_object_get_int64(json_object_array_get_idx(value, i));
                g_x_axis_normal.push_back((double)point);
            }
        }

        if (g_trace_map.contains(key)) {
            for (size_t i = 0; i < new_rows; i++) {
                ImS64 point = json_object_get_int64(json_object_array_get_idx(value, i));
                g_trace_map[key]->push_back(point);
            }
        }
    }

    g_x_current = g_trace_map[g_x_axes[g_x_axis]]->back();
    json_object_put(request);
    json_object_put(response);

#if !defined(NDEBUG)
    for (auto &trace : g_traces) trace->validate();
#endif

    if ((int64_t)g_traces[0]->size() >= g_entries * 2) {
        for (auto &trace : g_traces) trace->trim();
        g_x_axis_normal.trim();
    }

#if !defined(NDEBUG)
    for (auto &trace : g_traces) trace->validate();
#endif

    int64_t current_size = g_traces[0]->size();
    g_trace_len = std::min(current_size, g_entries);
    g_trace_offset = current_size > g_entries ? current_size - g_entries : 0l;

    mtx_unlock(&g_fetching_mutex);
}

int data_fetching_thread(void *data) {
    (void)data;

    assert(!data);
    assert(g_status == STATUS_RUNNING || g_status == STATUS_STOPPING);

    while (g_status == STATUS_RUNNING) {
        data_fetch();

        for (int i = 0; i < DATA_FETCH_INTERVAL_SUBDIV && g_status == STATUS_RUNNING; i++) {
            usleep((DATA_FETCH_INTERVAL * 1000000) / DATA_FETCH_INTERVAL_SUBDIV);
        }
    }

    assert(g_status == STATUS_STOPPING);
    g_status = STATUS_STOPPED;
    return 0;
}

void data_start_fetching(void) {
    log_info("Starting data fetching thread");
    g_status = STATUS_RUNNING;
    thrd_create(&g_fetching_thread, (thrd_start_t)data_fetching_thread, nullptr);
}

void data_stop_fetching(void) {
    assert(g_status == STATUS_RUNNING);
    log_info("Stopping data fetching thread");
    g_status = STATUS_STOPPING;
    thrd_join(g_fetching_thread, nullptr);
}

// ----------------------------------------------------------------------------
// GUI functions
// ----------------------------------------------------------------------------
void gui_render_data_input(const char *label, int64_t *target) {
    assert(target);

    if (ImGui::InputScalar(label, ImGuiDataType_U64, target, nullptr, nullptr, "%#lx")) {
        data_on_field_change();
    }
}

void gui_render_data_col(void) {
    const ImGuiViewport *viewport = ImGui::GetMainViewport();
    const ImVec2 win_pos = viewport->Pos;
    const ImVec2 win_size = ImVec2(-1.f, viewport->Size.y);

    ImGui::SetNextWindowPos(win_pos);
    ImGui::SetNextWindowSize(win_size);
    ImGui::Begin("data-col", nullptr, IMGUI_WINDOW_FLAGS);
    g_data_col_width = ImGui::GetWindowWidth();

    ImGui::SeparatorText("SALIS data client");
    ImGui::LabelText("name", NAME);
    ImGui::LabelText("seed", "%#lx", SEED);
    ImGui::LabelText("server", IP ":" PORT_STR);
    ImGui::LabelText("arch", ARCH);
    ImGui::LabelText("cores", "%d", CORES);
    ImGui::LabelText("mvec-size", "%#lx", MVEC_SIZE);
 #if defined(MVEC_LOOP)
    ImGui::LabelText("mvec-loop", "true");
 #else
    ImGui::LabelText("mvec-loop", "false");
 #endif
    ImGui::LabelText("data-push", "%#lx", DATA_PUSH_INTERVAL);

    ImGui::SeparatorText("Data fields");

    switch (g_status) {
    case STATUS_STOPPED:
        gui_render_data_input("entries", &g_entries);
        gui_render_data_input("nth", &g_nth);

        if (ImGui::BeginCombo("x-axis", g_x_axes[g_x_axis])) {
            for (int i = 0; i < CORES + 2; i++) {
                if (ImGui::Selectable(g_x_axes[i], g_x_axis == i)) {
                    data_reset_fields();
                    g_x_axis = i;
                }
            }

            ImGui::EndCombo();
        }

        gui_render_data_input("x-low", &g_x_low);
        gui_render_data_input("x-high", &g_x_high);
        gui_render_data_input("hm-left", &g_hm_left);
        gui_render_data_input("hm-pxl-count", &g_hm_pixel_count);
        gui_render_data_input("hm-pxl-pow", &g_hm_pixel_pow);
        break;
    case STATUS_RUNNING:
    case STATUS_STOPPING:
        ImGui::LabelText("entries", "%#lx", g_entries);
        ImGui::LabelText("nth", "%#lx", g_nth);
        ImGui::LabelText("x-axis", "%s", g_x_axes[g_x_axis]);
        ImGui::LabelText("x-low", "%#lx", g_x_low);
        ImGui::LabelText("x-high", "%#lx", g_x_high);
        ImGui::LabelText("hm-left", "%#lx", g_hm_left);
        ImGui::LabelText("hm-pxl-count", "%#lx", g_hm_pixel_count);
        ImGui::LabelText("hm-pxl-pow", "%#lx", g_hm_pixel_pow);
    }

    switch (g_status) {
    case STATUS_STOPPED:
        if (ImGui::Button("Run", ImVec2(-1.f, 0.f))) {
            data_start_fetching();
        }

        if (ImGui::Button("Reset", ImVec2(-1.f, 0.f))) {
            data_reset_fields();
        }

        break;
    case STATUS_RUNNING:
        if (ImGui::Button("Stop", ImVec2(-1.f, 0.f))) {
            data_stop_fetching();
        }

        ImGui::LabelText("##", "Running");
        break;
    case STATUS_STOPPING:
        ImGui::LabelText("##", "Stopping");
        break;
    }

    ImGui::SeparatorText("Layout");
    ImGui::DragInt("cols", &g_plot_cols, 1, PLOT_MIN_COLS, PLOT_MAX_COLS);
    ImGui::DragFloat("plot-height", &g_plot_height, PLOT_HEIGHT_INTERVAL, PLOT_MIN_HEIGHT, PLOT_MAX_HEIGHT, "%.0f");
    ImGui::DragFloat("hm-pow", &g_hm_scale_pow, HM_SCALE_POW_INTERVAL, HM_SCALE_POW_MIN, HM_SCALE_POW_MAX, "%.0f");

    ImGui::End();
}

int gui_plot_cell_index(int row, int col) {
    int index = row * PLOT_MAX_COLS + col;
    assert(index < (int)g_plot_cells.size());
    assert(index < (int)g_plot_cells_top.size());
    assert(index < (int)g_plot_cells_bottom.size());
    return index;
}

int gui_plot_cell_row_up() {
    for (int row = g_plot_row_selected - 1; row >= 0; row--) {
        if (g_plot_cells[gui_plot_cell_index(row, g_plot_col_selected)]) {
            return row;
        }
    }

    return g_plot_row_selected;
}

int gui_plot_cell_row_down() {
    for (int row = g_plot_row_selected + 1; row < (int)g_plots.size(); row++) {
        if (g_plot_cells[gui_plot_cell_index(row, g_plot_col_selected)]) {
            return row;
        }
    }

    return g_plot_row_selected;
}

void gui_render_plots(void) {
    const char *section_current = g_plots[0]->m_section;
    const char *section_next = nullptr;

    g_plots_covered.clear();
    g_plots_covered.resize(g_plots.size(), false);

    const ImGuiViewport *viewport = ImGui::GetMainViewport();
    const ImVec2 win_pos = g_data_col_visible ? ImVec2(g_data_col_width, viewport->Pos.y) : viewport->Pos;
    const ImVec2 win_size = g_data_col_visible ? ImVec2(viewport->Size.x - g_data_col_width, -1.f) : ImVec2(viewport->Size.x, -1.f);

    if (g_plot_scroll) {
        ImGui::SetNextWindowScroll(ImVec2(-1.f, g_plot_scroll_to));
        g_plot_scroll = false;
        g_plot_scroll_to = 0.f;
    }

    ImGui::SetNextWindowPos(win_pos);
    ImGui::SetNextWindowSize(win_size);
    ImGui::Begin("plots", nullptr, IMGUI_WINDOW_FLAGS);
    g_plot_scroll_current = ImGui::GetScrollY();
    g_plot_hovered = nullptr;

    int row = 0;
    int col = 0;

    mtx_lock(&g_fetching_mutex);

    while (section_current) {
        ImGui::SeparatorText(section_current);
        ImGui::BeginTable("plots-table", g_plot_cols);

        for (size_t i = 0; i < g_plots.size(); i++) {
            if (strcmp(g_plots[i]->m_section, section_current)) {
                section_next = (!section_next && !g_plots_covered[i]) ? g_plots[i]->m_section : section_next;
                continue;
            }

            ImGui::TableNextColumn();
            ImVec2 frame_size = ImVec2(ImGui::GetContentRegionAvail().x, g_plot_height);
            g_plot_cells[gui_plot_cell_index(row, col)] = g_plots[i];
            g_plot_cells_top[gui_plot_cell_index(row, col)] = ImGui::GetCursorPosY();

            if (g_plots[i] == g_plot_selected) {
                g_plot_col_selected = col;
                g_plot_row_selected = row;
                g_implot_style->Colors[ImPlotCol_FrameBg] = g_imgui_style->Colors[ImGuiCol_FrameBg];
            }

            g_plots[i]->render(frame_size);

            if (g_plots[i] == g_plot_selected) {
                g_implot_style->Colors[ImPlotCol_FrameBg] = COLOR_BLACK;
            }

            g_plot_cells_bottom[gui_plot_cell_index(row, col)] = ImGui::GetCursorPosY();
            col = (col + 1) % g_plot_cols;
            row += col ? 0 : 1;

            g_plots_covered[i] = true;
        }

        section_current = section_next;
        section_next = nullptr;
        ImGui::EndTable();
        row += col ? 1 : 0;
        col = 0;
    }

    mtx_unlock(&g_fetching_mutex);

    ImGui::End();
}

void gui_render_plot_maximized(void) {
    const ImGuiViewport *viewport = ImGui::GetMainViewport();
    ImGui::SetNextWindowPos(viewport->Pos);
    ImGui::SetNextWindowSize(viewport->Size);
    ImGui::Begin("plot-fullscreen", nullptr, IMGUI_WINDOW_FLAGS);

    ImVec2 frame_size = {
        viewport->Size.x - g_imgui_style->WindowPadding.x * 2,
        viewport->Size.y - g_imgui_style->WindowPadding.y * 2,
    };

    g_plot_selected->render(frame_size);

    ImGui::End();
}

void gui_plot_queue_scroll_to_position(bool increased_plot_height) {
    int row = 0;
    float selected_plot_top = 0.f;

    for (row = 0; row < (int)g_plots.size(); row++) {
        for (int col = 0; col < PLOT_MAX_COLS; col++) {
            if (g_plot_selected == g_plot_cells[gui_plot_cell_index(row, col)]) {
                selected_plot_top = g_plot_cells_top[gui_plot_cell_index(row, col)];
                goto loop_exit;
            }
        }
    }

    loop_exit:
    g_plot_scroll_to = selected_plot_top + (PLOT_HEIGHT_INTERVAL * (float)row * (increased_plot_height ? 1.f : -1.f)) - PLOT_SCROLL_MARGIN;
    g_plot_scroll = true;
}

void gui_plot_queue_scroll_to_selected() {
    const ImGuiViewport *viewport = ImGui::GetMainViewport();
    float plot_top = g_plot_cells_top[gui_plot_cell_index(g_plot_row_selected, g_plot_col_selected)];
    float plot_bottom = g_plot_cells_bottom[gui_plot_cell_index(g_plot_row_selected, g_plot_col_selected)];
    float win_bottom = g_plot_scroll_current + viewport->Size.y;

    if (plot_bottom > win_bottom) {
        g_plot_scroll_to = g_plot_scroll_current + (plot_bottom - win_bottom);
        g_plot_scroll = true;
    }

    if (plot_top < g_plot_scroll_current) {
        g_plot_scroll_to = plot_top - PLOT_SCROLL_MARGIN;
        g_plot_scroll = true;
    }
}

void gui_render(void) {
    if (g_plot_maximized) {
        gui_render_plot_maximized();
        return;
    }

    if (g_data_col_visible) gui_render_data_col();
    gui_render_plots();
}

// ----------------------------------------------------------------------------
// Main functions
// ----------------------------------------------------------------------------
void app_sig_handler(int signo) {
    (void)signo;

    log_warn("Signal received, will stop SALIS data client...");

    if (g_status == STATUS_RUNNING) {
        data_stop_fetching();
    }

    glfwSetWindowShouldClose(g_window, GLFW_TRUE);
}

void app_error_callback(int error, const char* description) {
    log_warn("GLFW error %d: %s", error, description);
}

void app_toggle_state() {
    switch (g_status) {
    case STATUS_STOPPED:
        data_start_fetching();
        break;
    case STATUS_RUNNING:
        data_stop_fetching();
        break;
    }
}

void app_key_callback_plot_maximized(int key, int mods) {
    switch (mods) {
    case GLFW_MOD_CONTROL:
        switch (key) {
        case GLFW_KEY_C:
            glfwSetWindowShouldClose(g_window, GLFW_TRUE);
            break;
        case GLFW_KEY_COMMA:
            g_hm_scale_pow = std::max(g_hm_scale_pow - HM_SCALE_POW_INTERVAL, HM_SCALE_POW_MIN);
            break;
        case GLFW_KEY_PERIOD:
            g_hm_scale_pow = std::min(g_hm_scale_pow + HM_SCALE_POW_INTERVAL, HM_SCALE_POW_MAX);
            break;
        }

        break;

    case 0:
        switch (key) {
        case GLFW_KEY_F:
            g_plot_maximized = false;
            break;
        case GLFW_KEY_SPACE:
            app_toggle_state();
            break;
        }

        break;
    }
}

void app_key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) {
    (void)window;
    (void)scancode;

    if (ImGui::IsAnyItemActive()) {
        return;
    }

    if (action != GLFW_PRESS && action != GLFW_REPEAT) {
        return;
    }

    if (g_plot_maximized) {
        app_key_callback_plot_maximized(key, mods);
        return;
    }

    switch (mods) {
    case GLFW_MOD_CONTROL:
        switch (key) {
        case GLFW_KEY_C:
            glfwSetWindowShouldClose(g_window, GLFW_TRUE);
            break;
        case GLFW_KEY_N:
            g_data_col_visible = !g_data_col_visible;
            break;
        case GLFW_KEY_LEFT:
            g_plot_cols = std::max(g_plot_cols - 1, PLOT_MIN_COLS);
            data_reset_plot_cells();
            break;
        case GLFW_KEY_RIGHT:
            g_plot_cols = std::min(g_plot_cols + 1, PLOT_MAX_COLS);
            data_reset_plot_cells();
            break;
        case GLFW_KEY_UP:
            g_plot_height = std::min(g_plot_height + PLOT_HEIGHT_INTERVAL, PLOT_MAX_HEIGHT);
            gui_plot_queue_scroll_to_position(true);
            break;
        case GLFW_KEY_DOWN:
            g_plot_height = std::max(g_plot_height - PLOT_HEIGHT_INTERVAL, PLOT_MIN_HEIGHT);
            gui_plot_queue_scroll_to_position(false);
            break;
        case GLFW_KEY_COMMA:
            g_hm_scale_pow = std::max(g_hm_scale_pow - HM_SCALE_POW_INTERVAL, HM_SCALE_POW_MIN);
            break;
        case GLFW_KEY_PERIOD:
            g_hm_scale_pow = std::min(g_hm_scale_pow + HM_SCALE_POW_INTERVAL, HM_SCALE_POW_MAX);
            break;
        }

        break;

    case 0:
        switch (key) {
        case GLFW_KEY_LEFT:
            g_plot_col_selected = std::max(g_plot_col_selected - 1, 0);
            g_plot_selected = g_plot_cells[gui_plot_cell_index(g_plot_row_selected, g_plot_col_selected)];
            break;
        case GLFW_KEY_RIGHT:
            g_plot_col_selected += (g_plot_col_selected < PLOT_MAX_COLS - 1 && g_plot_cells[gui_plot_cell_index(g_plot_row_selected, g_plot_col_selected + 1)]) ? 1 : 0;
            g_plot_selected = g_plot_cells[gui_plot_cell_index(g_plot_row_selected, g_plot_col_selected)];
            break;
        case GLFW_KEY_UP:
            g_plot_row_selected = gui_plot_cell_row_up();
            g_plot_selected = g_plot_cells[gui_plot_cell_index(g_plot_row_selected, g_plot_col_selected)];
            gui_plot_queue_scroll_to_selected();
            break;
        case GLFW_KEY_DOWN:
            g_plot_row_selected = gui_plot_cell_row_down();
            g_plot_selected = g_plot_cells[gui_plot_cell_index(g_plot_row_selected, g_plot_col_selected)];
            gui_plot_queue_scroll_to_selected();
            break;
        case GLFW_KEY_F:
            g_plot_maximized = !g_plot_maximized;
            break;
        case GLFW_KEY_SPACE:
            app_toggle_state();
            break;
        }

        break;
    }
}

void app_mouse_button_callback(GLFWwindow* window, int button, int action, int mods) {
    (void)window;
    (void)mods;

    if (button != GLFW_MOUSE_BUTTON_LEFT) return;

    switch (action) {
    case GLFW_PRESS:
        g_plot_selected = g_plot_hovered ? g_plot_hovered : g_plot_selected;
        break;
    }
}

void init() {
    signal(SIGINT, app_sig_handler);
    signal(SIGTERM, app_sig_handler);

    log_info("Starting SALIS data client");

    log_info("Initializing GLFW");
    glfwSetErrorCallback(app_error_callback);
    glfwInitHint(GLFW_WAYLAND_LIBDECOR, GLFW_WAYLAND_DISABLE_LIBDECOR);
    if (!glfwInit()) assert(false);

    float scale = ImGui_ImplGlfw_GetContentScaleForMonitor(glfwGetPrimaryMonitor());
    g_window = glfwCreateWindow((int)(800 * scale), (int)(600 * scale), "SALIS data client", nullptr, nullptr);
    assert(g_window);
    glfwSetKeyCallback(g_window, app_key_callback);
    glfwSetMouseButtonCallback(g_window, app_mouse_button_callback);
    glfwMakeContextCurrent(g_window);
    glfwSwapInterval(1); // enable vsync

    log_info("Initializing ImGui");
    IMGUI_CHECKVERSION();
    ImGui::CreateContext();
    ImPlot::CreateContext();

    g_imgui_io = &ImGui::GetIO();
    g_imgui_io->Fonts->AddFontFromFileTTF(FONT_SOURCE, FONT_SIZE);
    g_imgui_io->IniFilename = nullptr;

    g_imgui_style = &ImGui::GetStyle();
    g_imgui_style->Colors[ImGuiCol_WindowBg] = COLOR_BLACK;
    g_imgui_style->FontScaleDpi = scale;
    g_imgui_style->FontSizeBase = FONT_SIZE;
    g_imgui_style->ItemSpacing = ImVec2(g_imgui_style->ItemSpacing.x, 2.f);
    g_imgui_style->ScaleAllSizes(scale);

    g_implot_style = &ImPlot::GetStyle();
    g_implot_style->Colors[ImPlotCol_FrameBg] = COLOR_BLACK;
    g_hm_colormap = ImPlot::AddColormap("Inferno", g_hm_colormap_cols.data(), g_hm_colormap_cols.size(), false);

    ImGui_ImplGlfw_InitForOpenGL(g_window, true);
    ImGui_ImplOpenGL3_Init(GLSL_VERSION);

    for (auto &trace : g_core_traces) g_traces.push_back(&trace);
    for (auto &trace : g_arch_traces) g_traces.push_back(&trace);
    for (auto &trace : g_core_traces_heatmaps) g_traces.push_back(&trace);
    for (auto &trace : g_arch_traces_heatmaps) g_traces.push_back(&trace);
    for (auto &plot : g_core_plots) g_plots.push_back(&plot);
    for (auto &plot : g_arch_plots) g_plots.push_back(&plot);
    for (auto &plot : g_arch_plots_stacked) g_plots.push_back(&plot);
    for (auto &plot : g_core_plots_heatmaps) g_plots.push_back(&plot);
    for (auto &plot : g_arch_plots_heatmaps) g_plots.push_back(&plot);
    for (auto &i : g_traces) g_trace_map[i->m_name] = i;

    g_plot_cells = std::vector<Plot *>(g_plots.size() * PLOT_MAX_COLS);
    g_plot_cells_top = std::vector<float>(g_plots.size() * PLOT_MAX_COLS);
    g_plot_cells_bottom = std::vector<float>(g_plots.size() * PLOT_MAX_COLS);
    g_plot_selected = g_plots[0];

    g_hm_pixel_pow = data_max_hm_pixel_pow();

    mtx_init(&g_fetching_mutex, mtx_plain);
}

void exec() {
    while (!glfwWindowShouldClose(g_window)) {
        glfwPollEvents();

        ImGui_ImplOpenGL3_NewFrame();
        ImGui_ImplGlfw_NewFrame();
        ImGui::NewFrame();

        gui_render();

        ImGui::Render();
        int display_w;
        int display_h;
        glfwGetFramebufferSize(g_window, &display_w, &display_h);
        glViewport(0, 0, display_w, display_h);
        glClearColor(0.f, 0.f, 0.f, 1.f);
        glClear(GL_COLOR_BUFFER_BIT);
        ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
        glfwSwapBuffers(g_window);
    }
}

void quit() {
    mtx_destroy(&g_fetching_mutex);

    ImGui_ImplOpenGL3_Shutdown();
    ImGui_ImplGlfw_Shutdown();
    ImPlot::DestroyContext();
    ImGui::DestroyContext();

    log_info("Stopping SALIS data client");
    glfwDestroyWindow(g_window);
    glfwTerminate();
}

int main(int argc, char **argv) {
    (void)argc;
    (void)argv;

    init();
    exec();
    quit();

    return 0;
}