summaryrefslogtreecommitdiff
path: root/src/services/workspaces/hyprland-workspace-service.c
blob: 3abe1529956e2e4a973a154b8ab6c10fed2c4523 (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
#include "services/workspaces/hyprland-workspace-service.h"
#include <json-glib/json-glib.h>
#include <gtk/gtk.h>
#include <string.h>

typedef struct _EventData    EventData;
typedef struct _EventHandler EventHandler;

//
// FoobarHyprlandWorkspace:
//
// Representation of a workspace in Hyprland.
//

#define FOOBAR_TYPE_HYPRLAND_WORKSPACE foobar_hyprland_workspace_get_type( )

G_DECLARE_FINAL_TYPE( FoobarHyprlandWorkspace, foobar_hyprland_workspace, FOOBAR, HYPRLAND_WORKSPACE, GObject )

struct _FoobarHyprlandWorkspace
{
	GObject                         parent_instance;
	FoobarHyprlandWorkspaceService* service;
	gint64                          id;
	gchar*                          name;
	gchar*                          monitor;
	FoobarWorkspaceFlags            flags;
};

enum
{
	WORKSPACE_PROP_ID = 1,
	WORKSPACE_PROP_NAME,
	WORKSPACE_PROP_MONITOR,
	WORKSPACE_PROP_FLAGS,
	N_WORKSPACE_PROPS,
};

static void                     foobar_hyprland_workspace_class_init    ( FoobarHyprlandWorkspaceClass*   klass );
static void                     foobar_hyprland_workspace_interface_init( FoobarWorkspaceInterface*       iface );
static void                     foobar_hyprland_workspace_init          ( FoobarHyprlandWorkspace*        self );
static void                     foobar_hyprland_workspace_get_property  ( GObject*                        object,
                                                                          guint                           prop_id,
                                                                          GValue*                         value,
                                                                          GParamSpec*                     pspec );
static void                     foobar_hyprland_workspace_finalize      ( GObject*                        object );
static FoobarHyprlandWorkspace* foobar_hyprland_workspace_new           ( FoobarHyprlandWorkspaceService* service );
static gint64                   foobar_hyprland_workspace_get_id        ( FoobarWorkspace*                self );
static gchar const*             foobar_hyprland_workspace_get_name      ( FoobarWorkspace*                workspace );
static gchar const*             foobar_hyprland_workspace_get_monitor   ( FoobarWorkspace*                workspace );
static FoobarWorkspaceFlags     foobar_hyprland_workspace_get_flags     ( FoobarWorkspace*                workspace );
static void                     foobar_hyprland_workspace_activate      ( FoobarWorkspace*                workspace );
static void                     foobar_hyprland_workspace_set_id        ( FoobarHyprlandWorkspace*        self,
                                                                          gint64                          value );
static void                     foobar_hyprland_workspace_set_name      ( FoobarHyprlandWorkspace*        self,
                                                                          gchar const*                    value );
static void                     foobar_hyprland_workspace_set_monitor   ( FoobarHyprlandWorkspace*        self,
                                                                          gchar const*                    value );
static void                     foobar_hyprland_workspace_set_flags     ( FoobarHyprlandWorkspace*        self,
                                                                          FoobarWorkspaceFlags            value );

G_DEFINE_TYPE_WITH_CODE(
	FoobarHyprlandWorkspace, foobar_hyprland_workspace, G_TYPE_OBJECT,
	G_IMPLEMENT_INTERFACE( FOOBAR_TYPE_WORKSPACE, foobar_hyprland_workspace_interface_init ) );

//
// FoobarHyprlandWorkspaceService:
//
// Service monitoring the workspaces provided by the window manager. This is implemented by communicating directly with
// Hyprland through its IPC socket.
//
// Based on the waybar implementation:
// https://github.com/Alexays/Waybar/blob/master/src/modules/hyprland/workspaces.cpp
//

struct _FoobarHyprlandWorkspaceService
{
	GObject           parent_instance;
	GListStore*       workspaces;
	GtkSortListModel* sorted_workspaces;
	GCancellable*     event_cancellable;
	GThread*          event_thread;
	gchar*            rx_path;
	gchar*            tx_path;
};

enum
{
	PROP_WORKSPACES = 1,
	N_PROPS,
};

static void                     foobar_hyprland_workspace_service_class_init                        ( FoobarHyprlandWorkspaceServiceClass* klass );
static void                     foobar_hyprland_workspace_service_interface_init                    ( FoobarWorkspaceServiceInterface*     iface );
static void                     foobar_hyprland_workspace_service_init                              ( FoobarHyprlandWorkspaceService*      self );
static void                     foobar_hyprland_workspace_service_get_property                      ( GObject*                             object,
                                                                                                      guint                                prop_id,
                                                                                                      GValue*                              value,
                                                                                                      GParamSpec*                          pspec );
static void                     foobar_hyprland_workspace_service_dispose                           ( GObject*                             object );
static void                     foobar_hyprland_workspace_service_finalize                          ( GObject*                             object );
static GListModel*              foobar_hyprland_workspace_service_get_workspaces                    ( FoobarWorkspaceService*              service );
static gboolean                 foobar_hyprland_workspace_service_is_available                      ( FoobarWorkspaceService*              service );
static gboolean                 foobar_hyprland_workspace_service_handle_workspace_created          ( EventData*                           data );
static gboolean                 foobar_hyprland_workspace_service_handle_workspace_destroyed        ( EventData*                           data );
static gboolean                 foobar_hyprland_workspace_service_handle_workspace_moved            ( EventData*                           data );
static gboolean                 foobar_hyprland_workspace_service_handle_workspace_renamed          ( EventData*                           data );
static gboolean                 foobar_hyprland_workspace_service_handle_workspace_activated        ( EventData*                           data );
static gboolean                 foobar_hyprland_workspace_service_handle_special_workspace_activated( EventData*                           data );
static gboolean                 foobar_hyprland_workspace_service_handle_monitor_focused            ( EventData*                           data );
static gboolean                 foobar_hyprland_workspace_service_handle_window_urgent              ( EventData*                           data );
static gboolean                 foobar_hyprland_workspace_service_handle_config_reloaded            ( EventData*                           data );
static gpointer                 foobar_hyprland_workspace_service_event_thread_func                 ( gpointer                             userdata );
static void                     foobar_hyprland_workspace_service_dispatch_event                    ( FoobarHyprlandWorkspaceService*      self,
                                                                                                      gchar*                               message );
static gchar*                   foobar_hyprland_workspace_service_send_request                      ( FoobarHyprlandWorkspaceService*      self,
                                                                                                      gchar const*                         request,
                                                                                                      GError**                             error );
static JsonNode*                foobar_hyprland_workspace_service_send_json_request                 ( FoobarHyprlandWorkspaceService*      self,
                                                                                                      gchar const*                         request,
                                                                                                      GError**                             error );
static void                     foobar_hyprland_workspace_service_initialize                        ( FoobarHyprlandWorkspaceService*      self );
static void                     foobar_hyprland_workspace_service_update_active                     ( FoobarHyprlandWorkspaceService*      self,
                                                                                                      GListStore*                          workspaces );
static void                     foobar_hyprland_workspace_service_add_workspace                     ( FoobarHyprlandWorkspaceService*      self,
                                                                                                      GListStore*                          workspaces,
                                                                                                      JsonObject*                          workspace_object,
                                                                                                      gboolean                             is_persistent );
static FoobarHyprlandWorkspace* foobar_hyprland_workspace_service_find_workspace                    ( GListModel*                          workspaces,
                                                                                                      gint64                               id,
                                                                                                      guint*                               out_index );
static gboolean                 foobar_hyprland_workspace_service_is_invalid_name                   ( gchar const*                         name );
static gint64                   foobar_hyprland_workspace_service_parse_id                          ( gchar const*                         str );
static gchar*                   foobar_hyprland_workspace_service_get_hyprland_base_path            ( void );
static gint                     foobar_hyprland_workspace_service_compare_ids                       ( gconstpointer                        a,
                                                                                                      gconstpointer                        b );


G_DEFINE_TYPE_WITH_CODE(
	FoobarHyprlandWorkspaceService, foobar_hyprland_workspace_service, G_TYPE_OBJECT,
	G_IMPLEMENT_INTERFACE( FOOBAR_TYPE_WORKSPACE_SERVICE, foobar_hyprland_workspace_service_interface_init ) );

//
// EventData:
//
// Custom userdata passed to hyprland event handlers in a single pointer.
//

struct _EventData
{
	FoobarHyprlandWorkspaceService* service;
	gchar*                          name;
	gchar*                          payload;
};

static EventData* event_data_new ( FoobarHyprlandWorkspaceService* service,
                                   gchar const*                    name,
                                   gchar const*                    payload );
static void       event_data_free( EventData*                      self );

//
// EventHandler:
//
// Description for the handler of a single hyprland event.
//

struct _EventHandler
{
	gchar const* name;
	gboolean ( *fn )( EventData* data );
};

//
// Static list of registered event handlers.
//
static EventHandler const event_handlers[] =
	{
		{ .name = "createworkspacev2",  .fn = foobar_hyprland_workspace_service_handle_workspace_created },
		{ .name = "destroyworkspacev2", .fn = foobar_hyprland_workspace_service_handle_workspace_destroyed },
		{ .name = "moveworkspacev2",    .fn = foobar_hyprland_workspace_service_handle_workspace_moved },
		{ .name = "renameworkspace",    .fn = foobar_hyprland_workspace_service_handle_workspace_renamed },
		{ .name = "workspace",          .fn = foobar_hyprland_workspace_service_handle_workspace_activated },
		{ .name = "activespecial",      .fn = foobar_hyprland_workspace_service_handle_special_workspace_activated },
		{ .name = "focusedmon",         .fn = foobar_hyprland_workspace_service_handle_monitor_focused },
		{ .name = "urgent",             .fn = foobar_hyprland_workspace_service_handle_window_urgent },
		{ .name = "configreloaded",     .fn = foobar_hyprland_workspace_service_handle_config_reloaded },
	};

// ---------------------------------------------------------------------------------------------------------------------
// Workspace
// ---------------------------------------------------------------------------------------------------------------------

//
// Static initialization for workspaces.
//
void foobar_hyprland_workspace_class_init( FoobarHyprlandWorkspaceClass* klass )
{
	GObjectClass* object_klass = G_OBJECT_CLASS( klass );
	object_klass->get_property = foobar_hyprland_workspace_get_property;
	object_klass->finalize = foobar_hyprland_workspace_finalize;

	g_object_class_override_property( object_klass, WORKSPACE_PROP_ID, "id" );
	g_object_class_override_property( object_klass, WORKSPACE_PROP_NAME, "name" );
	g_object_class_override_property( object_klass, WORKSPACE_PROP_MONITOR, "monitor" );
	g_object_class_override_property( object_klass, WORKSPACE_PROP_FLAGS, "flags" );
}

//
// Interface initialization for workspaces.
//
void foobar_hyprland_workspace_interface_init( FoobarWorkspaceInterface* iface )
{
	iface->get_id = foobar_hyprland_workspace_get_id;
	iface->get_name = foobar_hyprland_workspace_get_name;
	iface->get_monitor = foobar_hyprland_workspace_get_monitor;
	iface->get_flags = foobar_hyprland_workspace_get_flags;
	iface->activate = foobar_hyprland_workspace_activate;
}

//
// Instance initialization for workspaces.
//
void foobar_hyprland_workspace_init( FoobarHyprlandWorkspace* self )
{
	(void)self;
}

//
// Property getter implementation, mapping a property id to a method.
//
void foobar_hyprland_workspace_get_property(
	GObject*    object,
	guint       prop_id,
	GValue*     value,
	GParamSpec* pspec )
{
	FoobarHyprlandWorkspace* self = (FoobarHyprlandWorkspace*)object;

	switch ( prop_id )
	{
		case WORKSPACE_PROP_ID:
			g_value_set_int64( value, foobar_workspace_get_id( FOOBAR_WORKSPACE( self ) ) );
			break;
		case WORKSPACE_PROP_NAME:
			g_value_set_string( value, foobar_workspace_get_name( FOOBAR_WORKSPACE( self ) ) );
			break;
		case WORKSPACE_PROP_MONITOR:
			g_value_set_string( value, foobar_workspace_get_monitor( FOOBAR_WORKSPACE( self ) ) );
			break;
		case WORKSPACE_PROP_FLAGS:
			g_value_set_flags( value, foobar_workspace_get_flags( FOOBAR_WORKSPACE( self ) ) );
			break;
		default:
			G_OBJECT_WARN_INVALID_PROPERTY_ID( object, prop_id, pspec );
			break;
	}
}

//
// Instance cleanup for workspaces.
//
void foobar_hyprland_workspace_finalize( GObject* object )
{
	FoobarHyprlandWorkspace* self = (FoobarHyprlandWorkspace*)object;

	g_clear_pointer( &self->name, g_free );
	g_clear_pointer( &self->monitor, g_free );

	G_OBJECT_CLASS( foobar_hyprland_workspace_parent_class )->finalize( object );
}

//
// Create a new workspace that is owned by the given service (captured as an unowned reference).
//
FoobarHyprlandWorkspace* foobar_hyprland_workspace_new( FoobarHyprlandWorkspaceService* service )
{
	FoobarHyprlandWorkspace* self = g_object_new( FOOBAR_TYPE_HYPRLAND_WORKSPACE, NULL );
	self->service = service;
	return self;
}

//
// Numeric ID of the workspace.
//
gint64 foobar_hyprland_workspace_get_id( FoobarWorkspace* workspace )
{
	FoobarHyprlandWorkspace* self = (FoobarHyprlandWorkspace*)workspace;
	return self->id;
}

//
// Optional human-readable workspace name.
//
gchar const* foobar_hyprland_workspace_get_name( FoobarWorkspace* workspace )
{
	FoobarHyprlandWorkspace* self = (FoobarHyprlandWorkspace*)workspace;
	return self->name;
}

//
// Connector ID of the workspace's monitor.
//
gchar const* foobar_hyprland_workspace_get_monitor( FoobarWorkspace* workspace )
{
	FoobarHyprlandWorkspace* self = (FoobarHyprlandWorkspace*)workspace;
	return self->monitor;
}

//
// Flags indicating the current state of the workspace.
//
FoobarWorkspaceFlags foobar_hyprland_workspace_get_flags( FoobarWorkspace* workspace )
{
	FoobarHyprlandWorkspace* self = (FoobarHyprlandWorkspace*)workspace;
	return self->flags;
}

//
// Let this workspace become the active one.
//
void foobar_hyprland_workspace_activate( FoobarWorkspace* workspace )
{
	FoobarHyprlandWorkspace* self = (FoobarHyprlandWorkspace*)workspace;

	if ( !self->service ) { return; }

	g_autofree gchar* request = NULL;
	if ( foobar_workspace_get_id( FOOBAR_WORKSPACE( self ) ) > 0 )
	{
		// Normal
		request = g_strdup_printf( "dispatch workspace %lld", (long long)foobar_workspace_get_id( FOOBAR_WORKSPACE( self ) ) );
	}
	else if ( !( foobar_workspace_get_flags( FOOBAR_WORKSPACE( self ) ) & FOOBAR_WORKSPACE_FLAGS_SPECIAL ) )
	{
		// Named (this includes persistent)
		request = g_strdup_printf( "dispatch workspace name:%s", foobar_workspace_get_name( FOOBAR_WORKSPACE( self ) ) );
	}
	else if ( foobar_workspace_get_id( FOOBAR_WORKSPACE( self ) ) != -99 )
	{
		// Named special
		request = g_strdup_printf( "dispatch togglespecialworkspace %s", foobar_workspace_get_name( FOOBAR_WORKSPACE( self ) ) );
	}
	else
	{
		// Special
		request = g_strdup( "dispatch togglespecialworkspace" );
	}

	g_autoptr( GError ) error = NULL;
	g_free( foobar_hyprland_workspace_service_send_request( self->service, request, &error ) );
	if ( error )
	{
		g_warning( "Unable to activate workspace: %s", error->message );
	}
}

//
// Numeric ID of the workspace.
//
void foobar_hyprland_workspace_set_id(
	FoobarHyprlandWorkspace* self,
	gint64                   value )
{
	g_return_if_fail( FOOBAR_IS_HYPRLAND_WORKSPACE( self ) );

	if ( self->id != value )
	{
		self->id = value;
		g_object_notify( G_OBJECT( self ), "id" );
	}
}

//
// Optional human-readable workspace name.
//
void foobar_hyprland_workspace_set_name(
	FoobarHyprlandWorkspace* self,
	gchar const*             value )
{
	g_return_if_fail( FOOBAR_IS_HYPRLAND_WORKSPACE( self ) );

	if ( g_strcmp0( self->name, value ) )
	{
		g_clear_pointer( &self->name, g_free );
		self->name = g_strdup( value );
		g_object_notify( G_OBJECT( self ), "name" );
	}
}

//
// Connector ID of the workspace's monitor.
//
void foobar_hyprland_workspace_set_monitor(
	FoobarHyprlandWorkspace* self,
	gchar const*             value )
{
	g_return_if_fail( FOOBAR_IS_HYPRLAND_WORKSPACE( self ) );

	if ( g_strcmp0( self->monitor, value ) )
	{
		g_clear_pointer( &self->monitor, g_free );
		self->monitor = g_strdup( value );
		g_object_notify( G_OBJECT( self ), "monitor" );
	}
}

//
// Flags indicating the current state of the workspace.
//
void foobar_hyprland_workspace_set_flags(
	FoobarHyprlandWorkspace*     self,
	FoobarWorkspaceFlags         value )
{
	g_return_if_fail( FOOBAR_IS_HYPRLAND_WORKSPACE( self ) );

	if ( self->flags != value )
	{
		self->flags = value;
		g_object_notify( G_OBJECT( self ), "flags" );
	}
}

// ---------------------------------------------------------------------------------------------------------------------
// Service Implementation
// ---------------------------------------------------------------------------------------------------------------------

//
// Static initialization for the workspace service.
//
void foobar_hyprland_workspace_service_class_init( FoobarHyprlandWorkspaceServiceClass* klass )
{
	GObjectClass* object_klass = G_OBJECT_CLASS( klass );
	object_klass->get_property = foobar_hyprland_workspace_service_get_property;
	object_klass->dispose = foobar_hyprland_workspace_service_dispose;
	object_klass->finalize = foobar_hyprland_workspace_service_finalize;

	g_object_class_override_property( object_klass, PROP_WORKSPACES, "workspaces" );
}

//
// Interface initialization for the workspace service.
//
void foobar_hyprland_workspace_service_interface_init( FoobarWorkspaceServiceInterface* iface )
{
	iface->get_workspaces = foobar_hyprland_workspace_service_get_workspaces;
	iface->is_available = foobar_hyprland_workspace_service_is_available;
}

//
// Instance initialization for the workspace service.
//
void foobar_hyprland_workspace_service_init( FoobarHyprlandWorkspaceService* self )
{
	self->workspaces = g_list_store_new( FOOBAR_TYPE_WORKSPACE );

	GtkCustomSorter* sorter = gtk_custom_sorter_new( foobar_workspace_sort_func, NULL, NULL );
	self->sorted_workspaces = gtk_sort_list_model_new(
		G_LIST_MODEL( g_object_ref( self->workspaces ) ),
		GTK_SORTER( sorter ) );

	g_autofree gchar* base_path = foobar_hyprland_workspace_service_get_hyprland_base_path( );
	if ( !base_path )
	{
		return;
	}

	self->tx_path = g_strdup_printf( "%s/.socket.sock", base_path );
	self->rx_path = g_strdup_printf( "%s/.socket2.sock", base_path );
	self->event_cancellable = g_cancellable_new( );
	self->event_thread = g_thread_new( "workspace-event-listener", foobar_hyprland_workspace_service_event_thread_func, self );

	foobar_hyprland_workspace_service_initialize( self );
}

//
// Property getter implementation, mapping a property id to a method.
//
void foobar_hyprland_workspace_service_get_property( GObject* object, guint prop_id, GValue* value, GParamSpec* pspec )
{
	FoobarHyprlandWorkspaceService* self = (FoobarHyprlandWorkspaceService*)object;

	switch ( prop_id )
	{
		case PROP_WORKSPACES:
			g_value_set_object( value, foobar_workspace_service_get_workspaces( FOOBAR_WORKSPACE_SERVICE( self ) ) );
			break;
		default:
			G_OBJECT_WARN_INVALID_PROPERTY_ID( object, prop_id, pspec );
			break;
	}
}

//
// Instance de-initialization for the workspace service.
//
// This is where the event thread is joined because it might still create new object references which is a bad thing to
// do in finalize.
//
void foobar_hyprland_workspace_service_dispose( GObject* object )
{
	FoobarHyprlandWorkspaceService* self = (FoobarHyprlandWorkspaceService*)object;

	if ( self->event_thread )
	{
		g_cancellable_cancel( self->event_cancellable );
		g_thread_join( self->event_thread );
		self->event_thread = NULL;
	}

	G_OBJECT_CLASS( foobar_hyprland_workspace_service_parent_class )->dispose( object );
}

//
// Instance cleanup for the workspace service.
//
void foobar_hyprland_workspace_service_finalize( GObject* object )
{
	FoobarHyprlandWorkspaceService* self = (FoobarHyprlandWorkspaceService*)object;

	for ( guint i = 0; i < g_list_model_get_n_items( G_LIST_MODEL( self->workspaces ) ); ++i )
	{
		FoobarHyprlandWorkspace* workspace = g_list_model_get_item( G_LIST_MODEL( self->workspaces ), i );
		workspace->service = NULL;
	}
	g_clear_object( &self->event_cancellable );
	g_clear_object( &self->sorted_workspaces );
	g_clear_object( &self->workspaces );
	g_clear_pointer( &self->rx_path, g_free );
	g_clear_pointer( &self->tx_path, g_free );

	G_OBJECT_CLASS( foobar_hyprland_workspace_service_parent_class )->finalize( object );
}

//
// Get a sorted list of all workspaces.
//
GListModel* foobar_hyprland_workspace_service_get_workspaces( FoobarWorkspaceService* service )
{
	FoobarHyprlandWorkspaceService* self = (FoobarHyprlandWorkspaceService*)service;
	return G_LIST_MODEL( self->sorted_workspaces );
}

//
// Check whether this service is connected to Hyprland.
//
gboolean foobar_hyprland_workspace_service_is_available( FoobarWorkspaceService* service )
{
	FoobarHyprlandWorkspaceService* self = (FoobarHyprlandWorkspaceService*)service;
	return self->event_thread != NULL;
}

// ---------------------------------------------------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------------------------------------------------

//
// Create a new Hyprland workspace service instance.
//
FoobarWorkspaceService* foobar_hyprland_workspace_service_new( void )
{
	return g_object_new( FOOBAR_TYPE_HYPRLAND_WORKSPACE_SERVICE, NULL );
}

// ---------------------------------------------------------------------------------------------------------------------
// Event Handlers
// ---------------------------------------------------------------------------------------------------------------------

//
// Handler for the "createworkspacev2" event.
//
// The payload has the format "<id>,<name>" where <id> is the numeric ID.
//
gboolean foobar_hyprland_workspace_service_handle_workspace_created( EventData* data )
{
	gchar* save;
	gchar const* id_str = strtok_r( data->payload, ",", &save );
	gchar const* name = strtok_r( NULL, ",", &save );
	g_return_val_if_fail( id_str && name, G_SOURCE_REMOVE );

	if ( foobar_hyprland_workspace_service_is_invalid_name( name ) ) { return G_SOURCE_REMOVE; }
	gint64 id = foobar_hyprland_workspace_service_parse_id( id_str );

	// Get additional information about the workspace.

	g_autoptr( GError ) error = NULL;
	g_autoptr( JsonNode ) workspaces_node = foobar_hyprland_workspace_service_send_json_request(
		data->service,
		"j/workspaces",
		&error );
	if ( !workspaces_node )
	{
		g_warning( "Unable to load workspaces: %s", error->message );
		return G_SOURCE_REMOVE;
	}

	JsonArray* workspaces_array = json_node_get_array( workspaces_node );
	JsonObject* workspace_object = NULL;
	for ( guint i = 0; i < json_array_get_length( workspaces_array ); ++i )
	{
		JsonObject* it = json_array_get_object_element( workspaces_array, i );
		if ( id == json_object_get_int_member( it, "id" ) )
		{
			workspace_object = it;
			break;
		}
	}

	if ( !workspace_object )
	{
		g_warning( "Unable to find new workspace." );
		return G_SOURCE_REMOVE;
	}

	// Check if the workspace is persistent by looking for a rule with its ID.

	gboolean is_persistent = FALSE;

	g_autoptr( JsonNode ) rules_node = foobar_hyprland_workspace_service_send_json_request(
		data->service,
		"j/workspacerules",
		&error );
	if ( !rules_node )
	{
		g_warning( "Unable to load workspace rules: %s", error->message );
		return G_SOURCE_REMOVE;
	}

	JsonArray* rules_array = json_node_get_array( rules_node );
	for ( guint i = 0; i < json_array_get_length( rules_array ); ++i )
	{
		JsonObject* rule_object = json_array_get_object_element( rules_array, i );
		gchar const* rule_id_str = json_object_get_string_member_with_default( rule_object, "workspaceString", NULL );
		if ( id == foobar_hyprland_workspace_service_parse_id( rule_id_str ) )
		{
			is_persistent = json_object_get_boolean_member_with_default( rule_object, "persistent", FALSE );
			break;
		}
	}

	foobar_hyprland_workspace_service_add_workspace( data->service, data->service->workspaces, workspace_object, is_persistent );
	foobar_hyprland_workspace_service_update_active( data->service, data->service->workspaces );
	return G_SOURCE_REMOVE;
}

//
// Handler for the "destroyworkspacev2" event.
//
// The payload has the format "<id>,<name>" where <id> is the numeric ID.
//
gboolean foobar_hyprland_workspace_service_handle_workspace_destroyed( EventData* data )
{
	gchar* save;
	gchar const* id_str = strtok_r( data->payload, ",", &save );
	gchar const* name = strtok_r( NULL, ",", &save );
	g_return_val_if_fail( id_str && name, G_SOURCE_REMOVE );

	if ( foobar_hyprland_workspace_service_is_invalid_name( name ) ) { return G_SOURCE_REMOVE; }
	gint64 id = foobar_hyprland_workspace_service_parse_id( id_str );

	GListStore* workspaces = data->service->workspaces;
	guint index;
	FoobarHyprlandWorkspace* workspace = foobar_hyprland_workspace_service_find_workspace( G_LIST_MODEL( workspaces ), id, &index );
	if ( workspace )
	{
		workspace->service = NULL;
		g_list_store_remove( workspaces, index );
	}

	return G_SOURCE_REMOVE;
}

//
// Handler for the "moveworkspacev2" event.
//
// The payload has the format "<id>,<name>,<monitor>" where <id> is the numeric ID of the workspace.
//
gboolean foobar_hyprland_workspace_service_handle_workspace_moved( EventData* data )
{
	gchar* save;
	gchar const* workspace_id_str = strtok_r( data->payload, ",", &save );
	gchar const* workspace_name = strtok_r( NULL, ",", &save );
	gchar const* monitor_name = strtok_r( NULL, ",", &save );
	g_return_val_if_fail( workspace_id_str && workspace_name && monitor_name, G_SOURCE_REMOVE );

	gint64 workspace_id = foobar_hyprland_workspace_service_parse_id( workspace_id_str );
	FoobarHyprlandWorkspace* workspace = foobar_hyprland_workspace_service_find_workspace(
		G_LIST_MODEL( data->service->workspaces ),
		workspace_id,
		NULL );
	if ( workspace )
	{
		foobar_hyprland_workspace_set_monitor( workspace, monitor_name );
		g_signal_emit_by_name( data->service, "monitor-configuration-changed" );
	}
	foobar_hyprland_workspace_service_update_active( data->service, data->service->workspaces );

	return G_SOURCE_REMOVE;
}

//
// Handler for the "renameworkspace" event.
//
// The payload has the format "<id>,<name>" where <id> is the numeric ID of the workspace.
//
gboolean foobar_hyprland_workspace_service_handle_workspace_renamed( EventData* data )
{
	gchar* save;
	gchar const* id_str = strtok_r( data->payload, ",", &save );
	gchar const* new_name = strtok_r( NULL, ",", &save );
	g_return_val_if_fail( id_str && new_name, G_SOURCE_REMOVE );

	gint64 id = foobar_hyprland_workspace_service_parse_id( id_str );
	FoobarHyprlandWorkspace* workspace = foobar_hyprland_workspace_service_find_workspace(
		G_LIST_MODEL( data->service->workspaces ),
		id,
		NULL );
	if ( workspace )
	{
		foobar_hyprland_workspace_set_name( workspace, new_name );
		gtk_sorter_changed(
			gtk_sort_list_model_get_sorter( data->service->sorted_workspaces ),
			GTK_SORTER_CHANGE_DIFFERENT );
	}

	return G_SOURCE_REMOVE;
}

//
// Handler for the "workspace" event.
//
gboolean foobar_hyprland_workspace_service_handle_workspace_activated( EventData* data )
{
	foobar_hyprland_workspace_service_update_active( data->service, data->service->workspaces );

	return G_SOURCE_REMOVE;
}

//
// Handler for the "activespecial" event.
//
gboolean foobar_hyprland_workspace_service_handle_special_workspace_activated( EventData* data )
{
	foobar_hyprland_workspace_service_update_active( data->service, data->service->workspaces );

	return G_SOURCE_REMOVE;
}

//
// Handler for the "focusedmon" event.
//
gboolean foobar_hyprland_workspace_service_handle_monitor_focused( EventData* data )
{
	foobar_hyprland_workspace_service_update_active( data->service, data->service->workspaces );

	return G_SOURCE_REMOVE;
}

//
// Handler for the "urgent" event.
//
// The payload has the format "<address>" where <address> is the sender window's address.
//
gboolean foobar_hyprland_workspace_service_handle_window_urgent( EventData* data )
{
	gchar const* address = data->payload;

	// Find the client with the given address.

	g_autoptr( GError ) error = NULL;
	g_autoptr( JsonNode ) clients_node = foobar_hyprland_workspace_service_send_json_request(
		data->service,
		"j/clients",
		&error );
	if ( !clients_node )
	{
		g_warning( "Unable to load clients: %s", error->message );
		return G_SOURCE_REMOVE;
	}

	JsonArray* clients_array = json_node_get_array( clients_node );
	JsonObject* client_object = NULL;
	for ( guint i = 0; i < json_array_get_length( clients_array ); ++i )
	{
		JsonObject*  it = json_array_get_object_element( clients_array, i );
		gchar const* it_address = json_object_get_string_member_with_default( it, "address", "" );
		if ( g_str_has_suffix( it_address, address ) )
		{
			client_object = it;
			break;
		}
	}

	if ( !client_object ) { return G_SOURCE_REMOVE; }

	// Find the workspace this window belongs to and mark it as "urgent".

	JsonObject* workspace_object = json_object_get_object_member( client_object, "workspace" );
	gint64 id = json_object_get_int_member( workspace_object, "id" );
	FoobarHyprlandWorkspace* workspace = foobar_hyprland_workspace_service_find_workspace(
		G_LIST_MODEL( data->service->workspaces ),
		id,
		NULL );
	if ( workspace )
	{
		FoobarWorkspaceFlags flags = foobar_workspace_get_flags( FOOBAR_WORKSPACE( workspace ) ) | FOOBAR_WORKSPACE_FLAGS_URGENT;
		foobar_hyprland_workspace_set_flags( workspace, flags );
	}

	return G_SOURCE_REMOVE;
}

//
// Handler for the "configreloaded" event.
//
gboolean foobar_hyprland_workspace_service_handle_config_reloaded( EventData* data )
{
	foobar_hyprland_workspace_service_initialize( data->service );

	return G_SOURCE_REMOVE;
}

// ---------------------------------------------------------------------------------------------------------------------
// Helper Methods
// ---------------------------------------------------------------------------------------------------------------------

//
// Implementation of the event thread.
//
// This thread listens on hyprland's event socket (socket.2.sock) for incoming event notifications and then submits
// their registered handlers (if any) to the main loop.
//
gpointer foobar_hyprland_workspace_service_event_thread_func( gpointer userdata )
{
	FoobarHyprlandWorkspaceService* self = (FoobarHyprlandWorkspaceService*)userdata;

	g_autoptr( GError ) error = NULL;
	g_autoptr( GSocket ) sock = g_socket_new(
		G_SOCKET_FAMILY_UNIX,
		G_SOCKET_TYPE_STREAM,
		G_SOCKET_PROTOCOL_DEFAULT,
		&error );
	if ( !sock )
	{
		g_warning( "Unable to create socket for hyprland communication: %s", error->message );
		return NULL;
	}

	g_autoptr( GSocketAddress ) addr = g_unix_socket_address_new( self->rx_path );
	if ( !g_socket_connect( sock, addr, self->event_cancellable, &error ) &&
			!g_cancellable_is_cancelled( self->event_cancellable ) )
	{
		g_warning( "Unable to connect socket to hyprland: %s", error->message );
		return NULL;
	}

	// Each event is sent as a complete line, separated by a newline character.

	GString* prev_buf = NULL; // for longer, incomplete messages
	gchar buf[1024];
	while ( !g_cancellable_is_cancelled( self->event_cancellable ) )
	{
		// Synchronously receive data from the socket, but support cancellation using Gio.

		gssize received = g_socket_receive( sock, buf, sizeof( buf ), self->event_cancellable, &error );
		if ( error && !g_cancellable_is_cancelled( self->event_cancellable ) )
		{
			g_warning( "Unable to receive events from hyprland: %s", error->message );
		}
		if ( received <= 0 ) { break; }

		gchar* start = buf;
		gchar* end = start + received;
		while ( start < end )
		{
			gchar* next_newline = g_strstr_len( start, end - start, "\n" );
			if ( !next_newline )
			{
				// Incomplete message (missing newline) -> store it in the buffer

				prev_buf = ( prev_buf != NULL )
					? g_string_append_len( prev_buf, start, end - start )
					: g_string_new_len( start, end - start );
				break;
			}

			if ( prev_buf )
			{
				// Prepend buffered data before the actual data.

				prev_buf = g_string_append_len( prev_buf, start, next_newline - start );
				foobar_hyprland_workspace_service_dispatch_event( self, prev_buf->str );

				g_string_free( prev_buf, TRUE );
				prev_buf = NULL;
			}
			else
			{
				// Skip allocation and use the buffer contents on the stack directly.

				*next_newline = '\0';
				foobar_hyprland_workspace_service_dispatch_event( self, start );
			}

			start = next_newline + 1;
		}
	}

	if ( prev_buf ) { g_string_free( prev_buf, TRUE ); }

	return NULL;
}

//
// Called when an entire event has been received on the event thread.
//
// This will look through the registered handlers and (if found) invoke the event's handler on the main thread.
//
void foobar_hyprland_workspace_service_dispatch_event(
	FoobarHyprlandWorkspaceService* self,
	gchar*                          message )
{
	gchar* delimiter = strstr( message, ">>" );
	if ( !delimiter )
	{
		g_warning( "Received an invalid message from hyprland: %s", message );
		return;
	}

	*delimiter = '\0';
	gchar* name = message;
	gchar* payload = delimiter + 2;
	for ( gsize i = 0; i < G_N_ELEMENTS( event_handlers ); ++i )
	{
		EventHandler handler = event_handlers[i];
		if ( !strcmp( name, handler.name ) )
		{
			g_idle_add_full(
				G_PRIORITY_DEFAULT,
				G_SOURCE_FUNC( handler.fn ),
				event_data_new( self, name, payload ),
				(GDestroyNotify)event_data_free );
			break;
		}
	}
}

//
// Synchronously send a command to hyprland's control socket (socket.sock), returning the entire response.
//
gchar* foobar_hyprland_workspace_service_send_request(
	FoobarHyprlandWorkspaceService* self,
	gchar const*                    request,
	GError**                        error )
{
	g_autoptr( GSocket ) sock = g_socket_new(
		G_SOCKET_FAMILY_UNIX,
		G_SOCKET_TYPE_STREAM,
		G_SOCKET_PROTOCOL_DEFAULT,
		error );
	if ( !sock ) { return NULL; }

	g_autoptr( GSocketAddress ) addr = g_unix_socket_address_new( self->tx_path );
	if ( !g_socket_connect( sock, addr, NULL, error ) ) { return NULL; }

	if ( g_socket_send( sock, request, strlen( request ), NULL, error ) == -1 ) { return NULL; }

	GString* str = g_string_sized_new( 0 );
	gchar    buf[8192];
	while ( TRUE )
	{
		gssize received = g_socket_receive( sock, buf, sizeof( buf ), self->event_cancellable, error );
		if ( received < 0 ) { return g_string_free( str, TRUE ); }

		if ( received == 0 ) { break; }
		str = g_string_append_len( str, buf, received );
	}

	return g_string_free( str, FALSE );
}

//
// Synchronously send a command to hyprland's control socket (socket.sock), returning the parsed the JSON response.
//
JsonNode* foobar_hyprland_workspace_service_send_json_request(
	FoobarHyprlandWorkspaceService* self,
	gchar const*                    request,
	GError**                        error )
{
	g_autofree gchar* json = foobar_hyprland_workspace_service_send_request( self, request, error );
	if ( !json ) { return NULL; }

	g_autoptr( JsonParser ) parser = json_parser_new( );
	if ( !json_parser_load_from_data( parser, json, (gssize)strlen( json ), error ) ) { return NULL; }

	return json_parser_steal_root( parser );
}

//
// Refresh the list of workspaces by actively sending a request to hyprland.
//
void foobar_hyprland_workspace_service_initialize( FoobarHyprlandWorkspaceService* self )
{
	for ( guint i = 0; i < g_list_model_get_n_items( G_LIST_MODEL( self->workspaces ) ); ++i )
	{
		FoobarHyprlandWorkspace* workspace = g_list_model_get_item( G_LIST_MODEL( self->workspaces ), i );
		workspace->service = NULL;
	}
	g_list_store_remove_all( self->workspaces );
	g_autoptr( GListStore ) workspaces = g_list_store_new( FOOBAR_TYPE_WORKSPACE );

	{
		g_autoptr( GError ) error = NULL;
		g_autoptr( JsonNode ) workspaces_node = foobar_hyprland_workspace_service_send_json_request(
			self,
			"j/workspaces",
			&error );
		if ( !workspaces_node )
		{
			g_warning( "Unable to load workspaces: %s", error->message );
			return;
		}

		JsonArray* workspaces_array = json_node_get_array( workspaces_node );
		for ( guint i = 0; i < json_array_get_length( workspaces_array ); ++i )
		{
			JsonObject* workspace_object = json_array_get_object_element( workspaces_array, i );
			foobar_hyprland_workspace_service_add_workspace( self, workspaces, workspace_object, FALSE );
		}
	}

	{
		// Load configured persistent workspaces.

		g_autoptr( GError ) error = NULL;
		g_autoptr( JsonNode ) rules_node = foobar_hyprland_workspace_service_send_json_request(
			self,
			"j/workspacerules",
			&error );
		if ( rules_node )
		{
			JsonArray* rules_array = json_node_get_array( rules_node );
			for ( guint i = 0; i < json_array_get_length( rules_array ); ++i )
			{
				JsonObject*  rule_object = json_array_get_object_element( rules_array, i );
				gchar const* name = json_object_get_string_member_with_default( rule_object, "workspaceString", NULL );
				if ( !name )
				{
					g_warning( "Found an invalid workspaceString value, skipping." );
					continue;
				}

				if ( !json_object_get_boolean_member_with_default( rule_object, "persistent", FALSE ) ) { continue; }

				gint64 id = foobar_hyprland_workspace_service_parse_id( name );
				json_object_set_int_member( rule_object, "id", id );
				json_object_set_string_member( rule_object, "name", name );

				foobar_hyprland_workspace_service_add_workspace( self, workspaces, rule_object, TRUE );
			}
		}
		else { g_warning( "Unable to load workspace rules: %s", error->message ); }
	}

	foobar_hyprland_workspace_service_update_active( self, workspaces );

	for ( guint i = 0; i < g_list_model_get_n_items( G_LIST_MODEL( workspaces ) ); ++i )
	{
		FoobarWorkspace* workspace = g_list_model_get_item( G_LIST_MODEL( workspaces ), i );
		g_list_store_append( self->workspaces, workspace );
	}
}

//
// Update the currently active/visible workspaces by actively sending a request to hyprland.
//
void foobar_hyprland_workspace_service_update_active(
	FoobarHyprlandWorkspaceService* self,
	GListStore*                     workspaces )
{
	g_autoptr( GArray ) visible_workspace_ids = g_array_new( FALSE, FALSE, sizeof( gint64 ) );
	gint64 active_workspace_id = 0;
	gint64 active_special_workspace_id = 0;

	{
		// Get all active workspaces

		g_autoptr( GError ) error = NULL;
		g_autoptr( JsonNode ) monitors_node = foobar_hyprland_workspace_service_send_json_request(
			self,
			"j/monitors",
			&error );
		if ( monitors_node )
		{
			JsonArray* monitors_array = json_node_get_array( monitors_node );
			for ( guint i = 0; i < json_array_get_length( monitors_array ); ++i )
			{
				JsonObject* monitor_object = json_array_get_object_element( monitors_array, i );
				gint64 workspace_id = 0;
				gint64 special_workspace_id = 0;

				if ( json_object_has_member( monitor_object, "activeWorkspace" ) )
				{
					JsonObject* workspace_object = json_object_get_object_member( monitor_object, "activeWorkspace" );
					workspace_id = json_object_get_int_member_with_default( workspace_object, "id", 0 );
					if ( workspace_id ) { g_array_append_val( visible_workspace_ids, workspace_id ); }
				}

				if ( json_object_has_member( monitor_object, "specialWorkspace" ) )
				{
					JsonObject* workspace_object = json_object_get_object_member( monitor_object, "specialWorkspace" );
					special_workspace_id = json_object_get_int_member_with_default( workspace_object, "id", 0 );
					if ( special_workspace_id ) { g_array_append_val( visible_workspace_ids, special_workspace_id ); }
				}

				// If this is the focused monitor, then the visible workspace is also the active one.

				if ( json_object_get_boolean_member_with_default( monitor_object, "focused", FALSE ) )
				{
					active_workspace_id = workspace_id;
					active_special_workspace_id = special_workspace_id;
				}
			}
		}
		else { g_warning( "Unable to load monitors: %s", error->message ); }
	}

	// Sort visible workspaces to allow binary search.

	g_array_sort( visible_workspace_ids, foobar_hyprland_workspace_service_compare_ids );

	// Go through all workspaces and update their state.

	for ( guint i = 0; i < g_list_model_get_n_items( G_LIST_MODEL( workspaces ) ); ++i )
	{
		FoobarHyprlandWorkspace* workspace = g_list_model_get_item( G_LIST_MODEL( workspaces ), i );
		FoobarWorkspaceFlags flags = foobar_workspace_get_flags( FOOBAR_WORKSPACE( workspace ) );
		gint64 id = foobar_workspace_get_id( FOOBAR_WORKSPACE( workspace ) );

		// Active
		gboolean is_active = id == active_workspace_id || id == active_special_workspace_id;
		flags = is_active ? flags | FOOBAR_WORKSPACE_FLAGS_ACTIVE : flags & ~FOOBAR_WORKSPACE_FLAGS_ACTIVE;

		// Disable urgency if workspace is active
		if ( is_active ) { flags = flags & ~FOOBAR_WORKSPACE_FLAGS_URGENT; }

		// Visible
		gboolean is_visible = g_array_binary_search(
			visible_workspace_ids,
			&id,
			foobar_hyprland_workspace_service_compare_ids,
			NULL );
		flags = is_visible ? flags | FOOBAR_WORKSPACE_FLAGS_VISIBLE : flags & ~FOOBAR_WORKSPACE_FLAGS_VISIBLE;

		foobar_hyprland_workspace_set_flags( workspace, flags );
	}
}

//
// Add or update a workspace described by a JSON object.
//
void foobar_hyprland_workspace_service_add_workspace(
	FoobarHyprlandWorkspaceService* self,
	GListStore*                     workspaces,
	JsonObject*                     workspace_object,
	gboolean                        is_persistent )
{
	gchar const* name = json_object_get_string_member( workspace_object, "name" );
	gint64 id = json_object_get_int_member( workspace_object, "id" );
	gboolean is_special = g_str_has_prefix( name, "special" );
	if ( g_str_has_prefix( name, "name:" ) ) { name += strlen( "name:" ); }
	else if ( g_str_has_prefix( name, "special:" ) ) { name += strlen( "special:" ); }

	FoobarHyprlandWorkspace* existing = foobar_hyprland_workspace_service_find_workspace( G_LIST_MODEL( workspaces ), id, NULL );
	if ( existing )
	{
		// Only update persistence.

		FoobarWorkspaceFlags flags = foobar_workspace_get_flags( FOOBAR_WORKSPACE( existing ) );
		flags = is_persistent ? flags | FOOBAR_WORKSPACE_FLAGS_PERSISTENT : flags & ~FOOBAR_WORKSPACE_FLAGS_PERSISTENT;
		foobar_hyprland_workspace_set_flags( existing, flags );
	}
	else
	{
		// Found a new workspace -> create a new object for it.

		FoobarWorkspaceFlags flags = FOOBAR_WORKSPACE_FLAGS_NONE;
		flags = is_persistent ? flags | FOOBAR_WORKSPACE_FLAGS_PERSISTENT : flags;
		flags = is_special ? flags | FOOBAR_WORKSPACE_FLAGS_SPECIAL : flags;

		g_autoptr( FoobarHyprlandWorkspace ) workspace = foobar_hyprland_workspace_new( self );
		foobar_hyprland_workspace_set_id( workspace, id );
		foobar_hyprland_workspace_set_name( workspace, name );
		foobar_hyprland_workspace_set_monitor( workspace, json_object_get_string_member( workspace_object, "monitor" ) );
		foobar_hyprland_workspace_set_flags( workspace, flags );
		g_list_store_append( workspaces, workspace );
	}
}

//
// Find an existing workspace object by its ID.
//
FoobarHyprlandWorkspace* foobar_hyprland_workspace_service_find_workspace(
	GListModel* workspaces,
	gint64      id,
	guint*      out_index )
{
	for ( guint i = 0; i < g_list_model_get_n_items( workspaces ); ++i )
	{
		FoobarHyprlandWorkspace* workspace = g_list_model_get_item( workspaces, i );
		if ( foobar_workspace_get_id( FOOBAR_WORKSPACE( workspace ) ) == id )
		{
			if ( out_index ) { *out_index = i; }
			return workspace;
		}
	}

	return NULL;
}

//
// Hyprland's IPC sometimes reports the creation of workspaces strangely named `special:special:<some_name>`. This
// function checks for that and is used to avoid creating (and then removing) such workspaces.
//
// See hyprwm/Hyprland#3424 for more info.
//
gboolean foobar_hyprland_workspace_service_is_invalid_name( gchar const* name )
{
	return g_str_has_prefix( name, "special:special:" );
}

//
// Parse an ID string and return its numeric code.
//
gint64 foobar_hyprland_workspace_service_parse_id( gchar const* str )
{
	if ( !g_strcmp0( str, "special" ) ) { return -99; }

	return strtoll( str, NULL, 10 );
}

//
// Get the base path for hyprland socket files.
//
gchar* foobar_hyprland_workspace_service_get_hyprland_base_path( void )
{
	gchar const* instance_signature = g_getenv( "HYPRLAND_INSTANCE_SIGNATURE" );
	if ( !instance_signature )
	{
		return NULL;
	}

	// for Hyprland >= 0.40
	gchar* result = g_strdup_printf( "%s/hypr/%s", g_get_user_runtime_dir( ), instance_signature );
	if ( g_file_test( result, G_FILE_TEST_EXISTS ) )
	{
		return result;
	}

	// for Hyprland < 0.40
	g_free( result );
	result = g_strdup_printf( "%s/hypr/%s", g_get_tmp_dir( ), instance_signature );
	if ( g_file_test( result, G_FILE_TEST_EXISTS ) )
	{
		return result;
	}

	g_free( result );
	return NULL;
}

//
// Comparison function for two workspace IDs, used for binary search.
//
gint foobar_hyprland_workspace_service_compare_ids(
	gconstpointer a,
	gconstpointer b )
{
	gint64 const* a_int = a;
	gint64 const* b_int = b;

	if ( *a_int < *b_int ) { return -1; }
	if ( *a_int > *b_int ) { return 1; }
	return 0;
}

//
// Create a new EventData structure.
//
static EventData* event_data_new(
	FoobarHyprlandWorkspaceService* service,
	gchar const*                    name,
	gchar const*                    payload )
{
	EventData* self = g_new0( EventData, 1 );
	self->service = g_object_ref( service );
	self->name = g_strdup( name );
	self->payload = g_strdup( payload );
	return self;
}

//
// Destroy an EventData structure.
//
static void event_data_free( EventData* self )
{
	if ( self )
	{
		g_object_unref( self->service );
		g_free( self->name );
		g_free( self->payload );
		g_free( self );
	}
}