#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "powertop.h"
#define PT_SUGG_DEF_SLICE 3
sugg_t *g_curr_sugg;
static sugg_t *sugg;
void
pt_sugg_add(char *text, int weight, char key, char *sb_msg, sugg_func_t *func)
{
sugg_t *new, *n, *pos = NULL;
if (text == NULL)
return;
if (sugg == NULL) {
if ((new = calloc(1, sizeof (sugg_t))) == NULL)
return;
if (sb_msg != NULL)
new->sb_msg = strdup(sb_msg);
if (text != NULL)
new->text = strdup(text);
new->weight = weight;
new->key = key;
new->func = func;
new->slice = 0;
sugg = new;
new->prev = NULL;
new->next = NULL;
} else {
for (n = sugg; n != NULL; n = n->next) {
if (strcmp(n->text, text) == 0)
return;
if (weight > n->weight && pos == NULL)
pos = n;
}
if ((new = calloc(1, sizeof (sugg_t))) == NULL)
return;
if (sb_msg != NULL)
new->sb_msg = strdup(sb_msg);
new->text = strdup(text);
new->weight = weight;
new->key = key;
new->func = func;
new->slice = 0;
if (pos == NULL) {
for (n = sugg; n->next != NULL; n = n->next)
;
n->next = new;
new->prev = n;
new->next = NULL;
} else {
if (pos == sugg) {
new->next = sugg;
new->prev = NULL;
sugg->prev = new;
sugg = new;
} else {
new->next = pos;
new->prev = pos->prev;
pos->prev->next = new;
pos->prev = new;
}
}
}
}
int
pt_sugg_remove(sugg_func_t *func)
{
sugg_t *n;
if (func == NULL)
return (0);
for (n = sugg; n != NULL; n = n->next) {
if (n->func == func) {
if (n == sugg) {
if (sugg->next == NULL) {
sugg = NULL;
} else {
sugg = n->next;
sugg->prev = NULL;
}
} else {
if (n->next == NULL) {
n->prev->next = NULL;
} else {
n->prev->next = n->next;
n->next->prev = n->prev;
}
}
break;
}
}
if (n == NULL)
return (0);
if (n == g_curr_sugg) {
g_curr_sugg = NULL;
if (n->sb_msg != NULL) {
pt_display_mod_status_bar(n->sb_msg);
pt_display_status_bar();
}
if (n->text != NULL)
pt_display_suggestions(NULL);
}
free(n->sb_msg);
free(n->text);
free(n);
return (1);
}
void
pt_sugg_pick(void)
{
sugg_t *n;
if (sugg == NULL) {
g_curr_sugg = NULL;
return;
}
search:
for (n = sugg; n != NULL; n = n->next) {
if (n->slice++ < PT_SUGG_DEF_SLICE) {
if (g_curr_sugg == n && !g_sig_resize)
return;
if (g_curr_sugg != NULL) {
if (g_curr_sugg->sb_msg != NULL) {
pt_display_mod_status_bar(
g_curr_sugg->sb_msg);
pt_display_status_bar();
}
if (g_curr_sugg->text != NULL)
pt_display_suggestions(NULL);
}
if (n->sb_msg != NULL) {
pt_display_mod_status_bar(n->sb_msg);
pt_display_status_bar();
}
pt_display_suggestions(n->text);
g_curr_sugg = n;
return;
}
}
for (n = sugg; n != NULL; n = n->next)
n->slice = 0;
goto search;
}
void
pt_sugg_as_root(void)
{
pt_sugg_add("Suggestion: run as root to get suggestions"
" for reducing system power consumption", 40, 0, NULL,
NULL);
}