summaryrefslogtreecommitdiffstats
path: root/swaybar/state.c
blob: 26cdcafee05f876fc7ddee2f63a50fc2a8289a26 (plain) (blame)
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
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

#include "list.h"
#include "log.h"
#include "config.h"
#include "status_line.h"
#include "state.h"

struct swaybar_state *init_state() {
	struct swaybar_state *state = calloc(1, sizeof(struct swaybar_state));
	state->config = init_config();
	state->status = init_status_line();
	state->output = malloc(sizeof(struct output));
	state->output->window = NULL;
	state->output->registry = NULL;
	state->output->workspaces = create_list();
	state->output->name = NULL;

	return state;
}

void free_workspaces(list_t *workspaces) {
	int i;
	for (i = 0; i < workspaces->length; ++i) {
		struct workspace *ws = workspaces->items[i];
		free(ws->name);
		free(ws);
	}
	list_free(workspaces);
}

static void free_output(struct output *output) {
	window_teardown(output->window);
	if (output->registry) {
		registry_teardown(output->registry);
	}

	free(output->name);

	if (output->workspaces) {
		free_workspaces(output->workspaces);
	}

	free(output);
}

static void terminate_status_command(pid_t pid) {
	if (pid) {
		// terminate status_command process
		int ret = kill(pid, SIGTERM);
		if (ret != 0) {
			sway_log(L_ERROR, "Unable to terminate status_command [pid: %d]", pid);
		} else {
			int status;
			waitpid(pid, &status, 0);
		}
	}
}

void free_state(struct swaybar_state *state) {
	free_config(state->config);
	free_output(state->output);
	free_status_line(state->status);

	/* close sockets/pipes */
	if (state->status_read_fd) {
		close(state->status_read_fd);
	}

	if (state->ipc_socketfd) {
		close(state->ipc_socketfd);
	}

	if (state->ipc_event_socketfd) {
		close(state->ipc_event_socketfd);
	}

	/* terminate status command process */
	terminate_status_command(state->status_command_pid);

	free(state);
}