aboutsummaryrefslogtreecommitdiff
path: root/gui.c
blob: 93281261881126a1aff70138f53cc4d279c5127e (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
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
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
/*
 *
 * Copyright (C) 2022 Jeremias Stotter <jeremias@stotter.eu>
 *
 * This file is part of network-simulator.
 *
 * network-simulator is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
 *
 * network-simulator is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with network-simulator. If not, see <https://www.gnu.org/licenses/>. 
*/

#include <string.h>
#include <gtk/gtk.h>
#include <gdk/gdk.h>
#include <time.h>
#include <math.h>

#include "shared.h"
#include "template.h"
#include "device.h"
#include "connection.h"
#include "gui_device.h"
#include "gui_packet.h"
#include "gui.h"
#include "files.h"
#include "undo-redo.h"
#include "helpers.h"
#include "interface.h"
#include "lua_functions.h"
#include "decorations.h"
#include "geometry.h"

#define INTERVAL_FAST 10
// The speed in step mode can be changed
int interval_play = 100;

int timestep();

bool fastmode = false;
bool play = false;
int timestep_timeout_source = 0;

enum {
	MODE_MOVE,
	MODE_NEW_DEVICE,
	MODE_NEW_CONNECTION,
	MODE_NEW_TEXT,
	MODE_NEW_RECT,
	MODE_NEW_CIRCLE,
	MODE_DELETE
};
int area_mode = MODE_MOVE;

struct device* clipboard = NULL;

// Area scale in percent
int area_scale = 100;

struct interface* connection_interface1 = NULL;

// True if the area is currently being clicked
bool area_pressed = false;
bool area_moving = false;
// The start postions of a click
double xstart = 0, ystart = 0;
double xnow = 0, ynow = 0;

// The main window
GtkWidget* window = NULL;
// The main drawing arean
GtkWidget* main_drawing_area = NULL;
// The packets currently drawn on the drawing area
struct timestep_entry_ll* drawing_entries = NULL;
// We need to keep the elements allocated until the rewind can not go back any further
struct timestep_entry_ll* allocated_entries = NULL;

GtkWidget* mode_label = NULL;
GtkWidget* zoom_label = NULL;
GtkWidget* device_view = NULL;
GtkWidget* connection_view = NULL;
GtkWidget* packet_list_box = NULL;
GtkWidget* rewind_button = NULL;
GtkWidget* play_button = NULL;
GtkWidget* forward_button = NULL;
GtkWidget* speed_slider = NULL;

GtkWidget* delete_button = NULL;
GtkWidget* move_button = NULL;
GtkWidget* text_button = NULL;
GtkWidget* rect_button = NULL;
GtkWidget* circle_button = NULL;

GListStore* file_filter_list = NULL;

// The packet list store
GListStore* packet_list_store = NULL;
enum {
	PACKET_COL_DEV1,
	PACKET_COL_DEV2,
	PACKET_COL_SIZE,
	PACKET_COL_DATA,
	PACKET_COL_STATUS,
	// This is a string set by the device containing a string of what we are transporting
	PACKET_COL_TYPE,
	PACKET_N_COL
};

GtkWidget* packet_tree = NULL;

char* save_path = NULL;

// Call this if we enter a mode that has no toolbar button
static inline void no_toolbar() {
	gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(move_button), false);
	gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(delete_button), false);
	gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(text_button), false);
}

// Call this on coordinate to normalize transformations from drawing
#define COORD_NORM(a) (a) / ((double)area_scale / 100.L)
#define COORD_UNORM(a) (a) * ((double)area_scale / 100.L)

// Do a few things to cleanly switch between modes
void update_mode() {
	area_moving = false;
	area_pressed = false;
	
	switch(area_mode) {
		case MODE_MOVE:
			gtk_label_set_text(GTK_LABEL(mode_label), "MOVE");
			gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(move_button), true);
			break;
		case MODE_NEW_DEVICE:
			gtk_label_set_text(GTK_LABEL(mode_label), "ADD DEVICE");
			no_toolbar();
			break;
		case MODE_NEW_CONNECTION:
			gtk_label_set_text(GTK_LABEL(mode_label), "ADD CONNECTION");
			no_toolbar();
			break;
		case MODE_NEW_TEXT:
			gtk_label_set_text(GTK_LABEL(mode_label), "NEW TEXT");
			gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(text_button), true);
			break;
		case MODE_NEW_RECT:
			gtk_label_set_text(GTK_LABEL(mode_label), "NEW RECTANGLE");
			gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(rect_button), true);
			break;
		case MODE_NEW_CIRCLE:
			gtk_label_set_text(GTK_LABEL(mode_label), "NEW CIRCLE");
			gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(circle_button), true);
			break;
		case MODE_DELETE:
			gtk_label_set_text(GTK_LABEL(mode_label), "DELETE");
			gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(delete_button), true);
			break;
	}
	if(area_mode != MODE_NEW_DEVICE)
		gtk_flow_box_unselect_all(GTK_FLOW_BOX(device_view));
	if(area_mode != MODE_NEW_CONNECTION)
		gtk_flow_box_unselect_all(GTK_FLOW_BOX(connection_view));
}

// User data should be a pointer but it's easier like this
void toolbar_toggle(GtkToggleButton* self, const int* new_mode) {
	if(!gtk_toggle_button_get_active(self)) return;
   	area_mode = *new_mode;
	update_mode();
}

// The selected devices
struct device_selection {
	SLL_HEAD(struct device_selection);
	struct device* selected_device;
}* selected_devices = NULL;

// Free a selection
void free_selection(struct device_selection* selection) {
	if(!selection) return;
	struct device_selection* next = NULL;
	for(struct device_selection* this_selection = selection; this_selection != NULL; this_selection = next) {
		next = this_selection->next;
		free(this_selection);
	}
}

bool device_in_selection(struct device_selection* selection, const struct device* device) {
	if(!selection) return false;
	LL_FOR(struct device_selection, selection, this_selection) {
		if(this_selection->selected_device == device) return true;
	}
	return false;
}

//char* selected_template = NULL;

void draw_arrow(cairo_t* cr,
				long x1, long y1,
				long x2, long y2,
				long head_size) {
	// Draw the arrow line
	cairo_move_to(cr, x1, y1);
	cairo_line_to(cr, x2, y2);
	cairo_stroke(cr);
	// Draw the arrow head
	// Get the angle of the line
	double dy = y2 - y1;
	double dx = x2 - x1;
	double theta = atan2(dx, dy);

	// Draw the arrow head
	cairo_move_to(cr, x2 + (sin(theta) * head_size), y2 + (cos(theta) * head_size));
	
	cairo_rotate(cr, -theta);

	cairo_rel_line_to(cr, -head_size, -head_size);
	
	cairo_rel_line_to(cr, head_size*2, 0);
	cairo_rel_line_to(cr, -head_size, head_size);
	cairo_fill(cr);
	
	cairo_rotate(cr, theta);
}

// Setup text stype
void setup_font(cairo_t* cr) {
	cairo_set_source_rgb(cr, 0, 0, 0);
	cairo_select_font_face(cr, "monospace", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL);
	cairo_set_font_size(cr, AREA_TEXT_SIZE);
}

void draw_interface_indicator(cairo_t* cr, struct device* dev_1, struct device* dev_2, int ico_s, int number) {
	cairo_set_source_rgb(cr, 0, 0, 0);
	struct coordinate num1_coord = offset_along_line(dev_1->X + (ico_s >> 1),
													 dev_1->Y + (ico_s >> 1),
													 dev_2->X + (ico_s >> 1),
													 dev_2->Y + (ico_s >> 1),
													 ico_s * 0.705 + 5);
		
	setup_font(cr);
	char int_text[12] = {0};
	snprintf(int_text, 12, "%d", number);

	cairo_text_extents_t int_n_extend = {0};
	cairo_text_extents(cr, int_text, &int_n_extend);

	cairo_set_source_rgba(cr, 1, 1, 1, 0.7);
	// Draw a background for the text
	cairo_arc(cr, num1_coord.x, num1_coord.y,
			  int_n_extend.width > int_n_extend.height ? int_n_extend.width : int_n_extend.height,
			  0, 2*G_PI);
	cairo_fill(cr);
		
	cairo_move_to(cr, num1_coord.x - int_n_extend.width / 2, num1_coord.y + int_n_extend.height / 2);
	cairo_set_source_rgb(cr, 0, 0, 0);
	cairo_show_text(cr, int_text);
}

// Indexes can be smaller than 0, in which case device names will not be drawn
void draw_con(cairo_t* cr, struct device* dev_1, struct device* dev_2, double line_color[3], int index_1, int index_2) {
	// Set the color of the line
	cairo_set_source_rgb(cr, line_color[0], line_color[1], line_color[2]);
	cairo_set_line_width(cr, 4);
	// Draw the line
	int this_ico_s = dev_1->template->icon_size;
	cairo_move_to(cr,
				  dev_1->X + (this_ico_s >> 1),
				  dev_1->Y + (this_ico_s >> 1));

	// Draw a line to the other device
	int next_ico_size = dev_2->template->icon_size;
	cairo_line_to(cr,
				  dev_2->X + (next_ico_size >> 1),
				  dev_2->Y + (next_ico_size >> 1));
	cairo_stroke(cr);
	// If enabled, draw the number of the connected interface over the connection
	if(g_variant_get_boolean(g_action_get_state(g_action_map_lookup_action(G_ACTION_MAP(window), "toggle-interface-nums"))) && index_1 >= 0 && index_2 >= 0) {
		draw_interface_indicator(cr, dev_1, dev_2, this_ico_s, index_1);
		draw_interface_indicator(cr, dev_2, dev_1, dev_2->template->icon_size, index_2);
	}
}

void update_main_drawing_area(GtkDrawingArea* drawing_area,
                              cairo_t* cr,
                              int width, int height,
                              gpointer user_data)
{
	// Draw the background as white, here we just ignore gtk themes because the colors of the connector may be anything, so having a predictable background is kind of important
	cairo_set_source_rgb(cr, 1, 1, 1);
	cairo_paint(cr);

	double area_factor = (double)area_scale / (double)100;
	cairo_scale(cr, area_factor, area_factor);

	cairo_rectangle_t image_rect = {0, 0, width, height};
	
	// Create an own surface for the images so that they can be drawin in the foreground
	cairo_surface_t* image_surface = cairo_recording_surface_create(CAIRO_CONTENT_COLOR_ALPHA, &image_rect);
	cairo_t* image_layer = cairo_create(image_surface);
	//cairo_scale(image_layer, area_factor, area_factor);
	
	// Go through all the devices
	LL_FOR(struct device, start_device, current_device) {
		if(current_device->X > gtk_drawing_area_get_content_width(GTK_DRAWING_AREA (drawing_area)) - 250)
			gtk_drawing_area_set_content_width(GTK_DRAWING_AREA (drawing_area), current_device->X + 250);
		if(current_device->Y > gtk_drawing_area_get_content_height(GTK_DRAWING_AREA (drawing_area)) - 250)
			gtk_drawing_area_set_content_height(GTK_DRAWING_AREA (drawing_area), current_device->Y + 250);
		// Paint a selection indication if this device is selected
		if(area_mode == MODE_MOVE && selected_devices) {
			cairo_set_source_rgba(cr, 0, 0, 0, 0.1);
			if(device_in_selection(selected_devices, current_device)) {
				cairo_rectangle(cr, current_device->X-10, current_device->Y-10,
								current_device->template->icon_size + 20, current_device->template->icon_size + 20);
				cairo_fill(cr);
			}
		}
		// Paint the image
		gdk_cairo_set_source_pixbuf(image_layer, current_device->template->icon, current_device->X, current_device->Y);
		cairo_paint(image_layer);
		// Draw the text
		setup_font(cr);
		// Get the text extend
		cairo_text_extents_t extents;
		cairo_text_extents(cr, current_device->name, &extents);
		// Move to the center
		cairo_move_to(cr, current_device->X + ((current_device->template->icon_size - extents.width) / 2), current_device->Y + current_device->template->icon_size + extents.height + 2);
		cairo_show_text(cr, current_device->name);
		
		// Go through all the interfaces of all the devices
		// If there is a connection draw a line
		for(int i = 0; i < current_device->template->slots; i++) {
			struct interface* draw_interface = &(current_device->interfaces[i]);
			if(!draw_interface->template) continue;

			struct connection* draw_connection = draw_interface->connection;
			if(!draw_connection || !draw_connection->template) continue;

			// Only draw if the device is still there and we are the first interface
			if(draw_connection->interface1 == draw_interface && !draw_connection->interface2->parent_device->deleted) {
				double* line_color = draw_connection->template->color;
				// First move to the center position of this device
				draw_con(cr, current_device, draw_connection->interface2->parent_device, line_color, i, draw_connection->interface2->parent_index);
			}
		}
	}

	// Draw inidcations to mark what is currently being sent
	if(drawing_entries) {
		for(struct timestep_entry_ll* cur_entry = drawing_entries;
			cur_entry && cur_entry->send_timestamp == drawing_entries->send_timestamp;
			cur_entry = cur_entry->next) {
			struct send_queue_entry* cur_queue = cur_entry->send_entry;
			struct interface* interface1 = cur_queue->parent_interface;
			if(!interface1->connection)
				continue;
			struct interface* interface2 = cur_queue->parent_interface->connection->interface1 == interface1 ?
				cur_queue->parent_interface->connection->interface2 :
				cur_queue->parent_interface->connection->interface1;
			if(!interface2->connection)
				continue;
			struct device* dev1 = interface1->parent_device;
			struct device* dev2 = interface2->parent_device;
			if(fastmode) {
				// Make the color of the connection darker while sending
				double color[3];
				memcpy(color, interface1->connection->template->color, 3 * sizeof(double));
				for(int i = 0; i < 3; i++) {
					color[i] -= 0.3;
					if(color[i] < 0) color[i] = 0;
				}
				
				draw_con(cr, interface1->parent_device, interface2->parent_device, color, -1, -1);
				
			} else {
				cairo_set_source_rgb(image_layer, cur_queue->color[0], cur_queue->color[1], cur_queue->color[2]);
				cairo_set_line_width(image_layer, 6);
				// Draw an arrow of the currently sending things
				int dev1_offset = dev1->template->icon_size / 2;
				int dev2_offset = dev2->template->icon_size / 2;
				// We draw this to the image layer so that the arrow is in front
				draw_arrow(image_layer, dev1->X + dev1_offset, dev1->Y + dev1_offset,
						   dev2->X + dev2_offset, dev2->Y + dev2_offset, 10);
			}
		}
	}

	cairo_set_source_rgb(cr, 0, 0, 0);
	cairo_set_line_width(cr, 2);
	// Draw decorations
	// This doesn't work for new deco types
	LL_FOR(struct deco, start_deco, cur_deco) {
		setup_font(cr);
		cairo_text_extents_t extent;
		cairo_text_extents(cr, cur_deco->text, &extent);
		cairo_move_to(cr, cur_deco->X + cur_deco->width / 2.0 - extent.width / 2.0,
					  cur_deco->Y + cur_deco->height / 2.0 + extent.height / 2.0);
		cairo_show_text(cr, cur_deco->text);
		cairo_new_path(cr);
		// Only set decoration width to text width if this is a text only deco
		if(cur_deco->type == deco_type_text) {
			cur_deco->height = extent.height;
			cur_deco->width = extent.width;
		} else if(cur_deco->type == deco_type_rect) { // Draw a rectangle for rect type
			cairo_rectangle(cr, cur_deco->X, cur_deco->Y, cur_deco->width, cur_deco->height);
			cairo_stroke(cr);
		} else if(cur_deco->type == deco_type_circle) { // Draw circle
			// Scale to make circle
			cairo_save(cr);
			cairo_translate(cr, cur_deco->X + cur_deco->width / 2.0,
							cur_deco->Y + cur_deco->height / 2.0);
			cairo_scale(cr, cur_deco->width / 2, cur_deco->height / 2);
			cairo_arc(cr, 0, 0, 1, 0, 2*G_PI);
			
			// Scale back
			cairo_restore(cr);
			cairo_stroke(cr);
		}
	}
	
	// Draw the image surface on top
	cairo_set_source_surface(cr, image_surface, 0, 0);
	cairo_paint(cr);
	// Draw a selection rectangle if we are in MODE_MOVE
	cairo_set_source_rgb(cr, 0, 0, 0);
	cairo_set_line_width(cr, 2);
	if(area_mode == MODE_MOVE && area_pressed && !area_moving) {
		const double dashes[] = {12.0, 6.0};
		cairo_set_dash(cr, dashes, 2, 0);
		cairo_rectangle(cr, xstart, ystart, xnow-xstart, ynow-ystart);
		cairo_stroke(cr);

		cairo_set_dash(cr, NULL, 0, 0);
	}
	
	// Destroy the image surface
	cairo_destroy(image_layer);
	cairo_surface_destroy(image_surface);
}

// Call after a packet drawing has completed to make the packet disapear from the gui
int clean_draw() {
	// Free what we don't need
	if(!drawing_entries) return false;
	// Only free the oldest entries
	unsigned long oldest_timestamp = drawing_entries->send_timestamp;
	struct timestep_entry_ll* cur_entry = drawing_entries;
	// In step mode point to allocated entries so that we can free later
	if(!fastmode)
		allocated_entries = drawing_entries;
	else
		drawing_entries = NULL;
	
	for(; cur_entry;) {
		if(cur_entry->send_timestamp != oldest_timestamp) {
			drawing_entries = cur_entry;
			break;
		}
		// In fast mode free now
		if(fastmode) {
			// If we are in fastmode here remove the reference to the previous entry, effectively making this the new start of the linked list
			cur_entry->prev = NULL;
			free(cur_entry->send_entry);
			struct timestep_entry_ll* next = cur_entry->next;
			free(cur_entry);
			cur_entry = next;
		} else { // Otherwise just advance
			cur_entry = cur_entry->next;
		}
	}
	// In fast mode we can point allocated entries to drawing entries now
	allocated_entries = drawing_entries;
	
	gtk_widget_queue_draw(main_drawing_area);
	return false;
}

// Select the currently drawing packet in the sidebar
void sidebar_select_current() {
	if(!drawing_entries) return;
	// Set the active element in the list to the current entry
	GtkSelectionModel* selection = gtk_column_view_get_model(GTK_COLUMN_VIEW(packet_tree));
	// See how many indices we have
	gtk_selection_model_unselect_all(selection);
	struct timestep_entry_ll* sel_entry = drawing_entries;
	unsigned long sel_time = sel_entry->send_timestamp;
	do {
		gtk_selection_model_select_item(selection, sel_entry->send_entry->gui_index, true);
		sel_entry = sel_entry->next;
	} while(sel_entry && sel_entry->send_timestamp == sel_time);
}

// This function will do timestep while in simulation mode
int simulation_timestep(gpointer user_data) {
	struct timestep_entry_ll* last_time_entry = drawing_entries;
	while(last_time_entry && last_time_entry->next && last_time_entry->next->send_timestamp == drawing_entries->send_timestamp)
		last_time_entry = last_time_entry->next;
	// We are already at the newest packet, make time advance
	if(!drawing_entries || drawing_entries->next == allocated_entries || !last_time_entry->next) {
		timestep();
	} else {
		// Just go forward in the packet list
		drawing_entries = last_time_entry->next;
		gtk_widget_queue_draw(main_drawing_area);
	}
	sidebar_select_current();
	return true;
}

// Turn on fast mode
void toggle_fast_mode(GtkWidget* self, gpointer data) {
	if(!gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(self))) return;
	// Set the play button to inactive
	gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(play_button), false);
	// Add a timeout
	timestep_timeout_source = g_timeout_add_full(G_PRIORITY_LOW,
												 INTERVAL_FAST,
												 timestep,
												 NULL,
												 NULL
												 );
	fastmode = true;
	gtk_widget_set_visible(packet_list_box, false);
	// Make the buttons inacetive
	gtk_widget_set_sensitive(rewind_button, false);
	gtk_widget_set_sensitive(play_button, false);
	gtk_widget_set_sensitive(forward_button, false);
	gtk_widget_set_sensitive(speed_slider, false);
	// Clear the packet list
	// Kinda shitty way to manually free this, maybe look into g_boxed someday?
	g_list_store_remove_all(packet_list_store);
	while(allocated_entries != drawing_entries && drawing_entries) {
		free(drawing_entries->send_entry);
		struct timestep_entry_ll* old_entry = drawing_entries;
		drawing_entries = drawing_entries->next;
		free(old_entry);
	}
	// Clean all the drawn packets
	clean_draw();
}

// Turn on step mode
void toggle_step_mode(GtkWidget* self, gpointer data) {
	if(!gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(self))) return;
	if(fastmode) g_source_remove(timestep_timeout_source);
	fastmode = false;
	gtk_widget_set_visible(packet_list_box, true);
	// Make the buttons active
	gtk_widget_set_sensitive(rewind_button, true);
	gtk_widget_set_sensitive(play_button, true);
	gtk_widget_set_sensitive(forward_button, true);
	gtk_widget_set_sensitive(speed_slider, true);
	// Remove any blinking connection
	clean_draw();
}

void change_step_speed(GtkWidget* self, gpointer user_data) {
	if(fastmode) return;
	interval_play = 1000 - gtk_range_get_value(GTK_RANGE(self));
	if(play) {
		g_source_remove(timestep_timeout_source);
		timestep_timeout_source = g_timeout_add_full(G_PRIORITY_LOW,
													 interval_play,
													 simulation_timestep,
													 NULL,
													 NULL);
	}
}

// Start stop autoplay
void toggle_play(GtkWidget* self, gpointer data) {
	if(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(self))) {
		play = true;
		timestep_timeout_source = g_timeout_add_full(G_PRIORITY_LOW,
													 interval_play,
													 simulation_timestep,
													 NULL,
													 NULL
													 );
	} else {
		if(play) g_source_remove(timestep_timeout_source);
		play = false;
	}
}

struct dev_template* selected_device_template = NULL;

// Retrieve the device from the template list and store it in selected_template
void select_device_template(GtkFlowBox* self, GtkFlowBoxChild* child, void* user_data) {
	selected_device_template = &device_templates[gtk_flow_box_child_get_index(child)];
	
	area_mode = MODE_NEW_DEVICE;
	update_mode();
}

struct connection_template* selected_connection_template = NULL;

void select_connection_template(GtkFlowBox* self, GtkFlowBoxChild* child, void* user_data) {
	selected_connection_template = &connection_templates[gtk_flow_box_child_get_index(child)];
	
	area_mode = MODE_NEW_CONNECTION;
	connection_interface1 = NULL;
	update_mode();
}

struct device_selection* add_device_to_selection(struct device_selection* sel, struct device* dev) {
	struct device_selection* new_selection = malloc_or_abort(sizeof(struct device_selection));
	new_selection->next = sel;
	new_selection->selected_device = dev;
	return new_selection;
}

// This function gets the devices which are fully or partially in the square defined by the points x1, y1, x2, y2
struct device_selection* get_device_at(double x1, double y1, double x2, double y2) {
	struct device_selection* start_selection = NULL;
	LL_FOR(struct device, start_device, cur_device) {
		if(!rect_rect_intersect(x1, x2, y1, y2,
							   cur_device->X, cur_device->X + cur_device->template->icon_size,
							   cur_device->Y, cur_device->Y + cur_device->template->icon_size))
			continue;
		start_selection = add_device_to_selection(start_selection, cur_device);
	}
	return start_selection;
}

// This function gets the first connection it finds that intersect the square x1, y1, x2, y2
struct connection* get_connection_at(double x1, double y1, double x2, double y2) {
	// Go through all the devices
	LL_FOR(struct device, start_device, cur_device) {
		// Go through all the interfaces this device has
		for(int i = 0; i < cur_device->template->slots; i++) {
			struct interface* cur_interface = &cur_device->interfaces[i];
			// If there is no interface continue on
			if(!cur_interface->parent_device) continue;
			// Check the connection of the interface
			struct connection* test_con = cur_interface->connection;
			if(!test_con) continue;
			// Check if the current interface is interface 1 of the connection, this will avoid checking a connection twice, effectively doubling the speed this needs to finish if there is no connection in the square
			if(test_con->interface1 != cur_interface) continue;
			struct device* opposite_device = test_con->interface2->parent_device;
			// We are going to test if the connection intersects with one of the diagonals
			double a_x = (double)opposite_device->X + (double)opposite_device->template->icon_size / 2.f;
			double a_y = (double)opposite_device->Y + (double)opposite_device->template->icon_size / 2.f;
			double b_x = (double)cur_device->X + (double)cur_device->template->icon_size / 2.f;
			double b_y = (double)cur_device->Y + (double)cur_device->template->icon_size / 2.f;
			if(line_line_intersect(a_x, a_y, b_x, b_y,
								   x1, y1, x2, y2) ||
			   line_line_intersect(a_x, a_y, b_x, b_y,
								   x1, y2, x2, y1)
			   )
				return test_con;
		}
	}
	return NULL;
}

struct deco* get_deco_at(double x1, double y1, double x2, double y2) {
	LL_FOR(struct deco, start_deco, cur_text) {
		if(rect_rect_intersect(x1, x2, y1, y2,
							   cur_text->X, cur_text->X + cur_text->width,
							   cur_text->Y, cur_text->Y + cur_text->height)) {
			return cur_text;
		}
	}
	return NULL;
}

/*
 * ====== DAWING AREA EVENT HANDLERS ======
 */

// Remoce the popover
void interface_select_close(GtkPopover* self, gpointer user_data) {
	// Don't know if this is the propper way to do things
	gtk_widget_unparent(GTK_WIDGET(self));
}

// An interface has been clicked
void selection_clicked(GtkButton* self, gpointer user_data) {
	if(!connection_interface1) {
		connection_interface1 = (struct interface*)user_data;
	} else {
		// Delete any old connection
		struct undo_entry* undo_new_del = NULL;
		if(connection_interface1->connection) {
			struct undo_del_con_data* undo_del_con_new = NULL;
			NEW_UNDO_STRUCT(undo_del_con, undo_del_con_data, undo_new_del, undo_del_con_new);
			undo_del_con_new->int1 = connection_interface1;
			undo_del_con_new->int2 = (connection_interface1->connection->interface1 == connection_interface1 ? connection_interface1->connection->interface2 : connection_interface1->connection->interface1);
			undo_del_con_new->template = connection_interface1->connection->template;
		}
		
		delete_connection(connection_interface1->connection);
		delete_connection(((struct interface*)user_data)->connection);
		// Create the connection
		new_connection(connection_interface1, (struct interface*)user_data, selected_connection_template);
		struct undo_entry* undo_new_add = NULL;
		struct undo_add_con_data* undo_add_con_new = NULL;
		NEW_UNDO_STRUCT(undo_add_con, undo_add_con_data, undo_new_add, undo_add_con_new);
		if(undo_new_del) {
			undo_new_del->prev_sibling = undo_new_add;
			undo_new_add->next_sibling = undo_new_del;
		}
		undo_add_con_new->int1 = connection_interface1;
		undo_add_con_new->int2 = (struct interface*)user_data;
		undo_add_con_new->template = selected_connection_template;
		undo_add_entry(undo_new_add);
		
		connection_interface1 = NULL;
	}
	GtkWidget* parent_popover = gtk_widget_get_ancestor(GTK_WIDGET(self), GTK_TYPE_POPOVER);
	if(parent_popover) {
		gtk_popover_popdown(GTK_POPOVER(parent_popover));
		gtk_widget_unparent(parent_popover);
	}
	// Upadate the drawing area
	gtk_widget_queue_draw(main_drawing_area);
}

// Selects the interface at coordinates x and y
void select_interface_at(double x, double y) {
	struct device_selection* dev_sel = get_device_at(x,y,x,y);
	// No device was found under the cursor
	if(!dev_sel) return;
	struct device* dev = dev_sel->selected_device;
	free_selection(dev_sel);

	// Create the popover for selection
	
	GtkWidget* selection_popover = gtk_popover_new();
	g_signal_connect(G_OBJECT(selection_popover), "closed", G_CALLBACK(interface_select_close), NULL);
	gtk_widget_set_parent(selection_popover, main_drawing_area);
	gtk_popover_set_pointing_to(GTK_POPOVER(selection_popover), &((GdkRectangle){x, y, 0, 0}));
	// Fill in the popover with corresponding buttons
	GtkWidget* selection_box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 2);
	int functioning_interfaces = 0;
	for(int i = 0; i < dev->template->slots; i++) {
		// Check if the interface is used
		if(!dev->interfaces[i].template) continue;
		functioning_interfaces++;
		char interface_label[256];
		snprintf(interface_label, 256, "%s%d: %s", dev->interfaces[i].connection ? "*" : "", i, dev->interfaces[i].template->name);
		GtkWidget* button = gtk_button_new_with_label(interface_label);
		gtk_box_append(GTK_BOX(selection_box), button);
		g_signal_connect(G_OBJECT(button), "clicked", G_CALLBACK(selection_clicked), &dev->interfaces[i]);
	}
	// There are no interfaces
	if(!functioning_interfaces) {
		printf("NO INTERFACES!\n");
		GtkWidget* label_no_interface = gtk_label_new("no interfaces");
		gtk_box_append(GTK_BOX(selection_box), label_no_interface);
	}
	gtk_popover_set_child(GTK_POPOVER(selection_popover), selection_box);	
	gtk_popover_popup(GTK_POPOVER(selection_popover));
}

double x_last = 0, y_last = 0;

struct deco* current_move_deco = NULL;
// This will point to the device we are currently moving
struct device* current_move_dev = NULL;

struct deco* sizing_deco = NULL;

// Mouseclick start
void drawing_area_click(GtkGestureClick* self, gint n_press, gdouble x, gdouble y, gpointer user_data) {
	x = COORD_NORM(x);
	y = COORD_NORM(y);
	xstart = x;
	ystart = y;
	x_last = xstart, y_last = ystart;
	area_pressed = true;
	if(area_mode == MODE_NEW_RECT || area_mode == MODE_NEW_CIRCLE) {
		sizing_deco = deco_new(area_mode == MODE_NEW_RECT ?
										 deco_type_rect :
										 deco_type_circle);
			sizing_deco->X = x;
			sizing_deco->Y = y;

			struct undo_entry* undo_new = NULL;
			struct undo_add_deco_data* undo_add_deco_data_new = NULL;
			
			NEW_UNDO_STRUCT(undo_add_deco, undo_add_deco_data, undo_new, undo_add_deco_data_new);
			undo_add_deco_data_new->deco = sizing_deco;
			sizing_deco->refs++;
			undo_add_entry(undo_new);
			return;
	}
	struct device_selection* single_device;
	struct deco* clicked_deco;
	if((single_device  = get_device_at(x,y,x,y))) {
		current_move_dev = single_device->selected_device;
		area_moving = true;
		free_selection(single_device);
	} else if((clicked_deco = get_deco_at(x,y,x,y))) {
		current_move_deco = clicked_deco;
		area_moving = true;
	} else
		area_moving = false;
}

static inline void move_single_dev(struct device* dev, double xoff, double yoff) {
	dev->X += xoff;
	if(dev->X < 0) dev->X = 0;
	dev->Y += yoff;
	if(dev->Y < 0) dev->Y = 0;
}

// Adds another device to the undo_device_action
void add_move_undo_device(size_t* devices_size, struct device* dev, struct undo_entry* entry) {
	size_t devices_offset = *devices_size;
	struct undo_move_data* data = entry->undo_data;
	*devices_size += strlen(dev->name) + 1;
	data->devices = realloc_or_abort(data->devices, *devices_size);
	char* insert_at = data->devices + devices_offset;
	strcpy(insert_at, dev->name);
	data->dev_n++;
}

// This will move a device or select the devices below the area
// Set undo to true if this should be recorded in the undo stack
void move_things(double x, double y, bool undo) {
	double xoff = x - x_last;
	double yoff = y - y_last;
	// Get the device at the selection
	if(current_move_deco) {
		current_move_deco->X += xoff;
		current_move_deco->Y += yoff;
		if(undo) {
			struct undo_entry* undo_new;
			struct undo_move_deco_data* undo_move_deco_new;
			current_move_deco->refs++;
			NEW_UNDO_STRUCT(undo_move_deco, undo_move_deco_data, undo_new, undo_move_deco_new);
			undo_move_deco_new->X_off = x - xstart;
			undo_move_deco_new->Y_off = y - ystart;
			undo_move_deco_new->deco = current_move_deco;
			undo_add_entry(undo_new);
		}
	} else {
		struct device_selection* single_device = get_device_at(x_last,y_last,x_last,y_last);
		if(single_device) {
			struct device* move_dev = single_device->selected_device;
			if(current_move_dev && device_in_selection(single_device, current_move_dev))
				move_dev = current_move_dev;
			// Add the action to the list
			struct undo_entry* undo_new = NULL;
			struct undo_move_data* undo_move_new = NULL;
			size_t devices_size = 0;
			if(undo) {
				NEW_UNDO_STRUCT(undo_move, undo_move_data, undo_new, undo_move_new);
				undo_move_new->X_off = x - xstart;
				undo_move_new->Y_off = y - ystart;
				undo_move_new->devices = NULL;
				undo_move_new->dev_n = 0;
				undo_add_entry(undo_new);
			}
			// See if the device is part of the selection, if so move all of them
			if(device_in_selection(selected_devices, move_dev)) {
				// Move all devices by the offset
				LL_FOR(struct device_selection, selected_devices, this_selection) {
					move_single_dev(this_selection->selected_device, xoff, yoff);
					if(undo) {
						add_move_undo_device(&devices_size, this_selection->selected_device, undo_new);
					}
				}
				// Otherwise move just the one device
			} else {
				free_selection(selected_devices);
				selected_devices = NULL;
				move_single_dev(move_dev, xoff, yoff);
				if(undo) {
					add_move_undo_device(&devices_size, move_dev, undo_new);
				}
			}
			free_selection(single_device);
			// Select the devices in the selection area
		} else {
			free_selection(selected_devices);
			printf("SELECTING DEVICES\n");
			selected_devices = get_device_at(x_last < x ? x_last : x, y_last < y ? y_last : y, x_last < x ? x : x_last, y_last < y ? y : y_last);
		}
	}
	x_last = x, y_last = y;
	gtk_widget_queue_draw(main_drawing_area);
}

// Delete the devices in the current selection
void delete_selection() {
	struct undo_entry* prev = NULL;
	LL_FOR(struct device_selection, selected_devices, cur_sel) {
		struct undo_entry* undo_entry_new;
		struct undo_del_dev_data* undo_del_dev_new;
		NEW_UNDO_STRUCT(undo_del_dev, undo_del_dev_data, undo_entry_new, undo_del_dev_new);
		undo_entry_new->prev_sibling = prev;
		undo_del_dev_new->dev = cur_sel->selected_device;

		delete_device(&start_device, cur_sel->selected_device);
		
		// Add the first entry to the global list, add all other entries to the siblings
		if(prev)
			prev->next_sibling = undo_entry_new;
		else
			undo_add_entry(undo_entry_new);
		
		prev = undo_entry_new;
	}
}

void rename_text_activate(GtkText* self, gpointer user_data) {
	struct device* dev = (struct device*)user_data;

	const char* new_name = gtk_entry_buffer_get_text(gtk_text_get_buffer(self));
	
	struct device* exist_dev = dev_from_name(start_device, new_name);

	if(exist_dev == dev);
	else if(exist_dev) {
		fprintf(stderr, "Error: Device with name %s already exists\n", new_name);
	} else {
		// Add an entry
		struct undo_entry* uentry;
		struct undo_ren_data* ren_data;
		
		NEW_UNDO_STRUCT(undo_ren_dev, undo_ren_data, uentry, ren_data);
		ren_data->dev = dev;
		ren_data->old_name = malloc_or_abort(strlen(dev->name) + 1);
		strcpy(ren_data->old_name, dev->name);
		ren_data->new_name = malloc_or_abort(strlen(new_name) + 1);
		strcpy(ren_data->new_name, new_name);
		
		rename_device(dev, new_name);

		undo_add_entry(uentry);
	}
	// Destruct
	GtkWidget* parent = gtk_widget_get_parent(gtk_widget_get_parent(GTK_WIDGET(self)));
	gtk_popover_popdown(GTK_POPOVER(parent));
	gtk_widget_unparent(parent);

	gtk_widget_queue_draw(main_drawing_area);
}

void text_popover_close(GtkPopover* self, gpointer user_data) {
	g_signal_emit_by_name(G_OBJECT(gtk_popover_get_child(self)), "activate");
}

GtkWidget* new_text_popover_point_to(double x, double y, char* text, GCallback callback, void* callback_data) {
	GtkWidget* popover = gtk_popover_new();
	gtk_widget_set_parent(popover, main_drawing_area);
	// Point to the device text
	GdkRectangle text_rect = {.x = COORD_UNORM(x), .y = COORD_UNORM(y), .width = 1, .height = 1};
	gtk_popover_set_pointing_to(GTK_POPOVER(popover), &text_rect);
	GtkWidget* pop_text = gtk_text_new();
	gtk_entry_buffer_set_text(gtk_text_get_buffer(GTK_TEXT(pop_text)), text ? text : "", -1);
	gtk_popover_set_child(GTK_POPOVER(popover), pop_text);

	g_signal_connect(G_OBJECT(popover), "closed", G_CALLBACK(text_popover_close), callback_data);
	g_signal_connect(G_OBJECT(pop_text),
					 "activate",
					 G_CALLBACK(callback),
					 callback_data);
	gtk_popover_popup(GTK_POPOVER(popover));
	return popover;
}

void gui_rename_device(struct device* dev) {
	new_text_popover_point_to(dev->X + dev->template->icon_size / 2,
							  dev->Y + dev->template->icon_size + AREA_TEXT_SIZE,
							  dev->name, G_CALLBACK(rename_text_activate), dev);
}

void deco_activate(GtkText* self, struct deco* deco) {
	const char* new_text = gtk_entry_buffer_get_text(gtk_text_get_buffer(self));

	struct undo_entry* undo_new = NULL;
	struct undo_set_deco_data* undo_set_deco_data_new = NULL;
	NEW_UNDO_STRUCT(undo_set_deco, undo_set_deco_data, undo_new, undo_set_deco_data_new);
	deco->refs++;
	undo_set_deco_data_new->new_text = malloc(strlen(new_text) + 1);
	strcpy(undo_set_deco_data_new->new_text, new_text);
	undo_set_deco_data_new->old_text = malloc(strlen(deco->text) + 1);
	strcpy(undo_set_deco_data_new->old_text, deco->text);
	undo_set_deco_data_new->deco = deco;
	undo_add_entry(undo_new);
	
	deco_text_set(deco, new_text);
	
	gtk_widget_queue_draw(main_drawing_area);

	GtkWidget* parent = gtk_widget_get_parent(gtk_widget_get_parent(GTK_WIDGET(self)));
	gtk_popover_popdown(GTK_POPOVER(parent));
	gtk_widget_unparent(parent);
}

void gui_change_deco_text(struct deco* deco) {
	new_text_popover_point_to(deco->X + deco->width / 2.0, deco->Y + deco->height / 2.0,
							  deco->text,
							  G_CALLBACK(deco_activate), deco);
}

// Mouseclick release
void drawing_area_release(GtkGestureClick* self, gint n_press, gdouble x, gdouble y, gpointer user_data) {
	x = COORD_NORM(x);
	y = COORD_NORM(y);
	// Offset between start click and now
	int xoff = x - xstart;
	int yoff = y - ystart;
	struct undo_entry* undo_new = NULL;
	// Click not drag
	switch(area_mode) {
		case MODE_MOVE:
			// Open the device window on a short press
			if(xoff < 5 && xoff > -5 && yoff < 5 && yoff > -5) {
				struct device_selection* clicked_device = get_device_at(x,y,x,y);
				struct deco* clicked_deco = NULL;
				if(clicked_device) {
					show_device_window(clicked_device->selected_device);
					free_selection(clicked_device);
				} else if((clicked_device = get_device_at(x,y-AREA_TEXT_SIZE,x,y-AREA_TEXT_SIZE))) {
					gui_rename_device(clicked_device->selected_device);
				} else if((clicked_deco = get_deco_at(x,y,x,y))) {
					gui_change_deco_text(clicked_deco);
				} else {
					// Nothing has been clicked, free the selection
					free_selection(selected_devices);
					selected_devices = NULL;
					gtk_widget_queue_draw(main_drawing_area);
				}
			} else {
				move_things(x,y,true);	
			}
			current_move_dev = NULL;
			current_move_deco = NULL;
			area_moving = false;
			break;
		case MODE_NEW_DEVICE:;
			char* dev_name = malloc_or_abort(strlen(selected_device_template->name) + 6);
			strcpy(dev_name, selected_device_template->name);
			// Use at most two digits
			for(int i = 1; dev_from_name(start_device, dev_name) && i < 100; i++) {
				sprintf(dev_name, "%s (%d)", selected_device_template->name, i);
			}
			struct device* created_device = new_device(&start_device, dev_name, selected_device_template, true);
			free(dev_name);
			if(created_device) {
				created_device->X = x - (created_device->template->icon_size >> 2);
				created_device->Y = y - (created_device->template->icon_size >> 2);
				// Add the action to the list
				struct undo_add_dev_data* undo_add_new;
				NEW_UNDO_STRUCT(undo_add_dev, undo_add_dev_data, undo_new, undo_add_new);
				undo_add_new->dev = created_device;
				undo_add_new->template = created_device->template;
				undo_add_entry(undo_new);
			}
			break;
		case MODE_NEW_CONNECTION:
			select_interface_at(x, y);
			break;
		case MODE_NEW_TEXT:;
			struct deco* new_deco = deco_new(deco_type_text);
			new_deco->X = x;
			new_deco->Y = y;
			gui_change_deco_text(new_deco);

			struct undo_add_deco_data* undo_add_deco_data_new = NULL;
			NEW_UNDO_STRUCT(undo_add_deco, undo_add_deco_data, undo_new, undo_add_deco_data_new);
			undo_add_deco_data_new->deco = new_deco;
			new_deco->refs++;
			undo_add_entry(undo_new);
			
			break;
		case MODE_NEW_RECT:
		case MODE_NEW_CIRCLE:;
			sizing_deco = NULL;
			break;
		case MODE_DELETE:;
			struct device_selection* del_device = get_device_at(x,y,x,y);
			// If we clicked a device delete it
			if(del_device) {
				// Use free device later once this action is removed from the undo stack
				// Add the action to the list
				struct undo_del_dev_data* undo_del_new;
				NEW_UNDO_STRUCT(undo_del_dev, undo_del_dev_data, undo_new, undo_del_new);
				undo_del_new->dev = del_device->selected_device;
				delete_device(&start_device, del_device->selected_device);
				undo_add_entry(undo_new);
				
				free_selection(del_device);
				break;
			}
			struct connection* delete_con = get_connection_at(x-2,y-2,x+2,y+2);
			if(delete_con) {
		
				struct undo_del_con_data* undo_del_con_new = NULL;
				NEW_UNDO_STRUCT(undo_del_con, undo_del_con_data, undo_new, undo_del_con_new);
				undo_del_con_new->int1 = delete_con->interface1;
				undo_del_con_new->int2 = delete_con->interface2;
				undo_del_con_new->template = delete_con->template;
				undo_add_entry(undo_new);
				delete_connection(delete_con);
				break;
			}
			struct deco* delete_text = get_deco_at(x,y,x,y);
			if(delete_text) {
				struct undo_del_deco_data* undo_del_deco_data_new = NULL;
				NEW_UNDO_STRUCT(undo_del_deco, undo_del_deco_data, undo_new, undo_del_deco_data_new);
				undo_del_deco_data_new->deco = delete_text;
				delete_text->refs++;
				undo_add_entry(undo_new);
				
				deco_unappend(delete_text);
			}
			break;
	}
	gtk_widget_queue_draw(main_drawing_area);
	area_pressed = false;
}

// Insert devices in the clipboard
void paste_selection_clipboard() {
	if(!clipboard) return;
	free_selection(selected_devices);
	selected_devices = NULL;
	struct undo_entry* first_sibling = NULL;
	struct undo_entry* prev_sibling = NULL;
	while(clipboard) {
		struct undo_entry* undo_new = NULL;
		struct undo_add_dev_data* undo_add_dev_new = NULL;
		NEW_UNDO_STRUCT(undo_add_dev, undo_add_dev_data, undo_new, undo_add_dev_new);
		undo_add_dev_new->dev = clipboard;
		undo_add_dev_new->template = clipboard->template;
		if(!prev_sibling)
			first_sibling = undo_new;
		else {
			prev_sibling->next_sibling = undo_new;
			undo_new->prev_sibling = prev_sibling;
		}
		prev_sibling = undo_new;
		struct device* next_dev = clipboard->next;
		append_device(&start_device, clipboard);
		selected_devices = add_device_to_selection(selected_devices, clipboard);
		clipboard = next_dev;
	}
	if(first_sibling)
		undo_add_entry(first_sibling);
}

#define COPY_SUFFIX " - COPY"

// This will copy a selection to the clipboard
void copy_selection_clipboard(struct device_selection* selection) {
	// First, free any old clipboard
	struct device* free_dev = clipboard;
	while(free_dev) {
		clipboard = free_dev->next;
		delete_device(&start_device, free_dev);
		free_device(free_dev);
		free_dev = clipboard;
	}
	LL_FOR(struct device_selection, selection, cur_selection) {
		struct device* dev = cur_selection->selected_device;
		if(!dev)
			continue;
		// Create the new device
		char* dev_name = malloc_or_abort(strlen(dev->name) + strlen(COPY_SUFFIX) + 1);
		// Check if device with this name already exists
		sprintf(dev_name, "%s"COPY_SUFFIX, dev->name);
		if(dev_from_name(start_device, dev_name)) {
			char* dev_name_new = malloc_or_abort(strlen(dev_name) + 4);
			strcpy(dev_name_new, dev_name);
			for(int i = 1; dev_from_name(start_device, dev_name_new) && i < 100; i++) {
				sprintf(dev_name_new, "%s %d", dev_name, i);
			}
			free(dev_name);
			dev_name = dev_name_new;
		}
		struct device* new_dev = new_device(&clipboard, dev_name, selected_device_template, false);
		// Load the state
		// Ask the old device to save its state and pass it to the new device
		if(my_lua_call(dev->lua_vm, "save_state", 1, -1)) {
			size_t state_len = 0;
			const char* state = lua_tolstring(dev->lua_vm, -1, &state_len);
			my_lua_call(new_dev->lua_vm, "load_state", 1, LUA_TSTRING, state_len, state, -1);
		}
		// Set the location of the device
		new_dev->X = dev->X + 10;
		new_dev->Y = dev->Y + 10;
		// Copy the interfaces
		for(int i = 0; i < dev->template->slots; i++) {
			if(!dev->interfaces[i].parent_device)
				continue;
			new_interface(new_dev, i, dev->interfaces[i].template);
			// Check in the originial how the neighbour device is called
			if(dev->interfaces[i].connection) {
				char* neigh_name;
				int neigh_index;
				if(&dev->interfaces[i] == dev->interfaces[i].connection->interface1) {
					neigh_name = dev->interfaces[i].connection->interface2->parent_device->name;
					neigh_index = dev->interfaces[i].connection->interface2->parent_index;
				} else {
					neigh_name = dev->interfaces[i].connection->interface1->parent_device->name;
					neigh_index = dev->interfaces[i].connection->interface1->parent_index;
				}
				char* neigh_name_full = malloc_or_abort(strlen(neigh_name) + strlen(COPY_SUFFIX) + 1);
				sprintf(neigh_name_full, "%s"COPY_SUFFIX, neigh_name);
				// Check if the neighbour device is already there
				struct device* neigh = dev_from_name(clipboard, neigh_name_full);
				free(neigh_name_full);
				if(neigh) {
					new_connection(&new_dev->interfaces[i],
								   &neigh->interfaces[neigh_index],
								   dev->interfaces[i].connection->template);
				}
			}
		}
		free(dev_name);
	}
}

// Keyboard
bool drawing_area_key(GtkEventControllerKey* self, guint keyval, guint keycode, GdkModifierType state, gpointer user_data) {
	switch(keyval) {
		case GDK_KEY_Escape:
			area_mode = MODE_MOVE;
			free_selection(selected_devices);
			selected_devices = NULL;
			gtk_widget_queue_draw(gtk_event_controller_get_widget(GTK_EVENT_CONTROLLER(self)));
			update_mode();
			return true;
		case GDK_KEY_Delete:
		case GDK_KEY_BackSpace:
			// In this case delete the selection if available and switch to deleteion mode
			delete_selection();
			area_mode = MODE_DELETE;
			gtk_widget_queue_draw(main_drawing_area);
			update_mode();
			return true;
		case GDK_KEY_c:
			// The CTRL Key was not pressed, return
			if(!(state & GDK_CONTROL_MASK))
				return false;
				
			copy_selection_clipboard(selected_devices);
			gtk_widget_queue_draw(main_drawing_area);
			return true;
		case GDK_KEY_v:
			if(!(state & GDK_CONTROL_MASK))
				return false;

			paste_selection_clipboard();
			gtk_widget_queue_draw(main_drawing_area);
			return true;
		default:
			return false;
	}
}

// Mouse movement
void drawing_area_motion(GtkEventControllerKey* self, gdouble x, gdouble y, gpointer user_data) {
	x = COORD_NORM(x);
	y = COORD_NORM(y);
	xnow = x;
	ynow = y;
	
	if(area_mode == MODE_MOVE && area_moving)
		move_things(x, y, false);
	else if(area_mode == MODE_NEW_RECT || area_mode == MODE_NEW_CIRCLE) {
			if(sizing_deco) {
				// Change deco size
				sizing_deco->width = x - xstart;
				sizing_deco->height = y - ystart;
			}
	}
	if(area_pressed)
		gtk_widget_queue_draw(gtk_event_controller_get_widget(GTK_EVENT_CONTROLLER(self)));
}

// === Called by a device when it sends something
// Will be used to fill the tree of packets

// Type is a string set by the device to identify the protocol of the packet
// Encapsulated protocols will look like this for example:
// HTTP,TCP,ETH
// The highest level protocol should be written first
// This will be used by the gui to display the packet
int gui_send_info(struct interface* send_interface, const char* send_data, int data_len, const char* type) {
	if(!fastmode) {
		if(!send_interface || !send_interface->connection) return -1;
		
		GObject* data_object = g_object_new(G_TYPE_OBJECT, NULL);
		g_object_set_data(data_object, "Status", "Buffered");
		g_object_set_data(data_object, "Device1", send_interface->parent_device->name);
		g_object_set_data(data_object, "Device2", send_interface == send_interface->connection->interface1 ?
						  send_interface->connection->interface2->parent_device->name :
						  send_interface->connection->interface1->parent_device->name);
		char* data_buffer = malloc_or_abort(data_len);
		memcpy(data_buffer, send_data, data_len);
		g_object_set_data_full(data_object, "Data", data_buffer, free);

		int* size_buffer = malloc_or_abort(sizeof(int));
		*size_buffer = data_len;
		g_object_set_data_full(data_object, "Size", size_buffer, free);

		// @todo this is not freed now
		int* timestamp_buffer = malloc_or_abort(sizeof(unsigned long));
		*timestamp_buffer = 0;
		g_object_set_data(data_object, "Timestamp", timestamp_buffer);
		
		g_object_set_data(data_object, "Type", (char*)type);

		g_list_store_append(packet_list_store, data_object);
		int index = g_list_model_get_n_items(G_LIST_MODEL(packet_list_store))-1;
		
		return index;
	} else return 0;
}
// === Called by the connection when it sends a frame
void gui_con_send(struct connection* con, int send_side) {
	// Don't add the packet to the gui when we are in fast mode
	if(!fastmode) {
		struct interface* inter = (send_side == 1) ? con->interface1 : con->interface2;
		int gui_index = inter->start_queue->gui_index;
		GObject* data_object = g_list_model_get_object(G_LIST_MODEL(packet_list_store), gui_index);

		g_object_set_data(data_object, "Status", "Sent");
		*(int*)g_object_get_data(data_object, "Timestamp") = timestamp;
	}
}

// Called by the timestep function when a timestep is done and the gui should take action accordingly
void gui_timestep(unsigned long timestamp, struct timestep_entry_ll* sent_entries) {
	if(!fastmode)
		// If we are not in fastmode we clean drawing packets every time we step forward
		clean_draw();
	if(!sent_entries)
		return;
	if(!drawing_entries) {
		drawing_entries = sent_entries;
	} else {
		// Append sent_entries
		struct timestep_entry_ll* last_entry;
		LL_LAST(drawing_entries, last_entry);
		if(last_entry) {
			last_entry->next = sent_entries;
			// And make the last first entry in sent_entries point to the last entry so we gat a nice doubly linked list
			sent_entries->prev = last_entry;
		}
		if(sent_entries->send_timestamp != drawing_entries->send_timestamp)
			drawing_entries = sent_entries;
	}
	// If we are in fastmode add a very short timer for every update
   	gtk_widget_queue_draw(main_drawing_area);
	// Check before timeout
	// In fastmode remove the packets after some time
	if(fastmode)
		g_timeout_add_full(
						   G_PRIORITY_DEFAULT,
						   75,
						   clean_draw,
						   NULL,
						   NULL
						   );
}

void update_zoom(GtkWidget* self, const int* change) {
	if(change) {
		area_scale += *change;
		if(area_scale < 1) area_scale = 1;
		if(area_scale > 1000) area_scale = 1000;
	}
	// @todo update drawing area content width accordingly
	char scale_text[6];
	sprintf(scale_text, "%d%%", area_scale%1000);
	gtk_label_set_text(GTK_LABEL(zoom_label), scale_text);
	gtk_widget_queue_draw(main_drawing_area);
}

// === Called when a packet in the list is selected
void packet_selected(GtkColumnView* self, int position, gpointer user_data) {
	GObject* data_object = g_list_model_get_object(G_LIST_MODEL(packet_list_store)
												   , position);
	char* data = g_object_get_data(data_object, "Data");
	char* data_type = g_object_get_data(data_object, "Type");
	int* data_size = g_object_get_data(data_object, "Size");
	
	show_packet_window(*data_size, data, data_type);
}

void forward_timestep(GtkButton* self, gpointer user_data) {
	simulation_timestep(NULL);
}

void rewind_timestep(GtkButton* self, gpointer user_data) {
	if(!drawing_entries || fastmode) return;
	// First stop playback
	gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(play_button), false);
	// Move drawing entries back to the last timestep
	unsigned long cur_timestamp = drawing_entries->send_timestamp;
	while(drawing_entries->prev && drawing_entries->send_timestamp >= cur_timestamp)
		drawing_entries = drawing_entries->prev;
	// Rewing to the beginning of the previous timestamp
	cur_timestamp = drawing_entries->send_timestamp;
	while(drawing_entries->prev && drawing_entries->prev->send_timestamp == cur_timestamp)
		drawing_entries = drawing_entries->prev;
	// Redraw the area
	gtk_widget_queue_draw(main_drawing_area);
	sidebar_select_current();
}

void save_response(GObject* save_dialog, GAsyncResult* res, gpointer data) {
	GFile* result_file = gtk_file_dialog_save_finish (GTK_FILE_DIALOG(save_dialog),
													  res,
													  NULL);
	if(result_file) {
		if(save_path)
			g_free(save_path);
		save_path = g_file_get_path(result_file);
		g_object_unref(result_file);
		if(save_path) {
			//@todo: check for errors when saving
			save_file(save_path);
			printf("Saved to\n");
			g_free(save_path);
		}
		actions_since_save = 0;
		
	}
	gtk_widget_queue_draw(main_drawing_area);
}

void gui_save_as_action(GSimpleAction* self, GVariant* parameter, gpointer user_data) {
	GtkFileDialog* save_dialog = gtk_file_dialog_new();
	gtk_file_dialog_save(save_dialog, GTK_WINDOW(window), NULL, save_response, NULL);
}

void gui_save_action(GSimpleAction* self, GVariant* parameter, gpointer user_data) {
	if(save_path) {
		save_file(save_path);
		actions_since_save = 0;
	} else {
		gui_save_as_action(self, parameter, user_data);
	}
}

void load_response(GObject* load_dialog, GAsyncResult* res, gpointer data) {
	GFile* result_file = gtk_file_dialog_open_finish (GTK_FILE_DIALOG(load_dialog),
													  res,
													  NULL);
	if(result_file) {
		// Free all devices
		for(struct device* cur_dev = start_device; cur_dev;) {
			struct device* free_dev = cur_dev;
			cur_dev = cur_dev->next;
			delete_device(&start_device, free_dev);
			free_device(free_dev);
		}
		// Free all undo actions
		free_all_undo();
		actions_since_save = 0;
		free_selection(selected_devices);
		selected_devices = NULL;
		
		if(save_path)
			g_free(save_path);
		save_path = g_file_get_path(result_file);
		g_object_unref(result_file);
		load_file(save_path);
	}
	gtk_widget_queue_draw(main_drawing_area);
}
void do_load() {
	GtkFileDialog* load_dialog = gtk_file_dialog_new();
	gtk_file_dialog_set_filters(load_dialog, G_LIST_MODEL(file_filter_list));
	gtk_file_dialog_open(load_dialog, GTK_WINDOW(window), NULL, load_response, NULL);
}
void load_yn_response(GObject* self, GAsyncResult* response_id, gpointer data) {
	int result = gtk_alert_dialog_choose_finish(GTK_ALERT_DIALOG(self), response_id, NULL);
	if(result == 0)
		do_load();
}
void gui_load_action(GSimpleAction* self, GVariant* parameter, gpointer user_data) {
	// File filter for only allowing json files
	if(actions_since_save > 0) {
		GtkAlertDialog* load_yn_dialog = gtk_alert_dialog_new("You made changes since you last saved, do you really want to load another file and overwrite those changes?");
		gtk_alert_dialog_set_buttons(load_yn_dialog, (const char*[]){"Yes", "No", NULL});
		gtk_alert_dialog_set_cancel_button(load_yn_dialog, 1);
		gtk_alert_dialog_choose(load_yn_dialog, GTK_WINDOW(window), NULL, load_yn_response, NULL);
	} else
		// No changes have been made, just load
		do_load();
}

void gui_undo_action(GSimpleAction* self, GVariant* parameter, gpointer user_data) {
	undo();
	gtk_widget_queue_draw(main_drawing_area);
}

void gui_redo_action(GSimpleAction* self, GVariant* parameter, gpointer user_data) {
	redo();
	gtk_widget_queue_draw(main_drawing_area);
}

// Ask the user if he wants to close without saving
void close_yn_response(GObject* self, GAsyncResult* response_id, gpointer data) {
	int result = gtk_alert_dialog_choose_finish(GTK_ALERT_DIALOG(self), response_id, NULL);
	if(result == 0)
		// I don't know why this won't just accept a normal gtk_window_close...
		gtk_application_remove_window(gtk_window_get_application(GTK_WINDOW(window)), GTK_WINDOW(window));
}

bool gui_close(GtkWindow* window) {
	if(actions_since_save) {
		GtkAlertDialog* close_yn_dialog = gtk_alert_dialog_new("You made changes since you last saved, do you really want to close the application?");
		gtk_alert_dialog_set_buttons(close_yn_dialog, (const char*[]){"Yes", "No", NULL});
		gtk_alert_dialog_set_cancel_button(close_yn_dialog, 1);
		gtk_alert_dialog_choose(close_yn_dialog, GTK_WINDOW(window), NULL, close_yn_response, NULL);
		return true;
	}
	return false;
}

void gui_select_all_action(GSimpleAction* self, GVariant* parameter, gpointer user_data) {
	free_selection(selected_devices);
	selected_devices = get_device_at(0, 0, gtk_drawing_area_get_content_width(GTK_DRAWING_AREA(main_drawing_area)), gtk_drawing_area_get_content_height(GTK_DRAWING_AREA(main_drawing_area)));
	gtk_widget_queue_draw(main_drawing_area);
}

void draw_area_print(GtkPrintOperation* self,
					 GtkPrintContext* context,
					 gint page_nr,
					 gpointer user_data) {
	cairo_t* cr = gtk_print_context_get_cairo_context(context);

	int my_width = gtk_drawing_area_get_content_width(GTK_DRAWING_AREA(main_drawing_area));
	int my_height = gtk_drawing_area_get_content_height(GTK_DRAWING_AREA(main_drawing_area));

	int pr_width = gtk_print_context_get_width(context);
	int pr_height = gtk_print_context_get_height(context);

	double scale_w = (double)pr_width / (double)my_width;
	double scale_h = (double)pr_height / (double)my_height;
	
	if(scale_h < scale_w)
		cairo_scale(cr, scale_h, scale_h);
	else
		cairo_scale(cr, scale_w, scale_w);
	
	gtk_widget_queue_draw(GTK_WIDGET(main_drawing_area));
	
}

void gui_print_action(GSimpleAction* self, GVariant* parameter, gpointer user_data) {
	GtkPrintOperation* printop = gtk_print_operation_new();
	gtk_print_operation_set_embed_page_setup(printop, true);
	gtk_print_operation_set_n_pages(printop, 1);
	g_signal_connect(G_OBJECT(printop), "draw-page", G_CALLBACK(draw_area_print), NULL);
	gtk_print_operation_run(printop, GTK_PRINT_OPERATION_ACTION_PRINT_DIALOG, GTK_WINDOW(window), NULL);
}

void gui_toggle_interface_nums_action(GSimpleAction* action, GVariant* value, gpointer user_data) {
	GVariant* new_state = g_variant_new_boolean(!g_variant_get_boolean(g_action_get_state(G_ACTION(action))));
	g_simple_action_set_state(action, new_state);
	gtk_widget_queue_draw(main_drawing_area);
}

void gui_reload_templates(GSimpleAction* action, GVariant* value, gpointer user_data) {
	reload_templates();
}

void packet_list_item_text_factory_bind(GtkSignalListItemFactory* self, GObject* object, gpointer user_data) {
	gtk_list_item_set_child(GTK_LIST_ITEM(object), gtk_label_new(g_object_get_data(gtk_list_item_get_item(GTK_LIST_ITEM(object)), user_data)));
}


GtkListItemFactory* packet_list_string_data_factory_new(char* key) {
	GtkListItemFactory* new_factory = gtk_signal_list_item_factory_new();
	g_signal_connect(G_OBJECT(new_factory), "bind", G_CALLBACK(packet_list_item_text_factory_bind), key);
	return new_factory;
}

void packet_list_item_int_factory_bind(GtkSignalListItemFactory* self, GObject* object, gpointer user_data) {
	char text[16] = "";
	sprintf(text, "%d", *(int*)g_object_get_data(gtk_list_item_get_item(GTK_LIST_ITEM(object)), user_data));
	gtk_list_item_set_child(GTK_LIST_ITEM(object), gtk_label_new(text));
}

GtkListItemFactory* packet_list_int_data_factory_new(char* key) {
	GtkListItemFactory* new_factory = gtk_signal_list_item_factory_new();
	g_signal_connect(G_OBJECT(new_factory), "bind", G_CALLBACK(packet_list_item_int_factory_bind), key);
	return new_factory;
}

struct {
	uint32_t magic;
	uint16_t major_version;
	uint16_t minor_version;
	int32_t tc_correction;
	uint32_t timeacc;
	uint32_t snaplen;
	uint32_t ll_type;
} pcap_header = {
	0xa1b2c3d4,
	2,4,
	0,
	0,
	UINT32_MAX,
	1 // Ethernet
};

struct pcap_packet_header {
	uint32_t sec;
	uint32_t used;
	// in this case these should always be the same
	uint32_t ilen;
	uint32_t olen;
};

void pcap_save_response(GObject* pcap_save_dialog, GAsyncResult* res, gpointer data) {

	GFile* result_file = gtk_file_dialog_save_finish (GTK_FILE_DIALOG(pcap_save_dialog),
													  res,
													  NULL);
	if(result_file) {
		char* pcap_filename = g_file_get_path(result_file);
		g_object_unref(result_file);
		if(pcap_filename) {
			int packet_n = g_list_model_get_n_items(G_LIST_MODEL(packet_list_store));
			FILE* pcap_file = fopen(pcap_filename, "w");
			fwrite(&pcap_header, sizeof(pcap_header), 1, pcap_file);
			for(int i = 0; i < packet_n; i++) {
				GObject* data_object = g_list_model_get_object(G_LIST_MODEL(packet_list_store), i);
				struct pcap_packet_header current_header = {
					*(uint32_t*)g_object_get_data(data_object, "Timestamp"),
					0,
					*(uint32_t*)g_object_get_data(data_object, "Size")-8,
					*(uint32_t*)g_object_get_data(data_object, "Size")-8
				};
				if(current_header.ilen < 0) {
					fprintf(stderr, "Packet size too small!\n");
					return;
				}
				fwrite(&current_header, sizeof(struct pcap_packet_header), 1, pcap_file);
				fwrite((char*)g_object_get_data(data_object, "Data")+8, current_header.ilen, 1, pcap_file);
			}
			printf("Exported PCAP\n");
			fclose(pcap_file);
			g_free(pcap_filename);
		}
	}
	
}

void export_pcap(GtkButton* self, gpointer user_data) {
	GtkFileDialog* save_dialog = gtk_file_dialog_new();
	gtk_file_dialog_save(save_dialog, GTK_WINDOW(window), NULL, pcap_save_response, NULL);
}

/*
 * ====== GTK INITIALIZATION ======
 */
extern int sim_flag;
void activate_main_window(GtkApplication* app, gpointer user_data) {
	// Initialize filter list
	file_filter_list = g_list_store_new(GTK_TYPE_FILE_FILTER);
	GtkFileFilter* json_filter = gtk_file_filter_new();
	gtk_file_filter_add_suffix(json_filter, "json");
	gtk_file_filter_set_name(json_filter, "JSON");
	g_list_store_append(file_filter_list, json_filter);
	GtkFileFilter* all_filter = gtk_file_filter_new();
	gtk_file_filter_add_pattern(all_filter, "*");
	gtk_file_filter_set_name(all_filter, "ALL");
	g_list_store_append(file_filter_list, all_filter);	
	
	window = gtk_application_window_new(app);
	// Needed for gui_packet
	GtkCssProvider* css_prov = gtk_css_provider_new();
	gtk_css_provider_load_from_string(css_prov, ".frame_no_left { border-left-style: dotted; }\n\
.frame_no_right { border-right-style: dotted; }\n\
.data_frame { border-radius: 0px; border-width: 2px; margin: -1px; }");
	gtk_style_context_add_provider_for_display(gdk_display_get_default(),
											   GTK_STYLE_PROVIDER(css_prov),
											   GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
	
	gtk_window_set_title(GTK_WINDOW(window), "Netsim");
	gtk_window_set_default_size(GTK_WINDOW(window), 1000, 750);

	g_signal_connect(G_OBJECT(window), "close_request", G_CALLBACK(gui_close), NULL);
	
	// Actions
	const GActionEntry netsim_actions[] = {
		// File menu entries
		{ "undo", gui_undo_action, NULL, NULL, NULL},
		{ "redo", gui_redo_action, NULL, NULL, NULL},
		{ "save", gui_save_action, NULL, NULL, NULL },
		{ "save-as", gui_save_as_action, NULL, NULL ,NULL},
		{ "load", gui_load_action, NULL, NULL, NULL},
		{ "select-all", gui_select_all_action, NULL, NULL, NULL},
		{ "print", gui_print_action, NULL, NULL, NULL },
		// View menu entries
		{ "toggle-interface-nums", gui_toggle_interface_nums_action, NULL, "true", NULL},
		// Dev menu entries
	    { "reload-templates", gui_reload_templates, NULL, NULL, NULL}
	};
	g_action_map_add_action_entries(G_ACTION_MAP(window), netsim_actions, G_N_ELEMENTS(netsim_actions), NULL);
	
	// Create the main box
	GtkWidget* window_box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 2);
	gtk_window_set_child(GTK_WINDOW(window), window_box);

	// Create the menu bar
	GMenu* file_menu = g_menu_new();
	
	g_menu_append(G_MENU(file_menu), "Undo", "win.undo");
	g_menu_append(G_MENU(file_menu), "Redo", "win.redo");
	g_menu_append(G_MENU(file_menu), "Save", "win.save");
	g_menu_append(G_MENU(file_menu), "Save As", "win.save-as");
	g_menu_append(G_MENU(file_menu), "Load", "win.load");
	g_menu_append(G_MENU(file_menu), "Print", "win.print");

	GMenu* view_menu = g_menu_new();

	g_menu_append(G_MENU(view_menu), "Show interface indexes", "win.toggle-interface-nums");

	GMenu* dev_menu = g_menu_new();
	g_menu_append(G_MENU(dev_menu), "Reload Templates", "win.reload-templates");

	struct {
		const char* action;
		const char* keys[2];
	} shortcuts[] = {
		{"win.undo", { "<Control>z", NULL }},
		{"win.redo", { "<Control>r", NULL }},
		{"win.save", { "<Control>s", NULL }},
		{"win.save-as", { "<Control><Shift>s", NULL }},
		{"win.load", { "<Control>o", NULL }},
		{"win.select-all", {"<Control>a", NULL}},
		{"win.print", {"<Control>p", NULL}},
		{"win.toggle-interface-nums", {"<Control>i", NULL}},
		{NULL, {NULL}}
	};

	for(int i = 0; shortcuts[i].action; i++) {
		gtk_application_set_accels_for_action(app, shortcuts[i].action, shortcuts[i].keys);
	}
	
	GMenu* menu_bar_menu = g_menu_new();
	g_menu_append_submenu(G_MENU(menu_bar_menu), "File", G_MENU_MODEL(file_menu));
	g_menu_append_submenu(G_MENU(menu_bar_menu), "View", G_MENU_MODEL(view_menu));
	g_menu_append_submenu(G_MENU(menu_bar_menu), "Development", G_MENU_MODEL(dev_menu));
	
	GtkWidget* menu_bar = gtk_popover_menu_bar_new_from_model(G_MENU_MODEL(menu_bar_menu));
	gtk_box_append(GTK_BOX(window_box), menu_bar);

	// Add a toolbar to the top of the window
	GtkWidget* toolbar_box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 3);
	gtk_box_append(GTK_BOX(window_box), toolbar_box);

	// Create the button for the different modes
	static struct {
		int mode;
		char* tooltip;
		char* icon_name;
		GtkWidget** button;
	} toolbar_buttons[] = {
		{MODE_MOVE, "Move mode", "edit-select-all-symbolic", &move_button},
		{MODE_DELETE, "Delete mode", "edit-delete-symbolic", &delete_button},
		{MODE_NEW_RECT, "New Rectangle", "media-playback-stop-symbolic", &rect_button },
		{MODE_NEW_CIRCLE, "New Circle", "media-record-symbolic", &circle_button },
		{MODE_NEW_TEXT, "Text mode", "insert-text-symbolic", &text_button},
		{0, NULL, NULL, NULL}
	};

	for(int i = 0; toolbar_buttons[i].button; i++) {
		GtkWidget* button = gtk_toggle_button_new();
		gtk_box_append(GTK_BOX(toolbar_box), button);
		gtk_button_set_icon_name(GTK_BUTTON(button), toolbar_buttons[i].icon_name);
		gtk_widget_set_tooltip_text(button, toolbar_buttons[i].tooltip);
		g_signal_connect(G_OBJECT(button), "toggled", G_CALLBACK(toolbar_toggle), &(toolbar_buttons[i].mode));
		gtk_toggle_button_set_group(GTK_TOGGLE_BUTTON(button), GTK_TOGGLE_BUTTON(*(toolbar_buttons[0].button)));
		*(toolbar_buttons[i].button) = button;
	}
	
	// Create a vertical split
	// We need two panes becaus panes can only have one split
	GtkWidget* main_pane = gtk_paned_new(GTK_ORIENTATION_HORIZONTAL);
	gtk_box_append(GTK_BOX(window_box), main_pane);
	gtk_paned_set_position(GTK_PANED(main_pane), 300);
	gtk_paned_set_wide_handle(GTK_PANED(main_pane), true);
	gtk_widget_set_vexpand(main_pane, true);
	// Create the second pane
	GtkWidget* right_pane = gtk_paned_new(GTK_ORIENTATION_HORIZONTAL);
	gtk_paned_set_end_child(GTK_PANED(main_pane), right_pane);
	gtk_paned_set_position(GTK_PANED(right_pane), 500);
	gtk_paned_set_wide_handle(GTK_PANED(right_pane), true);
	gtk_widget_set_vexpand(right_pane, true);

	// Create the left Box
	GtkWidget* left_box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 4);
	gtk_paned_set_start_child(GTK_PANED(main_pane), left_box);

	// Create a Stack Switcher
	GtkWidget* stack_switcher = gtk_stack_switcher_new();
	gtk_box_append(GTK_BOX(left_box), stack_switcher);
	// Create the stack for the stack sidebar
	GtkWidget* sidebar_stack = gtk_stack_new();
	gtk_widget_set_vexpand(sidebar_stack, true);
	gtk_box_append(GTK_BOX(left_box), sidebar_stack);
	
	// Attach the stack to the stack switcher
	gtk_stack_switcher_set_stack(GTK_STACK_SWITCHER(stack_switcher), GTK_STACK(sidebar_stack));
	
	device_view = gtk_flow_box_new();
	gtk_flow_box_set_activate_on_single_click(GTK_FLOW_BOX(device_view), true);
	gtk_flow_box_set_selection_mode(GTK_FLOW_BOX(device_view), GTK_SELECTION_SINGLE);
	gtk_flow_box_set_homogeneous(GTK_FLOW_BOX(device_view), true);
	
	for(int i = 0; i < device_template_n; i++) {
		GtkWidget* device_template_box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
		gtk_box_set_homogeneous(GTK_BOX(device_template_box), true);
		gtk_widget_set_valign(device_template_box, GTK_ALIGN_CENTER);
		
		GtkWidget* device_template_icon = gtk_image_new_from_file(device_templates[i].icon_path);
		gtk_image_set_pixel_size(GTK_IMAGE(device_template_icon), device_templates[i].icon_size);
		GtkWidget* device_template_label = gtk_label_new(device_templates[i].name);

		gtk_box_append(GTK_BOX(device_template_box), device_template_icon);
		gtk_box_append(GTK_BOX(device_template_box), device_template_label);

		gtk_flow_box_append(GTK_FLOW_BOX(device_view), device_template_box);
	}
	
	g_signal_connect(G_OBJECT(device_view), "child-activated", G_CALLBACK(select_device_template), NULL);
	
	// Create a scrolled window to put the selection into
	GtkWidget* device_view_scroll = gtk_scrolled_window_new();
	gtk_scrolled_window_set_child(GTK_SCROLLED_WINDOW(device_view_scroll), device_view);

	gtk_widget_set_vexpand(device_view_scroll, false);
	gtk_widget_set_vexpand_set(device_view_scroll, true);
	// Add everything to the stack
	gtk_stack_add_titled(GTK_STACK(sidebar_stack), device_view_scroll, NULL, "Devices");

	// === Create the connections tab
	
	connection_view = gtk_flow_box_new();
	gtk_flow_box_set_activate_on_single_click(GTK_FLOW_BOX(device_view), true);
	gtk_flow_box_set_selection_mode(GTK_FLOW_BOX(device_view), GTK_SELECTION_SINGLE);
	gtk_flow_box_set_homogeneous(GTK_FLOW_BOX(connection_view), true);
	
	for(int i = 0; i < connection_template_n; i++) {
		GtkWidget* connection_template_box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
		gtk_box_set_homogeneous(GTK_BOX(connection_template_box), true);
		gtk_widget_set_valign(connection_template_box, GTK_ALIGN_CENTER);
		// Create a pixbuf with the right color
		GdkPixbuf* connection_icon = gdk_pixbuf_new(GDK_COLORSPACE_RGB, false, 8, 16, 16);
		uint32_t color = 0;
		for(int j = 0; j < 3; j++) {
			// Move previous byte to the left
			// Every color component is a value from 0 to 1, so multiply by 255 to get the single byte representation
			color = color | ((uint32_t)(connection_templates[i].color[j] * 255) & 0xFF);
			color = color << 8;
		}
		gdk_pixbuf_fill(connection_icon, color);
		GtkWidget* connection_template_icon = gtk_image_new_from_paintable(GDK_PAINTABLE(gdk_texture_new_for_pixbuf(connection_icon)));
		GtkWidget* connection_template_label = gtk_label_new(connection_templates[i].name);

		gtk_box_append(GTK_BOX(connection_template_box), connection_template_icon);
		gtk_box_append(GTK_BOX(connection_template_box), connection_template_label);

		gtk_flow_box_append(GTK_FLOW_BOX(connection_view), connection_template_box);
	}

	g_signal_connect(G_OBJECT(connection_view), "child-activated", G_CALLBACK(select_connection_template), NULL);

	
	// Scroll window
	GtkWidget* connection_view_scroll = gtk_scrolled_window_new();
	gtk_scrolled_window_set_child(GTK_SCROLLED_WINDOW(connection_view_scroll), connection_view);
	// Add to the stack
	gtk_stack_add_titled(GTK_STACK(sidebar_stack), connection_view_scroll, NULL, "Connections");

	// === Packet details
	// Create a tree view
	GtkWidget* packet_tree_scroll = gtk_scrolled_window_new();
	//packet_tree = gtk_tree_view_new_with_model(GTK_TREE_MODEL(packet_list));
	packet_list_store = g_list_store_new(G_TYPE_OBJECT);

	GtkSingleSelection* packet_list_selection = gtk_single_selection_new(G_LIST_MODEL(packet_list_store));
	
	packet_tree = gtk_column_view_new(GTK_SELECTION_MODEL(packet_list_selection));
	gtk_column_view_set_single_click_activate(GTK_COLUMN_VIEW(packet_tree), true);
	gtk_scrolled_window_set_child(GTK_SCROLLED_WINDOW(packet_tree_scroll), packet_tree);
	g_signal_connect(G_OBJECT(packet_tree), "activate", G_CALLBACK(packet_selected), NULL);

	gtk_column_view_append_column(GTK_COLUMN_VIEW(packet_tree), gtk_column_view_column_new("T", packet_list_int_data_factory_new("Timestamp")));
	gtk_column_view_append_column(GTK_COLUMN_VIEW(packet_tree), gtk_column_view_column_new("Status", packet_list_string_data_factory_new("Status")));
	gtk_column_view_append_column(GTK_COLUMN_VIEW(packet_tree), gtk_column_view_column_new("Device1", packet_list_string_data_factory_new("Device1")));
	gtk_column_view_append_column(GTK_COLUMN_VIEW(packet_tree), gtk_column_view_column_new("Device2", packet_list_string_data_factory_new("Device2")));

	gtk_column_view_append_column(GTK_COLUMN_VIEW(packet_tree), gtk_column_view_column_new("Protocols", packet_list_string_data_factory_new("Type")));
	
	gtk_column_view_append_column(GTK_COLUMN_VIEW(packet_tree), gtk_column_view_column_new("Size", packet_list_int_data_factory_new("Size")));

	packet_list_box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
	gtk_widget_set_vexpand(packet_tree_scroll, true);
	gtk_box_append(GTK_BOX(packet_list_box), packet_tree_scroll);

	GtkWidget* pcap_export_button = gtk_button_new_with_label("Export to PCAP file");
	gtk_box_append(GTK_BOX(packet_list_box), pcap_export_button);
	g_signal_connect(G_OBJECT(pcap_export_button), "clicked", G_CALLBACK(export_pcap), NULL);
	
	gtk_paned_set_end_child(GTK_PANED(right_pane), packet_list_box);

	// === Create the time controls
	// There will be two different types of the simulation, fast and step
	// In fast mode once one simulation cycle finishes we instantly move on
	// in step mode we wait for the user to skip to the next timestep or for a timer to run out

	// Create the play/pause next and previous button for the step controls
	rewind_button = gtk_button_new();
	gtk_button_set_icon_name (GTK_BUTTON(rewind_button), "go-previous-symbolic");
	g_signal_connect(G_OBJECT(rewind_button), "clicked", G_CALLBACK(rewind_timestep), NULL);

	play_button = gtk_toggle_button_new();
	gtk_button_set_icon_name (GTK_BUTTON(play_button), "media-playback-start-symbolic");
	g_signal_connect(G_OBJECT(play_button), "toggled", G_CALLBACK(toggle_play), NULL);

	forward_button = gtk_button_new();
	gtk_button_set_icon_name (GTK_BUTTON(forward_button), "go-next-symbolic");
	g_signal_connect(G_OBJECT(forward_button), "clicked", G_CALLBACK(forward_timestep), NULL);

	// The buttons are added to the gui below
	GtkWidget* time_mode_box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 4);
	gtk_box_set_homogeneous(GTK_BOX(time_mode_box), true);
	GtkWidget* fast_toggle_button = gtk_toggle_button_new_with_label("Fast");
	// The signal is connected at the end of this function so everything gets set up in the right mode
	// Toggle on fast mode when this button is clicked
	g_signal_connect(G_OBJECT(fast_toggle_button), "toggled", G_CALLBACK(toggle_fast_mode), NULL);
	
	GtkWidget* step_toggle_button = gtk_toggle_button_new_with_label("Step");
	g_signal_connect(G_OBJECT(step_toggle_button), "toggled", G_CALLBACK(toggle_step_mode), NULL);
	gtk_toggle_button_set_group(GTK_TOGGLE_BUTTON(step_toggle_button), GTK_TOGGLE_BUTTON(fast_toggle_button));

	// Add the buttons to the box
	gtk_box_append(GTK_BOX(time_mode_box), fast_toggle_button);
	gtk_box_append(GTK_BOX(time_mode_box), step_toggle_button);
	gtk_box_append(GTK_BOX(left_box), time_mode_box);

	GtkWidget* step_control_box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 4);
	gtk_box_set_homogeneous(GTK_BOX(step_control_box), true);

	gtk_box_append(GTK_BOX(step_control_box), rewind_button);
	gtk_box_append(GTK_BOX(step_control_box), play_button);
	gtk_box_append(GTK_BOX(step_control_box), forward_button);
	gtk_box_append(GTK_BOX(left_box), step_control_box);

	// Add a speed slider during simulation mode
	speed_slider = gtk_scale_new_with_range(GTK_ORIENTATION_HORIZONTAL, 1, 1000, 1);
	gtk_range_set_value(GTK_RANGE(speed_slider), interval_play);
	g_signal_connect(G_OBJECT(speed_slider), "value-changed", G_CALLBACK(change_step_speed), NULL);
	gtk_box_append(GTK_BOX(left_box), speed_slider);
	
	// Create the right container
	GtkWidget* right_box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 2);
	gtk_paned_set_start_child(GTK_PANED(right_pane), right_box);
	// Use a scrolling window to be able to move around in the drawing area
	// This will be the main application window where drawin happens
	GtkWidget* draw_scroll_window = gtk_scrolled_window_new();
	gtk_box_append(GTK_BOX(right_box), draw_scroll_window);
	// Add a drawing area to the scrolled window
	main_drawing_area = gtk_drawing_area_new();
	gtk_widget_set_vexpand(main_drawing_area, true);
	gtk_drawing_area_set_draw_func(GTK_DRAWING_AREA(main_drawing_area), update_main_drawing_area, NULL, NULL);
	gtk_drawing_area_set_content_width (GTK_DRAWING_AREA (main_drawing_area), 1000);
	gtk_drawing_area_set_content_height (GTK_DRAWING_AREA (main_drawing_area), 1000);
	// Handle mouse events for the drawing area
	GtkGesture* drawing_area_click_controller = gtk_gesture_click_new();
	g_signal_connect(G_OBJECT(drawing_area_click_controller), "pressed", G_CALLBACK(drawing_area_click), NULL);
	g_signal_connect(G_OBJECT(drawing_area_click_controller), "released", G_CALLBACK(drawing_area_release), NULL);
	gtk_widget_add_controller(main_drawing_area, GTK_EVENT_CONTROLLER(drawing_area_click_controller));
	// Handle keyboard events fot the drawing area
	GtkEventController* drawing_area_key_controller = gtk_event_controller_key_new();
	g_signal_connect(G_OBJECT(drawing_area_key_controller), "key-pressed", G_CALLBACK(drawing_area_key), NULL);
	gtk_widget_add_controller(window, GTK_EVENT_CONTROLLER(drawing_area_key_controller));
	// Handle mouse movement inside the drawing area
	GtkEventController* drawing_area_motion_controller = gtk_event_controller_motion_new();
	g_signal_connect(G_OBJECT(drawing_area_motion_controller), "motion", G_CALLBACK(drawing_area_motion), NULL);
	gtk_widget_add_controller(main_drawing_area, GTK_EVENT_CONTROLLER(drawing_area_motion_controller));
	// Set the drawing area as child for the scrolling window
	// Add a viewport around the drawing area
	GtkWidget* drawing_area_viewport = gtk_viewport_new(NULL, NULL);
	gtk_viewport_set_scroll_to_focus(GTK_VIEWPORT(drawing_area_viewport), false);
	gtk_viewport_set_child(GTK_VIEWPORT(drawing_area_viewport), main_drawing_area);
	gtk_scrolled_window_set_child(GTK_SCROLLED_WINDOW(draw_scroll_window), drawing_area_viewport);

	// Add a box at the bottom for label indicator and zomm
	GtkWidget* bottom_box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 2);
	gtk_box_append(GTK_BOX(right_box), bottom_box);
	
	// Add a label indicating the mode we are in
	mode_label = gtk_label_new("");
	gtk_widget_set_hexpand(mode_label, true);
	update_mode();
	gtk_box_append(GTK_BOX(bottom_box), mode_label);
	
	// Add a button to zoom out
	GtkWidget* zoom_out_btn = gtk_button_new_with_label("-");
	gtk_box_append(GTK_BOX(bottom_box), zoom_out_btn);
	static int zoom_out_ammount = -5;
	g_signal_connect(G_OBJECT(zoom_out_btn), "clicked", G_CALLBACK(update_zoom), &zoom_out_ammount);
	// Add a label for the zoom level
	zoom_label = gtk_label_new(NULL);
	update_zoom(NULL, NULL);
	gtk_box_append(GTK_BOX(bottom_box), zoom_label);
	// Add a button to zoom in
	GtkWidget* zoom_in_btn = gtk_button_new_with_label("+");
	gtk_box_append(GTK_BOX(bottom_box), zoom_in_btn);
	static int zoom_in_ammount = 5;
	g_signal_connect(G_OBJECT(zoom_in_btn), "clicked", G_CALLBACK(update_zoom), &zoom_in_ammount);

	if(sim_flag)
		gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(step_toggle_button), true);
	else
		// Switch to fast mode
		gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(fast_toggle_button), true);

	
	// Show the window
	gtk_widget_set_visible(window, true);
}
Jeremias Stotters git repositories generated by CGIT