id
int64 0
755k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
65
| repo_stars
int64 100
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 9
values | repo_extraction_date
stringclasses 92
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
22,559
|
tailhead.cc
|
brndnmtthws_conky/src/tailhead.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <cctype>
#include <cstring>
#include <memory>
#include "common.h"
#include "config.h"
#include "conky.h"
#include "logging.h"
#include "text_object.h"
#define MAX_HEADTAIL_LINES 30
#define DEFAULT_MAX_HEADTAIL_USES 2
struct headtail {
int wantedlines{0};
std::string logfile;
char *buffer{nullptr};
int current_use{0};
int max_uses{0};
int reported{0};
headtail() = default;
~headtail() { free(buffer); }
};
static void tailstring(char *string, int endofstring, int wantedlines) {
int i, linescounted = 0;
string[endofstring] = 0;
if (endofstring > 0) {
if (string[endofstring - 1] ==
'\n') { // work with or without \n at end of file
string[endofstring - 1] = 0;
}
for (i = endofstring - 1; i >= 0 && linescounted < wantedlines; i--) {
if (string[i] == '\n') { linescounted++; }
}
if (i > 0) { strfold(string, i + 2); }
}
}
void free_tailhead(struct text_object *obj) {
auto *ht = static_cast<struct headtail *>(obj->data.opaque);
obj->data.opaque = nullptr;
delete ht;
}
void init_tailhead(const char *type, const char *arg, struct text_object *obj,
void *free_at_crash) {
unsigned int args;
auto *ht = new headtail;
std::unique_ptr<char[]> tmp(new char[DEFAULT_TEXT_BUFFER_SIZE]);
memset(tmp.get(), 0, DEFAULT_TEXT_BUFFER_SIZE);
ht->max_uses = DEFAULT_MAX_HEADTAIL_USES;
// XXX: Buffer overflow ?
args = sscanf(arg, "%s %d %d", tmp.get(), &ht->wantedlines, &ht->max_uses);
if (args < 2 || args > 3) {
free_tailhead(obj);
CRIT_ERR_FREE(
obj, free_at_crash,
"%s needs a file as 1st and a number of lines as 2nd argument", type);
}
if (ht->max_uses < 1) {
free_tailhead(obj);
CRIT_ERR_FREE(obj, free_at_crash,
"invalid arg for %s, next_check must be larger than 0", type);
}
if (ht->wantedlines > 0 && ht->wantedlines <= MAX_HEADTAIL_LINES) {
ht->logfile = to_real_path(tmp.get());
ht->buffer = nullptr;
ht->current_use = 0;
} else {
free_tailhead(obj);
CRIT_ERR_FREE(
obj, free_at_crash,
"invalid arg for %s, number of lines must be between 1 and %d", type,
MAX_HEADTAIL_LINES);
}
obj->data.opaque = ht;
}
static void print_tailhead(const char *type, struct text_object *obj, char *p,
unsigned int p_max_size) {
int fd, i, endofstring = 0, linescounted = 0;
FILE *fp;
struct stat st {};
auto *ht = static_cast<struct headtail *>(obj->data.opaque);
if (ht == nullptr) { return; }
// empty the buffer and reset the counter if we used it the max number of
// times
if ((ht->buffer != nullptr) && ht->current_use >= ht->max_uses - 1) {
free_and_zero(ht->buffer);
ht->current_use = 0;
}
// use the buffer if possible
if (ht->buffer != nullptr) {
strncpy(p, ht->buffer, p_max_size);
ht->current_use++;
} else { // otherwise find the needed data
if (stat(ht->logfile.c_str(), &st) == 0) {
if (S_ISFIFO(st.st_mode)) {
fd = open_fifo(ht->logfile.c_str(), &ht->reported);
if (fd != -1) {
if (strcmp(type, "head") == 0) {
for (i = 0; linescounted < ht->wantedlines; i++) {
if (read(fd, p + i, 1) <= 0) { break; }
if (p[i] == '\n') { linescounted++; }
}
p[i] = 0;
} else if (strcmp(type, "tail") == 0) {
i = read(fd, p, p_max_size - 1);
tailstring(p, i, ht->wantedlines);
} else {
CRIT_ERR(
"If you are seeing this then there is a bug in the code, "
"report it !");
}
}
close(fd);
} else {
fp = open_file(ht->logfile.c_str(), &ht->reported);
if (fp != nullptr) {
if (strcmp(type, "head") == 0) {
for (i = 0; i < ht->wantedlines; i++) {
if (fgets(p + endofstring, p_max_size - endofstring, fp) ==
nullptr) {
break;
}
endofstring = strlen(p);
}
} else if (strcmp(type, "tail") == 0) {
fseek(fp, -static_cast<long>(p_max_size), SEEK_END);
i = fread(p, 1, p_max_size - 1, fp);
tailstring(p, i, ht->wantedlines);
} else {
CRIT_ERR(
"If you are seeing this then there is a bug in the code, "
"report it !");
}
fclose(fp);
}
}
ht->buffer = strdup(p);
} else {
CRIT_ERR("$%s can't find information about %s", type,
ht->logfile.c_str());
}
}
}
void print_head(struct text_object *obj, char *p, unsigned int p_max_size) {
print_tailhead("head", obj, p, p_max_size);
}
void print_tail(struct text_object *obj, char *p, unsigned int p_max_size) {
print_tailhead("tail", obj, p, p_max_size);
}
/* FIXME: use something more general (see also tail.c, head.c */
#define BUFSZ 0x1000
void print_lines(struct text_object *obj, char *p, unsigned int p_max_size) {
static int rep = 0;
FILE *fp = open_file(obj->data.s, &rep);
char buf[BUFSZ];
int j, lines;
if (fp == nullptr) {
snprintf(p, p_max_size, "%s", "File Unreadable");
return;
}
lines = 0;
while (fgets(buf, BUFSZ, fp) != nullptr) {
for (j = 0; buf[j] != 0; j++) {
if (buf[j] == '\n') { lines++; }
}
}
snprintf(p, p_max_size, "%d", lines);
fclose(fp);
}
void print_words(struct text_object *obj, char *p, unsigned int p_max_size) {
static int rep = 0;
FILE *fp = open_file(obj->data.s, &rep);
char buf[BUFSZ];
int j, words;
char inword = 0;
if (fp == nullptr) {
snprintf(p, p_max_size, "%s", "File Unreadable");
return;
}
words = 0;
while (fgets(buf, BUFSZ, fp) != nullptr) {
for (j = 0; buf[j] != 0; j++) {
if (isspace(static_cast<unsigned char>(buf[j])) == 0) {
if (inword == 0) {
words++;
inword = 1;
}
} else {
inword = 0;
}
}
}
snprintf(p, p_max_size, "%d", words);
fclose(fp);
}
| 7,209
|
C++
|
.cc
| 223
| 26.852018
| 80
| 0.587906
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,560
|
llua.cc
|
brndnmtthws_conky/src/llua.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Copyright (c) 2009 Toni Spets
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "config.h"
#include "build.h"
#include "conky.h"
#include "geometry.h"
#include "llua.h"
#include "logging.h"
#ifdef BUILD_GUI
#include "gui.h"
#ifdef BUILD_X11
#include "x11-settings.h"
#include "x11.h"
#endif /* BUILD_X11 */
#ifdef BUILD_MOUSE_EVENTS
#include "mouse-events.h"
#endif /* BUILD_MOUSE_EVENTS */
#endif /* BUILD_GUI */
extern "C" {
#include <tolua++.h>
}
#ifdef HAVE_SYS_INOTIFY_H
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wc99-extensions"
#include <sys/inotify.h>
#pragma clang diagnostic pop
void llua_append_notify(const char *name);
void llua_rm_notifies(void);
static int llua_block_notify = 0;
#endif /* HAVE_SYS_INOTIFY_H */
// POSIX compliant
#include <sys/stat.h>
static void llua_load(const char *script);
lua_State *lua_L = nullptr;
namespace {
class lua_load_setting : public conky::simple_config_setting<std::string> {
using Base = conky::simple_config_setting<std::string>;
protected:
void lua_setter(lua::state &l, bool init) override {
lua::stack_sentry s(l, -2);
Base::lua_setter(l, init);
if (init) {
std::string files = do_convert(l, -1).first;
while (!files.empty()) {
std::string::size_type pos = files.find(' ');
if (pos > 0) {
std::string file(files, 0, pos);
llua_load(file.c_str());
}
files.erase(0, pos == std::string::npos ? pos : pos + 1);
}
}
++s;
}
void cleanup(lua::state &l) override {
lua::stack_sentry s(l, -1);
#ifdef HAVE_SYS_INOTIFY_H
llua_rm_notifies();
#endif /* HAVE_SYS_INOTIFY_H */
if (lua_L == nullptr) { return; }
lua_close(lua_L);
lua_L = nullptr;
}
public:
lua_load_setting() : Base("lua_load", std::string(), false) {}
};
lua_load_setting lua_load;
conky::simple_config_setting<std::string> lua_startup_hook("lua_startup_hook",
std::string(), true);
conky::simple_config_setting<std::string> lua_shutdown_hook("lua_shutdown_hook",
std::string(),
true);
#ifdef BUILD_GUI
conky::simple_config_setting<std::string> lua_draw_hook_pre("lua_draw_hook_pre",
std::string(),
true);
conky::simple_config_setting<std::string> lua_draw_hook_post(
"lua_draw_hook_post", std::string(), true);
#ifdef BUILD_MOUSE_EVENTS
conky::simple_config_setting<std::string> lua_mouse_hook("lua_mouse_hook",
std::string(), true);
#endif /* BUILD_MOUSE_EVENTS */
#endif
} // namespace
static int llua_conky_parse(lua_State *L) {
int n = lua_gettop(L); /* number of arguments */
char *str;
auto *buf = static_cast<char *>(calloc(1, max_user_text.get(*state)));
if (n != 1) {
lua_pushstring(
L, "incorrect arguments, conky_parse(string) takes exactly 1 argument");
lua_error(L);
}
if (lua_isstring(L, 1) == 0) {
lua_pushstring(L, "incorrect argument (expecting a string)");
lua_error(L);
}
str = strdup(lua_tostring(L, 1));
evaluate(str, buf, max_user_text.get(*state));
lua_pushstring(L, buf);
free(str);
free(buf);
return 1; /* number of results */
}
static int llua_conky_set_update_interval(lua_State *L) {
int n = lua_gettop(L); /* number of arguments */
if (n != 1) {
lua_pushstring(L,
"incorrect arguments, conky_set_update_interval(number) "
"takes exactly 1 argument");
lua_error(L);
}
if (lua_isnumber(L, 1) == 0) {
lua_pushstring(L, "incorrect argument (expecting a number)");
lua_error(L);
}
state->pushnumber(lua_tonumber(L, 1));
update_interval.lua_set(*state);
return 0; /* number of results */
}
void llua_init() {
std::string libs(PACKAGE_LIBDIR "/lib?.so;");
std::string old_path, new_path;
if (lua_L != nullptr) { return; }
lua_L = luaL_newstate();
/* add our library path to the lua package.cpath global var */
luaL_openlibs(lua_L);
lua_getglobal(lua_L, "package");
lua_getfield(lua_L, -1, "cpath");
old_path = std::string(lua_tostring(lua_L, -1));
new_path = libs + old_path;
lua_pushstring(lua_L, new_path.c_str());
lua_setfield(lua_L, -3, "cpath");
lua_pop(lua_L, 2);
lua_pushstring(lua_L, PACKAGE_NAME " " VERSION " compiled for " BUILD_ARCH);
lua_setglobal(lua_L, "conky_build_info");
lua_pushstring(lua_L, VERSION);
lua_setglobal(lua_L, "conky_version");
lua_pushstring(lua_L, BUILD_ARCH);
lua_setglobal(lua_L, "conky_build_arch");
lua_pushstring(lua_L, current_config.c_str());
lua_setglobal(lua_L, "conky_config");
lua_pushcfunction(lua_L, &llua_conky_parse);
lua_setglobal(lua_L, "conky_parse");
lua_pushcfunction(lua_L, &llua_conky_set_update_interval);
lua_setglobal(lua_L, "conky_set_update_interval");
#if defined(BUILD_X11)
/* register tolua++ user types */
tolua_open(lua_L);
tolua_usertype(lua_L, "Drawable");
tolua_usertype(lua_L, "Visual");
tolua_usertype(lua_L, "Display");
#endif /* BUILD_X11 */
}
inline bool file_exists(const char *path) {
struct stat buffer;
return (stat(path, &buffer) == 0);
}
void llua_load(const char *script) {
int error;
std::string path = to_real_path(script);
if (!file_exists(path.c_str())) {
NORM_ERR("llua_load: specified script file '%s' doesn't exist",
path.c_str());
// return without initializing lua_L because other parts of the code rely
// on it being null if the script is not loaded
return;
}
llua_init();
error = luaL_dofile(lua_L, path.c_str());
if (error != 0) {
NORM_ERR("llua_load: %s", lua_tostring(lua_L, -1));
lua_pop(lua_L, 1);
#ifdef HAVE_SYS_INOTIFY_H
} else if (!llua_block_notify && inotify_fd != -1) {
llua_append_notify(path.c_str());
#endif /* HAVE_SYS_INOTIFY_H */
}
}
/*
* Returns the first space-delimited token of the string starting at position
* *len. On return *len contains the length of the token. Spaces inside brackets
* are ignored, so that eg. '${foo bar}' is treated as a single token. Sets *len
* to zero and *str points to the end of the string when there are no more
* tokens.
*/
static const char *tokenize(const char *str, size_t *len) {
str += *len;
*len = 0;
while ((str != nullptr) && (isspace(static_cast<unsigned char>(*str)) != 0)) {
++str;
}
size_t level = 0;
while ((str != nullptr) && (str[*len] != 0) &&
(level > 0 || (isspace(static_cast<unsigned char>(str[*len])) == 0))) {
switch (str[*len]) {
case '{':
++level;
break;
case '}':
--level;
break;
}
++*len;
}
if (str != nullptr && (str[*len] == 0) && level > 0) {
NORM_ERR("tokenize: improperly nested token: %s", str);
}
return str;
}
/*
llua_do_call does a flexible call to any Lua function
string: <function> [par1] [par2...]
retc: the number of return values expected
*/
static char *llua_do_call(const char *string, int retc) {
static char func[64];
int argc = 0;
size_t len = 0;
const char *ptr = tokenize(string, &len);
/* proceed only if the function name is present */
if (len == 0U) { return nullptr; }
/* call only conky_ prefixed functions */
if (strncmp(ptr, LUAPREFIX, strlen(LUAPREFIX)) != 0) {
snprintf(func, sizeof func, "%s", LUAPREFIX);
} else {
*func = 0;
}
strncat(func, ptr, std::min(len, sizeof(func) - strlen(func) - 1));
/* push the function name to stack */
lua_getglobal(lua_L, func);
/* parse all function parameters from args and push them to the stack */
while (ptr = tokenize(ptr, &len), len != 0u) {
lua_pushlstring(lua_L, ptr, len);
argc++;
}
if (lua_pcall(lua_L, argc, retc, 0) != 0) {
NORM_ERR("llua_do_call: function %s execution failed: %s", func,
lua_tostring(lua_L, -1));
lua_pop(lua_L, -1);
return nullptr;
}
return func;
}
#if 0
/*
* same as llua_do_call() except passes everything after func as one arg.
*/
static char *llua_do_read_call(const char *function, const char *arg, int retc)
{
static char func[64];
snprintf(func, 64, "conky_%s", function);
/* push the function name to stack */
lua_getglobal(lua_L, func);
/* push function parameter to the stack */
lua_pushstring(lua_L, arg);
if (lua_pcall(lua_L, 1, retc, 0) != 0) {
NORM_ERR("llua_do_call: function %s execution failed: %s", func, lua_tostring(lua_L, -1));
lua_pop(lua_L, -1);
return nullptr;
}
return func;
}
#endif
/* call a function with args, and return a string from it (must be free'd) */
static char *llua_getstring(const char *args) {
char *func;
char *ret = nullptr;
if (lua_L == nullptr) { return nullptr; }
func = llua_do_call(args, 1);
if (func != nullptr) {
if (lua_isstring(lua_L, -1) == 0) {
NORM_ERR(
"llua_getstring: function %s didn't return a string, result "
"discarded",
func);
} else {
ret = strdup(lua_tostring(lua_L, -1));
lua_pop(lua_L, 1);
}
}
return ret;
}
#if 0
/* call a function with args, and return a string from it (must be free'd) */
static char *llua_getstring_read(const char *function, const char *arg)
{
char *func;
char *ret = nullptr;
if(!lua_L) return nullptr;
func = llua_do_read_call(function, arg, 1);
if (func) {
if(!lua_isstring(lua_L, -1)) {
NORM_ERR("llua_getstring_read: function %s didn't return a string, result discarded", func);
} else {
ret = strdup(lua_tostring(lua_L, -1));
lua_pop(lua_L, 1);
}
}
return ret;
}
#endif
/* call a function with args, and put the result in ret */
static int llua_getnumber(const char *args, double *ret) {
char *func;
if (lua_L == nullptr) { return 0; }
func = llua_do_call(args, 1);
if (func != nullptr) {
if (lua_isnumber(lua_L, -1) == 0) {
NORM_ERR(
"llua_getnumber: function %s didn't return a number, result "
"discarded",
func);
} else {
*ret = lua_tonumber(lua_L, -1);
lua_pop(lua_L, 1);
return 1;
}
}
return 0;
}
#ifdef HAVE_SYS_INOTIFY_H
struct _lua_notify_s {
int wd;
char name[DEFAULT_TEXT_BUFFER_SIZE];
struct _lua_notify_s *next;
};
static struct _lua_notify_s *lua_notifies = 0;
static struct _lua_notify_s *llua_notify_list_do_alloc(const char *name) {
struct _lua_notify_s *ret =
(struct _lua_notify_s *)malloc(sizeof(struct _lua_notify_s));
memset(ret, 0, sizeof(struct _lua_notify_s));
strncpy(ret->name, name, DEFAULT_TEXT_BUFFER_SIZE);
return ret;
}
void llua_append_notify(const char *name) {
/* do it */
struct _lua_notify_s *new_tail = 0;
if (!lua_notifies) {
/* empty, fresh new digs */
new_tail = lua_notifies = llua_notify_list_do_alloc(name);
} else {
struct _lua_notify_s *tail = lua_notifies;
while (tail->next) { tail = tail->next; }
// should be @ the end now
new_tail = llua_notify_list_do_alloc(name);
tail->next = new_tail;
}
new_tail->wd = inotify_add_watch(inotify_fd, new_tail->name, IN_MODIFY);
}
void llua_rm_notifies(void) {
/* git 'er done */
struct _lua_notify_s *head = lua_notifies;
struct _lua_notify_s *next = 0;
if (!lua_notifies) return;
inotify_rm_watch(inotify_fd, head->wd);
if (head->next) next = head->next;
free(head);
while (next) {
head = next;
next = head->next;
inotify_rm_watch(inotify_fd, head->wd);
free(head);
}
lua_notifies = 0;
}
void llua_inotify_query(int wd, int mask) {
struct _lua_notify_s *head = lua_notifies;
if (mask & IN_MODIFY || mask & IN_IGNORED) {
/* for whatever reason, i keep getting IN_IGNORED when the file is
* modified */
while (head) {
if (head->wd == wd) {
llua_block_notify = 1;
llua_load(head->name);
llua_block_notify = 0;
NORM_ERR("Lua script '%s' reloaded", head->name);
if (mask & IN_IGNORED) {
/* for some reason we get IN_IGNORED here
* sometimes, so we need to re-add the watch */
head->wd = inotify_add_watch(inotify_fd, head->name, IN_MODIFY);
}
return;
}
head = head->next;
}
}
}
#endif /* HAVE_SYS_INOTIFY_H */
void llua_set_number(const char *key, double value) {
lua_pushnumber(lua_L, value);
lua_setfield(lua_L, -2, key);
}
void llua_startup_hook() {
if ((lua_L == nullptr) || lua_startup_hook.get(*state).empty()) { return; }
llua_do_call(lua_startup_hook.get(*state).c_str(), 0);
}
void llua_shutdown_hook() {
if ((lua_L == nullptr) || lua_shutdown_hook.get(*state).empty()) { return; }
llua_do_call(lua_shutdown_hook.get(*state).c_str(), 0);
}
#ifdef BUILD_GUI
void llua_draw_pre_hook() {
if ((lua_L == nullptr) || lua_draw_hook_pre.get(*state).empty()) { return; }
llua_do_call(lua_draw_hook_pre.get(*state).c_str(), 0);
}
void llua_draw_post_hook() {
if ((lua_L == nullptr) || lua_draw_hook_post.get(*state).empty()) { return; }
llua_do_call(lua_draw_hook_post.get(*state).c_str(), 0);
}
#ifdef BUILD_MOUSE_EVENTS
template <typename EventT>
bool llua_mouse_hook(const EventT &ev) {
if ((lua_L == nullptr) || lua_mouse_hook.get(*state).empty()) {
return false;
}
const std::string raw_hook_name = lua_mouse_hook.get(*state);
std::string hook_name;
if (raw_hook_name.rfind("conky_", 0) == 0) {
hook_name = raw_hook_name;
} else {
hook_name = "conky_" + raw_hook_name;
}
int ty = lua_getglobal(lua_L, hook_name.c_str());
if (ty == LUA_TNIL) {
int ty_raw = lua_getglobal(lua_L, raw_hook_name.c_str());
if (ty_raw == LUA_TFUNCTION) {
// TODO: (1.22.0) Force conky_ prefix on use_mouse_hook like llua_do_call
// does
// - keep only else case, remove ty_raw and make hook_name const.
NORM_ERR(
"llua_mouse_hook: hook %s declaration is missing 'conky_' prefix",
raw_hook_name.c_str());
hook_name = raw_hook_name;
ty = ty_raw;
lua_insert(lua_L, -2);
lua_pop(lua_L, 1);
} else {
NORM_ERR("llua_mouse_hook: hook %s is not defined", hook_name.c_str());
lua_pop(lua_L, 2);
return false;
}
} else if (ty != LUA_TFUNCTION) {
NORM_ERR("llua_mouse_hook: hook %s is not a function", hook_name.c_str());
lua_pop(lua_L, 1);
return false;
}
ev.push_lua_table(lua_L);
bool result = false;
if (lua_pcall(lua_L, 1, 1, 0) != LUA_OK) {
NORM_ERR("llua_mouse_hook: hook %s execution failed: %s", hook_name.c_str(),
lua_tostring(lua_L, -1));
lua_pop(lua_L, 1);
} else {
result = lua_toboolean(lua_L, -1);
lua_pop(lua_L, 1);
}
return result;
}
template bool llua_mouse_hook<conky::mouse_scroll_event>(
const conky::mouse_scroll_event &ev);
template bool llua_mouse_hook<conky::mouse_button_event>(
const conky::mouse_button_event &ev);
template bool llua_mouse_hook<conky::mouse_move_event>(
const conky::mouse_move_event &ev);
template bool llua_mouse_hook<conky::mouse_crossing_event>(
const conky::mouse_crossing_event &ev);
#endif /* BUILD_MOUSE_EVENTS */
void llua_set_userdata(const char *key, const char *type, void *value) {
tolua_pushusertype(lua_L, value, type);
lua_setfield(lua_L, -2, key);
}
void llua_setup_window_table(conky::rect<int> text_rect) {
if (lua_L == nullptr) { return; }
lua_newtable(lua_L);
#ifdef BUILD_X11
if (out_to_x.get(*state)) {
llua_set_userdata("drawable", "Drawable", (void *)&window.drawable);
llua_set_userdata("visual", "Visual", window.visual);
llua_set_userdata("display", "Display", display);
}
#endif /*BUILD_X11*/
#ifdef BUILD_GUI
if (out_to_gui(*state)) {
#ifdef BUILD_X11
llua_set_number("width", window.geometry.width());
llua_set_number("height", window.geometry.height());
#endif /*BUILD_X11*/
llua_set_number("border_inner_margin", border_inner_margin.get(*state));
llua_set_number("border_outer_margin", border_outer_margin.get(*state));
llua_set_number("border_width", border_width.get(*state));
llua_set_number("text_start_x", text_rect.x());
llua_set_number("text_start_y", text_rect.y());
llua_set_number("text_width", text_rect.width());
llua_set_number("text_height", text_rect.height());
lua_setglobal(lua_L, "conky_window");
}
#endif /*BUILD_GUI*/
}
void llua_update_window_table(conky::rect<int> text_rect) {
if (lua_L == nullptr) { return; }
lua_getglobal(lua_L, "conky_window");
if (lua_isnil(lua_L, -1)) {
/* window table isn't populated yet */
lua_pop(lua_L, 1);
return;
}
#ifdef BUILD_X11
llua_set_number("width", window.geometry.width());
llua_set_number("height", window.geometry.height());
#endif /*BUILD_X11*/
llua_set_number("text_start_x", text_rect.x());
llua_set_number("text_start_y", text_rect.y());
llua_set_number("text_width", text_rect.width());
llua_set_number("text_height", text_rect.height());
lua_setglobal(lua_L, "conky_window");
}
#endif /* BUILD_GUI */
void llua_setup_info(struct information *i, double u_interval) {
if (lua_L == nullptr) { return; }
lua_newtable(lua_L);
llua_set_number("update_interval", u_interval);
llua_set_number("cpu_count", i->cpu_count);
lua_setglobal(lua_L, "conky_info");
}
void llua_update_info(struct information *i, double u_interval) {
if (lua_L == nullptr) { return; }
lua_getglobal(lua_L, "conky_info");
if (lua_isnil(lua_L, -1)) {
/* window table isn't populated yet */
lua_pop(lua_L, 1);
return;
}
llua_set_number("update_interval", u_interval);
(void)i;
lua_setglobal(lua_L, "conky_info");
}
void print_lua(struct text_object *obj, char *p, unsigned int p_max_size) {
char *str = llua_getstring(obj->data.s);
if (str != nullptr) {
snprintf(p, p_max_size, "%s", str);
free(str);
}
}
void print_lua_parse(struct text_object *obj, char *p,
unsigned int p_max_size) {
char *str = llua_getstring(obj->data.s);
if (str != nullptr) {
evaluate(str, p, p_max_size);
free(str);
}
}
double lua_barval(struct text_object *obj) {
double per;
if (llua_getnumber(obj->data.s, &per) != 0) { return per; }
return 0;
}
| 19,137
|
C++
|
.cc
| 577
| 28.925477
| 95
| 0.636373
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
22,561
|
smapi.cc
|
brndnmtthws_conky/src/smapi.cc
|
/*
*
* smapi.c: conky support for IBM Thinkpad smapi
*
* Copyright (C) 2007 Phil Sutter <Phil@nwl.cc>
*
* This library 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 2 of the License, or
* (at your option) any later version.
*
* This library 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 this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA.
*
*/
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "conky.h" /* text_buffer_size, PACKAGE_NAME, maybe more */
#include "logging.h"
#include "temphelper.h"
#define SYS_SMAPI_PATH "/sys/devices/platform/smapi"
static int smapi_read_int(const char *path) {
FILE *fp;
int i = 0;
if ((fp = fopen(path, "r"))) {
if (fscanf(fp, "%i\n", &i) < 0) perror("fscanf()");
fclose(fp);
}
return i;
}
static int smapi_bat_installed_internal(int idx) {
char path[128];
struct stat sb;
int ret = 0;
snprintf(path, 127, SYS_SMAPI_PATH "/BAT%i", idx);
if (!stat(path, &sb) && (sb.st_mode & S_IFMT) == S_IFDIR) {
snprintf(path, 127, SYS_SMAPI_PATH "/BAT%i/installed", idx);
ret = (smapi_read_int(path) == 1) ? 1 : 0;
}
return ret;
}
static char *smapi_read_str(const char *path) {
FILE *fp;
char str[256] = "failed";
if ((fp = fopen(path, "r")) != nullptr) {
if (fscanf(fp, "%255s\n", str) < 0) perror("fscanf()");
fclose(fp);
}
return strndup(str, text_buffer_size.get(*state));
}
static char *smapi_get_str(const char *fname) {
char path[128];
if (snprintf(path, 127, SYS_SMAPI_PATH "/%s", fname) < 0) return nullptr;
return smapi_read_str(path);
}
static char *smapi_get_bat_str(int idx, const char *fname) {
char path[128];
if (snprintf(path, 127, SYS_SMAPI_PATH "/BAT%i/%s", idx, fname) < 0)
return nullptr;
return smapi_read_str(path);
}
static int smapi_get_bat_int(int idx, const char *fname) {
char path[128];
if (snprintf(path, 127, SYS_SMAPI_PATH "/BAT%i/%s", idx, fname) < 0) return 0;
return smapi_read_int(path);
}
static char *smapi_get_bat_val(const char *args) {
char fname[128];
int idx, cnt;
if (sscanf(args, "%i %n", &idx, &cnt) <= 0 ||
snprintf(fname, 127, "%s", (args + cnt)) < 0) {
NORM_ERR("smapi: wrong arguments, should be 'bat,<int>,<str>'");
return nullptr;
}
if (!smapi_bat_installed_internal(idx)) return nullptr;
return smapi_get_bat_str(idx, fname);
}
static char *smapi_get_val(const char *args) {
char str[128];
if (!args || sscanf(args, "%127s", str) <= 0) return nullptr;
if (!strcmp(str, "bat")) return smapi_get_bat_val(args + 4);
return smapi_get_str(str);
}
void print_smapi(struct text_object *obj, char *p, unsigned int p_max_size) {
char *s;
if (!obj->data.s) return;
s = smapi_get_val(obj->data.s);
snprintf(p, p_max_size, "%s", s);
free(s);
}
uint8_t smapi_bat_percentage(struct text_object *obj) {
int idx, val = 0;
if (obj->data.s && sscanf(obj->data.s, "%i", &idx) == 1) {
val = smapi_bat_installed_internal(idx)
? smapi_get_bat_int(idx, "remaining_percent")
: 0;
} else
NORM_ERR("argument to smapi_bat_perc must be an integer");
return val;
}
void print_smapi_bat_temp(struct text_object *obj, char *p,
unsigned int p_max_size) {
int idx, val;
if (obj->data.s && sscanf(obj->data.s, "%i", &idx) == 1) {
val = smapi_bat_installed_internal(idx)
? smapi_get_bat_int(idx, "temperature")
: 0;
/* temperature is in milli degree celsius */
temp_print(p, p_max_size, val / 1000, TEMP_CELSIUS, 1);
} else
NORM_ERR("argument to smapi_bat_temp must be an integer");
}
void print_smapi_bat_power(struct text_object *obj, char *p,
unsigned int p_max_size) {
int idx, val;
if (obj->data.s && sscanf(obj->data.s, "%i", &idx) == 1) {
val = smapi_bat_installed_internal(idx)
? smapi_get_bat_int(idx, "power_now")
: 0;
/* power_now is in mW, set to W with one digit precision */
snprintf(p, p_max_size, "%.1f", ((double)val / 1000));
} else
NORM_ERR("argument to smapi_bat_power must be an integer");
}
double smapi_bat_barval(struct text_object *obj) {
if (obj->data.i >= 0 && smapi_bat_installed_internal(obj->data.i))
return smapi_get_bat_int(obj->data.i, "remaining_percent");
return 0;
}
int smapi_bat_installed(struct text_object *obj) {
int idx;
if (obj->data.s && sscanf(obj->data.s, "%i", &idx) == 1) {
if (!smapi_bat_installed_internal(idx)) { return 0; }
} else
NORM_ERR("argument to if_smapi_bat_installed must be an integer");
return 1;
}
| 5,147
|
C++
|
.cc
| 148
| 31.128378
| 80
| 0.647698
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
22,562
|
x11-color.cc
|
brndnmtthws_conky/src/x11-color.cc
|
#include "colours.h"
#include <X11/Xlib.h>
unsigned long Colour::to_x11_color(Display *display, int screen,
bool transparency, bool premultiply) {
static std::unordered_map<Colour, unsigned long, Colour::Hash> x11_pixels;
if (display == nullptr) {
/* cannot work if display is not open */
return 0;
}
unsigned long pixel;
/* Either get a cached X11 pixel or allocate one */
if (auto pixel_iter = x11_pixels.find(*this);
pixel_iter != x11_pixels.end()) {
pixel = pixel_iter->second;
} else {
XColor xcolor{};
xcolor.red = this->red * 257;
xcolor.green = this->green * 257;
xcolor.blue = this->blue * 257;
if (XAllocColor(display, DefaultColormap(display, screen), &xcolor) == 0) {
// NORM_ERR("can't allocate X color");
return 0;
}
/* Save pixel value in the cache to avoid reallocating it */
x11_pixels[*this] = xcolor.pixel;
pixel = static_cast<unsigned long>(xcolor.pixel);
}
pixel &= 0xffffff;
#ifdef BUILD_ARGB
if (transparency) {
if (premultiply)
pixel = (red * alpha / 255) << 16 | (green * alpha / 255) << 8 |
(blue * alpha / 255);
pixel |= ((unsigned long)alpha << 24);
}
#endif /* BUILD_ARGB */
return pixel;
}
| 1,279
|
C++
|
.cc
| 38
| 28.473684
| 79
| 0.621862
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,563
|
solaris.cc
|
brndnmtthws_conky/src/solaris.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <dirent.h>
#include <kstat.h>
#include <limits.h>
#include <net/if.h>
#include <procfs.h>
#include <project.h>
#include <sys/loadavg.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include <sys/stat.h>
#include <sys/swap.h>
#include <sys/sysinfo.h>
#include <sys/task.h>
#include <unistd.h>
#include "common.h"
#include "conky.h"
#include "diskio.h"
#include "top.h"
#include <assert.h>
#include "net_stat.h"
#include "solaris.h"
static kstat_ctl_t *kstat;
static time_t kstat_updated;
static int pageshift = INT_MAX;
static pthread_mutex_t kstat_mtx = PTHREAD_MUTEX_INITIALIZER;
static int pagetok(int pages) {
if (pageshift == INT_MAX) {
int pagesize = sysconf(_SC_PAGESIZE);
pageshift = 0;
while ((pagesize >>= 1) > 0) pageshift++;
pageshift -= 10; /* 2^10 = 1024 */
}
return (pageshift > 0 ? pages << pageshift : pages >> -pageshift);
}
static void update_kstat() {
time_t now;
pthread_mutex_lock(&kstat_mtx);
now = time(nullptr);
if (kstat == nullptr) {
if ((kstat = kstat_open()) == nullptr) {
pthread_mutex_unlock(&kstat_mtx);
NORM_ERR("can't open kstat: %s", strerror(errno));
return;
}
kstat_updated = 0;
}
if (now - kstat_updated < 2) {
/* Do not update kstats too often */
pthread_mutex_unlock(&kstat_mtx);
return;
}
if (kstat_chain_update(kstat) == -1) {
pthread_mutex_unlock(&kstat_mtx);
perror("kstat_chain_update");
return;
}
kstat_updated = now;
pthread_mutex_unlock(&kstat_mtx);
}
static kstat_named_t *get_kstat(const char *module, int inst, const char *name,
const char *stat) {
kstat_t *ksp;
update_kstat();
pthread_mutex_lock(&kstat_mtx);
ksp = kstat_lookup(kstat, (char *)module, inst, (char *)name);
if (ksp == nullptr) {
NORM_ERR("cannot lookup kstat %s:%d:%s:%s %s", module, inst, name, stat,
strerror(errno));
pthread_mutex_unlock(&kstat_mtx);
return nullptr;
}
if (kstat_read(kstat, ksp, nullptr) >= 0) {
if (ksp->ks_type == KSTAT_TYPE_NAMED || ksp->ks_type == KSTAT_TYPE_TIMER) {
kstat_named_t *knp =
(kstat_named_t *)kstat_data_lookup(ksp, (char *)stat);
pthread_mutex_unlock(&kstat_mtx);
return knp;
} else {
NORM_ERR("kstat %s:%d:%s:%s has unexpected type %d", module, inst, name,
stat, ksp->ks_type);
pthread_mutex_unlock(&kstat_mtx);
return nullptr;
}
}
NORM_ERR("cannot read kstat %s:%d:%s:%s", module, inst, name, stat);
pthread_mutex_unlock(&kstat_mtx);
return nullptr;
}
void prepare_update() { kstat_updated = 0; }
int update_meminfo() {
kstat_named_t *knp;
int nswap = swapctl(SC_GETNSWP, 0);
struct swaptable *swt;
struct swapent *swe;
char path[PATH_MAX];
unsigned long stp, sfp;
/* RAM stats */
knp = get_kstat("unix", -1, "system_pages", "freemem");
if (knp != nullptr) info.memfree = pagetok(knp->value.ui32);
info.memmax = pagetok(sysconf(_SC_PHYS_PAGES));
if (info.memmax > info.memfree)
info.mem = info.memmax - info.memfree;
else /* for non-global zones with capped memory */
info.mem = info.memmax;
/* Swap stats */
if (nswap < 1) return 0;
/* for swapctl(2) */
swt =
(struct swaptable *)malloc(nswap * sizeof(struct swapent) + sizeof(int));
if (swt == nullptr) return 0;
swt->swt_n = nswap;
swe = &(swt->swt_ent[0]);
/* We are not interested in ste_path */
for (int i = 0; i < nswap; i++) swe[i].ste_path = path;
nswap = swapctl(SC_LIST, swt);
swe = &(swt->swt_ent[0]);
stp = sfp = 0;
for (int i = 0; i < nswap; i++) {
if ((swe[i].ste_flags & ST_INDEL) || (swe[i].ste_flags & ST_DOINGDEL))
continue;
stp += swe->ste_pages;
sfp += swe->ste_free;
}
free(swt);
info.swapfree = pagetok(sfp);
info.swapmax = pagetok(stp);
info.swap = info.swapmax - info.swapfree;
return 0;
}
int check_mount(struct text_object *obj) {
/* stub */
(void)obj;
return 0;
}
double get_battery_perct_bar(struct text_object *obj) {
/* Not implemented */
(void)obj;
return 100.0;
}
double get_acpi_temperature(int fd) {
/* Not implemented */
(void)fd;
return 0.0;
}
int update_total_processes(void) {
kstat_named_t *knp = get_kstat("unix", -1, "system_misc", "nproc");
if (knp != nullptr) info.procs = knp->value.ui32;
return 0;
}
void get_battery_stuff(char *buf, unsigned int n, const char *bat, int item) {
/* Not implemented */
}
int update_running_processes(void) {
/* There is no kstat for this, see update_proc_entry() */
return 0;
}
int update_net_stats(void) {
struct ifconf ifc;
int sockfd;
char buf[1024];
double d = current_update_time - last_update_time;
if (d < 0.1) return 0;
/* Find all active net interfaces */
if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
NORM_ERR("cannot create socket: %s", strerror(errno));
return 0;
}
ifc.ifc_buf = buf;
ifc.ifc_len = sizeof(buf);
if (ioctl(sockfd, SIOCGIFCONF, &ifc) < 0) {
NORM_ERR("ioctl(SIOCGIFCONF) failed: %s", strerror(errno));
(void)close(sockfd);
return 0;
}
(void)close(sockfd);
/* Collect stats for all active interfaces */
for (int i = 0; i < ifc.ifc_len / sizeof(struct ifreq); i++) {
struct net_stat *ns;
struct ifreq *ifr = &ifc.ifc_req[i];
long long last_recv, last_trans;
long long r, t;
kstat_named_t *knp;
ns = get_net_stat((const char *)ifr->ifr_name, nullptr, NULL);
ns->up = 1;
memcpy(&(ns->addr), &ifr->ifr_addr, sizeof(ifr->ifr_addr));
/* Skip the loopback interface, it does not have kstat data */
if (ifr->ifr_flags & IFF_LOOPBACK || strcmp(ifr->ifr_name, "lo0") == 0)
continue;
last_recv = ns->recv;
last_trans = ns->trans;
/* Get received bytes */
knp = get_kstat("link", -1, ifr->ifr_name, "rbytes");
if (knp == nullptr) {
NORM_ERR("cannot read rbytes for %s\n", ifr->ifr_name);
continue;
}
r = (long long)knp->value.ui32;
if (r <= ns->last_read_recv) {
ns->recv += ((long long)4294967295U - ns->last_read_recv) + r;
} else {
ns->recv += (r - ns->last_read_recv);
}
ns->last_read_recv = r;
/* Get transceived bytes */
knp = get_kstat("link", -1, ifr->ifr_name, "obytes");
if (knp == nullptr) {
NORM_ERR("cannot read obytes for %s\n", ifr->ifr_name);
continue;
}
t = (long long)knp->value.ui32;
if (t < ns->last_read_trans) {
ns->trans += ((long long)4294967295U - ns->last_read_trans) + t;
} else {
ns->trans += (t - ns->last_read_trans);
}
ns->last_read_trans = t;
ns->recv_speed = (ns->recv - last_recv) / d;
ns->trans_speed = (ns->trans - last_trans) / d;
}
return 0;
}
int update_cpu_usage(void) {
static int last_cpu_cnt = 0;
static int *last_cpu_use = nullptr;
double d = current_update_time - last_update_time;
double total_cpu_usage = 0;
int cpu;
if (d < 0.1) return 0;
update_kstat();
info.cpu_count = sysconf(_SC_NPROCESSORS_ONLN);
/* (Re)allocate the array with previous values */
if (last_cpu_cnt != info.cpu_count || last_cpu_use == nullptr) {
last_cpu_use =
(int *)realloc(last_cpu_use, (info.cpu_count + 1) * sizeof(int));
last_cpu_cnt = info.cpu_count;
if (last_cpu_use == nullptr) return 0;
}
info.cpu_usage = (float *)malloc((info.cpu_count + 1) * sizeof(float));
pthread_mutex_lock(&kstat_mtx);
for (cpu = 1; cpu <= info.cpu_count; cpu++) {
char stat_name[PATH_MAX];
unsigned long cpu_user, cpu_nice, cpu_system, cpu_idle;
unsigned long cpu_use;
cpu_stat_t *cs;
kstat_t *ksp;
snprintf(stat_name, PATH_MAX, "cpu_stat%d", cpu - 1);
ksp = kstat_lookup(kstat, (char *)"cpu_stat", cpu - 1, stat_name);
if (ksp == nullptr) continue;
if (kstat_read(kstat, ksp, nullptr) == -1) continue;
cs = (cpu_stat_t *)ksp->ks_data;
cpu_idle = cs->cpu_sysinfo.cpu[CPU_IDLE];
cpu_user = cs->cpu_sysinfo.cpu[CPU_USER];
cpu_nice = cs->cpu_sysinfo.cpu[CPU_WAIT];
cpu_system = cs->cpu_sysinfo.cpu[CPU_KERNEL];
cpu_use = cpu_user + cpu_nice + cpu_system;
info.cpu_usage[cpu] = (double)(cpu_use - last_cpu_use[cpu]) / d / 100.0;
total_cpu_usage += info.cpu_usage[cpu];
last_cpu_use[cpu] = cpu_use;
}
pthread_mutex_unlock(&kstat_mtx);
info.cpu_usage[0] = total_cpu_usage / info.cpu_count;
return 0;
}
void free_cpu(struct text_object *) { /* no-op */
}
void update_proc_entry(struct process *p) {
psinfo_t proc;
int fd;
char pfn[PATH_MAX];
snprintf(pfn, PATH_MAX, "/proc/%d/psinfo", p->pid);
/* Ignore errors here as the process can be gone */
if ((fd = open(pfn, O_RDONLY)) < 0) return;
if (pread(fd, &proc, sizeof(psinfo_t), 0) != sizeof(psinfo_t)) {
(void)close(fd);
return;
}
(void)close(fd);
free_and_zero(p->name);
free_and_zero(p->basename);
p->name = strndup(proc.pr_fname, text_buffer_size.get(*::state));
p->basename = strndup(proc.pr_fname, text_buffer_size.get(*::state));
p->uid = proc.pr_uid;
/* see proc(4) */
p->amount = (double)proc.pr_pctcpu / (double)0x8000 * 100.0;
p->rss = proc.pr_rssize * 1024; /* to bytes */
p->vsize = proc.pr_size * 1024; /* to bytes */
p->total_cpu_time = proc.pr_time.tv_sec * 100; /* to hundredths of secs */
if (proc.pr_lwp.pr_sname == 'O' || proc.pr_lwp.pr_sname == 'R')
info.run_procs++;
p->time_stamp = g_time;
}
void get_top_info(void) {
DIR *dir;
struct dirent *entry;
if (!(dir = opendir("/proc"))) { return; }
info.run_procs = 0;
while ((entry = readdir(dir))) {
pid_t pid;
if (entry == nullptr) break;
if (sscanf(entry->d_name, "%u", &pid) != 1) continue;
update_proc_entry(get_process(pid));
}
(void)closedir(dir);
}
/*
* Because Solaris systems often have 100s or 1000s of disks, we don't collect
* data for all of them but only for those mentioned in conkyrc.
* Instead of disk's special file in SVR4 format, we use the driver name and
* and the instance number to specify the disk or partition. For example: sd0,
* ssd3, or sd5,b.
*/
int update_diskio(void) {
unsigned int tot_read = 0;
unsigned int tot_written = 0;
update_kstat();
pthread_mutex_lock(&kstat_mtx);
for (struct diskio_stat *cur = &stats; cur; cur = cur->next) {
unsigned int read, written;
kstat_io_t *ksio;
kstat_t *ksp;
if (cur->dev == nullptr) continue;
if ((ksp = kstat_lookup(kstat, nullptr, -1, cur->dev)) == NULL) continue;
if (kstat_read(kstat, ksp, nullptr) == -1) continue;
ksio = (kstat_io_t *)ksp->ks_data;
tot_read += read = (unsigned int)(ksio->nread / 512);
tot_written += written = (unsigned int)(ksio->nwritten / 512);
update_diskio_values(cur, read, written);
}
update_diskio_values(&stats, tot_read, tot_written);
pthread_mutex_unlock(&kstat_mtx);
return 0;
}
void get_battery_short_status(char *buffer, unsigned int n, const char *bat) {
/* Not implemented */
(void)bat;
if (buffer && n > 0) memset(buffer, 0, n);
}
void get_acpi_fan(char *p_client_buffer, size_t client_buffer_size) {
/* Not implemented */
if (p_client_buffer && client_buffer_size > 0)
memset(p_client_buffer, 0, client_buffer_size);
}
void get_acpi_ac_adapter(char *p_client_buffer, size_t client_buffer_size,
const char *adapter) {
/* Not implemented */
if (p_client_buffer && client_buffer_size > 0)
memset(p_client_buffer, 0, client_buffer_size);
}
int get_battery_perct(const char *bat) {
/* Not implemented */
(void)bat;
return 1;
}
int get_entropy_poolsize(unsigned int *val) {
/* Not implemented */
(void)val;
return 1;
}
char get_freq(char *p_client_buffer, size_t client_buffer_size,
const char *p_format, int divisor, unsigned int cpu) {
char stat_name[PATH_MAX];
kstat_named_t *knp;
snprintf(stat_name, PATH_MAX, "cpu_info%d", cpu - 1);
knp = get_kstat("cpu_info", cpu - 1, stat_name, "current_clock_Hz");
if (knp == nullptr) return 0;
snprintf(p_client_buffer, client_buffer_size, p_format,
(float)knp->value.ui32 / divisor / 1000000.0);
return 1;
}
int update_uptime(void) {
kstat_named_t *knp;
knp = get_kstat("unix", -1, "system_misc", "boot_time");
if (knp == nullptr) return 0;
info.uptime = time(nullptr) - knp->value.ui32;
return 1;
}
int open_acpi_temperature(const char *name) {
/* Not implemented */
(void)name;
return 1;
}
int get_entropy_avail(unsigned int *val) {
/* Not implemented */
(void)val;
return 1;
}
int update_load_average(void) {
double load[3];
getloadavg(load, 3);
info.loadavg[0] = (float)load[0];
info.loadavg[1] = (float)load[1];
info.loadavg[2] = (float)load[2];
return 0;
}
void get_cpu_count(void) {
kstat_named_t *knp = get_kstat("unix", -1, "system_misc", "ncpus");
if (knp != nullptr) info.cpu_count = knp->value.ui32;
}
| 13,921
|
C++
|
.cc
| 425
| 29.105882
| 79
| 0.642346
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,564
|
read_tcpip.cc
|
brndnmtthws_conky/src/read_tcpip.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <fcntl.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/time.h>
#include <unistd.h>
#include <cerrno>
#include <cinttypes>
#include <cstdlib>
#include <string>
#include "conky.h"
#include "logging.h"
#include "text_object.h"
#ifndef SOCK_CLOEXEC
#define SOCK_CLOEXEC O_CLOEXEC
#endif /* SOCK_CLOEXEC */
struct read_tcpip_data {
char *host;
unsigned int port;
};
void parse_read_tcpip_arg(struct text_object *obj, const char *arg,
void *free_at_crash) {
struct read_tcpip_data *rtd;
rtd = static_cast<struct read_tcpip_data *>(
malloc(sizeof(struct read_tcpip_data)));
memset(rtd, 0, sizeof(struct read_tcpip_data));
rtd->host = static_cast<char *>(malloc(text_buffer_size.get(*state)));
sscanf(arg, "%s", rtd->host);
sscanf(arg + strlen(rtd->host), "%u", &(rtd->port));
if (rtd->port == 0) {
rtd->port = strtol(rtd->host, nullptr, 10);
strncpy(rtd->host, "localhost", 10);
}
if (rtd->port < 1 || rtd->port > 65535) {
CRIT_ERR_FREE(
obj, free_at_crash,
"read_tcp and read_udp need a port from 1 to 65535 as argument");
}
obj->data.opaque = rtd;
}
void parse_tcp_ping_arg(struct text_object *obj, const char *arg,
void *free_at_crash) {
#define DEFAULT_TCP_PING_PORT 80
struct sockaddr_in *addr;
char *hostname;
struct hostent *he;
addr = static_cast<struct sockaddr_in *>(malloc(sizeof(struct sockaddr_in)));
obj->data.opaque = addr;
memset(addr, 0, sizeof(struct sockaddr_in));
hostname = static_cast<char *>(malloc(strlen(arg) + 1));
switch (sscanf(arg, "%s %" SCNu16, hostname, &(addr->sin_port))) {
case 1:
addr->sin_port = DEFAULT_TCP_PING_PORT;
break;
case 2:
break;
default: // this point should never be reached
free(hostname);
CRIT_ERR_FREE(obj, free_at_crash, "tcp_ping: Reading arguments failed");
}
if ((he = gethostbyname(hostname)) == nullptr) {
NORM_ERR("tcp_ping: Problem with resolving '%s', using 'localhost' instead",
hostname);
if ((he = gethostbyname("localhost")) == nullptr) {
free(hostname);
CRIT_ERR_FREE(obj, free_at_crash,
"tcp_ping: Resolving 'localhost' also failed");
}
}
if (he != nullptr) {
free(hostname);
addr->sin_port = htons(addr->sin_port);
addr->sin_family = he->h_addrtype;
memcpy(&(addr->sin_addr), he->h_addr, he->h_length);
}
}
void print_tcp_ping(struct text_object *obj, char *p, unsigned int p_max_size) {
struct timeval tv1 {
}, tv2{}, timeout{};
auto *addr = static_cast<struct sockaddr_in *>(obj->data.opaque);
int addrlen = sizeof(struct sockaddr);
int sock = socket(addr->sin_family, SOCK_STREAM | SOCK_CLOEXEC, IPPROTO_TCP);
unsigned long long usecdiff;
fd_set writefds;
if (sock != -1) {
fcntl(sock, F_SETFL, O_NONBLOCK | fcntl(sock, F_GETFL));
FD_ZERO(&writefds);
FD_SET(sock, &writefds);
#define TCP_PING_TIMEOUT 10
timeout.tv_sec = TCP_PING_TIMEOUT;
timeout.tv_usec = (TCP_PING_TIMEOUT - timeout.tv_sec) * 1000000;
connect(sock, reinterpret_cast<struct sockaddr *>(addr),
addrlen); // this will "fail" because sock is non-blocking
if (errno == EINPROGRESS) { // but EINPROGRESS is only a "false fail"
gettimeofday(&tv1, nullptr);
if (select(sock + 1, nullptr, &writefds, nullptr, &timeout) != -1) {
int ret = 0;
socklen_t len = sizeof(ret);
gettimeofday(&tv2, nullptr);
usecdiff =
((tv2.tv_sec - tv1.tv_sec) * 1000000) + tv2.tv_usec - tv1.tv_usec;
if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &ret, &len) == 0 && ret == 0) {
snprintf(p, p_max_size, "%llu", (usecdiff / 1000U));
} else {
#define TCP_PING_FAILED "down"
snprintf(p, p_max_size, "%s", TCP_PING_FAILED);
}
} else {
NORM_ERR("tcp_ping: Couldn't wait on the 'pong'");
}
} else {
NORM_ERR("tcp_ping: Couldn't start connection");
}
close(sock);
} else {
NORM_ERR("tcp_ping: Couldn't create socket");
}
}
void print_read_tcpip(struct text_object *obj, char *p, int p_max_size,
int protocol) {
int sock, received;
fd_set readfds;
struct timeval tv {};
auto *rtd = static_cast<struct read_tcpip_data *>(obj->data.opaque);
struct addrinfo hints {};
struct addrinfo *airesult, *rp;
char portbuf[8];
if (rtd == nullptr) { return; }
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = protocol == IPPROTO_TCP ? SOCK_STREAM : SOCK_DGRAM;
hints.ai_flags = 0;
hints.ai_protocol = protocol;
snprintf(portbuf, 8, "%u", rtd->port);
if (getaddrinfo(rtd->host, portbuf, &hints, &airesult) != 0) {
NORM_ERR("%s: Problem with resolving the hostname",
protocol == IPPROTO_TCP ? "read_tcp" : "read_udp");
return;
}
for (rp = airesult; rp != nullptr; rp = rp->ai_next) {
sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (sock == -1) { continue; }
if (connect(sock, rp->ai_addr, rp->ai_addrlen) != -1) { break; }
close(sock);
return;
}
freeaddrinfo(airesult);
if (rp == nullptr) {
if (protocol == IPPROTO_TCP) {
NORM_ERR("read_tcp: Couldn't create a connection");
} else {
NORM_ERR("read_udp: Couldn't listen"); // other error because udp is
// connectionless
}
return;
}
if (protocol == IPPROTO_UDP) {
// when using udp send a zero-length packet to let the other end know of our
// existence
if (write(sock, nullptr, 0) < 0) {
NORM_ERR("read_udp: Couldn't create a empty package");
}
}
FD_ZERO(&readfds);
FD_SET(sock, &readfds);
tv.tv_sec = 1;
tv.tv_usec = 0;
if (select(sock + 1, &readfds, nullptr, nullptr, &tv) > 0) {
received = recv(sock, p, p_max_size, 0);
if (received != -1) {
p[received] = 0;
} else {
p[0] = 0;
}
}
close(sock);
}
void print_read_tcp(struct text_object *obj, char *p, unsigned int p_max_size) {
print_read_tcpip(obj, p, p_max_size, IPPROTO_TCP);
}
void print_read_udp(struct text_object *obj, char *p, unsigned int p_max_size) {
print_read_tcpip(obj, p, p_max_size, IPPROTO_UDP);
}
void free_read_tcpip(struct text_object *obj) {
auto *rtd = static_cast<struct read_tcpip_data *>(obj->data.opaque);
if (rtd == nullptr) { return; }
free_and_zero(rtd->host);
free_and_zero(obj->data.opaque);
}
void free_tcp_ping(struct text_object *obj) {
auto *addr = static_cast<struct sockaddr_in *>(obj->data.opaque);
if (addr == nullptr) { return; }
free_and_zero(obj->data.opaque);
}
| 7,765
|
C++
|
.cc
| 221
| 30.660633
| 82
| 0.643531
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
22,565
|
mouse-events.cc
|
brndnmtthws_conky/src/mouse-events.cc
|
/*
* mouse_events.cc: conky support for mouse events
*
* Copyright (C) 2020 Tin Svagelj tin.svagelj@live.com
*
* This program 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.
*
* This program 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 this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
#include "mouse-events.h"
#include <array>
#include <ctime>
#include <string>
#include <type_traits>
#include "logging.h"
#ifdef BUILD_XINPUT
#include <cstring>
#endif
extern "C" {
#include <lua.h>
#include <X11/Xatom.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
}
namespace conky {
#ifdef BUILD_MOUSE_EVENTS
/* Lua helper functions */
void push_table_value(lua_State *L, std::string key, std::string value) {
lua_pushstring(L, key.c_str());
lua_pushstring(L, value.c_str());
lua_settable(L, -3);
}
template <typename T>
typename std::enable_if<std::is_integral<T>::value>::type push_table_value(
lua_State *L, std::string key, T value) {
lua_pushstring(L, key.c_str());
lua_pushinteger(L, value);
lua_settable(L, -3);
}
template <typename T>
typename std::enable_if<std::is_floating_point<T>::value>::type
push_table_value(lua_State *L, std::string key, T value) {
lua_pushstring(L, key.c_str());
lua_pushnumber(L, value);
lua_settable(L, -3);
}
void push_table_value(lua_State *L, std::string key, bool value) {
lua_pushstring(L, key.c_str());
lua_pushboolean(L, value);
lua_settable(L, -3);
}
template <std::size_t N>
void push_bitset(lua_State *L, std::bitset<N> it,
std::array<std::string, N> labels) {
lua_newtable(L);
for (std::size_t i = 0; i < N; i++)
push_table_value(L, labels[i], it.test(i));
}
const std::array<std::string, 6> mod_names = {{
"shift",
"control",
"alt",
"super",
"caps_lock",
"num_lock",
}};
void push_mods(lua_State *L, modifier_state_t mods) {
lua_pushstring(L, "mods");
push_bitset(L, mods, mod_names);
lua_settable(L, -3);
}
// Returns ms since Epoch.
inline std::size_t current_time_ms() {
struct timespec spec;
clock_gettime(CLOCK_REALTIME, &spec);
return static_cast<std::size_t>(static_cast<std::uint64_t>(spec.tv_sec) *
1'000 +
spec.tv_nsec / 1'000'000);
}
void push_table_value(lua_State *L, std::string key, mouse_event_t type) {
lua_pushstring(L, key.c_str());
switch (type) {
case mouse_event_t::PRESS:
lua_pushstring(L, "button_down");
break;
case mouse_event_t::RELEASE:
lua_pushstring(L, "button_up");
break;
case mouse_event_t::SCROLL:
lua_pushstring(L, "mouse_scroll");
break;
case mouse_event_t::MOVE:
lua_pushstring(L, "mouse_move");
break;
case mouse_event_t::AREA_ENTER:
lua_pushstring(L, "mouse_enter");
break;
case mouse_event_t::AREA_LEAVE:
lua_pushstring(L, "mouse_leave");
break;
default:
lua_pushnil(L);
break;
}
lua_settable(L, -3);
}
void push_table_value(lua_State *L, std::string key,
scroll_direction_t direction) {
lua_pushstring(L, key.c_str());
switch (direction) {
case scroll_direction_t::DOWN:
lua_pushstring(L, "down");
break;
case scroll_direction_t::UP:
lua_pushstring(L, "up");
break;
case scroll_direction_t::LEFT:
lua_pushstring(L, "left");
break;
case scroll_direction_t::RIGHT:
lua_pushstring(L, "right");
break;
default:
lua_pushnil(L);
break;
}
lua_settable(L, -3);
}
void push_table_value(lua_State *L, std::string key, mouse_button_t button) {
lua_pushstring(L, key.c_str());
switch (button) {
case mouse_button_t::LEFT:
lua_pushstring(L, "left");
break;
case mouse_button_t::RIGHT:
lua_pushstring(L, "right");
break;
case mouse_button_t::MIDDLE:
lua_pushstring(L, "middle");
break;
case mouse_button_t::BACK:
lua_pushstring(L, "back");
break;
case mouse_button_t::FORWARD:
lua_pushstring(L, "forward");
break;
default:
lua_pushnil(L);
break;
}
lua_settable(L, -3);
}
/* Class methods */
mouse_event::mouse_event(mouse_event_t type)
: type(type), time(current_time_ms()){};
void mouse_event::push_lua_table(lua_State *L) const {
lua_newtable(L);
push_table_value(L, "type", this->type);
push_table_value(L, "time", this->time);
push_lua_data(L);
}
void mouse_positioned_event::push_lua_data(lua_State *L) const {
push_table_value(L, "x", this->pos.x());
push_table_value(L, "y", this->pos.y());
push_table_value(L, "x_abs", this->pos_absolute.x());
push_table_value(L, "y_abs", this->pos_absolute.y());
}
void mouse_move_event::push_lua_data(lua_State *L) const {
mouse_positioned_event::push_lua_data(L);
push_mods(L, this->mods);
}
void mouse_scroll_event::push_lua_data(lua_State *L) const {
mouse_positioned_event::push_lua_data(L);
push_table_value(L, "direction", this->direction);
push_mods(L, this->mods);
}
void mouse_button_event::push_lua_data(lua_State *L) const {
mouse_positioned_event::push_lua_data(L);
push_table_value(L, "button_code", static_cast<std::uint32_t>(this->button));
push_table_value(L, "button", this->button);
push_mods(L, this->mods);
}
#endif /* BUILD_MOUSE_EVENTS */
#ifdef BUILD_XINPUT
/// Last global device id.
size_t last_device_id = 0;
static std::map<size_t, device_info> device_info_cache{};
static std::map<xi_device_id, size_t> xi_id_mapping{};
device_info *device_info::from_xi_id(xi_device_id device_id, Display *display) {
if (xi_id_mapping.count(device_id) > 0) {
return &device_info_cache[xi_id_mapping[device_id]];
}
if (display == nullptr) return nullptr;
int num_devices;
XIDeviceInfo *device = XIQueryDevice(display, device_id, &num_devices);
if (num_devices == 0) return nullptr;
device_info info =
device_info{.id = device_id, .name = std::string(device->name)};
size_t id = last_device_id++;
info.init_xi_device(display, device);
XIFreeDeviceInfo(device);
device_info_cache[id] = info;
xi_id_mapping[device_id] = id;
return &device_info_cache[id];
}
void handle_xi_device_change(const XIHierarchyEvent *event) {
if ((event->flags & XISlaveRemoved) != 0) {
for (int i = 0; i < event->num_info; i++) {
auto info = event->info[i];
if ((info.flags & XISlaveRemoved) == 0) continue;
if (xi_id_mapping.count(info.deviceid) == 0) continue;
size_t id = xi_id_mapping[info.deviceid];
xi_id_mapping.erase(info.deviceid);
device_info_cache.erase(id);
}
}
if ((event->flags & XISlaveAdded) != 0) {
for (int i = 0; i < event->num_info; i++) {
auto info = event->info[i];
if ((info.flags & XISlaveAdded) == 0) continue;
if (info.use == IsXPointer || info.use == IsXExtensionPointer)
conky::device_info::from_xi_id(info.deviceid, event->display);
}
}
}
/// Allows override of valuator indices in `xorg.conf` in case they're wrong for
/// some device (unlikely).
size_t fixed_valuator_index(Display *display, XIDeviceInfo *device,
valuator_t valuator) {
const std::array<const char *, VALUATOR_COUNT> atom_names = {
"ConkyValuatorMoveX", "ConkyValuatorMoveY", "ConkyValuatorScrollX",
"ConkyValuatorScrollY"};
Atom override_atom = XInternAtom(display, atom_names[*valuator], False);
unsigned char *value;
Atom type_return;
int format_return;
unsigned long num_items;
unsigned long bytes_after;
do {
if (XIGetProperty(display, device->deviceid, override_atom, 0, 1, False,
XA_INTEGER, &type_return, &format_return, &num_items,
&bytes_after,
reinterpret_cast<unsigned char **>(&value)) == 0) {
if (num_items == 0) break;
if (type_return != XA_INTEGER) {
NORM_ERR(
"invalid '%s' option value, expected a single integer; value will "
"be ignored",
atom_names[*valuator]);
XFree(value);
break;
}
uint32_t result = *reinterpret_cast<uint32_t *>(value);
XFree(value);
return static_cast<size_t>(result);
}
} while (true);
return *valuator;
}
/// Allows override of valuator value type in `xorg.conf` in case they're wrong
/// for some device (happens with VMs and some devices/setups).
bool fixed_valuator_relative(Display *display, XIDeviceInfo *device,
valuator_t valuator,
XIValuatorClassInfo *class_info) {
const std::array<const char *, 2> atom_names = {
"ConkyValuatorMoveMode",
"ConkyValuatorScrollMode",
};
Atom override_atom = XInternAtom(display, atom_names[*valuator >> 1], False);
unsigned char *value_return;
Atom type_return;
int format_return;
unsigned long num_items;
unsigned long bytes_after;
do {
if (XIGetProperty(display, device->deviceid, override_atom, 0, 9, False,
XA_ATOM, &type_return, &format_return, &num_items,
&bytes_after,
reinterpret_cast<unsigned char **>(&value_return)) == 0) {
if (num_items == 0) break;
if (type_return != XA_ATOM) {
NORM_ERR(
"invalid '%s' option value, expected an atom (string); value will "
"be ignored",
atom_names[*valuator >> 1]);
XFree(value_return);
break;
}
Atom return_atom = *reinterpret_cast<Atom *>(value_return);
XFree(value_return);
char *value = XGetAtomName(display, return_atom);
// lowercase value
for (auto c = value; *c; ++c) *c = tolower(*c);
bool relative = false;
if (strcmp(reinterpret_cast<char *>(value), "relative") == 0) {
relative = true;
} else if (strcmp(reinterpret_cast<char *>(value), "absolute") != 0) {
NORM_ERR(
"unknown '%s' option value: '%s', expected 'absolute' or "
"'relative'; "
"value will be ignored",
atom_names[*valuator >> 1]);
XFree(value);
break;
}
XFree(value);
return relative;
}
} while (true);
return class_info->mode == XIModeRelative;
}
void device_info::init_xi_device(
Display *display, std::variant<xi_device_id, XIDeviceInfo *> source) {
XIDeviceInfo *device = nullptr;
if (std::holds_alternative<XIDeviceInfo *>(source)) {
device = std::get<XIDeviceInfo *>(source);
} else if (std::holds_alternative<xi_device_id>(source)) {
int num_devices;
device =
XIQueryDevice(display, std::get<xi_device_id>(source), &num_devices);
if (num_devices == 0) return;
}
if (device == nullptr) return;
std::array<size_t, VALUATOR_COUNT> valuator_indices;
for (size_t i = 0; i < VALUATOR_COUNT; i++) {
valuator_indices[i] =
fixed_valuator_index(display, device, static_cast<valuator_t>(i));
}
// class order is undefined!
for (int i = 0; i < device->num_classes; i++) {
if (device->classes[i]->type != XIValuatorClass) continue;
XIValuatorClassInfo *class_info = (XIValuatorClassInfo *)device->classes[i];
// check if one of used (mapped) valuators
valuator_t valuator = valuator_t::UNKNOWN;
for (size_t i = 0; i < VALUATOR_COUNT; i++) {
if (valuator_indices[i] == class_info->number) {
valuator = static_cast<valuator_t>(i);
break;
}
}
if (valuator == valuator_t::UNKNOWN) { continue; }
auto info = conky_valuator_info{
.index = static_cast<size_t>(class_info->number),
.min = class_info->min,
.max = class_info->max,
.value = class_info->value,
.relative =
fixed_valuator_relative(display, device, valuator, class_info),
};
this->valuators[*valuator] = info;
}
if (std::holds_alternative<xi_device_id>(source)) {
XIFreeDeviceInfo(device);
}
}
conky_valuator_info &device_info::valuator(valuator_t valuator) {
return this->valuators[*valuator];
}
xi_event_data *xi_event_data::read_cookie(Display *display, const void *data) {
const XIDeviceEvent *source = reinterpret_cast<const XIDeviceEvent *>(data);
xi_event_type event_type = source->evtype;
if (!(event_type == XI_Motion || event_type == XI_ButtonPress ||
event_type == XI_ButtonRelease)) {
return nullptr;
}
std::bitset<32> buttons;
for (size_t bi = 1; bi < source->buttons.mask_len * 8; bi++) {
if (XIMaskIsSet(source->buttons.mask, bi)) buttons[bi] = true;
}
std::map<size_t, double> valuators{};
double *values = source->valuators.values;
for (size_t vi = 0; vi < source->valuators.mask_len * 8; vi++) {
if (XIMaskIsSet(source->valuators.mask, vi)) valuators[vi] = *values++;
}
auto device = device_info::from_xi_id(source->deviceid, source->display);
if (device == nullptr) return nullptr; // shouldn't happen
auto result = new xi_event_data{
.evtype = static_cast<xi_event_type>(source->evtype),
.serial = source->serial,
.send_event = source->send_event,
.display = source->display,
.extension = source->extension,
.time = source->time,
.device = device,
.sourceid = source->sourceid,
.detail = source->detail,
.root = source->root,
.event = source->event,
.child = source->child,
.pos_absolute = vec2d{source->root_x, source->root_y},
.pos = vec2d{source->event_x, source->event_y},
.flags = source->flags,
.buttons = buttons,
.valuators = valuators,
.mods = source->mods,
.group = source->group,
.valuators_relative = {0.0, 0.0, 0.0, 0.0},
};
for (size_t v = 0; v < VALUATOR_COUNT; v++) {
valuator_t valuator = static_cast<valuator_t>(v);
auto &valuator_info = device->valuator(valuator);
if (result->valuators.count(valuator_info.index) == 0) { continue; }
auto current = result->valuators[valuator_info.index];
if (valuator_info.relative) {
result->valuators_relative[v] = current;
} else {
// XXX these doubles come from int values and might wrap around though
// it's hard to tell what int type is the source as it depends on the
// device/driver.
result->valuators_relative[v] = current - valuator_info.value;
}
valuator_info.value = current;
}
return result;
}
bool xi_event_data::test_valuator(valuator_t valuator) const {
return this->valuators.count(this->device->valuator(valuator).index) > 0;
}
conky_valuator_info *xi_event_data::valuator_info(valuator_t valuator) const {
return &this->device->valuator(valuator);
}
std::optional<double> xi_event_data::valuator_value(valuator_t valuator) const {
auto info = this->valuator_info(valuator);
if (info == nullptr) return std::nullopt;
size_t index = info->index;
if (this->valuators.count(index) == 0) return std::nullopt;
return this->valuators.at(index);
}
std::optional<double> xi_event_data::valuator_relative_value(
valuator_t valuator) const {
return this->valuators_relative.at(*valuator);
}
std::vector<std::tuple<int, XEvent *>> xi_event_data::generate_events(
Window target, Window child, conky::vec2d target_pos) const {
std::vector<std::tuple<int, XEvent *>> result{};
if (this->evtype == XI_Motion) {
auto device_info = this->device;
bool is_move = this->test_valuator(valuator_t::MOVE_X) ||
this->test_valuator(valuator_t::MOVE_Y);
bool is_scroll = this->test_valuator(valuator_t::SCROLL_X) ||
this->test_valuator(valuator_t::SCROLL_Y);
if (is_move) {
XEvent *produced = new XEvent;
std::memset(produced, 0, sizeof(XEvent));
XMotionEvent *e = &produced->xmotion;
e->type = MotionNotify;
e->display = this->display;
e->root = this->root;
e->window = target;
e->subwindow = child;
e->time = CurrentTime;
e->x = static_cast<int>(target_pos.x());
e->y = static_cast<int>(target_pos.y());
e->x_root = static_cast<int>(this->pos_absolute.x());
e->y_root = static_cast<int>(this->pos_absolute.y());
e->state = this->mods.effective;
e->is_hint = NotifyNormal;
e->same_screen = True;
result.emplace_back(std::make_tuple(PointerMotionMask, produced));
}
if (is_scroll) {
XEvent *produced = new XEvent;
std::memset(produced, 0, sizeof(XEvent));
uint scroll_direction = 4;
auto vertical = this->valuator_relative_value(valuator_t::SCROLL_Y);
double vertical_value = vertical.value_or(0.0);
if (vertical_value != 0.0) {
scroll_direction = vertical_value < 0.0 ? Button4 : Button5;
} else {
auto horizontal = this->valuator_relative_value(valuator_t::SCROLL_X);
double horizontal_value = horizontal.value_or(0.0);
if (horizontal_value != 0.0) {
scroll_direction = horizontal_value < 0.0 ? 6 : 7;
}
}
XButtonEvent *e = &produced->xbutton;
e->display = display;
e->root = this->root;
e->window = target;
e->subwindow = child;
e->time = CurrentTime;
e->x = static_cast<int>(target_pos.x());
e->y = static_cast<int>(target_pos.y());
e->x_root = static_cast<int>(this->pos_absolute.x());
e->y_root = static_cast<int>(this->pos_absolute.y());
e->state = this->mods.effective;
e->button = scroll_direction;
e->same_screen = True;
XEvent *press = new XEvent;
e->type = ButtonPress;
std::memcpy(press, produced, sizeof(XEvent));
result.emplace_back(std::make_tuple(ButtonPressMask, press));
e->type = ButtonRelease;
result.emplace_back(std::make_tuple(ButtonReleaseMask, produced));
}
} else {
XEvent *produced = new XEvent;
std::memset(produced, 0, sizeof(XEvent));
XButtonEvent *e = &produced->xbutton;
e->display = display;
e->root = this->root;
e->window = target;
e->subwindow = child;
e->time = CurrentTime;
e->x = static_cast<int>(target_pos.x());
e->y = static_cast<int>(target_pos.y());
e->x_root = static_cast<int>(this->pos_absolute.x());
e->y_root = static_cast<int>(this->pos_absolute.y());
e->state = this->mods.effective;
e->button = this->detail;
e->same_screen = True;
long event_mask = NoEventMask;
switch (this->evtype) {
case XI_ButtonPress:
e->type = ButtonPress;
event_mask = ButtonPressMask;
break;
case XI_ButtonRelease:
e->type = ButtonRelease;
event_mask = ButtonReleaseMask;
switch (this->detail) {
case 1:
event_mask |= Button1MotionMask;
break;
case 2:
event_mask |= Button2MotionMask;
break;
case 3:
event_mask |= Button3MotionMask;
break;
case 4:
event_mask |= Button4MotionMask;
break;
case 5:
event_mask |= Button5MotionMask;
break;
}
break;
}
result.emplace_back(std::make_tuple(event_mask, produced));
}
return result;
}
#endif /* BUILD_XINPUT */
} // namespace conky
| 19,719
|
C++
|
.cc
| 555
| 29.963964
| 80
| 0.634278
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,566
|
top.cc
|
brndnmtthws_conky/src/top.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2005 Adi Zaimi, Dan Piponi <dan@tanelorn.demon.co.uk>,
* Dave Clark <clarkd@skynet.ca>
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "top.h"
#include "logging.h"
#include "prioqueue.h"
/* hash table size - always a power of 2 */
#define HTABSIZE 256
struct process *first_process = nullptr;
unsigned long g_time = 0;
/* a simple hash table to speed up find_process() */
struct proc_hash_entry {
struct proc_hash_entry *next;
struct process *proc;
};
static struct proc_hash_entry proc_hash_table[HTABSIZE];
static void hash_process(struct process *p) {
struct proc_hash_entry *phe;
static char first_run = 1;
int bucket;
/* better make sure all next pointers are zero upon first access */
if (first_run != 0) {
memset(proc_hash_table, 0, sizeof(struct proc_hash_entry) * HTABSIZE);
first_run = 0;
}
/* get the bucket index */
bucket = p->pid & (HTABSIZE - 1);
/* insert a new element on bucket's top */
phe = static_cast<struct proc_hash_entry *>(
malloc(sizeof(struct proc_hash_entry)));
phe->proc = p;
phe->next = proc_hash_table[bucket].next;
proc_hash_table[bucket].next = phe;
}
static void unhash_process(struct process *p) {
struct proc_hash_entry *phe, *tmp;
/* get the bucket head */
phe = &proc_hash_table[p->pid & (HTABSIZE - 1)];
/* find the entry pointing to p and drop it */
while (phe->next != nullptr) {
if (phe->next->proc == p) {
tmp = phe->next;
phe->next = phe->next->next;
free(tmp);
return;
}
phe = phe->next;
}
}
static void __unhash_all_processes(struct proc_hash_entry *phe) {
if (phe->next != nullptr) { __unhash_all_processes(phe->next); }
free(phe->next);
}
static void unhash_all_processes() {
int i;
for (i = 0; i < HTABSIZE; i++) {
__unhash_all_processes(&proc_hash_table[i]);
proc_hash_table[i].next = nullptr;
}
}
struct process *get_first_process() { return first_process; }
void free_all_processes() {
struct process *next = nullptr, *pr = first_process;
while (pr != nullptr) {
next = pr->next;
free_and_zero(pr->name);
free_and_zero(pr->basename);
free(pr);
pr = next;
}
first_process = nullptr;
/* drop the whole hash table */
unhash_all_processes();
}
struct process *get_process_by_name(const char *name) {
struct process *p = first_process;
while (p != nullptr) {
/* Try matching against the full command line first. If that fails,
* fall back to the basename.
*/
if (((p->name != nullptr) && (strcmp(p->name, name) == 0)) ||
((p->basename != nullptr) && (strcmp(p->basename, name) == 0))) {
return p;
}
p = p->next;
}
return nullptr;
}
static struct process *find_process(pid_t pid) {
struct proc_hash_entry *phe;
phe = &proc_hash_table[pid & (HTABSIZE - 1)];
while (phe->next != nullptr) {
if (phe->next->proc->pid == pid) { return phe->next->proc; }
phe = phe->next;
}
return nullptr;
}
static struct process *new_process(pid_t pid) {
auto *p = static_cast<struct process *>(malloc(sizeof(struct process)));
/* Do stitching necessary for doubly linked list */
p->previous = nullptr;
p->next = first_process;
if (p->next != nullptr) { p->next->previous = p; }
first_process = p;
p->pid = pid;
p->name = nullptr;
p->basename = nullptr;
p->amount = 0;
p->user_time = 0;
p->total = 0;
p->kernel_time = 0;
p->previous_user_time = ULONG_MAX;
p->previous_kernel_time = ULONG_MAX;
p->total_cpu_time = 0;
p->vsize = 0;
p->rss = 0;
#ifdef BUILD_IOSTATS
p->read_bytes = 0;
p->previous_read_bytes = ULLONG_MAX;
p->write_bytes = 0;
p->previous_write_bytes = ULLONG_MAX;
p->io_perc = 0;
#endif /* BUILD_IOSTATS */
p->time_stamp = 0;
p->counted = 1;
p->changed = 0;
/* process_find_name(p); */
/* add the process to the hash table */
hash_process(p);
return p;
}
/* Get / create a new process object and insert it into the process list */
struct process *get_process(pid_t pid) {
struct process *p = find_process(pid);
return p != nullptr ? p : new_process(pid);
}
/******************************************
* Functions *
******************************************/
/******************************************
* Destroy and remove a process *
******************************************/
static void delete_process(struct process *p) {
#if defined(PARANOID)
assert(p->id == 0x0badfeed);
/*
* Ensure that deleted processes aren't reused.
*/
p->id = 0x007babe;
#endif /* defined(PARANOID) */
/*
* Maintain doubly linked list.
*/
if (p->next != nullptr) { p->next->previous = p->previous; }
if (p->previous != nullptr) {
p->previous->next = p->next;
} else {
first_process = p->next;
}
free_and_zero(p->name);
free_and_zero(p->basename);
/* remove the process from the hash table */
unhash_process(p);
free(p);
}
/******************************************
* Strip dead process entries *
******************************************/
static void process_cleanup() {
struct process *p = first_process;
while (p != nullptr) {
struct process *current = p;
#if defined(PARANOID)
assert(p->id == 0x0badfeed);
#endif /* defined(PARANOID) */
p = p->next;
/* Delete processes that have died */
if (current->time_stamp != g_time) {
delete_process(current);
if (current == first_process) { first_process = nullptr; }
current = nullptr;
}
}
}
/******************************************
* Find the top processes *
******************************************/
/* cpu comparison function for prio queue */
static int compare_cpu(void *va, void *vb) {
auto *a = static_cast<struct process *>(va),
*b = static_cast<struct process *>(vb);
if (b->amount > a->amount) { return 1; }
if (a->amount > b->amount) { return -1; }
return 0;
}
/* mem comparison function for prio queue */
static int compare_mem(void *va, void *vb) {
auto *a = static_cast<struct process *>(va),
*b = static_cast<struct process *>(vb);
if (b->rss > a->rss) { return 1; }
if (a->rss > b->rss) { return -1; }
return 0;
}
/* CPU time comparison function for prio queue */
static int compare_time(void *va, void *vb) {
auto *a = static_cast<struct process *>(va),
*b = static_cast<struct process *>(vb);
if (b->total_cpu_time > a->total_cpu_time) { return 1; }
if (b->total_cpu_time < a->total_cpu_time) { return -1; }
return 0;
}
#ifdef BUILD_IOSTATS
/* I/O comparison function for prio queue */
static int compare_io(void *va, void *vb) {
auto *a = static_cast<struct process *>(va),
*b = static_cast<struct process *>(vb);
if (b->io_perc > a->io_perc) { return 1; }
if (a->io_perc > b->io_perc) { return -1; }
return 0;
}
#endif /* BUILD_IOSTATS */
/* ****************************************************************** *
* Get a sorted list of the top cpu hogs and top mem hogs. * Results are stored
* in the cpu,mem arrays in decreasing order[0-9]. *
* ****************************************************************** */
static void process_find_top(struct process **cpu, struct process **mem,
struct process **ptime
#ifdef BUILD_IOSTATS
,
struct process **io
#endif /* BUILD_IOSTATS */
) {
prio_queue_t cpu_queue, mem_queue, time_queue;
#ifdef BUILD_IOSTATS
prio_queue_t io_queue;
#endif
struct process *cur_proc = nullptr;
int i;
if ((top_cpu == 0) && (top_mem == 0) && (top_time == 0)
#ifdef BUILD_IOSTATS
&& (top_io == 0)
#endif /* BUILD_IOSTATS */
&& (top_running == 0)) {
return;
}
cpu_queue = init_prio_queue();
pq_set_compare(cpu_queue, &compare_cpu);
pq_set_max_size(cpu_queue, MAX_SP);
mem_queue = init_prio_queue();
pq_set_compare(mem_queue, &compare_mem);
pq_set_max_size(mem_queue, MAX_SP);
time_queue = init_prio_queue();
pq_set_compare(time_queue, &compare_time);
pq_set_max_size(time_queue, MAX_SP);
#ifdef BUILD_IOSTATS
io_queue = init_prio_queue();
pq_set_compare(io_queue, &compare_io);
pq_set_max_size(io_queue, MAX_SP);
#endif
/* g_time is the time_stamp entry for process. It is updated when the
* process information is updated to indicate that the process is still
* alive (and must not be removed from the process list in
* process_cleanup()) */
++g_time;
/* OS-specific function updating process list */
get_top_info();
process_cleanup(); /* cleanup list from exited processes */
cur_proc = first_process;
while (cur_proc != nullptr) {
if (top_cpu != 0) { insert_prio_elem(cpu_queue, cur_proc); }
if (top_mem != 0) { insert_prio_elem(mem_queue, cur_proc); }
if (top_time != 0) { insert_prio_elem(time_queue, cur_proc); }
#ifdef BUILD_IOSTATS
if (top_io != 0) { insert_prio_elem(io_queue, cur_proc); }
#endif /* BUILD_IOSTATS */
cur_proc = cur_proc->next;
}
for (i = 0; i < MAX_SP; i++) {
if (top_cpu != 0) {
cpu[i] = static_cast<process *>(pop_prio_elem(cpu_queue));
}
if (top_mem != 0) {
mem[i] = static_cast<process *>(pop_prio_elem(mem_queue));
}
if (top_time != 0) {
ptime[i] = static_cast<process *>(pop_prio_elem(time_queue));
}
#ifdef BUILD_IOSTATS
if (top_io != 0) {
io[i] = static_cast<process *>(pop_prio_elem(io_queue));
}
#endif /* BUILD_IOSTATS */
}
free_prio_queue(cpu_queue);
free_prio_queue(mem_queue);
free_prio_queue(time_queue);
#ifdef BUILD_IOSTATS
free_prio_queue(io_queue);
#endif /* BUILD_IOSTATS */
}
int update_top() {
// if nothing else has ever set up info, we need to update it here, because
// info.memmax is used to print percentages in `print_top_mem`
if (info.memmax == 0) { update_meminfo(); }
process_find_top(info.cpu, info.memu, info.time
#ifdef BUILD_IOSTATS
,
info.io
#endif
);
info.first_process = get_first_process();
return 0;
}
static char *format_time(unsigned long timeval, const int width) {
char buf[10];
unsigned long nt; // narrow time, for speed on 32-bit
unsigned cc; // centiseconds
unsigned nn; // multi-purpose whatever
nt = timeval;
cc = nt % 100; // centiseconds past second
nt /= 100; // total seconds
nn = nt % 60; // seconds past the minute
nt /= 60; // total minutes
if (width >= snprintf(buf, sizeof buf, "%lu:%02u.%02u", nt, nn, cc)) {
return strndup(buf, text_buffer_size.get(*state));
}
if (width >= snprintf(buf, sizeof buf, "%lu:%02u", nt, nn)) {
return strndup(buf, text_buffer_size.get(*state));
}
nn = nt % 60; // minutes past the hour
nt /= 60; // total hours
if (width >= snprintf(buf, sizeof buf, "%lu,%02u", nt, nn)) {
return strndup(buf, text_buffer_size.get(*state));
}
nn = nt; // now also hours
if (width >= snprintf(buf, sizeof buf, "%uh", nn)) {
return strndup(buf, text_buffer_size.get(*state));
}
nn /= 24; // now days
if (width >= snprintf(buf, sizeof buf, "%ud", nn)) {
return strndup(buf, text_buffer_size.get(*state));
}
nn /= 7; // now weeks
if (width >= snprintf(buf, sizeof buf, "%uw", nn)) {
return strndup(buf, text_buffer_size.get(*state));
}
// well shoot, this outta' fit...
return strndup("<inf>", text_buffer_size.get(*state));
}
struct top_data {
struct process **list;
int num;
int was_parsed;
char *s;
};
static conky::range_config_setting<unsigned int> top_name_width(
"top_name_width", 0, std::numeric_limits<unsigned int>::max(), 15, true);
static conky::simple_config_setting<bool> top_name_verbose("top_name_verbose",
false, true);
static void print_top_name(struct text_object *obj, char *p,
unsigned int p_max_size) {
auto *td = static_cast<struct top_data *>(obj->data.opaque);
int width;
if ((td == nullptr) || (td->list == nullptr) ||
(td->list[td->num] == nullptr)) {
return;
}
width = std::min(p_max_size,
static_cast<unsigned int>(top_name_width.get(*state)) + 1);
if (top_name_verbose.get(*state)) {
/* print the full command line */
snprintf(p, width + 1, "%-*s", width, td->list[td->num]->name);
} else {
/* print only the basename (i.e. executable name) */
snprintf(p, width + 1, "%-*s", width, td->list[td->num]->basename);
}
}
static void print_top_mem(struct text_object *obj, char *p,
unsigned int p_max_size) {
auto *td = static_cast<struct top_data *>(obj->data.opaque);
int width;
if ((td == nullptr) || (td->list == nullptr) ||
(td->list[td->num] == nullptr)) {
return;
}
width = std::min(p_max_size, static_cast<unsigned int>(7));
snprintf(p, width, "%6.2f",
(static_cast<float>(td->list[td->num]->rss) / info.memmax) / 10);
}
static void print_top_time(struct text_object *obj, char *p,
unsigned int p_max_size) {
auto *td = static_cast<struct top_data *>(obj->data.opaque);
int width;
char *timeval;
if ((td == nullptr) || (td->list == nullptr) ||
(td->list[td->num] == nullptr)) {
return;
}
width = std::min(p_max_size, static_cast<unsigned int>(10));
timeval = format_time(td->list[td->num]->total_cpu_time, 9);
snprintf(p, width, "%9s", timeval);
free(timeval);
}
static void print_top_user(struct text_object *obj, char *p,
unsigned int p_max_size) {
auto *td = static_cast<struct top_data *>(obj->data.opaque);
struct passwd *pw;
if ((td == nullptr) || (td->list == nullptr) ||
(td->list[td->num] == nullptr)) {
return;
}
pw = getpwuid(td->list[td->num]->uid);
if (pw != nullptr) {
snprintf(p, p_max_size, "%.8s", pw->pw_name);
} else {
snprintf(p, p_max_size, "%d", td->list[td->num]->uid);
}
}
#define PRINT_TOP_GENERATOR(name, width, fmt, field) \
static void print_top_##name(struct text_object *obj, char *p, \
unsigned int p_max_size) { \
struct top_data *td = (struct top_data *)obj->data.opaque; \
if (!td || !td->list || !td->list[td->num]) return; \
snprintf(p, std::min(p_max_size, width), fmt, td->list[td->num]->field); \
}
#define PRINT_TOP_HR_GENERATOR(name, field, denom) \
static void print_top_##name(struct text_object *obj, char *p, \
unsigned int p_max_size) { \
struct top_data *td = (struct top_data *)obj->data.opaque; \
if (!td || !td->list || !td->list[td->num]) return; \
human_readable(td->list[td->num]->field / (denom), p, p_max_size); \
}
PRINT_TOP_GENERATOR(cpu, (unsigned int)7, "%6.2f", amount)
PRINT_TOP_GENERATOR(pid, (unsigned int)8, "%7i", pid)
PRINT_TOP_GENERATOR(uid, (unsigned int)6, "%5i", uid)
PRINT_TOP_HR_GENERATOR(mem_res, rss, 1)
PRINT_TOP_HR_GENERATOR(mem_vsize, vsize, 1)
#ifdef BUILD_IOSTATS
PRINT_TOP_HR_GENERATOR(read_bytes, read_bytes, active_update_interval())
PRINT_TOP_HR_GENERATOR(write_bytes, write_bytes, active_update_interval())
PRINT_TOP_GENERATOR(io_perc, (unsigned int)7, "%6.2f", io_perc)
#endif /* BUILD_IOSTATS */
static void free_top(struct text_object *obj) {
auto *td = static_cast<struct top_data *>(obj->data.opaque);
if (td == nullptr) { return; }
free_and_zero(td->s);
free_and_zero(obj->data.opaque);
}
int parse_top_args(const char *s, const char *arg, struct text_object *obj) {
struct top_data *td;
char buf[64];
int n;
if (arg == nullptr) {
NORM_ERR("top needs arguments");
return 0;
}
obj->data.opaque = td =
static_cast<struct top_data *>(malloc(sizeof(struct top_data)));
memset(td, 0, sizeof(struct top_data));
if (s[3] == 0) {
td->list = info.cpu;
top_cpu = 1;
} else if (strcmp(&s[3], "_mem") == EQUAL) {
td->list = info.memu;
top_mem = 1;
} else if (strcmp(&s[3], "_time") == EQUAL) {
td->list = info.time;
top_time = 1;
#ifdef BUILD_IOSTATS
} else if (strcmp(&s[3], "_io") == EQUAL) {
td->list = info.io;
top_io = 1;
#endif /* BUILD_IOSTATS */
} else {
#ifdef BUILD_IOSTATS
NORM_ERR("Must be top, top_mem, top_time or top_io");
#else /* BUILD_IOSTATS */
NORM_ERR("Must be top, top_mem or top_time");
#endif /* BUILD_IOSTATS */
free_and_zero(obj->data.opaque);
return 0;
}
td->s = strndup(arg, text_buffer_size.get(*state));
if (sscanf(arg, "%63s %i", buf, &n) == 2) {
if (strcmp(buf, "name") == EQUAL) {
obj->callbacks.print = &print_top_name;
} else if (strcmp(buf, "cpu") == EQUAL) {
obj->callbacks.print = &print_top_cpu;
} else if (strcmp(buf, "pid") == EQUAL) {
obj->callbacks.print = &print_top_pid;
} else if (strcmp(buf, "mem") == EQUAL) {
obj->callbacks.print = &print_top_mem;
} else if (strcmp(buf, "time") == EQUAL) {
obj->callbacks.print = &print_top_time;
} else if (strcmp(buf, "mem_res") == EQUAL) {
obj->callbacks.print = &print_top_mem_res;
} else if (strcmp(buf, "mem_vsize") == EQUAL) {
obj->callbacks.print = &print_top_mem_vsize;
} else if (strcmp(buf, "uid") == EQUAL) {
obj->callbacks.print = &print_top_uid;
} else if (strcmp(buf, "user") == EQUAL) {
obj->callbacks.print = &print_top_user;
#ifdef BUILD_IOSTATS
} else if (strcmp(buf, "io_read") == EQUAL) {
obj->callbacks.print = &print_top_read_bytes;
} else if (strcmp(buf, "io_write") == EQUAL) {
obj->callbacks.print = &print_top_write_bytes;
} else if (strcmp(buf, "io_perc") == EQUAL) {
obj->callbacks.print = &print_top_io_perc;
#endif /* BUILD_IOSTATS */
} else {
NORM_ERR("invalid type arg for top");
#ifdef BUILD_IOSTATS
NORM_ERR(
"must be one of: name, cpu, pid, mem, time, mem_res, mem_vsize, "
"io_read, io_write, io_perc");
#else /* BUILD_IOSTATS */
NORM_ERR("must be one of: name, cpu, pid, mem, time, mem_res, mem_vsize");
#endif /* BUILD_IOSTATS */
free_and_zero(td->s);
free_and_zero(obj->data.opaque);
return 0;
}
if (n < 1 || n > MAX_SP) {
NORM_ERR("invalid num arg for top. Must be between 1 and %d.", MAX_SP);
free_and_zero(td->s);
free_and_zero(obj->data.opaque);
return 0;
}
td->num = n - 1;
} else {
NORM_ERR("invalid argument count for top");
free_and_zero(td->s);
free_and_zero(obj->data.opaque);
return 0;
}
obj->callbacks.free = &free_top;
return 1;
}
| 19,662
|
C++
|
.cc
| 565
| 30.769912
| 80
| 0.604283
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
22,567
|
cpu.cc
|
brndnmtthws_conky/src/cpu.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include "config.h"
#include "conky.h"
#include "text_object.h"
#ifdef __x86_64__
#define CPU_FEATURE(x, z) __asm__ __volatile__("cpuid" : "=a"(z) : "a"(x))
#define CPU_REGS(x, y, z) \
__asm__ __volatile__("cpuid" : "=a"(z), "=b"(y) : "a"(x))
#define CPU_STR2(regizter, a, b, c, d) \
__asm__ __volatile__("cpuid" \
: "=a"(a), "=b"(b), "=c"(c), "=d"(d) \
: "a"(regizter))
#define AmD 0x68747541
#define InteL 0x756e6547
#if defined(__FreeBSD__)
#define TICKZ 100L
#else
#define TICKZ sysconf(_SC_CLK_TCK)
#endif /* __FreeBSD__ */
uint8_t has_tsc_reg(void) {
uint_fast16_t vend = 0;
uint_fast16_t leafs = 0;
uint_fast16_t eax = 0;
uint_fast16_t ecx = 0;
uint_fast16_t edx = 0;
uint_fast16_t ebx = 0;
CPU_REGS(0x00000000, vend, leafs);
if (0x00000001 > leafs) { return 1U; }
if (static_cast<uint32_t>(vend) != AmD &&
static_cast<uint32_t>(vend) != InteL) {
return 1U;
}
CPU_STR2(0x00000001, eax, ebx, ecx, edx);
if (0U == (edx & (1U << 4U))) { return 1U; }
return 0U;
}
uintmax_t rdtsc(void) {
unsigned int tickhi = 0;
unsigned int ticklo = 0;
uint_fast16_t eax = 0;
uint_fast16_t ecx = 0;
uint_fast16_t edx = 0;
uint_fast16_t ebx = 0;
uint_fast16_t regz = 0;
uint_fast16_t x = 0;
if (0U != (has_tsc_reg())) { goto seeya; }
__asm__ __volatile__(
"cpuid\n\t"
"rdtsc\n\t"
: "=a"(ticklo), "=d"(tickhi)::"%rbx", "%rcx");
CPU_FEATURE(0x80000000, regz);
if (0x80000001 > static_cast<uint32_t>(regz)) { goto seeya; }
CPU_STR2(0x80000001, eax, ebx, ecx, edx);
if (0U != (edx & (1U << 27U))) {
for (x = 0; x < 6U; x++) {
__asm__ __volatile__(
"rdtscp\n\t"
"mov %%edx, %0\n\t"
"mov %%eax, %1\n\t"
"cpuid\n\t"
: "=r"(tickhi), "=r"(ticklo)::"%rax", "%rbx", "%rcx", "%rdx");
}
}
seeya:
return ((static_cast<uintmax_t>(tickhi) << 32) |
static_cast<uintmax_t>(ticklo));
}
void get_cpu_clock_speed(char *str1, unsigned int p_max_size) {
uintmax_t x = 0;
uintmax_t z = 0;
struct timespec tc = {0L, 0L};
tc.tv_nsec = TICKZ * 1000000L;
x = rdtsc();
if (-1 == (nanosleep(&tc, NULL))) { return; }
z = rdtsc();
snprintf(str1, p_max_size, "%ju MHz", ((z - x) / 100000U));
}
void print_freq2(struct text_object *obj, char *p, unsigned int p_max_size) {
(void)obj;
get_cpu_clock_speed(p, p_max_size);
}
#else
char *l337;
#endif /* __x86_64__ */
| 3,687
|
C++
|
.cc
| 117
| 28.162393
| 77
| 0.61402
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,568
|
moc.cc
|
brndnmtthws_conky/src/moc.cc
|
/*
*
* MOC Conky integration
*
* Please see COPYING for details
*
* Copyright (c) 2008, Henri Häkkinen
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "conky.h"
#include "logging.h"
#include "text_object.h"
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <mutex>
#include "update-cb.hh"
namespace {
struct moc_result {
std::string state;
std::string file;
std::string title;
std::string artist;
std::string song;
std::string album;
std::string totaltime;
std::string timeleft;
std::string curtime;
std::string bitrate;
std::string rate;
};
class moc_cb : public conky::callback<moc_result> {
using Base = conky::callback<moc_result>;
protected:
void work() override;
public:
explicit moc_cb(uint32_t period) : Base(period, false, Tuple()) {}
};
void moc_cb::work() {
moc_result moc;
FILE *fp;
fp = popen("mocp -i", "r");
if (fp == nullptr) {
moc.state = "Can't run 'mocp -i'";
} else {
while (1) {
char line[100];
char *p;
/* Read a line from the pipe and strip the possible '\n'. */
if (fgets(line, 100, fp) == nullptr) { break; }
if ((p = strrchr(line, '\n')) != nullptr) { *p = '\0'; }
/* Parse infos. */
if (strncmp(line, "State:", 6) == 0) {
moc.state = line + 7;
} else if (strncmp(line, "File:", 5) == 0) {
moc.file = line + 6;
} else if (strncmp(line, "Title:", 6) == 0) {
moc.title = line + 7;
} else if (strncmp(line, "Artist:", 7) == 0) {
moc.artist = line + 8;
} else if (strncmp(line, "SongTitle:", 10) == 0) {
moc.song = line + 11;
} else if (strncmp(line, "Album:", 6) == 0) {
moc.album = line + 7;
} else if (strncmp(line, "TotalTime:", 10) == 0) {
moc.totaltime = line + 11;
} else if (strncmp(line, "TimeLeft:", 9) == 0) {
moc.timeleft = line + 10;
} else if (strncmp(line, "CurrentTime:", 12) == 0) {
moc.curtime = line + 13;
} else if (strncmp(line, "Bitrate:", 8) == 0) {
moc.bitrate = line + 9;
} else if (strncmp(line, "Rate:", 5) == 0) {
moc.rate = line + 6;
}
}
}
pclose(fp);
std::lock_guard<std::mutex> l(result_mutex);
result = moc;
}
} // namespace
#define MOC_PRINT_GENERATOR(type, alt) \
void print_moc_##type(struct text_object *obj, char *p, \
unsigned int p_max_size) { \
(void)obj; \
uint32_t period = std::max( \
lround(music_player_interval.get(*state) / active_update_interval()), \
1l); \
const moc_result &moc = \
conky::register_cb<moc_cb>(period)->get_result_copy(); \
snprintf(p, p_max_size, "%s", \
(moc.type.length() ? moc.type.c_str() : (alt))); \
}
MOC_PRINT_GENERATOR(state, "??")
MOC_PRINT_GENERATOR(file, "no file")
MOC_PRINT_GENERATOR(title, "no title")
MOC_PRINT_GENERATOR(artist, "no artist")
MOC_PRINT_GENERATOR(song, "no song")
MOC_PRINT_GENERATOR(album, "no album")
MOC_PRINT_GENERATOR(totaltime, "0:00")
MOC_PRINT_GENERATOR(timeleft, "0:00")
MOC_PRINT_GENERATOR(curtime, "0:00")
MOC_PRINT_GENERATOR(bitrate, "0Kbps")
MOC_PRINT_GENERATOR(rate, "0KHz")
#undef MOC_PRINT_GENERATOR
| 4,228
|
C++
|
.cc
| 119
| 31.394958
| 79
| 0.565111
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
22,569
|
iconv_tools.cc
|
brndnmtthws_conky/src/iconv_tools.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <iconv.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "config.h"
#include "logging.h"
#include "text_object.h"
#define ICONV_CODEPAGE_LENGTH 20
static long iconv_selected;
static long iconv_count = 0;
static char iconv_converting = 0;
static iconv_t **iconv_cd = 0;
int register_iconv(iconv_t *new_iconv) {
iconv_cd = (void ***)realloc(iconv_cd, sizeof(iconv_t *) * (iconv_count + 1));
if (!iconv_cd) { CRIT_ERR("Out of memory"); }
iconv_cd[iconv_count] = (void **)malloc(sizeof(iconv_t));
if (!iconv_cd[iconv_count]) { CRIT_ERR("Out of memory"); }
memcpy(iconv_cd[iconv_count], new_iconv, sizeof(iconv_t));
iconv_count++;
return iconv_count;
}
void free_iconv(struct text_object *obj) {
long i;
(void)obj;
if (!iconv_cd) return;
for (i = 0; i < iconv_count; i++) {
if (iconv_cd[i]) {
iconv_close(*iconv_cd[i]);
free(iconv_cd[i]);
}
}
free(iconv_cd);
iconv_cd = 0;
}
void iconv_convert(size_t *a, char *buff_in, char *p, size_t p_max_size) {
int bytes;
size_t dummy1, dummy2;
#if defined(__DragonFly__)
const char *ptr = buff_in;
#else
char *ptr = buff_in;
#endif
char *outptr = p;
if (*a <= 0 || !iconv_converting || iconv_selected <= 0 ||
iconv_cd[iconv_selected - 1] == (iconv_t)(-1))
return;
dummy1 = dummy2 = *a;
strncpy(buff_in, p, p_max_size);
iconv(*iconv_cd[iconv_selected - 1], nullptr, NULL, NULL, NULL);
while (dummy1 > 0) {
bytes =
iconv(*iconv_cd[iconv_selected - 1], &ptr, &dummy1, &outptr, &dummy2);
if (bytes == -1) {
NORM_ERR("Iconv codeset conversion failed");
break;
}
}
/* It is necessary when we are converting from multibyte to
* singlebyte codepage */
// a = outptr - p;
//(*a) = *a - dummy2;
(*a) = outptr - p;
}
void init_iconv_start(struct text_object *obj, void *free_at_crash,
const char *arg) {
char iconv_from[ICONV_CODEPAGE_LENGTH];
char iconv_to[ICONV_CODEPAGE_LENGTH];
if (iconv_converting) {
CRIT_ERR_FREE(obj, free_at_crash,
"You must stop your last iconv conversion before "
"starting another");
}
if (sscanf(arg, "%s %s", iconv_from, iconv_to) != 2) {
CRIT_ERR_FREE(obj, free_at_crash, "Invalid arguments for iconv_start");
} else {
iconv_t new_iconv;
new_iconv = iconv_open(iconv_to, iconv_from);
if (new_iconv == (iconv_t)(-1)) {
NORM_ERR("Can't convert from %s to %s.", iconv_from, iconv_to);
} else {
obj->data.i = register_iconv(&new_iconv);
iconv_converting = 1;
}
}
}
void init_iconv_stop(void) { iconv_converting = 0; }
void print_iconv_start(struct text_object *obj, char *p,
unsigned int p_max_size) {
(void)p;
(void)p_max_size;
iconv_converting = 1;
iconv_selected = obj->data.i;
}
void print_iconv_stop(struct text_object *obj, char *p,
unsigned int p_max_size) {
(void)obj;
(void)p;
(void)p_max_size;
iconv_converting = 0;
iconv_selected = 0;
}
| 4,108
|
C++
|
.cc
| 129
| 28.108527
| 80
| 0.657316
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
22,570
|
conky-imlib2.cc
|
brndnmtthws_conky/src/conky-imlib2.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Please see COPYING for details
*
* Copyright (c) 2005-2024 Brenden Matthews, et. al.
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "conky-imlib2.h"
#include "common.h"
#include "display-output.hh"
#include "logging.h"
#include "text_object.h"
#include <Imlib2.h>
#include <climits>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include "x11-settings.h"
#include "x11.h"
struct image_list_s {
char name[1024];
Imlib_Image image;
int x, y, w, h;
int wh_set;
char no_cache;
int flush_interval;
struct image_list_s *next;
};
struct image_list_s *image_list_start, *image_list_end;
std::array<std::array<int, 2>, 100> saved_coordinates;
/* areas to update */
Imlib_Updates updates, current_update;
/* our virtual framebuffer image we draw into */
Imlib_Image buffer, image;
conky::range_config_setting<unsigned int> imlib_cache_flush_interval(
"imlib_cache_flush_interval", 0, std::numeric_limits<unsigned int>::max(),
0, true);
conky::simple_config_setting<bool> imlib_draw_blended("draw_blended", true,
true);
namespace {
Imlib_Context context;
unsigned int cimlib_cache_flush_last = 0;
} // namespace
void imlib_cache_size_setting::lua_setter(lua::state &l, bool init) {
lua::stack_sentry s(l, -2);
Base::lua_setter(l, init);
if (display == nullptr || window.visual == nullptr) {
++s;
return;
}
if (init && out_to_x.get(l)) {
image_list_start = image_list_end = nullptr;
context = imlib_context_new();
imlib_context_push(context);
imlib_set_cache_size(do_convert(l, -1).first);
/* set the maximum number of colors to allocate for 8bpp and less to 256 */
imlib_set_color_usage(256);
/* dither for depths < 24bpp */
imlib_context_set_dither(1);
/* set the display , visual, colormap and drawable we are using */
imlib_context_set_display(display);
imlib_context_set_visual(window.visual);
imlib_context_set_colormap(window.colourmap);
imlib_context_set_drawable(window.drawable);
}
++s;
}
void imlib_cache_size_setting::cleanup(lua::state &l) {
lua::stack_sentry s(l, -1);
if (out_to_x.get(l)) {
cimlib_cleanup();
imlib_context_disconnect_display();
imlib_context_pop();
imlib_context_free(context);
}
}
void cimlib_cleanup() {
struct image_list_s *cur = image_list_start, *last = nullptr;
while (cur != nullptr) {
last = cur;
cur = last->next;
delete last;
}
image_list_start = image_list_end = nullptr;
}
void cimlib_add_image(const char *args) {
struct image_list_s *cur = nullptr;
const char *tmp;
cur = new struct image_list_s[sizeof(struct image_list_s)];
memset(cur, 0, sizeof(struct image_list_s));
if (sscanf(args, "%1023s", cur->name) == 0) {
NORM_ERR(
"Invalid args for $image. Format is: '<path to image> (-p"
"x,y) (-s WxH) (-n) (-f interval)' (got '%s')",
args);
delete[] cur;
return;
}
strncpy(cur->name, to_real_path(cur->name).c_str(), 1024);
cur->name[1023] = 0;
//
// now we check for optional args
tmp = strstr(args, "-p ");
if (tmp != nullptr) {
tmp += 3;
sscanf(tmp, "%i,%i", &cur->x, &cur->y);
cur->x = dpi_scale(cur->x);
cur->y = dpi_scale(cur->y);
}
tmp = strstr(args, "-s ");
if (tmp != nullptr) {
tmp += 3;
if (sscanf(tmp, "%ix%i", &cur->w, &cur->h) != 0) { cur->wh_set = 1; }
cur->w = dpi_scale(cur->w);
cur->h = dpi_scale(cur->h);
}
tmp = strstr(args, "-n");
if (tmp != nullptr) { cur->no_cache = 1; }
tmp = strstr(args, "-f ");
if (tmp != nullptr) {
tmp += 3;
if (sscanf(tmp, "%d", &cur->flush_interval) != 0) { cur->no_cache = 0; }
}
tmp = strstr(args, "-i ");
if (tmp != nullptr) {
tmp += 3;
int i;
if (sscanf(tmp, "%d", &i) == 1) {
const auto &coordinates = saved_coordinates.at(static_cast<size_t>(i));
cur->x = coordinates[0];
cur->y = coordinates[1];
}
}
if (cur->flush_interval < 0) {
NORM_ERR("Imlib2: flush interval should be >= 0");
cur->flush_interval = 0;
}
if (image_list_end != nullptr) {
image_list_end->next = cur;
image_list_end = cur;
} else {
image_list_start = image_list_end = cur;
}
}
static void cimlib_draw_image(struct image_list_s *cur, int *clip_x,
int *clip_y, int *clip_x2, int *clip_y2) {
int w, h;
time_t now = time(nullptr);
static int rep = 0;
if (imlib_context_get_drawable() != window.drawable) {
imlib_context_set_drawable(window.drawable);
}
image = imlib_load_image(cur->name);
if (image == nullptr) {
if (rep == 0) { NORM_ERR("Unable to load image '%s'", cur->name); }
rep = 1;
return;
}
rep = 0; /* reset so disappearing images are reported */
DBGP(
"Drawing image '%s' at (%i,%i) scaled to %ix%i, "
"caching interval set to %i (with -n opt %i)",
cur->name, cur->x, cur->y, cur->w, cur->h, cur->flush_interval,
cur->no_cache);
imlib_context_set_image(image);
/* turn alpha channel on */
imlib_image_set_has_alpha(1);
w = imlib_image_get_width();
h = imlib_image_get_height();
if (cur->wh_set == 0) {
cur->w = dpi_scale(w);
cur->h = dpi_scale(h);
}
imlib_context_set_image(buffer);
imlib_blend_image_onto_image(image, 1, 0, 0, w, h, cur->x, cur->y, cur->w,
cur->h);
imlib_context_set_image(image);
if ((cur->no_cache != 0) ||
((cur->flush_interval != 0) && now % cur->flush_interval == 0)) {
imlib_free_image_and_decache();
} else {
imlib_free_image();
}
if (cur->x < *clip_x) { *clip_x = cur->x; }
if (cur->y < *clip_y) { *clip_y = cur->y; }
if (cur->x + cur->w > *clip_x2) { *clip_x2 = cur->x + cur->w; }
if (cur->y + cur->h > *clip_y2) { *clip_y2 = cur->y + cur->h; }
}
static void cimlib_draw_all(int *clip_x, int *clip_y, int *clip_x2,
int *clip_y2) {
struct image_list_s *cur = image_list_start;
while (cur != nullptr) {
cimlib_draw_image(cur, clip_x, clip_y, clip_x2, clip_y2);
cur = cur->next;
}
}
void cimlib_render(int x, int y, int width, int height, uint32_t flush_interval,
bool draw_blended) {
int clip_x = INT_MAX, clip_y = INT_MAX;
int clip_x2 = 0, clip_y2 = 0;
time_t now;
if (image_list_start == nullptr) {
return; /* are we actually drawing anything? */
}
/* cheque if it's time to flush our cache */
now = time(nullptr);
if ((flush_interval != 0u) &&
now - flush_interval > cimlib_cache_flush_last) {
int size = imlib_get_cache_size();
imlib_set_cache_size(0);
imlib_set_cache_size(size);
cimlib_cache_flush_last = now;
DBGP("Flushing Imlib2 cache (%li)\n", now);
}
/* take all the little rectangles to redraw and merge them into
* something sane for rendering */
buffer = imlib_create_image(width, height);
/* clear our buffer */
imlib_context_set_image(buffer);
imlib_image_clear();
/* check if we should blend when rendering */
if (draw_blended) {
/* we can blend stuff now */
imlib_context_set_blend(1);
} else {
imlib_context_set_blend(0);
}
/* turn alpha channel on */
imlib_image_set_has_alpha(1);
cimlib_draw_all(&clip_x, &clip_y, &clip_x2, &clip_y2);
/* set the buffer image as our current image */
imlib_context_set_image(buffer);
/* setup our clip rect */
if (clip_x == INT_MAX) { clip_x = 0; }
if (clip_y == INT_MAX) { clip_y = 0; }
/* render the image at 0, 0 */
imlib_render_image_part_on_drawable_at_size(
clip_x, clip_y, clip_x2 - clip_x, clip_y2 - clip_y, x + clip_x,
y + clip_y, clip_x2 - clip_x, clip_y2 - clip_y);
/* don't need that temporary buffer image anymore */
imlib_free_image();
}
void print_image_callback(struct text_object *obj, char *, unsigned int) {
cimlib_add_image(obj->data.s);
}
imlib_cache_size_setting imlib_cache_size;
| 8,653
|
C++
|
.cc
| 262
| 28.969466
| 80
| 0.628654
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,571
|
proc.cc
|
brndnmtthws_conky/src/proc.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "proc.h"
#include <dirent.h>
#include <unistd.h>
#include <cctype>
#include <memory>
#include <sstream>
#include "conky.h"
#include "core.h"
#include "logging.h"
char *readfile(const char *filename, int *total_read, char showerror) {
FILE *file;
char *buf = nullptr;
int bytes_read;
*total_read = 0;
file = fopen(filename, "re");
if (file != nullptr) {
do {
buf = static_cast<char *>(realloc(buf, *total_read + READSIZE + 1));
bytes_read = fread(buf + *total_read, 1, READSIZE, file);
*total_read += bytes_read;
buf[*total_read] = 0;
} while (bytes_read != 0);
fclose(file);
} else if (showerror != 0) {
NORM_ERR(READERR, filename);
}
return buf;
}
void pid_readlink(const char *file, char *p, unsigned int p_max_size) {
std::unique_ptr<char[]> buf(new char[p_max_size]);
memset(buf.get(), 0, p_max_size);
if (readlink(file, buf.get(), p_max_size) >= 0) {
snprintf(p, p_max_size, "%s", buf.get());
} else {
NORM_ERR(READERR, file);
}
}
struct ll_string {
char *string;
struct ll_string *next;
};
struct ll_string *addnode(struct ll_string *end, char *string) {
auto *current =
static_cast<struct ll_string *>(malloc(sizeof(struct ll_string)));
current->string = strdup(string);
current->next = nullptr;
if (end != nullptr) { end->next = current; }
return current;
}
void freelist(struct ll_string *front) {
if (front != nullptr) {
free(front->string);
if (front->next != nullptr) { freelist(front->next); }
free(front);
}
}
int inlist(struct ll_string *front, char *string) {
struct ll_string *current;
for (current = front; current != nullptr; current = current->next) {
if (strcmp(current->string, string) == 0) { return 1; }
}
return 0;
}
void print_pid_chroot(struct text_object *obj, char *p,
unsigned int p_max_size) {
std::ostringstream pathstream;
std::unique_ptr<char[]> buf(new char[max_user_text.get(*state)]);
generate_text_internal(buf.get(), max_user_text.get(*state), *obj->sub);
pathstream << PROCDIR "/" << buf.get() << "/root";
pid_readlink(pathstream.str().c_str(), p, p_max_size);
}
void print_pid_cmdline(struct text_object *obj, char *p,
unsigned int p_max_size) {
char *buf;
int i, bytes_read;
std::ostringstream pathstream;
std::unique_ptr<char[]> objbuf(new char[max_user_text.get(*state)]);
generate_text_internal(objbuf.get(), max_user_text.get(*state), *obj->sub);
if (*(objbuf.get()) != 0) {
pathstream << PROCDIR "/" << objbuf.get() << "/cmdline";
buf = readfile(pathstream.str().c_str(), &bytes_read, 1);
if (buf != nullptr) {
for (i = 0; i < bytes_read - 1; i++) {
if (buf[i] == 0) { buf[i] = ' '; }
}
snprintf(p, p_max_size, "%s", buf);
free(buf);
}
} else {
NORM_ERR("$pid_cmdline didn't receive a argument");
}
}
void print_pid_cwd(struct text_object *obj, char *p, unsigned int p_max_size) {
std::unique_ptr<char[]> buf(new char[p_max_size]);
int bytes_read;
std::ostringstream pathstream;
std::unique_ptr<char[]> objbuf(new char[max_user_text.get(*state)]);
generate_text_internal(objbuf.get(), max_user_text.get(*state), *obj->sub);
pathstream << PROCDIR "/" << objbuf.get() << "/cwd";
bytes_read = readlink(pathstream.str().c_str(), buf.get(), p_max_size);
if (bytes_read != -1) {
buf[bytes_read] = 0;
snprintf(p, p_max_size, "%s", buf.get());
} else {
NORM_ERR(READERR, pathstream.str().c_str());
}
}
void print_pid_environ(struct text_object *obj, char *p,
unsigned int p_max_size) {
int i, total_read;
pid_t pid;
std::ostringstream pathstream;
std::unique_ptr<char[]> objbuf(new char[max_user_text.get(*state)]);
char *buf, *var = strdup(obj->data.s);
;
generate_text_internal(objbuf.get(), max_user_text.get(*state), *obj->sub);
if (sscanf(objbuf.get(), "%d %s", &pid, var) == 2) {
for (i = 0; var[i] != 0; i++) {
var[i] = toupper(static_cast<unsigned char>(var[i]));
}
pathstream << PROCDIR "/" << pid << "/cwd";
buf = readfile(pathstream.str().c_str(), &total_read, 1);
if (buf != nullptr) {
for (i = 0; i < total_read; i += strlen(buf + i) + 1) {
if (strncmp(buf + i, var, strlen(var)) == 0 &&
*(buf + i + strlen(var)) == '=') {
snprintf(p, p_max_size, "%s", buf + i + strlen(var) + 1);
free(buf);
free(var);
return;
}
}
free(buf);
}
*p = 0;
}
free(var);
}
void print_pid_environ_list(struct text_object *obj, char *p,
unsigned int p_max_size) {
char *buf = nullptr;
char *buf2;
int bytes_read, total_read;
int i = 0;
std::ostringstream pathstream;
std::unique_ptr<char[]> objbuf(new char[max_user_text.get(*state)]);
generate_text_internal(objbuf.get(), max_user_text.get(*state), *obj->sub);
pathstream << PROCDIR "/" << objbuf.get() << "/environ";
buf = readfile(pathstream.str().c_str(), &total_read, 1);
if (buf != nullptr) {
for (bytes_read = 0; bytes_read < total_read; buf[i - 1] = ';') {
buf2 = strdup(buf + bytes_read);
bytes_read += strlen(buf2) + 1;
sscanf(buf2, "%[^=]", buf + i);
free(buf2);
i = strlen(buf) + 1;
}
buf[i - 1] = 0;
snprintf(p, p_max_size, "%s", buf);
free(buf);
}
}
void print_pid_exe(struct text_object *obj, char *p, unsigned int p_max_size) {
std::ostringstream pathstream;
std::unique_ptr<char[]> objbuf(new char[max_user_text.get(*state)]);
generate_text_internal(objbuf.get(), max_user_text.get(*state), *obj->sub);
pathstream << PROCDIR "/" << objbuf.get() << "/exe";
pid_readlink(pathstream.str().c_str(), p, p_max_size);
}
void print_pid_nice(struct text_object *obj, char *p, unsigned int p_max_size) {
char *buf = nullptr;
int bytes_read;
long int nice_value;
std::ostringstream pathstream;
std::unique_ptr<char[]> objbuf(new char[max_user_text.get(*state)]);
generate_text_internal(objbuf.get(), max_user_text.get(*state), *obj->sub);
if (!obj->data.s) {
pathstream << PROCDIR "/" << objbuf.get() << "/stat";
buf = readfile(pathstream.str().c_str(), &bytes_read, 1);
if (buf != nullptr) {
sscanf(buf,
"%*d %*s %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %*u %*u %*d "
"%*d %*d %ld",
&nice_value);
snprintf(p, p_max_size, "%ld", nice_value);
free(buf);
}
} else {
NORM_ERR("$pid_nice didn't receive a argument");
}
}
void print_pid_openfiles(struct text_object *obj, char *p,
unsigned int p_max_size) {
DIR *dir;
struct dirent *entry;
std::unique_ptr<char[]> buf(new char[p_max_size]);
int length, totallength = 0;
struct ll_string *files_front = nullptr;
struct ll_string *files_back = nullptr;
std::unique_ptr<char[]> objbuf(new char[max_user_text.get(*state)]);
generate_text_internal(objbuf.get(), max_user_text.get(*state), *obj->sub);
dir = opendir(objbuf.get());
if (dir != nullptr) {
while ((entry = readdir(dir)) != nullptr) {
if (entry->d_name[0] != '.') {
snprintf(buf.get(), p_max_size, "%s/%s", objbuf.get(), entry->d_name);
length = readlink(buf.get(), buf.get(), p_max_size);
buf[length] = 0;
if (inlist(files_front, buf.get()) == 0) {
files_back = addnode(files_back, buf.get());
snprintf(p + totallength, p_max_size - totallength, "%s; ",
buf.get());
totallength += length + strlen("; ");
}
if (files_front == nullptr) { files_front = files_back; }
}
}
closedir(dir);
freelist(files_front);
p[totallength - strlen("; ")] = 0;
} else {
p[0] = 0;
}
}
void print_pid_parent(struct text_object *obj, char *p,
unsigned int p_max_size) {
#define PARENT_ENTRY "PPid:\t"
#define PARENTNOTFOUND "Can't find the process parent in '%s'"
char *begin, *end, *buf = nullptr;
int bytes_read;
std::ostringstream pathstream;
std::unique_ptr<char[]> objbuf(new char[max_user_text.get(*state)]);
generate_text_internal(objbuf.get(), max_user_text.get(*state), *obj->sub);
pathstream << PROCDIR "/" << objbuf.get() << "/status";
buf = readfile(pathstream.str().c_str(), &bytes_read, 1);
if (buf != nullptr) {
begin = strstr(buf, PARENT_ENTRY);
if (begin != nullptr) {
begin += strlen(PARENT_ENTRY);
end = strchr(begin, '\n');
if (end != nullptr) { *(end) = 0; }
snprintf(p, p_max_size, "%s", begin);
} else {
NORM_ERR(PARENTNOTFOUND, pathstream.str().c_str());
}
free(buf);
}
}
void print_pid_priority(struct text_object *obj, char *p,
unsigned int p_max_size) {
char *buf = nullptr;
int bytes_read;
long int priority;
std::ostringstream pathstream;
std::unique_ptr<char[]> objbuf(new char[max_user_text.get(*state)]);
generate_text_internal(objbuf.get(), max_user_text.get(*state), *obj->sub);
if (*(objbuf.get()) != 0) {
pathstream << PROCDIR "/" << objbuf.get() << "/stat";
buf = readfile(pathstream.str().c_str(), &bytes_read, 1);
if (buf != nullptr) {
sscanf(buf,
"%*d %*s %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %*u %*u %*d "
"%*d %ld",
&priority);
snprintf(p, p_max_size, "%ld", priority);
free(buf);
}
} else {
NORM_ERR("$pid_priority didn't receive a argument");
}
}
void print_pid_state(struct text_object *obj, char *p,
unsigned int p_max_size) {
#define STATE_ENTRY "State:\t"
#define STATENOTFOUND "Can't find the process state in '%s'"
char *begin, *end, *buf = nullptr;
int bytes_read;
std::ostringstream pathstream;
std::unique_ptr<char[]> objbuf(new char[max_user_text.get(*state)]);
generate_text_internal(objbuf.get(), max_user_text.get(*state), *obj->sub);
pathstream << PROCDIR "/" << objbuf.get() << "/status";
buf = readfile(pathstream.str().c_str(), &bytes_read, 1);
if (buf != nullptr) {
begin = strstr(buf, STATE_ENTRY);
if (begin != nullptr) {
begin += strlen(STATE_ENTRY) +
3; // +3 will strip the char representing the short state and
// the space and '(' that follow
end = strchr(begin, '\n');
if (end != nullptr) {
*(end - 1) = 0; // -1 strips the ')'
}
snprintf(p, p_max_size, "%s", begin);
} else {
NORM_ERR(STATENOTFOUND, pathstream.str().c_str());
}
free(buf);
}
}
void print_pid_state_short(struct text_object *obj, char *p,
unsigned int p_max_size) {
char *begin, *buf = nullptr;
int bytes_read;
std::ostringstream pathstream;
std::unique_ptr<char[]> objbuf(new char[max_user_text.get(*state)]);
generate_text_internal(objbuf.get(), max_user_text.get(*state), *obj->sub);
pathstream << PROCDIR "/" << objbuf.get() << "/status";
buf = readfile(pathstream.str().c_str(), &bytes_read, 1);
if (buf != nullptr) {
begin = strstr(buf, STATE_ENTRY);
if (begin != nullptr) {
snprintf(p, p_max_size, "%c", *begin);
} else {
NORM_ERR(STATENOTFOUND, pathstream.str().c_str());
}
free(buf);
}
}
void print_pid_stderr(struct text_object *obj, char *p,
unsigned int p_max_size) {
std::ostringstream pathstream;
std::unique_ptr<char[]> objbuf(new char[max_user_text.get(*state)]);
generate_text_internal(objbuf.get(), max_user_text.get(*state), *obj->sub);
pathstream << PROCDIR "/" << objbuf.get() << "/fd/2";
pid_readlink(pathstream.str().c_str(), p, p_max_size);
}
void print_pid_stdin(struct text_object *obj, char *p,
unsigned int p_max_size) {
std::unique_ptr<char[]> objbuf(new char[max_user_text.get(*state)]);
std::ostringstream pathstream;
generate_text_internal(objbuf.get(), max_user_text.get(*state), *obj->sub);
pathstream << PROCDIR "/" << objbuf.get() << "/fd/0";
pid_readlink(pathstream.str().c_str(), p, p_max_size);
}
void print_pid_stdout(struct text_object *obj, char *p,
unsigned int p_max_size) {
std::ostringstream pathstream;
std::unique_ptr<char[]> objbuf(new char[max_user_text.get(*state)]);
generate_text_internal(objbuf.get(), max_user_text.get(*state), *obj->sub);
pathstream << PROCDIR "/" << objbuf.get() << "/fd/1";
pid_readlink(pathstream.str().c_str(), p, p_max_size);
}
void scan_cmdline_to_pid_arg(struct text_object *obj, const char *arg,
void *free_at_crash) {
unsigned int i;
std::unique_ptr<char[]> objbuf(new char[max_user_text.get(*state)]);
/* FIXME */
generate_text_internal(objbuf.get(), max_user_text.get(*state), *obj->sub);
if (strlen(arg) > 0) {
obj->data.s = strdup(arg);
for (i = 0; obj->data.s[i] != 0; i++) {
while (obj->data.s[i] == ' ' && obj->data.s[i + 1] == ' ') {
memmove(obj->data.s + i, obj->data.s + i + 1,
strlen(obj->data.s + i + 1) + 1);
}
}
if (obj->data.s[i - 1] == ' ') { obj->data.s[i - 1] = 0; }
} else {
CRIT_ERR_FREE(obj, free_at_crash, "${cmdline_to_pid commandline}");
}
}
void print_cmdline_to_pid(struct text_object *obj, char *p,
unsigned int p_max_size) {
DIR *dir;
struct dirent *entry;
char *buf;
int bytes_read, i;
std::ostringstream pathstream;
dir = opendir(PROCDIR);
if (dir != nullptr) {
while ((entry = readdir(dir)) != nullptr) {
pathstream << PROCDIR "/" << entry->d_name << "/cmdline";
buf = readfile(pathstream.str().c_str(), &bytes_read, 0);
if (buf != nullptr) {
for (i = 0; i < bytes_read - 1; i++) {
if (buf[i] == 0) { buf[i] = ' '; }
}
if (strstr(buf, obj->data.s) != nullptr) {
snprintf(p, p_max_size, "%s", entry->d_name);
free(buf);
closedir(dir);
return;
}
free(buf);
}
}
closedir(dir);
} else {
NORM_ERR(READERR, PROCDIR);
}
}
void print_pid_threads(struct text_object *obj, char *p,
unsigned int p_max_size) {
#define THREADS_ENTRY "Threads:\t"
#define THREADSNOTFOUND \
"Can't find the number of the threads of the process in '%s'"
char *begin, *end, *buf = nullptr;
int bytes_read;
std::ostringstream pathstream;
std::unique_ptr<char[]> objbuf(new char[max_user_text.get(*state)]);
generate_text_internal(objbuf.get(), max_user_text.get(*state), *obj->sub);
pathstream << PROCDIR "/" << objbuf.get() << "/status";
buf = readfile(pathstream.str().c_str(), &bytes_read, 1);
if (buf != nullptr) {
begin = strstr(buf, THREADS_ENTRY);
if (begin != nullptr) {
begin += strlen(THREADS_ENTRY);
end = strchr(begin, '\n');
if (end != nullptr) { *(end) = 0; }
snprintf(p, p_max_size, "%s", begin);
} else {
NORM_ERR(THREADSNOTFOUND, pathstream.str().c_str());
}
free(buf);
}
}
void print_pid_thread_list(struct text_object *obj, char *p,
unsigned int p_max_size) {
DIR *dir;
struct dirent *entry;
int totallength = 0;
std::ostringstream pathstream;
std::unique_ptr<char[]> objbuf(new char[max_user_text.get(*state)]);
generate_text_internal(objbuf.get(), max_user_text.get(*state), *obj->sub);
pathstream << PROCDIR "/" << objbuf.get() << "/task";
dir = opendir(pathstream.str().c_str());
if (dir != nullptr) {
while ((entry = readdir(dir)) != nullptr) {
if (entry->d_name[0] != '.') {
snprintf(p + totallength, p_max_size - totallength, "%s,",
entry->d_name);
totallength += strlen(entry->d_name) + 1;
}
}
closedir(dir);
if (totallength > 0 && p[totallength - 1] == ',') {
p[totallength - 1] = 0;
}
} else {
p[0] = 0;
}
}
void print_pid_time_kernelmode(struct text_object *obj, char *p,
unsigned int p_max_size) {
char *buf = nullptr;
int bytes_read;
unsigned long int umtime;
std::ostringstream pathstream;
std::unique_ptr<char[]> objbuf(new char[max_user_text.get(*state)]);
generate_text_internal(objbuf.get(), max_user_text.get(*state), *obj->sub);
if (*(objbuf.get()) != 0) {
pathstream << PROCDIR "/" << objbuf.get() << "/stat";
buf = readfile(pathstream.str().c_str(), &bytes_read, 1);
if (buf != nullptr) {
sscanf(buf, "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %lu",
&umtime);
snprintf(p, p_max_size, "%.2f", static_cast<float>(umtime) / 100);
free(buf);
}
} else {
NORM_ERR("$pid_time_kernelmode didn't receive a argument");
}
}
void print_pid_time_usermode(struct text_object *obj, char *p,
unsigned int p_max_size) {
char *buf = nullptr;
int bytes_read;
unsigned long int kmtime;
std::ostringstream pathstream;
std::unique_ptr<char[]> objbuf(new char[max_user_text.get(*state)]);
generate_text_internal(objbuf.get(), max_user_text.get(*state), *obj->sub);
if (*(objbuf.get()) != 0) {
pathstream << PROCDIR "/" << objbuf.get() << "/stat";
buf = readfile(pathstream.str().c_str(), &bytes_read, 1);
if (buf != nullptr) {
sscanf(buf, "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %*u %lu",
&kmtime);
snprintf(p, p_max_size, "%.2f", static_cast<float>(kmtime) / 100);
free(buf);
}
} else {
NORM_ERR("$pid_time_usermode didn't receive a argument");
}
}
void print_pid_time(struct text_object *obj, char *p, unsigned int p_max_size) {
char *buf = nullptr;
int bytes_read;
unsigned long int umtime, kmtime;
std::ostringstream pathstream;
std::unique_ptr<char[]> objbuf(new char[max_user_text.get(*state)]);
generate_text_internal(objbuf.get(), max_user_text.get(*state), *obj->sub);
if (*(objbuf.get()) != 0) {
pathstream << PROCDIR "/" << objbuf.get() << "/stat";
buf = readfile(pathstream.str().c_str(), &bytes_read, 1);
if (buf != nullptr) {
sscanf(buf, "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %lu %lu",
&umtime, &kmtime);
snprintf(p, p_max_size, "%.2f",
static_cast<float>(umtime + kmtime) / 100);
free(buf);
}
} else {
NORM_ERR("$pid_time didn't receive a argument");
}
}
enum xid_type { egid, euid, fsgid, fsuid, gid, sgid, suid, uid };
void print_pid_Xid(struct text_object *obj, char *p, int p_max_size,
xid_type type) {
char *begin, *end, *buf = nullptr;
int bytes_read;
std::ostringstream pathstream;
std::string errorstring;
std::unique_ptr<char[]> objbuf(new char[max_user_text.get(*state)]);
generate_text_internal(objbuf.get(), max_user_text.get(*state), *obj->sub);
pathstream << PROCDIR "/" << objbuf.get() << "/status";
buf = readfile(pathstream.str().c_str(), &bytes_read, 1);
if (buf != nullptr) {
switch (type) {
case egid:
begin = strstr(buf, "Gid:\t");
break;
case euid:
begin = strstr(buf, "Uid:\t");
break;
case fsgid:
begin = strstr(buf, "Gid:\t");
break;
case fsuid:
begin = strstr(buf, "Uid:\t");
break;
case gid:
begin = strstr(buf, "Gid:\t");
break;
case sgid:
begin = strstr(buf, "Gid:\t");
break;
case suid:
begin = strstr(buf, "Uid:\t");
break;
case uid:
begin = strstr(buf, "Uid:\t");
break;
default:
break;
}
if (begin != nullptr) {
switch (type) {
case gid:
begin += strlen("Gid:\t");
break;
case uid:
begin += strlen("Uid:\t");
break;
case egid:
case euid:
begin = strchr(begin, '\t');
begin++;
begin = strchr(begin, '\t');
begin++;
break;
case sgid:
case suid:
begin = strchr(begin, '\t');
begin++;
begin = strchr(begin, '\t');
begin++;
begin = strchr(begin, '\t');
begin++;
break;
case fsgid:
case fsuid:
begin = strchr(begin, '\t');
begin++;
begin = strchr(begin, '\t');
begin++;
begin = strchr(begin, '\t');
begin++;
begin = strchr(begin, '\t');
begin++;
break;
default:
break;
}
if (type == fsgid || type == fsuid) {
end = strchr(begin, '\n');
} else {
end = strchr(begin, '\t');
}
if (end != nullptr) { *(end) = 0; }
snprintf(p, p_max_size, "%s", begin);
} else {
errorstring = "Can't find the process ";
switch (type) {
case egid:
errorstring.append("effective gid");
break;
case euid:
errorstring.append("effective uid");
break;
case fsgid:
errorstring.append("process file system gid");
break;
case fsuid:
errorstring.append("process file system uid");
break;
case gid:
errorstring.append("real gid");
break;
case sgid:
errorstring.append("saved set gid");
break;
case suid:
errorstring.append("saved set uid");
break;
case uid:
errorstring.append("real uid");
break;
default:
break;
}
errorstring.append(" in '%s'");
NORM_ERR(errorstring.c_str(), pathstream.str().c_str());
}
free(buf);
}
}
void print_pid_egid(struct text_object *obj, char *p, unsigned int p_max_size) {
print_pid_Xid(obj, p, p_max_size, egid);
}
void print_pid_euid(struct text_object *obj, char *p, unsigned int p_max_size) {
print_pid_Xid(obj, p, p_max_size, euid);
}
void print_pid_fsgid(struct text_object *obj, char *p,
unsigned int p_max_size) {
print_pid_Xid(obj, p, p_max_size, fsgid);
}
void print_pid_fsuid(struct text_object *obj, char *p,
unsigned int p_max_size) {
print_pid_Xid(obj, p, p_max_size, fsuid);
}
void print_pid_gid(struct text_object *obj, char *p, unsigned int p_max_size) {
print_pid_Xid(obj, p, p_max_size, gid);
}
void print_pid_sgid(struct text_object *obj, char *p, unsigned int p_max_size) {
print_pid_Xid(obj, p, p_max_size, sgid);
}
void print_pid_suid(struct text_object *obj, char *p, unsigned int p_max_size) {
print_pid_Xid(obj, p, p_max_size, suid);
}
void print_pid_uid(struct text_object *obj, char *p, unsigned int p_max_size) {
print_pid_Xid(obj, p, p_max_size, uid);
}
void internal_print_pid_vm(struct text_object *obj, char *p, int p_max_size,
const char *entry, const char *errorstring) {
char *begin, *end, *buf = nullptr;
int bytes_read;
std::ostringstream pathstream;
std::unique_ptr<char[]> objbuf(new char[max_user_text.get(*state)]);
generate_text_internal(objbuf.get(), max_user_text.get(*state), *obj->sub);
pathstream << PROCDIR "/" << objbuf.get() << "/status";
buf = readfile(pathstream.str().c_str(), &bytes_read, 1);
if (buf != nullptr) {
begin = strstr(buf, entry);
if (begin != nullptr) {
begin += strlen(entry);
while (*begin == '\t' || *begin == ' ') { begin++; }
end = strchr(begin, '\n');
if (end != nullptr) { *(end) = 0; }
snprintf(p, p_max_size, "%s", begin);
} else {
NORM_ERR(errorstring, pathstream.str().c_str());
}
free(buf);
}
}
void print_pid_vmpeak(struct text_object *obj, char *p,
unsigned int p_max_size) {
internal_print_pid_vm(
obj, p, p_max_size, "VmPeak:\t",
"Can't find the process peak virtual memory size in '%s'");
}
void print_pid_vmsize(struct text_object *obj, char *p,
unsigned int p_max_size) {
internal_print_pid_vm(obj, p, p_max_size, "VmSize:\t",
"Can't find the process virtual memory size in '%s'");
}
void print_pid_vmlck(struct text_object *obj, char *p,
unsigned int p_max_size) {
internal_print_pid_vm(obj, p, p_max_size, "VmLck:\t",
"Can't find the process locked memory size in '%s'");
}
void print_pid_vmhwm(struct text_object *obj, char *p,
unsigned int p_max_size) {
internal_print_pid_vm(
obj, p, p_max_size, "VmHWM:\t",
"Can't find the process peak resident set size in '%s'");
}
void print_pid_vmrss(struct text_object *obj, char *p,
unsigned int p_max_size) {
internal_print_pid_vm(obj, p, p_max_size, "VmHWM:\t",
"Can't find the process resident set size in '%s'");
}
void print_pid_vmdata(struct text_object *obj, char *p,
unsigned int p_max_size) {
internal_print_pid_vm(obj, p, p_max_size, "VmData:\t",
"Can't find the process data segment size in '%s'");
}
void print_pid_vmstk(struct text_object *obj, char *p,
unsigned int p_max_size) {
internal_print_pid_vm(obj, p, p_max_size, "VmData:\t",
"Can't find the process stack segment size in '%s'");
}
void print_pid_vmexe(struct text_object *obj, char *p,
unsigned int p_max_size) {
internal_print_pid_vm(obj, p, p_max_size, "VmData:\t",
"Can't find the process text segment size in '%s'");
}
void print_pid_vmlib(struct text_object *obj, char *p,
unsigned int p_max_size) {
internal_print_pid_vm(
obj, p, p_max_size, "VmLib:\t",
"Can't find the process shared library code size in '%s'");
}
void print_pid_vmpte(struct text_object *obj, char *p,
unsigned int p_max_size) {
internal_print_pid_vm(
obj, p, p_max_size, "VmPTE:\t",
"Can't find the process page table entries size in '%s'");
}
#define READ_ENTRY "read_bytes: "
#define READNOTFOUND "Can't find the amount of bytes read in '%s'"
void print_pid_read(struct text_object *obj, char *p, unsigned int p_max_size) {
char *begin, *end, *buf = nullptr;
int bytes_read;
std::ostringstream pathstream;
std::unique_ptr<char[]> objbuf(new char[max_user_text.get(*state)]);
generate_text_internal(objbuf.get(), max_user_text.get(*state), *obj->sub);
pathstream << PROCDIR "/" << objbuf.get() << "/io";
buf = readfile(pathstream.str().c_str(), &bytes_read, 1);
if (buf != nullptr) {
begin = strstr(buf, READ_ENTRY);
if (begin != nullptr) {
end = strchr(begin, '\n');
if (end != nullptr) { *(end) = 0; }
snprintf(p, p_max_size, "%s", begin);
} else {
NORM_ERR(READNOTFOUND, pathstream.str().c_str());
}
free(buf);
}
}
#define WRITE_ENTRY "write_bytes: "
#define WRITENOTFOUND "Can't find the amount of bytes written in '%s'"
void print_pid_write(struct text_object *obj, char *p,
unsigned int p_max_size) {
char *begin, *end, *buf = nullptr;
int bytes_read;
std::ostringstream pathstream;
std::unique_ptr<char[]> objbuf(new char[max_user_text.get(*state)]);
generate_text_internal(objbuf.get(), max_user_text.get(*state), *obj->sub);
pathstream << PROCDIR "/" << objbuf.get() << "/io";
buf = readfile(pathstream.str().c_str(), &bytes_read, 1);
if (buf != nullptr) {
begin = strstr(buf, WRITE_ENTRY);
if (begin != nullptr) {
end = strchr(begin, '\n');
if (end != nullptr) { *(end) = 0; }
snprintf(p, p_max_size, "%s", begin);
} else {
NORM_ERR(WRITENOTFOUND, pathstream.str().c_str());
}
free(buf);
}
}
| 28,801
|
C++
|
.cc
| 802
| 30.05611
| 80
| 0.587345
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,572
|
core.cc
|
brndnmtthws_conky/src/core.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "config.h"
/* local headers */
#include "algebra.h"
#include "core.h"
#include "bsdapm.h"
#include "build.h"
#include "colour-settings.h"
#include "colours.h"
#include "combine.h"
#include "diskio.h"
#include "entropy.h"
#include "exec.h"
#include "i8k.h"
#include "misc.h"
#include "proc.h"
#include "text_object.h"
#ifdef BUILD_IMLIB2
#include "conky-imlib2.h"
#endif /* BUILD_IMLIB2 */
#ifdef BUILD_MYSQL
#include "mysql.h"
#endif /* BUILD_MYSQL */
#ifdef BUILD_ICAL
#include "ical.h"
#endif /* BUILD_ICAL */
#ifdef BUILD_IRC
#include "irc.h"
#endif /* BUILD_IRC */
#ifdef BUILD_GUI
#include "fonts.h"
#include "gui.h"
#endif /* BUILD_GUI */
#include "fs.h"
#ifdef BUILD_IBM
#include "ibm.h"
#include "smapi.h"
#endif /* BUILD_IBM */
#ifdef BUILD_ICONV
#include "iconv_tools.h"
#endif /* BUILD_ICONV */
#include "llua.h"
#include "logging.h"
#include "mail.h"
#include "mboxscan.h"
#include "mixer.h"
#include "nc.h"
#include "net_stat.h"
#ifdef BUILD_NVIDIA
#include "nvidia.h"
#endif /* BUILD_NVIDIA */
#include <inttypes.h>
#include "cpu.h"
#include "read_tcpip.h"
#include "scroll.h"
#include "specials.h"
#include "tailhead.h"
#include "temphelper.h"
#include "template.h"
#include "timeinfo.h"
#include "top.h"
#include "user.h"
#include "users.h"
#ifdef BUILD_CURL
#include "ccurl_thread.h"
#endif /* BUILD_CURL */
#ifdef BUILD_RSS
#include "rss.h"
#endif /* BUILD_RSS */
#ifdef BUILD_AUDACIOUS
#include "audacious.h"
#endif /* BUILD_AUDACIOUS */
#ifdef BUILD_CMUS
#include "cmus.h"
#endif /* BUILD_CMUS */
#ifdef BUILD_JOURNAL
#include "journal.h"
#endif /* BUILD_JOURNAL */
#ifdef BUILD_PULSEAUDIO
#include "pulseaudio.h"
#endif /* BUILD_PULSEAUDIO */
#ifdef BUILD_INTEL_BACKLIGHT
#include "intel_backlight.h"
#endif /* BUILD_INTEL_BACKLIGHT */
/* check for OS and include appropriate headers */
#if defined(__linux__)
#include "linux.h"
#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
#include "freebsd.h"
#elif defined(__DragonFly__)
#include "dragonfly.h"
#elif defined(__OpenBSD__)
#include "openbsd.h"
#elif defined(__APPLE__) && defined(__MACH__)
#include "darwin.h"
#endif
#define STRNDUP_ARG strndup(arg ? arg : "", text_buffer_size.get(*state))
#include <cctype>
#include <cstring>
/* strip a leading /dev/ if any, following symlinks first
*
* BEWARE: this function returns a pointer to static content
* which gets overwritten in consecutive calls. I.e.:
* this function is NOT reentrant.
*/
const char *dev_name(const char *path) {
static char buf[PATH_MAX];
if (path == nullptr) { return nullptr; }
#define DEV_NAME(x) \
((x) != nullptr && strlen(x) > 5 && strncmp(x, "/dev/", 5) == 0 ? (x) + 5 \
: (x))
if (realpath(path, buf) == nullptr) { return DEV_NAME(path); }
return DEV_NAME(buf);
#undef DEV_NAME
}
static struct text_object *new_text_object_internal() {
auto *obj = static_cast<text_object *>(malloc(sizeof(struct text_object)));
memset(obj, 0, sizeof(struct text_object));
return obj;
}
static struct text_object *create_plain_text(const char *s) {
struct text_object *obj;
if (s == nullptr || *s == '\0') { return nullptr; }
obj = new_text_object_internal();
obj_be_plain_text(obj, s);
return obj;
}
#ifdef BUILD_CURL
void stock_parse_arg(struct text_object *obj, const char *arg) {
char stock[8];
char data[16];
obj->data.s = nullptr;
if (sscanf(arg, "%7s %15s", stock, data) != 2) {
NORM_ERR("wrong number of arguments for $stock");
return;
}
if (!strcasecmp("ask", data)) {
strncpy(data, "a", 3);
} else if (!strcasecmp("adv", data)) {
strncpy(data, "a2", 3);
} else if (!strcasecmp("asksize", data)) {
strncpy(data, "a5", 3);
} else if (!strcasecmp("bid", data)) {
strncpy(data, "b", 3);
} else if (!strcasecmp("askrt", data)) {
strncpy(data, "b2", 3);
} else if (!strcasecmp("bidrt", data)) {
strncpy(data, "b3", 3);
} else if (!strcasecmp("bookvalue", data)) {
strncpy(data, "b4", 3);
} else if (!strcasecmp("bidsize", data)) {
strncpy(data, "b6", 3);
} else if (!strcasecmp("change", data)) {
strncpy(data, "c1", 3);
} else if (!strcasecmp("commission", data)) {
strncpy(data, "c3", 3);
} else if (!strcasecmp("changert", data)) {
strncpy(data, "c6", 3);
} else if (!strcasecmp("ahcrt", data)) {
strncpy(data, "c8", 3);
} else if (!strcasecmp("ds", data)) {
strncpy(data, "d", 3);
} else if (!strcasecmp("ltd", data)) {
strncpy(data, "d1", 3);
} else if (!strcasecmp("tradedate", data)) {
strncpy(data, "d2", 3);
} else if (!strcasecmp("es", data)) {
strncpy(data, "e", 3);
} else if (!strcasecmp("ei", data)) {
strncpy(data, "e1", 3);
} else if (!strcasecmp("epsecy", data)) {
strncpy(data, "e7", 3);
} else if (!strcasecmp("epseny", data)) {
strncpy(data, "e8", 3);
} else if (!strcasecmp("epsenq", data)) {
strncpy(data, "e9", 3);
} else if (!strcasecmp("floatshares", data)) {
strncpy(data, "f6", 3);
} else if (!strcasecmp("dayslow", data)) {
strncpy(data, "g", 3);
} else if (!strcasecmp("dayshigh", data)) {
strncpy(data, "h", 3);
} else if (!strcasecmp("52weeklow", data)) {
strncpy(data, "j", 3);
} else if (!strcasecmp("52weekhigh", data)) {
strncpy(data, "k", 3);
} else if (!strcasecmp("hgp", data)) {
strncpy(data, "g1", 3);
} else if (!strcasecmp("ag", data)) {
strncpy(data, "g3", 3);
} else if (!strcasecmp("hg", data)) {
strncpy(data, "g4", 3);
} else if (!strcasecmp("hgprt", data)) {
strncpy(data, "g5", 3);
} else if (!strcasecmp("hgrt", data)) {
strncpy(data, "g6", 3);
} else if (!strcasecmp("moreinfo", data)) {
strncpy(data, "i", 3);
} else if (!strcasecmp("obrt", data)) {
strncpy(data, "i5", 3);
} else if (!strcasecmp("mc", data)) {
strncpy(data, "j1", 3);
} else if (!strcasecmp("mcrt", data)) {
strncpy(data, "j3", 3);
} else if (!strcasecmp("ebitda", data)) {
strncpy(data, "j4", 3);
} else if (!strcasecmp("c52wlow", data)) {
strncpy(data, "j5", 3);
} else if (!strcasecmp("pc52wlow", data)) {
strncpy(data, "j6", 3);
} else if (!strcasecmp("cprt", data)) {
strncpy(data, "k2", 3);
} else if (!strcasecmp("lts", data)) {
strncpy(data, "k3", 3);
} else if (!strcasecmp("c52whigh", data)) {
strncpy(data, "k4", 3);
} else if (!strcasecmp("pc52whigh", data)) {
strncpy(data, "k5", 3);
} else if (!strcasecmp("ltp", data)) {
strncpy(data, "l1", 3);
} else if (!strcasecmp("hl", data)) {
strncpy(data, "l2", 3);
} else if (!strcasecmp("ll", data)) {
strncpy(data, "l3", 3);
} else if (!strcasecmp("dr", data)) {
strncpy(data, "m", 3);
} else if (!strcasecmp("drrt", data)) {
strncpy(data, "m2", 3);
} else if (!strcasecmp("50ma", data)) {
strncpy(data, "m3", 3);
} else if (!strcasecmp("200ma", data)) {
strncpy(data, "m4", 3);
} else if (!strcasecmp("c200ma", data)) {
strncpy(data, "m5", 3);
} else if (!strcasecmp("pc200ma", data)) {
strncpy(data, "m6", 3);
} else if (!strcasecmp("c50ma", data)) {
strncpy(data, "m7", 3);
} else if (!strcasecmp("pc50ma", data)) {
strncpy(data, "m8", 3);
} else if (!strcasecmp("name", data)) {
strncpy(data, "n", 3);
} else if (!strcasecmp("notes", data)) {
strncpy(data, "n4", 3);
} else if (!strcasecmp("open", data)) {
strncpy(data, "o", 3);
} else if (!strcasecmp("pc", data)) {
strncpy(data, "p", 3);
} else if (!strcasecmp("pricepaid", data)) {
strncpy(data, "p1", 3);
} else if (!strcasecmp("cip", data)) {
strncpy(data, "p2", 3);
} else if (!strcasecmp("ps", data)) {
strncpy(data, "p5", 3);
} else if (!strcasecmp("pb", data)) {
strncpy(data, "p6", 3);
} else if (!strcasecmp("edv", data)) {
strncpy(data, "q", 3);
} else if (!strcasecmp("per", data)) {
strncpy(data, "r", 3);
} else if (!strcasecmp("dpd", data)) {
strncpy(data, "r1", 3);
} else if (!strcasecmp("perrt", data)) {
strncpy(data, "r2", 3);
} else if (!strcasecmp("pegr", data)) {
strncpy(data, "r5", 3);
} else if (!strcasecmp("pepsecy", data)) {
strncpy(data, "r6", 3);
} else if (!strcasecmp("pepseny", data)) {
strncpy(data, "r7", 3);
} else if (!strcasecmp("symbol", data)) {
strncpy(data, "s", 3);
} else if (!strcasecmp("sharesowned", data)) {
strncpy(data, "s1", 3);
} else if (!strcasecmp("shortratio", data)) {
strncpy(data, "s7", 3);
} else if (!strcasecmp("ltt", data)) {
strncpy(data, "t1", 3);
} else if (!strcasecmp("tradelinks", data)) {
strncpy(data, "t6", 3);
} else if (!strcasecmp("tt", data)) {
strncpy(data, "t7", 3);
} else if (!strcasecmp("1ytp", data)) {
strncpy(data, "t8", 3);
} else if (!strcasecmp("volume", data)) {
strncpy(data, "v", 3);
} else if (!strcasecmp("hv", data)) {
strncpy(data, "v1", 3);
} else if (!strcasecmp("hvrt", data)) {
strncpy(data, "v7", 3);
} else if (!strcasecmp("52weekrange", data)) {
strncpy(data, "w", 3);
} else if (!strcasecmp("dvc", data)) {
strncpy(data, "w1", 3);
} else if (!strcasecmp("dvcrt", data)) {
strncpy(data, "w4", 3);
} else if (!strcasecmp("se", data)) {
strncpy(data, "x", 3);
} else if (!strcasecmp("dy", data)) {
strncpy(data, "y", 3);
} else {
NORM_ERR(
"\"%s\" is not supported by $stock. Supported: 1ytp, 200ma, 50ma, "
"52weeklow, 52weekhigh, 52weekrange, adv, ag, ahcrt, ask, askrt, "
"asksize, bid, bidrt, bidsize, bookvalue, c200ma, c50ma, c52whigh, "
"c52wlow, change, changert, cip, commission, cprt, dayshigh, dayslow, "
"dpd, dr, drrt, ds, dvc, dvcrt, dy, ebitda, edv, ei, epsecy, epsenq, "
"epseny, es, floatshares, hg, hgp, hgprt, hl, hv, hvrt, ll, ltd, ltp, "
"lts, ltt, mc, mcrt, moreinfo, name, notes, obrt, open, pb, pc, "
"pc200ma, pc50ma, pc52whigh, pc52wlow, pegr, pepsecy, pepseny, per, "
"perrt, pricepaid, ps, se, sharesowned, shortratio, symbol, tradedate, "
"tradelinks, tt, volume",
data);
return;
}
#define MAX_FINYAH_URL_LENGTH 75
obj->data.s = static_cast<char *>(malloc(MAX_FINYAH_URL_LENGTH));
snprintf(obj->data.s, MAX_FINYAH_URL_LENGTH,
"http://download.finance.yahoo.com/d/quotes.csv?s=%s&f=%s", stock,
data);
}
#endif /* BUILD_CURL */
legacy_cb_handle *create_cb_handle(int (*fn)()) {
if (fn != nullptr) {
return new legacy_cb_handle(conky::register_cb<legacy_cb>(1, fn));
}
{ return nullptr; }
}
/* construct_text_object() creates a new text_object */
struct text_object *construct_text_object(char *s, const char *arg, long line,
void **ifblock_opaque,
void *free_at_crash) {
// struct text_object *obj = new_text_object();
struct text_object *obj = new_text_object_internal();
obj->line = line;
/* helper defines for internal use only */
#define __OBJ_HEAD(a, n) \
if (!strcmp(s, #a)) { \
obj->cb_handle = create_cb_handle(n);
#define __OBJ_IF obj_be_ifblock_if(ifblock_opaque, obj)
#define __OBJ_ARG(...) \
if (!arg) { \
free(s); \
CRIT_ERR_FREE(obj, free_at_crash, __VA_ARGS__); \
}
/* defines to be used below */
#define OBJ(a, n) __OBJ_HEAD(a, n) {
#define OBJ_ARG(a, n, ...) __OBJ_HEAD(a, n) __OBJ_ARG(__VA_ARGS__) {
#define OBJ_IF(a, n) \
__OBJ_HEAD(a, n) __OBJ_IF; \
{
#define OBJ_IF_ARG(a, n, ...) \
__OBJ_HEAD(a, n) __OBJ_ARG(__VA_ARGS__) __OBJ_IF; \
{
#define END \
} \
} \
else
#ifdef BUILD_GUI
if (s[0] == '#') {
obj->data.l = parse_color(s).to_argb32();
obj->callbacks.print = &new_fg;
} else
#endif /* BUILD_GUI */
#ifndef __OpenBSD__
OBJ(acpitemp, nullptr)
obj->data.i = open_acpi_temperature(arg);
obj->callbacks.print = &print_acpitemp;
obj->callbacks.free = &free_acpitemp;
END OBJ(acpiacadapter, nullptr) if (arg != nullptr) {
#ifdef __linux__
if (strpbrk(arg, "/.") != nullptr) {
/*
* a bit of paranoia. screen out funky paths
* i hope no device will have a '.' in its name
*/
NORM_ERR("acpiacadapter: arg must not contain '/' or '.'");
} else
obj->data.opaque = strdup(arg);
#else
NORM_ERR("acpiacadapter: arg is only used on linux");
#endif
}
obj->callbacks.print = &print_acpiacadapter;
obj->callbacks.free = &gen_free_opaque;
#endif /* !__OpenBSD__ */
END OBJ(freq, nullptr) get_cpu_count();
if ((arg == nullptr) || strlen(arg) >= 3 ||
strtol(&arg[0], nullptr, 10) == 0 ||
static_cast<unsigned int>(strtol(&arg[0], nullptr, 10)) >
info.cpu_count) {
obj->data.i = 1;
/* NORM_ERR("freq: Invalid CPU number or you don't have that many CPUs! "
"Displaying the clock for CPU 1."); */
} else {
obj->data.i = strtol(&arg[0], nullptr, 10);
}
obj->callbacks.print = &print_freq;
END OBJ(freq_g, nullptr) get_cpu_count();
if ((arg == nullptr) || strlen(arg) >= 3 ||
strtol(&arg[0], nullptr, 10) == 0 ||
static_cast<unsigned int>(strtol(&arg[0], nullptr, 10)) >
info.cpu_count) {
obj->data.i = 1;
/* NORM_ERR("freq_g: Invalid CPU number or you don't have that many "
"CPUs! Displaying the clock for CPU 1."); */
} else {
obj->data.i = strtol(&arg[0], nullptr, 10);
}
obj->callbacks.print = &print_freq_g;
#if defined(__linux__)
END OBJ(cpugovernor, nullptr) get_cpu_count();
if ((arg == nullptr) || strlen(arg) >= 3 ||
strtol(&arg[0], nullptr, 10) == 0 ||
static_cast<unsigned int>(strtol(&arg[0], nullptr, 10)) >
info.cpu_count) {
obj->data.i = 1;
/* NORM_ERR("cpugovernor: Invalid CPU number or you don't have that "
"many CPUs! Displaying the scaling governor for CPU 1."); */
} else {
obj->data.i = strtol(&arg[0], nullptr, 10);
}
obj->callbacks.print = &print_cpugovernor;
#endif /* __linux__ */
END OBJ_ARG(read_tcp, nullptr,
"read_tcp: Needs \"(host) port\" as argument(s)")
parse_read_tcpip_arg(obj, arg, free_at_crash);
obj->callbacks.print = &print_read_tcp;
obj->callbacks.free = &free_read_tcpip;
END OBJ_ARG(read_udp, nullptr,
"read_udp: Needs \"(host) port\" as argument(s)")
parse_read_tcpip_arg(obj, arg, free_at_crash);
obj->callbacks.print = &print_read_udp;
obj->callbacks.free = &free_read_tcpip;
END OBJ_ARG(tcp_ping, nullptr,
"tcp_ping: Needs \"host (port)\" as argument(s)")
parse_tcp_ping_arg(obj, arg, free_at_crash);
obj->callbacks.print = &print_tcp_ping;
obj->callbacks.free = &free_tcp_ping;
#if defined(__linux__)
END OBJ(voltage_mv, 0) get_cpu_count();
if (!arg || strlen(arg) >= 3 || strtol(&arg[0], nullptr, 10) == 0 ||
(unsigned int)strtol(&arg[0], nullptr, 10) > info.cpu_count) {
obj->data.i = 1;
/* NORM_ERR("voltage_mv: Invalid CPU number or you don't have that many "
"CPUs! Displaying voltage for CPU 1."); */
} else {
obj->data.i = strtol(&arg[0], nullptr, 10);
}
obj->callbacks.print = &print_voltage_mv;
END OBJ(voltage_v, 0) get_cpu_count();
if (!arg || strlen(arg) >= 3 || strtol(&arg[0], nullptr, 10) == 0 ||
(unsigned int)strtol(&arg[0], nullptr, 10) > info.cpu_count) {
obj->data.i = 1;
/* NORM_ERR("voltage_v: Invalid CPU number or you don't have that many "
"CPUs! Displaying voltage for CPU 1."); */
} else {
obj->data.i = strtol(&arg[0], nullptr, 10);
}
obj->callbacks.print = &print_voltage_v;
#endif /* __linux__ */
#ifdef BUILD_WLAN
END OBJ(wireless_essid, &update_net_stats) obj->data.opaque =
get_net_stat(arg, obj, free_at_crash);
parse_net_stat_arg(obj, arg, free_at_crash);
obj->callbacks.print = &print_wireless_essid;
END OBJ(wireless_channel, &update_net_stats)
parse_net_stat_arg(obj, arg, free_at_crash);
obj->callbacks.print = &print_wireless_channel;
END OBJ(wireless_freq, &update_net_stats)
parse_net_stat_arg(obj, arg, free_at_crash);
obj->callbacks.print = &print_wireless_frequency;
END OBJ(wireless_mode, &update_net_stats)
parse_net_stat_arg(obj, arg, free_at_crash);
obj->callbacks.print = &print_wireless_mode;
END OBJ(wireless_bitrate, &update_net_stats)
parse_net_stat_arg(obj, arg, free_at_crash);
obj->callbacks.print = &print_wireless_bitrate;
END OBJ(wireless_ap, &update_net_stats)
parse_net_stat_arg(obj, arg, free_at_crash);
obj->callbacks.print = &print_wireless_ap;
END OBJ(wireless_link_qual, &update_net_stats)
parse_net_stat_arg(obj, arg, free_at_crash);
obj->callbacks.print = &print_wireless_link_qual;
END OBJ(wireless_link_qual_max, &update_net_stats)
parse_net_stat_arg(obj, arg, free_at_crash);
obj->callbacks.print = &print_wireless_link_qual_max;
END OBJ(wireless_link_qual_perc, &update_net_stats)
parse_net_stat_arg(obj, arg, free_at_crash);
obj->callbacks.print = &print_wireless_link_qual_perc;
END OBJ(wireless_link_bar, &update_net_stats)
parse_net_stat_bar_arg(obj, arg, free_at_crash);
obj->callbacks.barval = &wireless_link_barval;
#endif /* BUILD_WLAN */
#ifndef __OpenBSD__
END OBJ(acpifan, nullptr) obj->callbacks.print = &print_acpifan;
END OBJ(battery, nullptr) char bat[64];
if (arg != nullptr) {
sscanf(arg, "%63s", bat);
} else {
strncpy(bat, "BAT0", 5);
}
obj->data.s = strndup(bat, text_buffer_size.get(*state));
obj->callbacks.print = &print_battery;
obj->callbacks.free = &gen_free_opaque;
END OBJ(battery_short, nullptr) char bat[64];
if (arg != nullptr) {
sscanf(arg, "%63s", bat);
} else {
strncpy(bat, "BAT0", 5);
}
obj->data.s = strndup(bat, text_buffer_size.get(*state));
obj->callbacks.print = &print_battery_short;
obj->callbacks.free = &gen_free_opaque;
END OBJ(battery_status, 0) obj->data.s =
strndup(arg ? arg : "BAT0", text_buffer_size.get(*state));
obj->callbacks.print = &print_battery_status;
obj->callbacks.free = &gen_free_opaque;
END OBJ(battery_time, nullptr) char bat[64];
if (arg != nullptr) {
sscanf(arg, "%63s", bat);
} else {
strncpy(bat, "BAT0", 5);
}
obj->data.s = strndup(bat, text_buffer_size.get(*state));
obj->callbacks.print = &print_battery_time;
obj->callbacks.free = &gen_free_opaque;
END OBJ(battery_percent, nullptr) char bat[64];
if (arg != nullptr) {
sscanf(arg, "%63s", bat);
} else {
strncpy(bat, "BAT0", 5);
}
obj->data.s = strndup(bat, text_buffer_size.get(*state));
obj->callbacks.percentage = &battery_percentage;
obj->callbacks.free = &gen_free_opaque;
END OBJ(battery_power_draw, nullptr) char bat[64];
if (arg != nullptr) {
sscanf(arg, "%63s", bat);
} else {
strncpy(bat, "BAT0", 5);
}
obj->data.s = strndup(bat, text_buffer_size.get(*state));
obj->callbacks.print = &battery_power_draw;
obj->callbacks.free = &gen_free_opaque;
END OBJ(battery_bar, nullptr) char bat[64];
arg = scan_bar(obj, arg, 100);
if ((arg != nullptr) && strlen(arg) > 0) {
sscanf(arg, "%63s", bat);
} else {
strncpy(bat, "BAT0", 5);
}
obj->data.s = strndup(bat, text_buffer_size.get(*state));
obj->callbacks.barval = &get_battery_perct_bar;
obj->callbacks.free = &gen_free_opaque;
#endif /* !__OpenBSD__ */
#if defined(__linux__)
END OBJ_ARG(disk_protect, 0, "disk_protect needs an argument") obj->data.s =
strndup(dev_name(arg), text_buffer_size.get(*state));
obj->callbacks.print = &print_disk_protect_queue;
obj->callbacks.free = &gen_free_opaque;
END OBJ(i8k_version, &update_i8k) obj->callbacks.print = &print_i8k_version;
END OBJ(i8k_bios, &update_i8k) obj->callbacks.print = &print_i8k_bios;
END OBJ(i8k_serial, &update_i8k) obj->callbacks.print = &print_i8k_serial;
END OBJ(i8k_cpu_temp, &update_i8k) obj->callbacks.print = &print_i8k_cpu_temp;
END OBJ(i8k_left_fan_status, &update_i8k) obj->callbacks.print =
&print_i8k_left_fan_status;
END OBJ(i8k_right_fan_status, &update_i8k) obj->callbacks.print =
&print_i8k_right_fan_status;
END OBJ(i8k_left_fan_rpm, &update_i8k) obj->callbacks.print =
&print_i8k_left_fan_rpm;
END OBJ(i8k_right_fan_rpm, &update_i8k) obj->callbacks.print =
&print_i8k_right_fan_rpm;
END OBJ(i8k_ac_status, &update_i8k) obj->callbacks.print =
&print_i8k_ac_status;
END OBJ(i8k_buttons_status, &update_i8k) obj->callbacks.print =
&print_i8k_buttons_status;
#if defined(BUILD_IBM)
END OBJ(ibm_fan, 0) obj->callbacks.print = &get_ibm_acpi_fan;
END OBJ_ARG(ibm_temps, &get_ibm_acpi_temps, "ibm_temps: needs an argument")
parse_ibm_temps_arg(obj, arg);
obj->callbacks.print = &print_ibm_temps;
END OBJ(ibm_volume, 0) obj->callbacks.print = &get_ibm_acpi_volume;
END OBJ(ibm_brightness, 0) obj->callbacks.print = &get_ibm_acpi_brightness;
END OBJ(ibm_thinklight, 0) obj->callbacks.print = &get_ibm_acpi_thinklight;
#endif
/* information from sony_laptop kernel module
* /sys/devices/platform/sony-laptop */
END OBJ(sony_fanspeed, 0) obj->callbacks.print = &get_sony_fanspeed;
END OBJ_ARG(ioscheduler, 0, "get_ioscheduler needs an argument (e.g. hda)")
obj->data.s = strndup(dev_name(arg), text_buffer_size.get(*state));
obj->callbacks.print = &print_ioscheduler;
obj->callbacks.free = &gen_free_opaque;
END OBJ(laptop_mode, 0) obj->callbacks.print = &print_laptop_mode;
END OBJ_ARG(
pb_battery, 0,
"pb_battery: needs one argument: status, percent or time") if (strcmp(arg,
"st"
"at"
"u"
"s") ==
EQUAL) {
obj->data.i = PB_BATT_STATUS;
}
else if (strcmp(arg, "percent") == EQUAL) { obj->data.i = PB_BATT_PERCENT; }
else if (strcmp(arg, "time") == EQUAL) { obj->data.i = PB_BATT_TIME; }
else {
NORM_ERR("pb_battery: illegal argument '%s', defaulting to status", arg);
obj->data.i = PB_BATT_STATUS;
}
obj->callbacks.print = get_powerbook_batt_info;
#endif /* __linux__ */
#if (defined(__FreeBSD__) || defined(__linux__) || defined(__DragonFly__) || \
(defined(__APPLE__) && defined(__MACH__)))
END OBJ_IF_ARG(if_up, nullptr, "if_up needs an argument")
parse_if_up_arg(obj, arg);
obj->callbacks.iftest = &interface_up;
obj->callbacks.free = &free_if_up;
#endif
#if defined(__OpenBSD__)
END OBJ_ARG(obsd_sensors_temp, 0, "obsd_sensors_temp: needs an argument")
parse_obsd_sensor(obj, arg);
obj->callbacks.print = &print_obsd_sensors_temp;
END OBJ_ARG(obsd_sensors_fan, 0,
"obsd_sensors_fan: needs 2 arguments (device and sensor number)")
parse_obsd_sensor(obj, arg);
obj->callbacks.print = &print_obsd_sensors_fan;
END OBJ_ARG(obsd_sensors_volt, 0,
"obsd_sensors_volt: needs 2 arguments (device and sensor number)")
parse_obsd_sensor(obj, arg);
obj->callbacks.print = &print_obsd_sensors_volt;
END OBJ(obsd_vendor, 0) obj->callbacks.print = &get_obsd_vendor;
END OBJ(obsd_product, 0) obj->callbacks.print = &get_obsd_product;
#endif /* __OpenBSD__ */
END OBJ(buffers, &update_meminfo) obj->data.s = STRNDUP_ARG;
obj->callbacks.print = &print_buffers;
obj->callbacks.free = &gen_free_opaque;
END OBJ(cached, &update_meminfo) obj->data.s = STRNDUP_ARG;
obj->callbacks.print = &print_cached;
obj->callbacks.free = &gen_free_opaque;
#define SCAN_CPU(__arg, __var) \
{ \
int __offset = 0; \
if ((__arg) && sscanf(__arg, " cpu%d %n", &(__var), &__offset) > 0) \
(__arg) += __offset; \
else \
(__var) = 0; \
}
END OBJ(cpu, &update_cpu_usage) get_cpu_count();
SCAN_CPU(arg, obj->data.i);
obj->callbacks.percentage = &cpu_percentage;
obj->callbacks.free = &free_cpu;
DBGP2("Adding $cpu for CPU %d", obj->data.i);
#ifdef BUILD_GUI
END OBJ(cpugauge, &update_cpu_usage) get_cpu_count();
SCAN_CPU(arg, obj->data.i);
scan_gauge(obj, arg, 1);
obj->callbacks.gaugeval = &cpu_barval;
obj->callbacks.free = &free_cpu;
DBGP2("Adding $cpugauge for CPU %d", obj->data.i);
#endif
END OBJ(cpubar, &update_cpu_usage) get_cpu_count();
SCAN_CPU(arg, obj->data.i);
scan_bar(obj, arg, 1);
obj->callbacks.barval = &cpu_barval;
obj->callbacks.free = &free_cpu;
DBGP2("Adding $cpubar for CPU %d", obj->data.i);
#ifdef BUILD_GUI
END OBJ(cpugraph, &update_cpu_usage) get_cpu_count();
SCAN_CPU(arg, obj->data.i);
scan_graph(obj, arg, 1, FALSE);
DBGP2("Adding $cpugraph for CPU %d", obj->data.i);
obj->callbacks.graphval = &cpu_barval;
obj->callbacks.free = &free_cpu;
END OBJ(loadgraph, &update_load_average) scan_loadgraph_arg(obj, arg);
obj->callbacks.graphval = &loadgraphval;
#endif /* BUILD_GUI */
END OBJ(diskio, &update_diskio) parse_diskio_arg(obj, arg);
obj->callbacks.print = &print_diskio;
END OBJ(diskio_read, &update_diskio) parse_diskio_arg(obj, arg);
obj->callbacks.print = &print_diskio_read;
END OBJ(diskio_write, &update_diskio) parse_diskio_arg(obj, arg);
obj->callbacks.print = &print_diskio_write;
#ifdef BUILD_GUI
END OBJ(diskiograph, &update_diskio) parse_diskiograph_arg(obj, arg);
obj->callbacks.graphval = &diskiographval;
END OBJ(diskiograph_read, &update_diskio) parse_diskiograph_arg(obj, arg);
obj->callbacks.graphval = &diskiographval_read;
END OBJ(diskiograph_write, &update_diskio) parse_diskiograph_arg(obj, arg);
obj->callbacks.graphval = &diskiographval_write;
#endif /* BUILD_GUI */
END OBJ(color, nullptr) if (false
#ifdef BUILD_GUI
|| out_to_gui(*state)
#endif /* BUILD_GUI */
#ifdef BUILD_NCURSES
|| out_to_ncurses.get(*state)
#endif /* BUILD_NCURSES */
) {
Colour c = arg != nullptr ? parse_color(arg) : default_color.get(*state);
obj->data.l = c.to_argb32();
set_current_text_color(c);
}
obj->callbacks.print = &new_fg;
#ifdef BUILD_GUI
END OBJ(color0, nullptr) Colour c = color[0].get(*state);
obj->data.l = c.to_argb32();
set_current_text_color(c);
obj->callbacks.print = &new_fg;
END OBJ(color1, nullptr) Colour c = color[1].get(*state);
obj->data.l = c.to_argb32();
set_current_text_color(c);
obj->callbacks.print = &new_fg;
END OBJ(color2, nullptr) Colour c = color[2].get(*state);
obj->data.l = c.to_argb32();
set_current_text_color(c);
obj->callbacks.print = &new_fg;
END OBJ(color3, nullptr) Colour c = color[3].get(*state);
obj->data.l = c.to_argb32();
set_current_text_color(c);
obj->callbacks.print = &new_fg;
END OBJ(color4, nullptr) Colour c = color[4].get(*state);
obj->data.l = c.to_argb32();
set_current_text_color(c);
obj->callbacks.print = &new_fg;
END OBJ(color5, nullptr) Colour c = color[5].get(*state);
obj->data.l = c.to_argb32();
set_current_text_color(c);
obj->callbacks.print = &new_fg;
END OBJ(color6, nullptr) Colour c = color[6].get(*state);
obj->data.l = c.to_argb32();
set_current_text_color(c);
obj->callbacks.print = &new_fg;
END OBJ(color7, nullptr) Colour c = color[7].get(*state);
obj->data.l = c.to_argb32();
set_current_text_color(c);
obj->callbacks.print = &new_fg;
END OBJ(color8, nullptr) Colour c = color[8].get(*state);
obj->data.l = c.to_argb32();
set_current_text_color(c);
obj->callbacks.print = &new_fg;
END OBJ(color9, nullptr) Colour c = color[9].get(*state);
obj->data.l = c.to_argb32();
set_current_text_color(c);
obj->callbacks.print = &new_fg;
END OBJ(font, nullptr) scan_font(obj, arg);
obj->callbacks.print = &new_font;
obj->callbacks.free = &gen_free_opaque;
END OBJ(font0, nullptr) scan_font(obj, font_template[0].get(*state).c_str());
obj->callbacks.print = &new_font;
obj->callbacks.free = &gen_free_opaque;
END OBJ(font1, nullptr) scan_font(obj, font_template[1].get(*state).c_str());
obj->callbacks.print = &new_font;
obj->callbacks.free = &gen_free_opaque;
END OBJ(font2, nullptr) scan_font(obj, font_template[2].get(*state).c_str());
obj->callbacks.print = &new_font;
obj->callbacks.free = &gen_free_opaque;
END OBJ(font3, nullptr) scan_font(obj, font_template[3].get(*state).c_str());
obj->callbacks.print = &new_font;
obj->callbacks.free = &gen_free_opaque;
END OBJ(font4, nullptr) scan_font(obj, font_template[4].get(*state).c_str());
obj->callbacks.print = &new_font;
obj->callbacks.free = &gen_free_opaque;
END OBJ(font5, nullptr) scan_font(obj, font_template[5].get(*state).c_str());
obj->callbacks.print = &new_font;
obj->callbacks.free = &gen_free_opaque;
END OBJ(font6, nullptr) scan_font(obj, font_template[6].get(*state).c_str());
obj->callbacks.print = &new_font;
obj->callbacks.free = &gen_free_opaque;
END OBJ(font7, nullptr) scan_font(obj, font_template[7].get(*state).c_str());
obj->callbacks.print = &new_font;
obj->callbacks.free = &gen_free_opaque;
END OBJ(font8, nullptr) scan_font(obj, font_template[8].get(*state).c_str());
obj->callbacks.print = &new_font;
obj->callbacks.free = &gen_free_opaque;
END OBJ(font9, nullptr) scan_font(obj, font_template[9].get(*state).c_str());
obj->callbacks.print = &new_font;
obj->callbacks.free = &gen_free_opaque;
#endif /* BUILD_GUI */
END OBJ(conky_version, nullptr) obj_be_plain_text(obj, VERSION);
END OBJ(conky_build_arch, nullptr) obj_be_plain_text(obj, BUILD_ARCH);
END OBJ(downspeed, &update_net_stats)
parse_net_stat_arg(obj, arg, free_at_crash);
obj->callbacks.print = &print_downspeed;
END OBJ(downspeedf, &update_net_stats)
parse_net_stat_arg(obj, arg, free_at_crash);
obj->callbacks.print = &print_downspeedf;
#ifdef BUILD_GUI
END OBJ(downspeedgraph, &update_net_stats)
parse_net_stat_graph_arg(obj, arg, free_at_crash);
obj->callbacks.graphval = &downspeedgraphval;
#endif /* BUILD_GUI */
END OBJ(else, nullptr) obj_be_ifblock_else(ifblock_opaque, obj);
obj->callbacks.iftest = &gen_false_iftest;
END OBJ(endif, nullptr) obj_be_ifblock_endif(ifblock_opaque, obj);
obj->callbacks.print = &gen_print_nothing;
END OBJ(eval, nullptr) obj->data.s = STRNDUP_ARG;
obj->callbacks.print = &print_evaluate;
obj->callbacks.free = &gen_free_opaque;
#if defined(BUILD_IMLIB2) && defined(BUILD_GUI)
END OBJ(image, nullptr) obj->data.s = STRNDUP_ARG;
obj->callbacks.print = &print_image_callback;
obj->callbacks.free = &gen_free_opaque;
#endif /* BUILD_IMLIB2 */
#ifdef BUILD_MYSQL
END OBJ_ARG(mysql, 0, "mysql needs a query") obj->data.s = strdup(arg);
obj->callbacks.print = &print_mysql;
#endif /* BUILD_MYSQL */
END OBJ_ARG(no_update, nullptr, "no_update needs arguments")
scan_no_update(obj, arg);
obj->callbacks.print = &print_no_update;
obj->callbacks.free = &free_no_update;
END OBJ(cat, 0) obj->data.s = STRNDUP_ARG;
obj->callbacks.print = &print_cat;
obj->callbacks.free = &gen_free_opaque;
#ifdef BUILD_X11
END OBJ(key_num_lock, 0) obj->callbacks.print = &print_key_num_lock;
END OBJ(key_caps_lock, 0) obj->callbacks.print = &print_key_caps_lock;
END OBJ(key_scroll_lock, 0) obj->callbacks.print = &print_key_scroll_lock;
END OBJ(keyboard_layout, 0) obj->callbacks.print = &print_keyboard_layout;
END OBJ(mouse_speed, 0) obj->callbacks.print = &print_mouse_speed;
#endif /* BUILD_GUI */
#ifdef __FreeBSD__
END OBJ(sysctlbyname, 0) obj->data.s = STRNDUP_ARG;
obj->callbacks.print = &print_sysctlbyname;
obj->callbacks.free = &gen_free_opaque;
#endif /* __FreeBSD__ */
END OBJ(password, 0) obj->data.s =
strndup(arg ? arg : "20", text_buffer_size.get(*state));
obj->callbacks.print = &print_password;
obj->callbacks.free = &gen_free_opaque;
#ifdef __x86_64__
END OBJ(freq2, 0) obj->callbacks.print = &print_freq2;
#endif /* __x86_64__ */
END OBJ(startcase, 0) obj->data.s = STRNDUP_ARG;
obj->callbacks.print = &print_startcase;
obj->callbacks.free = &gen_free_opaque;
// Deprecated, for compatibility purposes only
END OBJ(start_case, 0) obj->data.s = STRNDUP_ARG;
obj->callbacks.print = &print_startcase;
obj->callbacks.free = &gen_free_opaque;
END OBJ(lowercase, 0) obj->data.s = STRNDUP_ARG;
obj->callbacks.print = &print_lowercase;
obj->callbacks.free = &gen_free_opaque;
END OBJ(uppercase, 0) obj->data.s = STRNDUP_ARG;
obj->callbacks.print = &print_uppercase;
obj->callbacks.free = &gen_free_opaque;
END OBJ(rstrip, 0) obj->data.s = STRNDUP_ARG;
obj->callbacks.print = &strip_trailing_whitespace;
obj->callbacks.free = &gen_free_opaque;
END OBJ(catp, 0) obj->data.s = STRNDUP_ARG;
obj->callbacks.print = &print_catp;
obj->callbacks.free = &gen_free_opaque;
END OBJ_ARG(exec, nullptr, "exec needs arguments: <command>")
scan_exec_arg(obj, arg, EF_EXEC);
obj->parse = false;
obj->thread = false;
register_exec(obj);
obj->callbacks.print = &print_exec;
obj->callbacks.free = &free_exec;
END OBJ_ARG(execi, nullptr, "execi needs arguments: <interval> <command>")
scan_exec_arg(obj, arg, EF_EXECI);
obj->parse = false;
obj->thread = false;
register_execi(obj);
obj->callbacks.print = &print_exec;
obj->callbacks.free = &free_execi;
END OBJ_ARG(execp, nullptr, "execp needs arguments: <command>")
scan_exec_arg(obj, arg, EF_EXEC);
obj->parse = true;
obj->thread = false;
register_exec(obj);
obj->callbacks.print = &print_exec;
obj->callbacks.free = &free_exec;
END OBJ_ARG(execpi, nullptr, "execpi needs arguments: <interval> <command>")
scan_exec_arg(obj, arg, EF_EXECI);
obj->parse = true;
obj->thread = false;
register_execi(obj);
obj->callbacks.print = &print_exec;
obj->callbacks.free = &free_execi;
END OBJ_ARG(execbar, nullptr,
"execbar needs arguments: [height],[width] <command>")
scan_exec_arg(obj, arg, EF_EXEC | EF_BAR);
register_exec(obj);
obj->callbacks.barval = &execbarval;
obj->callbacks.free = &free_exec;
END OBJ_ARG(execibar, nullptr,
"execibar needs arguments: <interval> [height],[width] <command>")
scan_exec_arg(obj, arg, EF_EXECI | EF_BAR);
register_execi(obj);
obj->callbacks.barval = &execbarval;
obj->callbacks.free = &free_execi;
#ifdef BUILD_GUI
END OBJ_ARG(execgauge, nullptr,
"execgauge needs arguments: [height],[width] <command>")
scan_exec_arg(obj, arg, EF_EXEC | EF_GAUGE);
register_exec(obj);
obj->callbacks.gaugeval = &execbarval;
obj->callbacks.free = &free_exec;
END OBJ_ARG(
execigauge, nullptr,
"execigauge needs arguments: <interval> [height],[width] <command>")
scan_exec_arg(obj, arg, EF_EXECI | EF_GAUGE);
register_execi(obj);
obj->callbacks.gaugeval = &execbarval;
obj->callbacks.free = &free_execi;
END OBJ_ARG(execgraph, nullptr,
"execgraph needs arguments: <command> [height],[width] [color1] "
"[color2] [scale] [-t|-l]")
scan_exec_arg(obj, arg, EF_EXEC | EF_GRAPH);
register_exec(obj);
obj->callbacks.graphval = &execbarval;
obj->callbacks.free = &free_exec;
END OBJ_ARG(execigraph, nullptr,
"execigraph needs arguments: <interval> <command> "
"[height],[width] [color1] [color2] [scale] [-t|-l]")
scan_exec_arg(obj, arg, EF_EXECI | EF_GRAPH);
register_execi(obj);
obj->callbacks.graphval = &execbarval;
obj->callbacks.free = &free_execi;
#endif /* BUILD_GUI */
END OBJ_ARG(texeci, nullptr, "texeci needs arguments: <interval> <command>")
scan_exec_arg(obj, arg, EF_EXECI);
obj->parse = false;
obj->thread = true;
register_execi(obj);
obj->callbacks.print = &print_exec;
obj->callbacks.free = &free_execi;
END OBJ_ARG(texecpi, nullptr, "texecpi needs arguments: <interval> <command>")
scan_exec_arg(obj, arg, EF_EXECI);
obj->parse = true;
obj->thread = true;
register_execi(obj);
obj->callbacks.print = &print_exec;
obj->callbacks.free = &free_execi;
END OBJ(fs_bar, &update_fs_stats) init_fs_bar(obj, arg);
obj->callbacks.barval = &fs_barval;
END OBJ(fs_bar_free, &update_fs_stats) init_fs_bar(obj, arg);
obj->callbacks.barval = &fs_free_barval;
END OBJ(fs_free, &update_fs_stats) init_fs(obj, arg);
obj->callbacks.print = &print_fs_free;
END OBJ(fs_used_perc, &update_fs_stats) init_fs(obj, arg);
obj->callbacks.percentage = &fs_used_percentage;
END OBJ(fs_free_perc, &update_fs_stats) init_fs(obj, arg);
obj->callbacks.percentage = &fs_free_percentage;
END OBJ(fs_size, &update_fs_stats) init_fs(obj, arg);
obj->callbacks.print = &print_fs_size;
END OBJ(fs_type, &update_fs_stats) init_fs(obj, arg);
obj->callbacks.print = &print_fs_type;
END OBJ(fs_used, &update_fs_stats) init_fs(obj, arg);
obj->callbacks.print = &print_fs_used;
#ifdef BUILD_GUI
END OBJ(hr, nullptr) obj->data.l =
arg != nullptr ? strtol(arg, nullptr, 10) : 1;
obj->callbacks.print = &new_hr;
#endif /* BUILD_GUI */
END OBJ(nameserver, &update_dns_data) parse_nameserver_arg(obj, arg);
obj->callbacks.print = &print_nameserver;
obj->callbacks.free = &free_dns_data;
END OBJ(offset, nullptr) obj->data.l =
arg != nullptr ? strtol(arg, nullptr, 10) : 1;
obj->callbacks.print = &new_offset;
END OBJ(voffset, nullptr) obj->data.l =
arg != nullptr ? strtol(arg, nullptr, 10) : 1;
obj->callbacks.print = &new_voffset;
END OBJ(save_coordinates, nullptr) obj->data.l =
arg != nullptr ? strtol(arg, nullptr, 10) : 0;
obj->callbacks.print = &new_save_coordinates;
END OBJ_ARG(goto, nullptr, "goto needs arguments") obj->data.l =
strtol(arg, nullptr, 10);
obj->callbacks.print = &new_goto;
#ifdef BUILD_GUI
END OBJ(tab, nullptr) scan_tab(obj, arg);
obj->callbacks.print = &new_tab;
#endif /* BUILD_GUI */
#ifdef __linux__
END OBJ_ARG(i2c, 0, "i2c needs arguments") parse_i2c_sensor(obj, arg);
obj->callbacks.print = &print_sysfs_sensor;
obj->callbacks.free = &free_sysfs_sensor;
END OBJ_ARG(platform, 0, "platform needs arguments")
parse_platform_sensor(obj, arg);
obj->callbacks.print = &print_sysfs_sensor;
obj->callbacks.free = &free_sysfs_sensor;
END OBJ_ARG(hwmon, 0, "hwmon needs argumanets") parse_hwmon_sensor(obj, arg);
obj->callbacks.print = &print_sysfs_sensor;
obj->callbacks.free = &free_sysfs_sensor;
#endif /* __linux__ */
END
/* we have four different types of top (top, top_mem, top_time and
* top_io). To avoid having almost-same code four times, we have this
* special handler. */
/* XXX: maybe fiddle them apart later, as print_top() does
* nothing else than just that, using an ugly switch(). */
if (strncmp(s, "top", 3) == EQUAL) {
if (parse_top_args(s, arg, obj) != 0) {
obj->cb_handle = create_cb_handle(update_top);
} else {
free(obj);
return nullptr;
}
}
else OBJ(addr, &update_net_stats) parse_net_stat_arg(obj, arg, free_at_crash);
obj->callbacks.print = &print_addr;
END
#ifdef __linux__
OBJ(addrs, &update_net_stats) parse_net_stat_arg(obj, arg, free_at_crash);
obj->callbacks.print = &print_addrs;
#ifdef BUILD_IPV6
END OBJ(v6addrs, &update_net_stats)
parse_net_stat_arg(obj, arg, free_at_crash);
obj->callbacks.print = &print_v6addrs;
#endif /* BUILD_IPV6 */
END
#endif /* __linux__ */
OBJ_ARG(tail, nullptr, "tail needs arguments")
init_tailhead("tail", arg, obj, free_at_crash);
obj->callbacks.print = &print_tail;
obj->callbacks.free = &free_tailhead;
END OBJ_ARG(head, nullptr, "head needs arguments")
init_tailhead("head", arg, obj, free_at_crash);
obj->callbacks.print = &print_head;
obj->callbacks.free = &free_tailhead;
END OBJ_ARG(lines, nullptr, "lines needs an argument") obj->data.s =
STRNDUP_ARG;
obj->callbacks.print = &print_lines;
obj->callbacks.free = &gen_free_opaque;
END OBJ_ARG(words, nullptr, "words needs a argument") obj->data.s =
STRNDUP_ARG;
obj->callbacks.print = &print_words;
obj->callbacks.free = &gen_free_opaque;
END OBJ(loadavg, &update_load_average) scan_loadavg_arg(obj, arg);
obj->callbacks.print = &print_loadavg;
END OBJ_IF_ARG(if_empty, nullptr, "if_empty needs an argument") obj->sub =
static_cast<text_object *>(malloc(sizeof(struct text_object)));
extract_variable_text_internal(obj->sub, arg);
obj->callbacks.iftest = &if_empty_iftest;
END OBJ_IF_ARG(if_match, nullptr, "if_match needs arguments") obj->sub =
static_cast<text_object *>(malloc(sizeof(struct text_object)));
extract_variable_text_internal(obj->sub, arg);
obj->callbacks.iftest = &check_if_match;
END OBJ_IF_ARG(if_existing, nullptr, "if_existing needs an argument or two")
obj->data.s = STRNDUP_ARG;
obj->callbacks.iftest = &if_existing_iftest;
obj->callbacks.free = &gen_free_opaque;
#if defined(__linux__) || defined(__FreeBSD__)
END OBJ_IF_ARG(if_mounted, 0, "if_mounted needs an argument") obj->data.s =
STRNDUP_ARG;
obj->callbacks.iftest = &check_mount;
obj->callbacks.free = &gen_free_opaque;
END OBJ_IF_ARG(if_running, &update_top, "if_running needs an argument")
top_running = 1;
obj->data.s = STRNDUP_ARG;
obj->callbacks.iftest = &if_running_iftest;
obj->callbacks.free = &gen_free_opaque;
#elif defined(__APPLE__) && defined(__MACH__)
END OBJ_IF_ARG(if_mounted, nullptr, "if_mounted needs an argument")
obj->data.s = STRNDUP_ARG;
obj->callbacks.iftest = &check_mount;
obj->callbacks.free = &gen_free_opaque;
/* System Integrity Protection */
END OBJ(sip_status, &get_sip_status) obj->data.s = STRNDUP_ARG;
obj->callbacks.print = &print_sip_status;
obj->callbacks.free = &gen_free_opaque;
#else
END OBJ_IF_ARG(if_running, 0, "if_running needs an argument")
char buf[DEFAULT_TEXT_BUFFER_SIZE];
snprintf(buf, DEFAULT_TEXT_BUFFER_SIZE, "pidof %s >/dev/null", arg);
obj->data.s = STRNDUP_ARG;
/* XXX: maybe use a different callback here */
obj->callbacks.iftest = &if_running_iftest;
#endif
END OBJ(kernel, nullptr) obj->callbacks.print = &print_kernel;
END OBJ(machine, nullptr) obj->callbacks.print = &print_machine;
#if defined(__DragonFly__)
END OBJ(version, 0) obj->callbacks.print = &print_version;
#endif
END OBJ(mails, nullptr) parse_local_mail_args(obj, arg);
obj->callbacks.print = &print_mails;
obj->callbacks.free = &free_local_mails;
END OBJ(new_mails, nullptr) parse_local_mail_args(obj, arg);
obj->callbacks.print = &print_new_mails;
obj->callbacks.free = &free_local_mails;
END OBJ(seen_mails, nullptr) parse_local_mail_args(obj, arg);
obj->callbacks.print = &print_seen_mails;
obj->callbacks.free = &free_local_mails;
END OBJ(unseen_mails, nullptr) parse_local_mail_args(obj, arg);
obj->callbacks.print = &print_unseen_mails;
obj->callbacks.free = &free_local_mails;
END OBJ(flagged_mails, nullptr) parse_local_mail_args(obj, arg);
obj->callbacks.print = &print_flagged_mails;
obj->callbacks.free = &free_local_mails;
END OBJ(unflagged_mails, nullptr) parse_local_mail_args(obj, arg);
obj->callbacks.print = &print_unflagged_mails;
obj->callbacks.free = &free_local_mails;
END OBJ(forwarded_mails, nullptr) parse_local_mail_args(obj, arg);
obj->callbacks.print = &print_forwarded_mails;
obj->callbacks.free = &free_local_mails;
END OBJ(unforwarded_mails, nullptr) parse_local_mail_args(obj, arg);
obj->callbacks.print = &print_unforwarded_mails;
obj->callbacks.free = &free_local_mails;
END OBJ(replied_mails, nullptr) parse_local_mail_args(obj, arg);
obj->callbacks.print = &print_replied_mails;
obj->callbacks.free = &free_local_mails;
END OBJ(unreplied_mails, nullptr) parse_local_mail_args(obj, arg);
obj->callbacks.print = &print_unreplied_mails;
obj->callbacks.free = &free_local_mails;
END OBJ(draft_mails, nullptr) parse_local_mail_args(obj, arg);
obj->callbacks.print = &print_draft_mails;
obj->callbacks.free = &free_local_mails;
END OBJ(trashed_mails, nullptr) parse_local_mail_args(obj, arg);
obj->callbacks.print = &print_trashed_mails;
obj->callbacks.free = &free_local_mails;
END OBJ(mboxscan, nullptr) parse_mboxscan_arg(obj, arg);
obj->callbacks.print = &print_mboxscan;
obj->callbacks.free = &free_mboxscan;
END OBJ(mem, &update_meminfo) obj->data.s = STRNDUP_ARG;
obj->callbacks.print = &print_mem;
obj->callbacks.free = &gen_free_opaque;
END OBJ(legacymem, &update_meminfo) obj->data.s = STRNDUP_ARG;
obj->callbacks.print = &print_legacymem;
obj->callbacks.free = &gen_free_opaque;
END OBJ(memwithbuffers, &update_meminfo) obj->data.s = STRNDUP_ARG;
obj->callbacks.print = &print_memwithbuffers;
obj->callbacks.free = &gen_free_opaque;
END OBJ(memeasyfree, &update_meminfo) obj->data.s = STRNDUP_ARG;
obj->callbacks.print = &print_memeasyfree;
obj->callbacks.free = &gen_free_opaque;
END OBJ(memfree, &update_meminfo) obj->data.s = STRNDUP_ARG;
obj->callbacks.print = &print_memfree;
obj->callbacks.free = &gen_free_opaque;
END OBJ(memmax, &update_meminfo) obj->data.s = STRNDUP_ARG;
obj->callbacks.print = &print_memmax;
obj->callbacks.free = &gen_free_opaque;
END OBJ(memperc, &update_meminfo) obj->callbacks.percentage = &mem_percentage;
#ifdef __linux__
END OBJ(memdirty, &update_meminfo) obj->data.s = STRNDUP_ARG;
obj->callbacks.print = &print_memdirty;
obj->callbacks.free = &gen_free_opaque;
END OBJ(memavail, &update_meminfo) obj->data.s = STRNDUP_ARG;
obj->callbacks.print = &print_memavail;
obj->callbacks.free = &gen_free_opaque;
END OBJ(shmem, &update_meminfo) obj->data.s = STRNDUP_ARG;
obj->callbacks.print = &print_shmem;
obj->callbacks.free = &gen_free_opaque;
END OBJ(free_bufcache, &update_meminfo) obj->data.s = STRNDUP_ARG;
obj->callbacks.print = &print_free_bufcache;
obj->callbacks.free = &gen_free_opaque;
END OBJ(free_cached, &update_meminfo) obj->data.s = STRNDUP_ARG;
obj->callbacks.print = &print_free_cached;
obj->callbacks.free = &gen_free_opaque;
#endif /* __linux__ */
#ifdef __FreeBSD__
END OBJ(memactive, &update_meminfo) obj->data.s = STRNDUP_ARG;
obj->callbacks.print = &print_memactive;
obj->callbacks.free = &gen_free_opaque;
END OBJ(meminactive, &update_meminfo) obj->data.s = STRNDUP_ARG;
obj->callbacks.print = &print_meminactive;
obj->callbacks.free = &gen_free_opaque;
END OBJ(memwired, &update_meminfo) obj->data.s = STRNDUP_ARG;
obj->callbacks.print = &print_memwired;
obj->callbacks.free = &gen_free_opaque;
END OBJ(memlaundry, &update_meminfo) obj->data.s = STRNDUP_ARG;
obj->callbacks.print = &print_memlaundry;
obj->callbacks.free = &gen_free_opaque;
#endif /* __FreeBSD__ */
#ifdef BUILD_GUI
END OBJ(memgauge, &update_meminfo) scan_gauge(obj, arg, 1);
obj->callbacks.gaugeval = &mem_barval;
#endif /* BUILD_GUI */
END OBJ(membar, &update_meminfo) scan_bar(obj, arg, 1);
obj->callbacks.barval = &mem_barval;
END OBJ(memwithbuffersbar, &update_meminfo) scan_bar(obj, arg, 1);
obj->callbacks.barval = &mem_with_buffers_barval;
#ifdef BUILD_GUI
END OBJ(memgraph, &update_meminfo) scan_graph(obj, arg, 1, FALSE);
obj->callbacks.graphval = &mem_barval;
END OBJ(memwithbuffersgraph, &update_meminfo) scan_graph(obj, arg, 1, FALSE);
obj->callbacks.graphval = &mem_with_buffers_barval;
#endif /* BUILD_GUI*/
#ifdef HAVE_SOME_SOUNDCARD_H
END OBJ(mixer, 0) parse_mixer_arg(obj, arg);
obj->callbacks.percentage = &mixer_percentage;
END OBJ(mixerl, 0) parse_mixer_arg(obj, arg);
obj->callbacks.percentage = &mixerl_percentage;
END OBJ(mixerr, 0) parse_mixer_arg(obj, arg);
obj->callbacks.percentage = &mixerr_percentage;
END OBJ(mixerbar, 0) scan_mixer_bar(obj, arg);
obj->callbacks.barval = &mixer_barval;
END OBJ(mixerlbar, 0) scan_mixer_bar(obj, arg);
obj->callbacks.barval = &mixerl_barval;
END OBJ(mixerrbar, 0) scan_mixer_bar(obj, arg);
obj->callbacks.barval = &mixerr_barval;
END OBJ_IF(if_mixer_mute, 0) parse_mixer_arg(obj, arg);
obj->callbacks.iftest = &check_mixer_muted;
#endif /* HAVE_SOME_SOUNDCARD_H */
#ifdef BUILD_GUI
END OBJ(monitor, nullptr) obj->callbacks.print = &print_monitor;
END OBJ(monitor_number, nullptr) obj->callbacks.print = &print_monitor_number;
END OBJ(desktop, nullptr) obj->callbacks.print = &print_desktop;
END OBJ(desktop_number, nullptr) obj->callbacks.print = &print_desktop_number;
END OBJ(desktop_name, nullptr) obj->callbacks.print = &print_desktop_name;
#endif /* BUILD_GUI */
END OBJ_ARG(format_time, nullptr, "format_time needs a pid as argument")
obj->sub = static_cast<text_object *>(malloc(sizeof(struct text_object)));
extract_variable_text_internal(obj->sub, arg);
obj->callbacks.print = &print_format_time;
END OBJ(nodename, nullptr) obj->callbacks.print = &print_nodename;
END OBJ(nodename_short, nullptr) obj->callbacks.print = &print_nodename_short;
END OBJ_ARG(cmdline_to_pid, nullptr,
"cmdline_to_pid needs a command line as argument")
scan_cmdline_to_pid_arg(obj, arg, free_at_crash);
obj->callbacks.print = &print_cmdline_to_pid;
obj->callbacks.free = &gen_free_opaque;
END OBJ_ARG(pid_chroot, nullptr, "pid_chroot needs a pid as argument")
extract_object_args_to_sub(obj, arg);
obj->callbacks.print = &print_pid_chroot;
END OBJ_ARG(pid_cmdline, nullptr, "pid_cmdline needs a pid as argument")
extract_object_args_to_sub(obj, arg);
obj->callbacks.print = &print_pid_cmdline;
END OBJ_ARG(pid_cwd, nullptr, "pid_cwd needs a pid as argument")
extract_object_args_to_sub(obj, arg);
obj->callbacks.print = &print_pid_cwd;
END OBJ_ARG(pid_environ, nullptr, "pid_environ needs arguments")
extract_object_args_to_sub(obj, arg);
obj->callbacks.print = &print_pid_environ;
END OBJ_ARG(pid_environ_list, nullptr,
"pid_environ_list needs a pid as argument")
extract_object_args_to_sub(obj, arg);
obj->callbacks.print = &print_pid_environ_list;
END OBJ_ARG(pid_exe, nullptr, "pid_exe needs a pid as argument")
extract_object_args_to_sub(obj, arg);
obj->callbacks.print = &print_pid_exe;
END OBJ_ARG(pid_nice, nullptr, "pid_nice needs a pid as argument")
extract_object_args_to_sub(obj, arg);
obj->callbacks.print = &print_pid_nice;
END OBJ_ARG(pid_openfiles, nullptr, "pid_openfiles needs a pid as argument")
extract_object_args_to_sub(obj, arg);
obj->callbacks.print = &print_pid_openfiles;
END OBJ_ARG(pid_parent, nullptr, "pid_parent needs a pid as argument")
extract_object_args_to_sub(obj, arg);
obj->callbacks.print = &print_pid_parent;
END OBJ_ARG(pid_priority, nullptr, "pid_priority needs a pid as argument")
extract_object_args_to_sub(obj, arg);
obj->callbacks.print = &print_pid_priority;
END OBJ_ARG(pid_state, nullptr, "pid_state needs a pid as argument")
extract_object_args_to_sub(obj, arg);
obj->callbacks.print = &print_pid_state;
END OBJ_ARG(pid_state_short, nullptr,
"pid_state_short needs a pid as argument")
extract_object_args_to_sub(obj, arg);
obj->callbacks.print = &print_pid_state_short;
END OBJ_ARG(pid_stderr, nullptr, "pid_stderr needs a pid as argument")
extract_object_args_to_sub(obj, arg);
obj->callbacks.print = &print_pid_stderr;
END OBJ_ARG(pid_stdin, nullptr, "pid_stdin needs a pid as argument")
extract_object_args_to_sub(obj, arg);
obj->callbacks.print = &print_pid_stdin;
END OBJ_ARG(pid_stdout, nullptr, "pid_stdout needs a pid as argument")
extract_object_args_to_sub(obj, arg);
obj->callbacks.print = &print_pid_stdout;
END OBJ_ARG(pid_threads, nullptr, "pid_threads needs a pid as argument")
extract_object_args_to_sub(obj, arg);
obj->callbacks.print = &print_pid_threads;
END OBJ_ARG(pid_thread_list, nullptr,
"pid_thread_list needs a pid as argument")
extract_object_args_to_sub(obj, arg);
obj->callbacks.print = &print_pid_thread_list;
END OBJ_ARG(pid_time_kernelmode, nullptr,
"pid_time_kernelmode needs a pid as argument")
extract_object_args_to_sub(obj, arg);
obj->callbacks.print = &print_pid_time_kernelmode;
END OBJ_ARG(pid_time_usermode, nullptr,
"pid_time_usermode needs a pid as argument")
extract_object_args_to_sub(obj, arg);
obj->callbacks.print = &print_pid_time_usermode;
END OBJ_ARG(pid_time, nullptr, "pid_time needs a pid as argument")
extract_object_args_to_sub(obj, arg);
obj->callbacks.print = &print_pid_time;
END OBJ_ARG(pid_uid, nullptr, "pid_uid needs a pid as argument")
extract_object_args_to_sub(obj, arg);
obj->callbacks.print = &print_pid_uid;
END OBJ_ARG(pid_euid, nullptr, "pid_euid needs a pid as argument")
extract_object_args_to_sub(obj, arg);
obj->callbacks.print = &print_pid_euid;
END OBJ_ARG(pid_suid, nullptr, "pid_suid needs a pid as argument")
extract_object_args_to_sub(obj, arg);
obj->callbacks.print = &print_pid_suid;
END OBJ_ARG(pid_fsuid, nullptr, "pid_fsuid needs a pid as argument")
extract_object_args_to_sub(obj, arg);
obj->callbacks.print = &print_pid_fsuid;
END OBJ_ARG(pid_gid, nullptr, "pid_gid needs a pid as argument")
extract_object_args_to_sub(obj, arg);
obj->callbacks.print = &print_pid_gid;
END OBJ_ARG(pid_egid, nullptr, "pid_egid needs a pid as argument")
extract_object_args_to_sub(obj, arg);
obj->callbacks.print = &print_pid_egid;
END OBJ_ARG(pid_sgid, nullptr, "pid_sgid needs a pid as argument")
extract_object_args_to_sub(obj, arg);
obj->callbacks.print = &print_pid_sgid;
END OBJ_ARG(pid_fsgid, nullptr, "pid_fsgid needs a pid as argument")
extract_object_args_to_sub(obj, arg);
obj->callbacks.print = &print_pid_fsgid;
END OBJ_ARG(gid_name, nullptr, "gid_name needs a gid as argument")
extract_object_args_to_sub(obj, arg);
obj->callbacks.print = &print_gid_name;
END OBJ_ARG(uid_name, nullptr, "uid_name needs a uid as argument")
extract_object_args_to_sub(obj, arg);
obj->callbacks.print = &print_uid_name;
END OBJ_ARG(pid_read, nullptr, "pid_read needs a pid as argument")
extract_object_args_to_sub(obj, arg);
obj->callbacks.print = &print_pid_read;
END OBJ_ARG(pid_vmpeak, nullptr, "pid_vmpeak needs a pid as argument")
extract_object_args_to_sub(obj, arg);
obj->callbacks.print = &print_pid_vmpeak;
END OBJ_ARG(pid_vmsize, nullptr, "pid_vmsize needs a pid as argument")
extract_object_args_to_sub(obj, arg);
obj->callbacks.print = &print_pid_vmsize;
END OBJ_ARG(pid_vmlck, nullptr, "pid_vmlck needs a pid as argument")
extract_object_args_to_sub(obj, arg);
obj->callbacks.print = &print_pid_vmlck;
END OBJ_ARG(pid_vmhwm, nullptr, "pid_vmhwm needs a pid as argument")
extract_object_args_to_sub(obj, arg);
obj->callbacks.print = &print_pid_vmhwm;
END OBJ_ARG(pid_vmrss, nullptr, "pid_vmrss needs a pid as argument")
extract_object_args_to_sub(obj, arg);
obj->callbacks.print = &print_pid_vmrss;
END OBJ_ARG(pid_vmdata, nullptr, "pid_vmdata needs a pid as argument")
extract_object_args_to_sub(obj, arg);
obj->callbacks.print = &print_pid_vmdata;
END OBJ_ARG(pid_vmstk, nullptr, "pid_vmstk needs a pid as argument")
extract_object_args_to_sub(obj, arg);
obj->callbacks.print = &print_pid_vmstk;
END OBJ_ARG(pid_vmexe, nullptr, "pid_vmexe needs a pid as argument")
extract_object_args_to_sub(obj, arg);
obj->callbacks.print = &print_pid_vmexe;
END OBJ_ARG(pid_vmlib, nullptr, "pid_vmlib needs a pid as argument")
extract_object_args_to_sub(obj, arg);
obj->callbacks.print = &print_pid_vmlib;
END OBJ_ARG(pid_vmpte, nullptr, "pid_vmpte needs a pid as argument")
extract_object_args_to_sub(obj, arg);
obj->callbacks.print = &print_pid_vmpte;
END OBJ_ARG(pid_write, nullptr, "pid_write needs a pid as argument")
extract_object_args_to_sub(obj, arg);
obj->callbacks.print = &print_pid_write;
#ifdef __DragonFly__
END OBJ(processes, &update_top)
#else
END OBJ(processes, &update_total_processes)
#endif
obj->callbacks.print = &print_processes;
#ifdef __linux__
END OBJ(distribution, 0) obj->callbacks.print = &print_distribution;
END OBJ(running_processes, &update_top) top_running = 1;
obj->callbacks.print = &print_running_processes;
END OBJ(threads, &update_threads) obj->callbacks.print = &print_threads;
END OBJ(running_threads, &update_stat) obj->callbacks.print =
&print_running_threads;
#else
#if defined(__DragonFly__)
END OBJ(running_processes, &update_top) obj->callbacks.print =
&print_running_processes;
#elif (defined(__APPLE__) && defined(__MACH__))
END OBJ(running_processes, &update_running_processes) obj->callbacks.print =
&print_running_processes;
END OBJ(threads, &update_threads) obj->callbacks.print = &print_threads;
END OBJ(running_threads, &update_running_threads) obj->callbacks.print =
&print_running_threads;
#else
END OBJ(running_processes, &update_running_processes) obj->callbacks.print =
&print_running_processes;
#endif
#endif /* __linux__ */
END OBJ(shadecolor, nullptr)
#ifdef BUILD_GUI
obj->data.l =
(arg != nullptr ? parse_color(arg) : default_shade_color.get(*state))
.to_argb32();
obj->callbacks.print = &new_bg;
#endif /* BUILD_GUI */
END OBJ(outlinecolor, nullptr)
#ifdef BUILD_GUI
obj->data.l =
(arg != nullptr ? parse_color(arg) : default_outline_color.get(*state))
.to_argb32();
obj->callbacks.print = &new_outline;
#endif /* BUILD_GUI */
END OBJ(stippled_hr, nullptr)
#ifdef BUILD_GUI
scan_stippled_hr(obj, arg);
obj->callbacks.print = &new_stippled_hr;
#endif /* BUILD_GUI */
END OBJ(swap, &update_meminfo) obj->data.s = STRNDUP_ARG;
obj->callbacks.print = &print_swap;
obj->callbacks.free = &gen_free_opaque;
END OBJ(swapfree, &update_meminfo) obj->data.s = STRNDUP_ARG;
obj->callbacks.print = &print_swapfree;
obj->callbacks.free = &gen_free_opaque;
END OBJ(swapmax, &update_meminfo) obj->data.s = STRNDUP_ARG;
obj->callbacks.print = &print_swapmax;
obj->callbacks.free = &gen_free_opaque;
END OBJ(swapperc, &update_meminfo) obj->callbacks.percentage =
&swap_percentage;
END OBJ(swapbar, &update_meminfo) scan_bar(obj, arg, 1);
obj->callbacks.barval = &swap_barval;
/* XXX: swapgraph, swapgauge? */
END OBJ(sysname, nullptr) obj->callbacks.print = &print_sysname;
END OBJ(time, nullptr) scan_time(obj, arg);
obj->callbacks.print = &print_time;
obj->callbacks.free = &free_time;
END OBJ(utime, nullptr) scan_time(obj, arg);
obj->callbacks.print = &print_utime;
obj->callbacks.free = &free_time;
END OBJ(tztime, nullptr) scan_tztime(obj, arg);
obj->callbacks.print = &print_tztime;
obj->callbacks.free = &free_tztime;
#ifdef BUILD_ICAL
END OBJ_ARG(ical, 0, "ical requires arguments")
parse_ical_args(obj, arg, free_at_crash, s);
obj->callbacks.print = &print_ical;
obj->callbacks.free = &free_ical;
#endif
#ifdef BUILD_IRC
END OBJ_ARG(irc, 0, "irc requires arguments") parse_irc_args(obj, arg);
obj->callbacks.print = &print_irc;
obj->callbacks.free = &free_irc;
#endif
#ifdef BUILD_ICONV
END OBJ_ARG(iconv_start, 0, "Iconv requires arguments")
init_iconv_start(obj, free_at_crash, arg);
obj->callbacks.print = &print_iconv_start;
obj->callbacks.free = &free_iconv;
END OBJ(iconv_stop, 0) init_iconv_stop();
obj->callbacks.print = &print_iconv_stop;
#endif
END OBJ(totaldown, &update_net_stats)
parse_net_stat_arg(obj, arg, free_at_crash);
obj->callbacks.print = &print_totaldown;
END OBJ(totalup, &update_net_stats)
parse_net_stat_arg(obj, arg, free_at_crash);
obj->callbacks.print = &print_totalup;
END OBJ(updates, nullptr) obj->callbacks.print = &print_updates;
END OBJ_IF(if_updatenr, nullptr) obj->data.i =
arg != nullptr ? strtol(arg, nullptr, 10) : 0;
if (obj->data.i == 0) {
CRIT_ERR_FREE(obj, free_at_crash,
"if_updatenr needs a number above 0 as argument");
}
set_updatereset(obj->data.i > get_updatereset() ? obj->data.i
: get_updatereset());
obj->callbacks.iftest = &updatenr_iftest;
END OBJ(alignr, nullptr) obj->data.l =
arg != nullptr ? strtol(arg, nullptr, 10) : 1;
obj->callbacks.print = &new_alignr;
END OBJ(alignc, nullptr) obj->data.l =
arg != nullptr ? strtol(arg, nullptr, 10) : 0;
obj->callbacks.print = &new_alignc;
END OBJ(upspeed, &update_net_stats)
parse_net_stat_arg(obj, arg, free_at_crash);
obj->callbacks.print = &print_upspeed;
END OBJ(upspeedf, &update_net_stats)
parse_net_stat_arg(obj, arg, free_at_crash);
obj->callbacks.print = &print_upspeedf;
#ifdef BUILD_GUI
END OBJ(upspeedgraph, &update_net_stats)
parse_net_stat_graph_arg(obj, arg, free_at_crash);
obj->callbacks.graphval = &upspeedgraphval;
#endif
END OBJ(uptime_short, &update_uptime) obj->callbacks.print =
&print_uptime_short;
END OBJ(uptime, &update_uptime) obj->callbacks.print = &print_uptime;
#if defined(__linux__)
END OBJ(user_names, &update_users) obj->callbacks.print = &print_user_names;
obj->callbacks.free = &free_user_names;
END OBJ(user_times, &update_users) obj->callbacks.print = &print_user_times;
obj->callbacks.free = &free_user_times;
END OBJ_ARG(user_time, 0, "user time needs a console name as argument")
obj->data.s = STRNDUP_ARG;
obj->callbacks.print = &print_user_time;
obj->callbacks.free = &free_user_time;
END OBJ(user_terms, &update_users) obj->callbacks.print = &print_user_terms;
obj->callbacks.free = &free_user_terms;
END OBJ(user_number, &update_users) obj->callbacks.print = &print_user_number;
END OBJ(gw_iface, &update_gateway_info) obj->callbacks.print =
&print_gateway_iface;
obj->callbacks.free = &free_gateway_info;
END OBJ_IF(if_gw, &update_gateway_info) obj->callbacks.iftest =
&gateway_exists;
obj->callbacks.free = &free_gateway_info;
END OBJ(gw_ip, &update_gateway_info) obj->callbacks.print = &print_gateway_ip;
obj->callbacks.free = &free_gateway_info;
END OBJ(iface, &update_gateway_info2) obj->data.s = STRNDUP_ARG;
obj->callbacks.print = &print_gateway_iface2;
obj->callbacks.free = &gen_free_opaque;
#endif /* __linux__ */
#if (defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || \
defined(__DragonFly__) || defined(__OpenBSD__)) && \
(defined(i386) || defined(__i386__))
END OBJ(apm_adapter, 0) obj->callbacks.print = &print_apm_adapter;
END OBJ(apm_battery_life, 0) obj->callbacks.print = &print_apm_battery_life;
END OBJ(apm_battery_time, 0) obj->callbacks.print = &print_apm_battery_time;
#endif /* __FreeBSD__ */
END OBJ(imap_unseen, nullptr) parse_imap_mail_args(obj, arg);
obj->callbacks.print = &print_imap_unseen;
obj->callbacks.free = &free_mail_obj;
END OBJ(imap_messages, nullptr) parse_imap_mail_args(obj, arg);
obj->callbacks.print = &print_imap_messages;
obj->callbacks.free = &free_mail_obj;
END OBJ(pop3_unseen, nullptr) parse_pop3_mail_args(obj, arg);
obj->callbacks.print = &print_pop3_unseen;
obj->callbacks.free = &free_mail_obj;
END OBJ(pop3_used, nullptr) parse_pop3_mail_args(obj, arg);
obj->callbacks.print = &print_pop3_used;
obj->callbacks.free = &free_mail_obj;
#ifdef BUILD_IBM
END OBJ_ARG(smapi, 0, "smapi needs an argument") obj->data.s = STRNDUP_ARG;
obj->callbacks.print = &print_smapi;
obj->callbacks.free = &gen_free_opaque;
END OBJ_IF_ARG(if_smapi_bat_installed, 0,
"if_smapi_bat_installed needs an argument") obj->data.s =
STRNDUP_ARG;
obj->callbacks.iftest = &smapi_bat_installed;
obj->callbacks.free = &gen_free_opaque;
END OBJ_ARG(smapi_bat_perc, 0, "smapi_bat_perc needs an argument")
obj->data.s = STRNDUP_ARG;
obj->callbacks.percentage = &smapi_bat_percentage;
obj->callbacks.free = &gen_free_opaque;
END OBJ_ARG(smapi_bat_temp, 0, "smapi_bat_temp needs an argument")
obj->data.s = STRNDUP_ARG;
obj->callbacks.print = &print_smapi_bat_temp;
obj->callbacks.free = &gen_free_opaque;
END OBJ_ARG(smapi_bat_power, 0, "smapi_bat_power needs an argument")
obj->data.s = STRNDUP_ARG;
obj->callbacks.print = &print_smapi_bat_power;
obj->callbacks.free = &gen_free_opaque;
END OBJ_ARG(smapi_bat_bar, 0, "smapi_bat_bar needs an argument") int cnt;
if (sscanf(arg, "%i %n", &obj->data.i, &cnt) <= 0) {
NORM_ERR("first argument to smapi_bat_bar must be an integer value");
obj->data.i = -1;
} else
arg = scan_bar(obj, arg + cnt, 100);
obj->callbacks.barval = &smapi_bat_barval;
#endif /* BUILD_IBM */
#ifdef BUILD_MPD
#define mpd_set_maxlen(name) \
if (arg) { \
int i; \
sscanf(arg, "%d", &i); \
if (i > 0) \
obj->data.i = i + 1; \
else \
NORM_ERR(#name ": invalid length argument"); \
}
END OBJ(mpd_artist, nullptr) mpd_set_maxlen(mpd_artist);
obj->callbacks.print = &print_mpd_artist;
END OBJ(mpd_albumartist, nullptr) mpd_set_maxlen(mpd_albumartist);
obj->callbacks.print = &print_mpd_albumartist;
END OBJ(mpd_title, nullptr) mpd_set_maxlen(mpd_title);
obj->callbacks.print = &print_mpd_title;
END OBJ(mpd_date, nullptr) mpd_set_maxlen(mpd_date);
obj->callbacks.print = &print_mpd_date;
END OBJ(mpd_comment, nullptr) mpd_set_maxlen(mpd_comment);
obj->callbacks.print = &print_mpd_comment;
END OBJ(mpd_random, nullptr) obj->callbacks.print = &print_mpd_random;
END OBJ(mpd_repeat, nullptr) obj->callbacks.print = &print_mpd_repeat;
END OBJ(mpd_elapsed, nullptr) obj->callbacks.print = &print_mpd_elapsed;
END OBJ(mpd_length, nullptr) obj->callbacks.print = &print_mpd_length;
END OBJ(mpd_track, nullptr) mpd_set_maxlen(mpd_track);
obj->callbacks.print = &print_mpd_track;
END OBJ(mpd_name, nullptr) mpd_set_maxlen(mpd_name);
obj->callbacks.print = &print_mpd_name;
END OBJ(mpd_file, nullptr) mpd_set_maxlen(mpd_file);
obj->callbacks.print = &print_mpd_file;
END OBJ(mpd_percent, nullptr) obj->callbacks.percentage = &mpd_percentage;
END OBJ(mpd_album, nullptr) mpd_set_maxlen(mpd_album);
obj->callbacks.print = &print_mpd_album;
END OBJ(mpd_vol, nullptr) obj->callbacks.print = &print_mpd_vol;
END OBJ(mpd_bitrate, nullptr) obj->callbacks.print = &print_mpd_bitrate;
END OBJ(mpd_status, nullptr) obj->callbacks.print = &print_mpd_status;
END OBJ(mpd_bar, nullptr) scan_bar(obj, arg, 1);
obj->callbacks.barval = &mpd_barval;
END OBJ(mpd_smart, nullptr) mpd_set_maxlen(mpd_smart);
obj->callbacks.print = &print_mpd_smart;
END OBJ_IF(if_mpd_playing, nullptr) obj->callbacks.iftest =
&check_mpd_playing;
#undef mpd_set_maxlen
#endif /* BUILD_MPD */
#ifdef BUILD_MOC
END OBJ(moc_state, nullptr) obj->callbacks.print = &print_moc_state;
END OBJ(moc_file, nullptr) obj->callbacks.print = &print_moc_file;
END OBJ(moc_title, nullptr) obj->callbacks.print = &print_moc_title;
END OBJ(moc_artist, nullptr) obj->callbacks.print = &print_moc_artist;
END OBJ(moc_song, nullptr) obj->callbacks.print = &print_moc_song;
END OBJ(moc_album, nullptr) obj->callbacks.print = &print_moc_album;
END OBJ(moc_totaltime, nullptr) obj->callbacks.print = &print_moc_totaltime;
END OBJ(moc_timeleft, nullptr) obj->callbacks.print = &print_moc_timeleft;
END OBJ(moc_curtime, nullptr) obj->callbacks.print = &print_moc_curtime;
END OBJ(moc_bitrate, nullptr) obj->callbacks.print = &print_moc_bitrate;
END OBJ(moc_rate, nullptr) obj->callbacks.print = &print_moc_rate;
#endif /* BUILD_MOC */
#ifdef BUILD_CMUS
END OBJ(cmus_state, 0) obj->callbacks.print = &print_cmus_state;
END OBJ(cmus_file, 0) obj->callbacks.print = &print_cmus_file;
END OBJ(cmus_title, 0) obj->callbacks.print = &print_cmus_title;
END OBJ(cmus_artist, 0) obj->callbacks.print = &print_cmus_artist;
END OBJ(cmus_album, 0) obj->callbacks.print = &print_cmus_album;
END OBJ(cmus_totaltime, 0) obj->callbacks.print = &print_cmus_totaltime;
END OBJ(cmus_timeleft, 0) obj->callbacks.print = &print_cmus_timeleft;
END OBJ(cmus_curtime, 0) obj->callbacks.print = &print_cmus_curtime;
END OBJ(cmus_random, 0) obj->callbacks.print = &print_cmus_random;
END OBJ(cmus_state, 0) obj->callbacks.print = &print_cmus_state;
END OBJ(cmus_file, 0) obj->callbacks.print = &print_cmus_file;
END OBJ(cmus_title, 0) obj->callbacks.print = &print_cmus_title;
END OBJ(cmus_artist, 0) obj->callbacks.print = &print_cmus_artist;
END OBJ(cmus_album, 0) obj->callbacks.print = &print_cmus_album;
END OBJ(cmus_totaltime, 0) obj->callbacks.print = &print_cmus_totaltime;
END OBJ(cmus_timeleft, 0) obj->callbacks.print = &print_cmus_timeleft;
END OBJ(cmus_curtime, 0) obj->callbacks.print = &print_cmus_curtime;
END OBJ(cmus_random, 0) obj->callbacks.print = &print_cmus_random;
END OBJ(cmus_repeat, 0) obj->callbacks.print = &print_cmus_repeat;
END OBJ(cmus_aaa, 0) obj->callbacks.print = &print_cmus_aaa;
END OBJ(cmus_track, 0) obj->callbacks.print = &print_cmus_track;
END OBJ(cmus_genre, 0) obj->callbacks.print = &print_cmus_genre;
END OBJ(cmus_date, 0) obj->callbacks.print = &print_cmus_date;
END OBJ(cmus_progress, 0) scan_bar(obj, arg, 1);
obj->callbacks.barval = &cmus_progress;
END OBJ(cmus_percent, 0) obj->callbacks.percentage = &cmus_percent;
#endif /* BUILD_CMUS */
#ifdef BUILD_XMMS2
END OBJ(xmms2_artist, &update_xmms2) obj->callbacks.print =
&print_xmms2_artist;
obj->callbacks.free = &free_xmms2;
END OBJ(xmms2_album, &update_xmms2) obj->callbacks.print = &print_xmms2_album;
obj->callbacks.free = &free_xmms2;
END OBJ(xmms2_title, &update_xmms2) obj->callbacks.print = &print_xmms2_title;
obj->callbacks.free = &free_xmms2;
END OBJ(xmms2_genre, &update_xmms2) obj->callbacks.print = &print_xmms2_genre;
obj->callbacks.free = &free_xmms2;
END OBJ(xmms2_comment, &update_xmms2) obj->callbacks.print =
&print_xmms2_comment;
obj->callbacks.free = &free_xmms2;
END OBJ(xmms2_url, &update_xmms2) obj->callbacks.print = &print_xmms2_url;
obj->callbacks.free = &free_xmms2;
END OBJ(xmms2_tracknr, &update_xmms2) obj->callbacks.print =
&print_xmms2_tracknr;
obj->callbacks.free = &free_xmms2;
END OBJ(xmms2_bitrate, &update_xmms2) obj->callbacks.print =
&print_xmms2_bitrate;
obj->callbacks.free = &free_xmms2;
END OBJ(xmms2_date, &update_xmms2) obj->callbacks.print = &print_xmms2_date;
obj->callbacks.free = &free_xmms2;
END OBJ(xmms2_id, &update_xmms2) obj->callbacks.print = &print_xmms2_id;
obj->callbacks.free = &free_xmms2;
END OBJ(xmms2_duration, &update_xmms2) obj->callbacks.print =
&print_xmms2_duration;
obj->callbacks.free = &free_xmms2;
END OBJ(xmms2_elapsed, &update_xmms2) obj->callbacks.print =
&print_xmms2_elapsed;
obj->callbacks.free = &free_xmms2;
END OBJ(xmms2_size, &update_xmms2) obj->callbacks.print = &print_xmms2_size;
obj->callbacks.free = &free_xmms2;
END OBJ(xmms2_status, &update_xmms2) obj->callbacks.print =
&print_xmms2_status;
obj->callbacks.free = &free_xmms2;
END OBJ(xmms2_percent, &update_xmms2) obj->callbacks.print =
&print_xmms2_percent;
obj->callbacks.free = &free_xmms2;
END OBJ(xmms2_bar, &update_xmms2) scan_bar(obj, arg, 1);
obj->callbacks.barval = &xmms2_barval;
obj->callbacks.free = &free_xmms2;
END OBJ(xmms2_smart, &update_xmms2) obj->callbacks.print = &print_xmms2_smart;
obj->callbacks.free = &free_xmms2;
END OBJ(xmms2_playlist, &update_xmms2) obj->callbacks.print =
&print_xmms2_playlist;
obj->callbacks.free = &free_xmms2;
END OBJ(xmms2_timesplayed, &update_xmms2) obj->callbacks.print =
&print_xmms2_timesplayed;
obj->callbacks.free = &free_xmms2;
END OBJ_IF(if_xmms2_connected, &update_xmms2) obj->callbacks.iftest =
&if_xmms2_connected;
obj->callbacks.free = &free_xmms2;
#endif /* BUILD_XMMS2 */
#ifdef BUILD_AUDACIOUS
END OBJ(audacious_status, 0) obj->callbacks.print = &print_audacious_status;
END OBJ_ARG(audacious_title, 0, "audacious_title needs an argument")
sscanf(arg, "%d", &obj->data.i);
if (obj->data.i > 0) {
++obj->data.i;
} else {
CRIT_ERR_FREE(obj, free_at_crash,
"audacious_title: invalid length argument");
}
obj->callbacks.print = &print_audacious_title;
END OBJ(audacious_length, 0) obj->callbacks.print = &print_audacious_length;
END OBJ(audacious_length_seconds, 0) obj->callbacks.print =
&print_audacious_length_seconds;
END OBJ(audacious_position, 0) obj->callbacks.print =
&print_audacious_position;
END OBJ(audacious_position_seconds, 0) obj->callbacks.print =
&print_audacious_position_seconds;
END OBJ(audacious_bitrate, 0) obj->callbacks.print = &print_audacious_bitrate;
END OBJ(audacious_frequency, 0) obj->callbacks.print =
&print_audacious_frequency;
END OBJ(audacious_channels, 0) obj->callbacks.print =
&print_audacious_channels;
END OBJ(audacious_filename, 0) obj->callbacks.print =
&print_audacious_filename;
END OBJ(audacious_playlist_length, 0) obj->callbacks.print =
&print_audacious_playlist_length;
END OBJ(audacious_playlist_position, 0) obj->callbacks.print =
&print_audacious_playlist_position;
END OBJ(audacious_main_volume, 0) obj->callbacks.print =
&print_audacious_main_volume;
END OBJ(audacious_bar, 0) scan_bar(obj, arg, 1);
obj->callbacks.barval = &audacious_barval;
#endif /* BUILD_AUDACIOUS */
#ifdef BUILD_CURL
END OBJ_ARG(curl, 0, "curl needs arguments: <uri> <interval in minutes>")
curl_parse_arg(obj, arg);
obj->callbacks.print = &curl_print;
obj->callbacks.free = &curl_obj_free;
END OBJ(github_notifications, 0) obj->callbacks.print = &print_github;
#endif /* BUILD_CURL */
#ifdef BUILD_RSS
END OBJ_ARG(rss, 0,
"rss needs arguments: <uri> <interval in minutes> <action> "
"[act_par] [spaces in front]") rss_scan_arg(obj, arg);
obj->callbacks.print = &rss_print_info;
obj->callbacks.free = &rss_free_obj_info;
#endif /* BUILD_RSS */
END OBJ_ARG(lua, nullptr,
"lua needs arguments: <function name> [function parameters]")
obj->data.s = STRNDUP_ARG;
obj->callbacks.print = &print_lua;
obj->callbacks.free = &gen_free_opaque;
END OBJ_ARG(
lua_parse, nullptr,
"lua_parse needs arguments: <function name> [function parameters]")
obj->data.s = STRNDUP_ARG;
obj->callbacks.print = &print_lua_parse;
obj->callbacks.free = &gen_free_opaque;
END OBJ_ARG(lua_bar, nullptr,
"lua_bar needs arguments: <height>,<width> <function name> "
"[function parameters]") arg = scan_bar(obj, arg, 100);
if (arg != nullptr) {
obj->data.s = STRNDUP_ARG;
} else {
CRIT_ERR_FREE(obj, free_at_crash,
"lua_bar needs arguments: <height>,<width> <function name> "
"[function parameters]");
}
obj->callbacks.barval = &lua_barval;
obj->callbacks.free = &gen_free_opaque;
#ifdef BUILD_GUI
END OBJ_ARG(
lua_graph, nullptr,
"lua_graph needs arguments: <function name> [height],[width] [gradient "
"colour 1] [gradient colour 2] [scale] [-t] [-l]") auto [buf, skip] =
scan_command(arg);
scan_graph(obj, arg + skip, 100, FALSE);
if (buf != nullptr) {
obj->data.s = buf;
} else {
CRIT_ERR_FREE(obj, free_at_crash,
"lua_graph needs arguments: <function name> [height],[width] "
"[gradient colour 1] [gradient colour 2] [scale] [-t] [-l]");
}
obj->callbacks.graphval = &lua_barval;
obj->callbacks.free = &gen_free_opaque;
END OBJ_ARG(lua_gauge, nullptr,
"lua_gauge needs arguments: <height>,<width> <function name> "
"[function parameters]") arg = scan_gauge(obj, arg, 100);
if (arg != nullptr) {
obj->data.s = STRNDUP_ARG;
} else {
CRIT_ERR_FREE(obj, free_at_crash,
"lua_gauge needs arguments: <height>,<width> <function name> "
"[function parameters]");
}
obj->callbacks.gaugeval = &lua_barval;
obj->callbacks.free = &gen_free_opaque;
#endif /* BUILD_GUI */
#ifdef BUILD_HDDTEMP
END OBJ(hddtemp, &update_hddtemp) if (arg) obj->data.s = STRNDUP_ARG;
obj->callbacks.print = &print_hddtemp;
obj->callbacks.free = &free_hddtemp;
#endif /* BUILD_HDDTEMP */
#ifdef BUILD_PORT_MONITORS
END OBJ_ARG(tcp_portmon, &tcp_portmon_update, "tcp_portmon: needs arguments")
tcp_portmon_init(obj, arg);
obj->callbacks.print = &tcp_portmon_action;
obj->callbacks.free = &tcp_portmon_free;
#endif /* BUILD_PORT_MONITORS */
END OBJ(entropy_avail, &update_entropy) obj->callbacks.print =
&print_entropy_avail;
END OBJ(entropy_perc, &update_entropy) obj->callbacks.percentage =
&entropy_percentage;
END OBJ(entropy_poolsize, &update_entropy) obj->callbacks.print =
&print_entropy_poolsize;
END OBJ(entropy_bar, &update_entropy) scan_bar(obj, arg, 1);
obj->callbacks.barval = &entropy_barval;
END OBJ_ARG(blink, nullptr, "blink needs a argument") obj->sub =
static_cast<text_object *>(malloc(sizeof(struct text_object)));
extract_variable_text_internal(obj->sub, arg);
obj->callbacks.print = &print_blink;
END OBJ_ARG(to_bytes, nullptr, "to_bytes needs a argument") obj->sub =
static_cast<text_object *>(malloc(sizeof(struct text_object)));
extract_variable_text_internal(obj->sub, arg);
obj->callbacks.print = &print_to_bytes;
#ifdef BUILD_CURL
END OBJ_ARG(stock, 0, "stock needs arguments") stock_parse_arg(obj, arg);
obj->callbacks.print = &print_stock;
obj->callbacks.free = &free_stock;
#endif /* BUILD_CURL */
END OBJ(scroll, nullptr)
#ifdef BUILD_GUI
/* allocate a follower to reset any color changes */
#endif /* BUILD_GUI */
parse_scroll_arg(obj, arg, free_at_crash, s);
obj->callbacks.print = &print_scroll;
obj->callbacks.free = &free_scroll;
END OBJ(combine, nullptr) try {
parse_combine_arg(obj, arg);
} catch (combine_needs_2_args_error &e) {
free(obj);
throw obj_create_error(e.what());
}
obj->callbacks.print = &print_combine;
obj->callbacks.free = &free_combine;
#ifdef BUILD_NVIDIA
END OBJ_ARG(nvidia, 0, "nvidia needs an argument") if (set_nvidia_query(
obj, arg,
text_node_t::
NONSPECIAL)) {
CRIT_ERR_FREE(obj, free_at_crash,
"nvidia: invalid argument"
" specified: '%s'",
arg);
}
obj->callbacks.print = &print_nvidia_value;
obj->callbacks.free = &free_nvidia;
END OBJ_ARG(
nvidiabar, 0,
"nvidiabar needs an argument") if (set_nvidia_query(obj, arg,
text_node_t::BAR)) {
CRIT_ERR_FREE(obj, free_at_crash,
"nvidiabar: invalid argument"
" specified: '%s'",
arg);
}
obj->callbacks.barval = &get_nvidia_barval;
obj->callbacks.free = &free_nvidia;
END OBJ_ARG(
nvidiagraph, 0,
"nvidiagraph needs an argument") if (set_nvidia_query(obj, arg,
text_node_t::
GRAPH)) {
CRIT_ERR_FREE(obj, free_at_crash,
"nvidiagraph: invalid argument"
" specified: '%s'",
arg);
}
obj->callbacks.graphval = &get_nvidia_barval;
obj->callbacks.free = &free_nvidia;
END OBJ_ARG(
nvidiagauge, 0,
"nvidiagauge needs an argument") if (set_nvidia_query(obj, arg,
text_node_t::
GAUGE)) {
CRIT_ERR_FREE(obj, free_at_crash,
"nvidiagauge: invalid argument"
" specified: '%s'",
arg);
}
obj->callbacks.gaugeval = &get_nvidia_barval;
obj->callbacks.free = &free_nvidia;
#endif /* BUILD_NVIDIA */
#ifdef BUILD_APCUPSD
END OBJ_ARG(
apcupsd, &update_apcupsd,
"apcupsd needs arguments: <host> <port>") if (apcupsd_scan_arg(arg) !=
0) {
CRIT_ERR_FREE(obj, free_at_crash, "apcupsd needs arguments: <host> <port>");
}
obj->callbacks.print = &gen_print_nothing;
END OBJ(apcupsd_name, &update_apcupsd) obj->callbacks.print =
&print_apcupsd_name;
END OBJ(apcupsd_model, &update_apcupsd) obj->callbacks.print =
&print_apcupsd_model;
END OBJ(apcupsd_upsmode, &update_apcupsd) obj->callbacks.print =
&print_apcupsd_upsmode;
END OBJ(apcupsd_cable, &update_apcupsd) obj->callbacks.print =
&print_apcupsd_cable;
END OBJ(apcupsd_status, &update_apcupsd) obj->callbacks.print =
&print_apcupsd_status;
END OBJ(apcupsd_linev, &update_apcupsd) obj->callbacks.print =
&print_apcupsd_linev;
END OBJ(apcupsd_load, &update_apcupsd) obj->callbacks.print =
&print_apcupsd_load;
END OBJ(apcupsd_loadbar, &update_apcupsd) scan_bar(obj, arg, 100);
obj->callbacks.barval = &apcupsd_loadbarval;
#ifdef BUILD_GUI
END OBJ(apcupsd_loadgraph, &update_apcupsd) scan_graph(obj, arg, 100, FALSE);
obj->callbacks.graphval = &apcupsd_loadbarval;
END OBJ(apcupsd_loadgauge, &update_apcupsd) scan_gauge(obj, arg, 100);
obj->callbacks.gaugeval = &apcupsd_loadbarval;
#endif /* BUILD_GUI */
END OBJ(apcupsd_charge, &update_apcupsd) obj->callbacks.print =
&print_apcupsd_charge;
END OBJ(apcupsd_timeleft, &update_apcupsd) obj->callbacks.print =
&print_apcupsd_timeleft;
END OBJ(apcupsd_temp, &update_apcupsd) obj->callbacks.print =
&print_apcupsd_temp;
END OBJ(apcupsd_lastxfer, &update_apcupsd) obj->callbacks.print =
&print_apcupsd_lastxfer;
#endif /* BUILD_APCUPSD */
#ifdef BUILD_JOURNAL
END OBJ_ARG(journal, 0, "journal needs arguments")
init_journal("journal", arg, obj, free_at_crash);
obj->callbacks.print = &print_journal;
obj->callbacks.free = &free_journal;
#endif /* BUILD_JOURNAL */
#ifdef BUILD_PULSEAUDIO
END OBJ_IF(if_pa_sink_muted, 0) obj->callbacks.iftest = &puau_muted;
obj->callbacks.free = &free_pulseaudio;
init_pulseaudio(obj);
END OBJ(pa_sink_description, 0) obj->callbacks.print =
&print_puau_sink_description;
obj->callbacks.free = &free_pulseaudio;
init_pulseaudio(obj);
END OBJ(pa_sink_active_port_name, 0) obj->callbacks.print =
&print_puau_sink_active_port_name;
obj->callbacks.free = &free_pulseaudio;
init_pulseaudio(obj);
END OBJ(pa_sink_active_port_description, 0) obj->callbacks.print =
&print_puau_sink_active_port_description;
obj->callbacks.free = &free_pulseaudio;
init_pulseaudio(obj);
END OBJ(pa_sink_volume, 0) obj->callbacks.percentage = &puau_vol;
obj->callbacks.free = &free_pulseaudio;
init_pulseaudio(obj);
END OBJ(pa_sink_volumebar, 0) scan_bar(obj, arg, 1);
init_pulseaudio(obj);
obj->callbacks.barval = &puau_volumebarval;
obj->callbacks.free = &free_pulseaudio;
END OBJ(pa_card_active_profile, 0) obj->callbacks.print =
&print_puau_card_active_profile;
obj->callbacks.free = &free_pulseaudio;
init_pulseaudio(obj);
END OBJ(pa_card_name, 0) obj->callbacks.print = &print_puau_card_name;
obj->callbacks.free = &free_pulseaudio;
init_pulseaudio(obj);
END OBJ_IF(if_pa_source_running, 0) obj->callbacks.iftest =
&puau_source_running;
obj->callbacks.free = &free_pulseaudio;
init_pulseaudio(obj);
END OBJ_IF(if_pa_source_muted, 0) obj->callbacks.iftest = &puau_source_muted;
obj->callbacks.free = &free_pulseaudio;
init_pulseaudio(obj);
#endif /* BUILD_PULSEAUDIO */
#ifdef BUILD_INTEL_BACKLIGHT
END OBJ(intel_backlight, 0) obj->callbacks.print = &print_intel_backlight;
obj->callbacks.free = &free_intel_backlight;
init_intel_backlight(obj);
#endif /* BUILD_INTEL_BACKLIGHT */
END {
auto *buf = static_cast<char *>(malloc(text_buffer_size.get(*state)));
NORM_ERR("unknown variable '$%s'", s);
snprintf(buf, text_buffer_size.get(*state), "${%s}", s);
obj_be_plain_text(obj, buf);
free(buf);
}
#undef OBJ
#undef OBJ_IF
#undef OBJ_ARG
#undef OBJ_IF_ARG
#undef __OBJ_HEAD
#undef __OBJ_IF
#undef __OBJ_ARG
#undef END
return obj;
}
/*
* - assumes that *string is '#'
* - removes the part from '#' to the end of line ('\n' or '\0')
* - it removes the '\n'
* - copies the last char into 'char *last' argument, which should be a pointer
* to a char rather than a string.
*/
static size_t remove_comment(char *string, char *last) {
char *end = string;
while (*end != '\0' && *end != '\n') { ++end; }
if (last != nullptr) { *last = *end; }
if (*end == '\n') { end++; }
strfold(string, end - string);
return end - string;
}
size_t remove_comments(char *string) {
char *curplace;
size_t folded = 0;
for (curplace = string; *curplace != 0; curplace++) {
if (*curplace == '\\' && *(curplace + 1) == '#') {
// strcpy can't be used for overlapping strings
strfold(curplace, 1);
folded += 1;
} else if (*curplace == '#') {
folded += remove_comment(curplace, nullptr);
}
}
return folded;
}
int extract_variable_text_internal(struct text_object *retval,
const char *const_p) {
struct text_object *obj;
char *p, *s, *orig_p;
long line;
void *ifblock_opaque = nullptr;
char *tmp_p;
char *arg = nullptr;
size_t len = 0;
p = strndup(const_p, max_user_text.get(*state) - 1);
while (text_contains_templates(p) != 0) {
char *tmp;
tmp = find_and_replace_templates(p);
free(p);
p = tmp;
}
s = orig_p = p;
if (static_cast<int>(strcmp(p, const_p) != 0) != 0) {
DBGP2("replaced all templates in text: input is\n'%s'\noutput is\n'%s'",
const_p, p);
} else {
DBGP2("no templates to replace");
}
memset(retval, 0, sizeof(struct text_object));
line = global_text_lines;
while (*p != 0) {
if (*p == '\n') { line++; }
if (*p == '$') {
*p = '\0';
obj = create_plain_text(s);
if (obj != nullptr) { append_object(retval, obj); }
*p = '$';
p++;
s = p;
if (*p != '$') {
auto *buf = static_cast<char *>(malloc(text_buffer_size.get(*state)));
const char *var;
/* variable is either $foo or ${foo} */
if (*p == '{') {
unsigned int brl = 1, brr = 0;
p++;
s = p;
while ((*p != 0) && brl != brr) {
if (*p == '{') { brl++; }
if (*p == '}') { brr++; }
p++;
}
p--;
} else {
s = p;
if (*p == '#') { p++; }
while ((*p != 0) && ((isalnum(static_cast<unsigned char>(*p)) != 0) ||
*p == '_')) {
p++;
}
}
/* copy variable to buffer */
len = (p - s > static_cast<int>(text_buffer_size.get(*state)) - 1)
? static_cast<int>(text_buffer_size.get(*state)) - 1
: (p - s);
strncpy(buf, s, len);
buf[len] = '\0';
if (*p == '}') { p++; }
s = p;
/* search for variable in environment */
var = getenv(buf);
if (var != nullptr) {
obj = create_plain_text(var);
if (obj != nullptr) { append_object(retval, obj); }
free(buf);
continue;
}
/* if variable wasn't found in environment, use some special */
arg = nullptr;
/* split arg */
if (strchr(buf, ' ') != nullptr) {
arg = strchr(buf, ' ');
*arg = '\0';
arg++;
while (isspace(static_cast<unsigned char>(*arg)) != 0) { arg++; }
if (*arg == 0) { arg = nullptr; }
}
/* lowercase variable name */
tmp_p = buf;
while (*tmp_p != 0) {
*tmp_p = tolower(static_cast<unsigned char>(*tmp_p));
tmp_p++;
}
try {
obj = construct_text_object(buf, arg, line, &ifblock_opaque, orig_p);
} catch (obj_create_error &e) {
free(buf);
free(orig_p);
throw;
}
if (obj != nullptr) { append_object(retval, obj); }
free(buf);
continue;
}
obj = create_plain_text("$");
s = p + 1;
if (obj != nullptr) { append_object(retval, obj); }
} else if (*p == '\\' && *(p + 1) == '#') {
strfold(p, 1);
} else if (*p == '#') {
char c;
if ((remove_comment(p, &c) != 0u) && p >= orig_p && c == '\n') {
/* if remove_comment removed a newline, we need to 'back up' with p */
p--;
}
}
p++;
}
obj = create_plain_text(s);
if (obj != nullptr) { append_object(retval, obj); }
if (ifblock_stack_empty(&ifblock_opaque) == 0) {
NORM_ERR("one or more $endif's are missing");
}
free(orig_p);
return 0;
}
void extract_object_args_to_sub(struct text_object *obj, const char *args) {
obj->sub =
static_cast<struct text_object *>(malloc(sizeof(struct text_object)));
memset(obj->sub, 0, sizeof(struct text_object));
extract_variable_text_internal(obj->sub, args);
}
/* Frees the list of text objects root points to. */
void free_text_objects(struct text_object *root) {
struct text_object *obj;
if ((root != nullptr) && (root->prev != nullptr)) {
for (obj = root->prev; obj != nullptr; obj = root->prev) {
root->prev = obj->prev;
if (obj->callbacks.free != nullptr) { (*obj->callbacks.free)(obj); }
free_text_objects(obj->sub);
free_and_zero(obj->sub);
free_and_zero(obj->special_data);
delete obj->cb_handle;
free(obj);
}
}
}
| 91,641
|
C++
|
.cc
| 2,180
| 37.51422
| 83
| 0.652079
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
22,573
|
ibm.cc
|
brndnmtthws_conky/src/ibm.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2007 Toni Spets
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "ibm.h"
#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "config.h"
#include "conky.h"
#include "logging.h"
#include "temphelper.h"
static int ibm_acpi_temps[8];
/* Here come the IBM ACPI-specific things. For reference, see
* http://ibm-acpi.sourceforge.net/README
* If IBM ACPI is installed, /proc/acpi/ibm contains the following files:
bay
beep
bluetooth
brightness
cmos
dock
driver
ecdump
fan
hotkey
led
light
thermal
video
volume
* The content of these files is described in detail in the aforementioned
* README - some of them also in the following functions accessing them.
* Peter Tarjan (ptarjan@citromail.hu) */
#define IBM_ACPI_DIR "/proc/acpi/ibm"
/* get fan speed on IBM/Lenovo laptops running the ibm acpi.
* /proc/acpi/ibm/fan looks like this (3 lines):
status: disabled
speed: 2944
commands: enable, disable
* Peter Tarjan (ptarjan@citromail.hu) */
void get_ibm_acpi_fan(struct text_object *obj, char *p,
unsigned int p_max_size) {
FILE *fp;
unsigned int speed = 0;
char fan[128];
(void)obj;
if (!p || p_max_size <= 0) { return; }
snprintf(fan, 127, "%s/fan", IBM_ACPI_DIR);
fp = fopen(fan, "r");
if (fp != nullptr) {
while (!feof(fp)) {
char line[256];
if (fgets(line, 255, fp) == nullptr) { break; }
if (sscanf(line, "speed: %u", &speed)) { break; }
}
} else {
CRIT_ERR(
"can't open '%s': %s\nYou are not using the IBM ACPI. Remove "
"ibm* from your " PACKAGE_NAME " config file.",
fan, strerror(errno));
}
fclose(fp);
snprintf(p, p_max_size, "%d", speed);
}
/* get the measured temperatures from the temperature sensors
* on IBM/Lenovo laptops running the ibm acpi.
* There are 8 values in /proc/acpi/ibm/thermal, and according to
* http://ibm-acpi.sourceforge.net/README
* these mean the following (at least on an IBM R51...)
* 0: CPU (also on the T series laptops)
* 1: Mini PCI Module (?)
* 2: HDD (?)
* 3: GPU (also on the T series laptops)
* 4: Battery (?)
* 5: N/A
* 6: Battery (?)
* 7: N/A
* I'm not too sure about those with the question mark, but the values I'm
* reading from *my* thermal file (on a T42p) look realistic for the
* hdd and the battery.
* #5 and #7 are always -128.
* /proc/acpi/ibm/thermal looks like this (1 line):
temperatures: 41 43 31 46 33 -128 29 -128
* Peter Tarjan (ptarjan@citromail.hu) */
int get_ibm_acpi_temps(void) {
FILE *fp;
char thermal[128];
snprintf(thermal, 127, "%s/thermal", IBM_ACPI_DIR);
fp = fopen(thermal, "r");
if (fp != nullptr) {
while (!feof(fp)) {
char line[256];
if (fgets(line, 255, fp) == nullptr) { break; }
if (sscanf(line, "temperatures: %d %d %d %d %d %d %d %d",
&ibm_acpi_temps[0], &ibm_acpi_temps[1], &ibm_acpi_temps[2],
&ibm_acpi_temps[3], &ibm_acpi_temps[4], &ibm_acpi_temps[5],
&ibm_acpi_temps[6], &ibm_acpi_temps[7])) {
break;
}
}
} else {
CRIT_ERR(
"can't open '%s': %s\nYou are not using the IBM ACPI. Remove "
"ibm* from your " PACKAGE_NAME " config file.",
thermal, strerror(errno));
}
fclose(fp);
return 0;
}
/* get volume (0-14) on IBM/Lenovo laptops running the ibm acpi.
* "Volume" here is none of the mixer volumes, but a "master of masters"
* volume adjusted by the IBM volume keys.
* /proc/acpi/ibm/fan looks like this (4 lines):
level: 4
mute: off
commands: up, down, mute
commands: level <level> (<level> is 0-15)
* Peter Tarjan (ptarjan@citromail.hu) */
void get_ibm_acpi_volume(struct text_object *obj, char *p,
unsigned int p_max_size) {
FILE *fp;
char volume[128];
unsigned int vol = -1;
char mute[3] = "";
(void)obj;
if (!p || p_max_size <= 0) { return; }
snprintf(volume, 127, "%s/volume", IBM_ACPI_DIR);
fp = fopen(volume, "r");
if (fp != nullptr) {
while (!feof(fp)) {
char line[256];
unsigned int read_vol = -1;
if (fgets(line, 255, fp) == nullptr) { break; }
if (sscanf(line, "level: %u", &read_vol)) {
vol = read_vol;
continue;
}
if (sscanf(line, "mute: %s", mute)) { break; }
}
} else {
CRIT_ERR(
"can't open '%s': %s\nYou are not using the IBM ACPI. Remove "
"ibm* from your " PACKAGE_NAME " config file.",
volume, strerror(errno));
}
fclose(fp);
if (strcmp(mute, "on") == 0)
snprintf(p, p_max_size, "%s", "mute");
else
snprintf(p, p_max_size, "%d", vol);
}
/* static FILE *fp = nullptr; */
/* get LCD brightness on IBM/Lenovo laptops running the ibm acpi.
* /proc/acpi/ibm/brightness looks like this (3 lines):
level: 7
commands: up, down
commands: level <level> (<level> is 0-7)
* Peter Tarjan (ptarjan@citromail.hu) */
void get_ibm_acpi_brightness(struct text_object *obj, char *p,
unsigned int p_max_size) {
FILE *fp;
unsigned int brightness = 0;
char filename[128];
(void)obj;
if (!p || p_max_size <= 0) { return; }
snprintf(filename, 127, "%s/brightness", IBM_ACPI_DIR);
fp = fopen(filename, "r");
if (fp != nullptr) {
while (!feof(fp)) {
char line[256];
if (fgets(line, 255, fp) == nullptr) { break; }
if (sscanf(line, "level: %u", &brightness)) { break; }
}
} else {
CRIT_ERR(
"can't open '%s': %s\nYou are not using the IBM ACPI. Remove "
"ibm* from your " PACKAGE_NAME " config file.",
filename, strerror(errno));
}
fclose(fp);
snprintf(p, p_max_size, "%d", brightness);
}
/* get ThinkLight status on IBM/Lenovo laptops running the ibm acpi.
* /proc/acpi/ibm/light looks like this (2 lines):
status: off
commands: on, off
* http://ibm-acpi.sourceforge.net/README reports that it's also possible to
* get "unknown" for a few models that do not make the status available.
* Lluis Esquerda (eskerda@gmail.com) */
void get_ibm_acpi_thinklight(struct text_object *obj, char *p,
unsigned int p_max_size) {
FILE *fp;
char thinklight[8];
char filename[128];
(void)obj;
if (!p || p_max_size <= 0) { return; }
snprintf(filename, 127, "%s/light", IBM_ACPI_DIR);
fp = fopen(filename, "r");
if (fp != nullptr) {
while (!feof(fp)) {
char line[256];
if (fgets(line, 255, fp) == nullptr) { break; }
if (sscanf(line, "status: %s", thinklight)) { break; }
}
} else {
CRIT_ERR(
"can't open '%s': %s\nYou are not using the IBM "
"ACPI. Remove ibm* from your " PACKAGE_NAME " config file.",
filename, strerror(errno));
}
fclose(fp);
snprintf(p, p_max_size, "%s", thinklight);
}
void parse_ibm_temps_arg(struct text_object *obj, const char *arg) {
if (!isdigit(arg[0]) || strlen(arg) > 1 || atoi(&arg[0]) >= 8) {
obj->data.l = 0;
NORM_ERR(
"Invalid temperature sensor! Sensor number must be 0 to 7. "
"Using 0 (CPU temp sensor).");
} else
obj->data.l = atoi(arg);
}
void print_ibm_temps(struct text_object *obj, char *p,
unsigned int p_max_size) {
temp_print(p, p_max_size, ibm_acpi_temps[obj->data.l], TEMP_CELSIUS, 1);
}
| 8,412
|
C++
|
.cc
| 254
| 29.106299
| 76
| 0.633831
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
22,574
|
wl.cc
|
brndnmtthws_conky/src/wl.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <config.h>
#include <cstring>
#include "conky.h"
#include "wl.h"
#ifdef BUILD_WAYLAND
namespace priv {
void out_to_wayland_setting::lua_setter(lua::state &l, bool init) {
lua::stack_sentry s(l, -2);
Base::lua_setter(l, init);
if (init && do_convert(l, -1).first) {
// init
}
++s;
}
void out_to_wayland_setting::cleanup(lua::state &l) {
lua::stack_sentry s(l, -1);
if (do_convert(l, -1).first) {
// deinit
}
l.pop();
}
} // namespace priv
priv::out_to_wayland_setting out_to_wayland;
static const char NOT_IN_WAYLAND[] = "Not running in Wayland";
__attribute__((weak)) void print_monitor(struct text_object *obj, char *p,
unsigned int p_max_size) {
(void)obj;
if (!out_to_wayland.get(*state)) {
strncpy(p, NOT_IN_WAYLAND, p_max_size);
return;
}
snprintf(p, p_max_size, "%d", -1);
}
__attribute__((weak)) void print_monitor_number(struct text_object *obj,
char *p,
unsigned int p_max_size) {
(void)obj;
if (!out_to_wayland.get(*state)) {
strncpy(p, NOT_IN_WAYLAND, p_max_size);
return;
}
snprintf(p, p_max_size, "%d", -1);
}
__attribute__((weak)) void print_desktop(struct text_object *obj, char *p,
unsigned int p_max_size) {
(void)obj;
if (!out_to_wayland.get(*state)) {
strncpy(p, NOT_IN_WAYLAND, p_max_size);
return;
}
snprintf(p, p_max_size, "%d", -1);
}
__attribute__((weak)) void print_desktop_number(struct text_object *obj,
char *p,
unsigned int p_max_size) {
(void)obj;
if (!out_to_wayland.get(*state)) {
strncpy(p, NOT_IN_WAYLAND, p_max_size);
return;
}
snprintf(p, p_max_size, "%d", -1);
}
__attribute__((weak)) void print_desktop_name(struct text_object *obj, char *p,
unsigned int p_max_size) {
(void)obj;
if (!out_to_wayland.get(*state)) {
strncpy(p, NOT_IN_WAYLAND, p_max_size);
} else {
strncpy(p, "NYI", p_max_size);
}
}
#endif
| 3,255
|
C++
|
.cc
| 100
| 26.8
| 79
| 0.616342
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,575
|
algebra.cc
|
brndnmtthws_conky/src/algebra.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "algebra.h"
#include <cctype>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <memory>
#include "config.h"
#include "conky.h"
#include "logging.h"
/* find the operand in the given expression
* returns the index of the first op character or -1 on error
*/
int find_match_op(const char *expr) {
unsigned int idx = 0;
/* if first operand is a string, skip it */
if (expr[idx] == '"') {
for (idx=1; expr[idx] && expr[idx] != '"'; idx++);
idx++;
}
for (; idx < strlen(expr); idx++) {
switch (expr[idx]) {
case '=':
case '!':
if (expr[idx + 1] != '=') { return -1; }
/* falls through */
case '<':
case '>':
return idx;
}
}
return -1;
}
int get_match_type(const char *expr) {
int idx;
const char *str;
if ((idx = find_match_op(expr)) == -1) { return -1; }
str = expr + idx;
if (*str == '=' && *(str + 1) == '=') { return OP_EQ; }
if (*str == '!' && *(str + 1) == '=') { return OP_NEQ; }
if (*str == '>') {
if (*(str + 1) == '=') { return OP_GEQ; }
return OP_GT;
}
if (*str == '<') {
if (*(str + 1) == '=') { return OP_LEQ; }
return OP_LT;
}
return -1;
}
/* generic compare function
*
* v is actually the difference of the compared values. For strings
* this is equal to the output of str(n)cmp(). Use a macro here, as
* it's type-independent.
*/
#define COMPARE(v, t) \
switch (t) { \
case OP_GT: \
return ((v) > 0); \
case OP_LT: \
return ((v) < 0); \
case OP_EQ: \
return ((v) == 0); \
case OP_GEQ: \
return ((v) >= 0); \
case OP_LEQ: \
return ((v) <= 0); \
case OP_NEQ: \
return ((v) != 0); \
} \
return 0
int lcompare(long a, enum match_type mtype, long b) {
DBGP2("comparing longs '%ld' and '%ld'", a, b);
COMPARE((a - b), mtype);
}
int dcompare(double a, enum match_type mtype, double b) {
DBGP2("comparing doubles '%.lf' and '%.lf'", a, b);
COMPARE((a - b), mtype);
}
int scompare(const char *a, enum match_type mtype, const char *b) {
DBGP2("comparing strings '%s' and '%s'", a, b);
COMPARE(strcmp(a, b), mtype);
}
enum arg_type get_arg_type(const char *arg) {
const char *p, *e;
p = arg;
e = arg + strlen(arg) - 1;
while (p != e && (*e != 0) && *e == ' ') { e--; }
while (p != e && *p == ' ') { p++; }
if (*p == '"' && *e == '"') { return ARG_STRING; }
if (*p == '-') { // allow negative values
p++;
}
while (p <= e) {
if (isdigit(static_cast<unsigned char>(*p)) == 0) { break; }
p++;
}
if (p == e + 1) { return ARG_LONG; }
if (*p == '.' || *p == ',') {
p++;
while (p <= e) {
if (isdigit(static_cast<unsigned char>(*p)) == 0) { return ARG_BAD; }
p++;
}
return ARG_DOUBLE;
}
return ARG_BAD;
}
char *arg_to_string(const char *arg) {
const char *start;
int len;
start = arg;
len = 0;
while ((*start != 0) && *start == ' ') { start++; }
if (!(*(start++) == '"')) { return nullptr; }
while (start[len] != '"') { len++; }
return strndup(start, len);
}
double arg_to_double(const char *arg) {
double d;
if (sscanf(arg, "%lf", &d) != 1) {
NORM_ERR("converting '%s' to double failed", arg);
return 0.0;
}
return d;
}
long arg_to_long(const char *arg) {
long l;
if (sscanf(arg, "%ld", &l) != 1) {
NORM_ERR("converting '%s' to long failed", arg);
return 0;
}
return l;
}
int compare(const char *expr) {
char *expr_dup;
int idx, mtype;
enum arg_type type1, type2;
long lng_a, lng_b;
double dbl_a, dbl_b;
idx = find_match_op(expr);
mtype = get_match_type(expr);
if ((idx <= 0) || mtype == -1) {
NORM_ERR("failed to parse compare string '%s'", expr);
return -2;
}
expr_dup = strdup(expr);
expr_dup[idx] = '\0';
if (expr_dup[idx + 1] == '=') { expr_dup[++idx] = '\0'; }
type1 = get_arg_type(expr_dup);
type2 = get_arg_type(expr_dup + idx + 1);
if (type1 == ARG_BAD || type2 == ARG_BAD) {
NORM_ERR("Bad arguments: '%s' and '%s'", expr_dup, (expr_dup + idx + 1));
free(expr_dup);
return -2;
}
if (type1 == ARG_LONG && type2 == ARG_DOUBLE) { type1 = ARG_DOUBLE; }
if (type1 == ARG_DOUBLE && type2 == ARG_LONG) { type2 = ARG_DOUBLE; }
if (type1 != type2) {
NORM_ERR("trying to compare args '%s' and '%s' of different type", expr_dup,
(expr_dup + idx + 1));
free(expr_dup);
return -2;
}
switch (type1) {
case ARG_STRING: {
char *a, *b;
a = arg_to_string(expr_dup);
b = arg_to_string(expr_dup + idx + 1);
idx = scompare(a, static_cast<enum match_type>(mtype), b);
free(a);
free(b);
free(expr_dup);
return idx;
}
case ARG_LONG:
lng_a = arg_to_long(expr_dup);
lng_b = arg_to_long(expr_dup + idx + 1);
free(expr_dup);
return lcompare(lng_a, static_cast<enum match_type>(mtype), lng_b);
case ARG_DOUBLE:
dbl_a = arg_to_double(expr_dup);
dbl_b = arg_to_double(expr_dup + idx + 1);
free(expr_dup);
return dcompare(dbl_a, static_cast<enum match_type>(mtype), dbl_b);
case ARG_BAD: /* make_gcc_happy() */;
}
/* not reached */
free(expr_dup);
return -2;
}
int check_if_match(struct text_object *obj) {
std::unique_ptr<char[]> expression(new char[max_user_text.get(*state)]);
int val;
int result = 1;
generate_text_internal(expression.get(), max_user_text.get(*state),
*obj->sub);
DBGP("parsed arg into '%s'", expression.get());
val = compare(expression.get());
if (val == -2) {
NORM_ERR("compare failed for expression '%s'", expression.get());
} else if (val == 0) {
result = 0;
}
return result;
}
| 6,842
|
C++
|
.cc
| 234
| 25.538462
| 80
| 0.574423
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
22,576
|
mixer.cc
|
brndnmtthws_conky/src/mixer.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include "conky.h"
#include "logging.h"
#include "specials.h"
#include "text_object.h"
#ifdef HAVE_LINUX_SOUNDCARD_H
#include <linux/soundcard.h>
#else
#ifdef __OpenBSD__
#include <soundcard.h>
#else
#include <sys/soundcard.h>
#endif /* __OpenBSD__ */
#endif /* HAVE_LINUX_SOUNDCARD_H */
#if defined(__sun)
#include <stropts.h>
#include <unistd.h>
#endif
#define MIXER_DEV "/dev/mixer"
static int mixer_fd;
static const char *devs[] = SOUND_DEVICE_NAMES;
int mixer_init(const char *name) {
unsigned int i;
if (name == 0 || name[0] == '\0') { name = "vol"; }
/* open mixer */
if (mixer_fd <= 0) {
mixer_fd = open(MIXER_DEV, O_RDONLY);
if (mixer_fd == -1) {
NORM_ERR("can't open %s: %s", MIXER_DEV, strerror(errno));
return -1;
}
}
for (i = 0; i < sizeof(devs) / sizeof(const char *); i++) {
if (strcasecmp(devs[i], name) == 0) { return i; }
}
return -1;
}
static int mixer_get(int i) {
static char rep = 0;
int val = -1;
if (ioctl(mixer_fd, MIXER_READ(i), &val) == -1) {
if (!rep) { NORM_ERR("mixer ioctl: %s", strerror(errno)); }
rep = 1;
return 0;
}
rep = 0;
return val;
}
static int mixer_get_avg(int i) {
int v = mixer_get(i);
return ((v >> 8) + (v & 0xFF)) / 2;
}
static int mixer_get_left(int i) { return mixer_get(i) >> 8; }
static int mixer_get_right(int i) { return mixer_get(i) & 0xFF; }
int mixer_is_mute(int i) { return !mixer_get(i); }
#define mixer_to_255(i, x) x
void parse_mixer_arg(struct text_object *obj, const char *arg) {
obj->data.l = mixer_init(arg);
}
uint8_t mixer_percentage(struct text_object *obj) {
return mixer_get_avg(obj->data.l);
}
uint8_t mixerl_percentage(struct text_object *obj) {
return mixer_get_left(obj->data.l);
}
uint8_t mixerr_percentage(struct text_object *obj) {
return mixer_get_right(obj->data.l);
}
int check_mixer_muted(struct text_object *obj) {
if (!mixer_is_mute(obj->data.l)) return 0;
return 1;
}
void scan_mixer_bar(struct text_object *obj, const char *arg) {
char buf1[64];
int n;
if (arg && sscanf(arg, "%63s %n", buf1, &n) >= 1) {
obj->data.i = mixer_init(buf1);
scan_bar(obj, arg + n, 100);
} else {
obj->data.i = mixer_init(nullptr);
scan_bar(obj, arg, 100);
}
}
double mixer_barval(struct text_object *obj) {
return mixer_to_255(obj->data.i, mixer_get_avg(obj->data.i));
}
double mixerl_barval(struct text_object *obj) {
return mixer_to_255(obj->data.i, mixer_get_left(obj->data.i));
}
double mixerr_barval(struct text_object *obj) {
return mixer_to_255(obj->data.i, mixer_get_right(obj->data.i));
}
| 3,738
|
C++
|
.cc
| 123
| 28
| 72
| 0.680234
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
22,577
|
display-console.cc
|
brndnmtthws_conky/src/display-console.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Please see COPYING for details
*
* Copyright (C) 2018 François Revol et al.
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <config.h>
#include "conky.h"
#include "display-console.hh"
#include "nc.h"
#include <iostream>
#include <sstream>
#include <unordered_map>
static conky::simple_config_setting<bool> extra_newline("extra_newline", false,
false);
namespace conky {
namespace {
conky::display_output_console console_output("console");
} // namespace
template <>
void register_output<output_t::CONSOLE>(display_outputs_t &outputs) {
outputs.push_back(&console_output);
}
display_output_console::display_output_console(const std::string &name_)
: display_output_base(name_) {
// lowest priority, it's a fallback
priority = 0;
}
bool display_output_console::detect() {
if ((out_to_stdout.get(*state) || out_to_stderr.get(*state))
#ifdef BUILD_NCURSES
&& !out_to_ncurses.get(*state)
#endif
) {
DBGP2("Display output '%s' enabled in config.", name.c_str());
return true;
}
return false;
}
bool display_output_console::initialize() { return true; }
bool display_output_console::shutdown() { return true; }
void display_output_console::draw_string(const char *s, int) {
if (out_to_stdout.get(*state)) {
printf("%s\n", s);
if (extra_newline.get(*state)) { fputc('\n', stdout); }
fflush(stdout); /* output immediately, don't buffer */
}
if (out_to_stderr.get(*state)) {
fprintf(stderr, "%s\n", s);
fflush(stderr); /* output immediately, don't buffer */
}
}
} // namespace conky
| 2,449
|
C++
|
.cc
| 72
| 30.875
| 79
| 0.701227
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,578
|
x11-settings.cc
|
brndnmtthws_conky/src/x11-settings.cc
|
#include "x11-settings.h"
#include "x11.h"
#include "conky-imlib2.h"
#include <X11/Xlib.h>
conky::simple_config_setting<std::string> display_name("display", std::string(),
false);
namespace priv {
void out_to_x_setting::lua_setter(lua::state &l, bool init) {
lua::stack_sentry s(l, -2);
Base::lua_setter(l, init);
if (init && do_convert(l, -1).first) { init_x11(); }
++s;
}
void out_to_x_setting::cleanup(lua::state &l) {
lua::stack_sentry s(l, -1);
if (do_convert(l, -1).first) { deinit_x11(); }
l.pop();
}
#ifdef BUILD_XDBE
bool use_xdbe_setting::set_up(lua::state &l) {
// double_buffer makes no sense when not drawing to X
if (!out_to_x.get(l) || !display || !window.window) { return false; }
int major, minor;
if (XdbeQueryExtension(display, &major, &minor) == 0) {
NORM_ERR("No compatible double buffer extension found");
return false;
}
window.back_buffer =
XdbeAllocateBackBufferName(display, window.window, XdbeBackground);
if (window.back_buffer != None) {
window.drawable = window.back_buffer;
} else {
NORM_ERR("Failed to allocate back buffer");
return false;
}
XFlush(display);
return true;
}
void use_xdbe_setting::lua_setter(lua::state &l, bool init) {
lua::stack_sentry s(l, -2);
Base::lua_setter(l, init);
if (init && do_convert(l, -1).first) {
if (!set_up(l)) {
l.pop();
l.pushboolean(false);
}
NORM_ERR("drawing to %s buffer",
do_convert(l, -1).first ? "double" : "single");
}
++s;
}
#else
bool use_xpmdb_setting::set_up(lua::state &l) {
// double_buffer makes no sense when not drawing to X
if (!out_to_x.get(l)) return false;
window.back_buffer =
XCreatePixmap(display, window.window, window.geometry.width() + 1, window.geometry.height() + 1,
DefaultDepth(display, screen));
if (window.back_buffer != None) {
window.drawable = window.back_buffer;
} else {
NORM_ERR("Failed to allocate back buffer");
return false;
}
XFlush(display);
return true;
}
void use_xpmdb_setting::lua_setter(lua::state &l, bool init) {
lua::stack_sentry s(l, -2);
Base::lua_setter(l, init);
if (init && do_convert(l, -1).first) {
if (!set_up(l)) {
l.pop();
l.pushboolean(false);
}
NORM_ERR("drawing to %s buffer",
do_convert(l, -1).first ? "double" : "single");
}
++s;
}
#endif
} // namespace priv
conky::simple_config_setting<int> head_index("xinerama_head", 0, true);
priv::out_to_x_setting out_to_x;
#ifdef BUILD_XFT
conky::simple_config_setting<bool> use_xft("use_xft", false, false);
#endif
conky::simple_config_setting<bool> forced_redraw("forced_redraw", false, false);
#ifdef BUILD_XDBE
priv::use_xdbe_setting use_xdbe;
#else
priv::use_xpmdb_setting use_xpmdb;
#endif
| 2,872
|
C++
|
.cc
| 93
| 26.677419
| 102
| 0.643481
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,579
|
fonts.cc
|
brndnmtthws_conky/src/fonts.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "fonts.h"
#include "display-output.hh"
#include "gui.h"
#include "logging.h"
unsigned int selected_font = 0;
std::vector<font_list> fonts;
char fontloaded = 0;
void font_setting::lua_setter(lua::state &l, bool init) {
lua::stack_sentry s(l, -2);
Base::lua_setter(l, init);
if (init) {
if (fonts.empty()) { fonts.resize(1); }
fonts[0].name = do_convert(l, -1).first;
}
++s;
}
font_setting font;
conky::simple_config_setting<std::string> font_template[10] = {
{"font0", ""}, {"font1", ""}, {"font2", ""}, {"font3", ""}, {"font4", ""},
{"font5", ""}, {"font6", ""}, {"font7", ""}, {"font8", ""}, {"font9", ""}};
void set_font() {
if (selected_font >= fonts.size()) return;
for (auto output : display_outputs()) output->set_font(selected_font);
}
void setup_fonts() {
DBGP2("setting up fonts");
for (auto output : display_outputs()) output->setup_fonts();
set_font();
}
int add_font(const char *data_in) {
if (!out_to_gui(*state)) { return 0; }
fonts.emplace_back();
fonts.rbegin()->name = data_in;
return fonts.size() - 1;
}
void free_fonts(bool utf8) {
for (auto output : display_outputs()) output->free_fonts(utf8);
fonts.clear();
selected_font = 0;
}
void load_fonts(bool utf8) {
DBGP2("loading fonts");
for (auto output : display_outputs()) output->load_fonts(utf8);
}
int font_height() {
assert(selected_font < fonts.size());
return display_output()->font_height(selected_font);
}
int font_ascent() {
assert(selected_font < fonts.size());
return display_output()->font_ascent(selected_font);
}
int font_descent() {
assert(selected_font < fonts.size());
return display_output()->font_descent(selected_font);
}
| 2,756
|
C++
|
.cc
| 84
| 30.5
| 79
| 0.690395
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,580
|
journal.cc
|
brndnmtthws_conky/src/journal.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <ctype.h>
#include <string.h>
#include <systemd/sd-journal.h>
#include <time.h>
#include <unistd.h>
#include <memory>
#include "common.h"
#include "config.h"
#include "conky.h"
#include "logging.h"
#include "text_object.h"
#define MAX_JOURNAL_LINES 200
class journal {
public:
int wantedlines;
int flags;
journal() : wantedlines(0), flags(SD_JOURNAL_LOCAL_ONLY) {}
};
void free_journal(struct text_object *obj) {
journal *j = (journal *)obj->data.opaque;
obj->data.opaque = nullptr;
delete j;
}
void init_journal(const char *type, const char *arg, struct text_object *obj,
void *free_at_crash) {
unsigned int args;
journal *j = new journal;
std::unique_ptr<char[]> tmp(new char[DEFAULT_TEXT_BUFFER_SIZE]);
memset(tmp.get(), 0, DEFAULT_TEXT_BUFFER_SIZE);
args = sscanf(arg, "%d %6s", &j->wantedlines, tmp.get());
if (args < 1 || args > 2) {
free_journal(obj);
CRIT_ERR_FREE(
obj, free_at_crash,
"%s a number of lines as 1st argument and optionally a journal "
"type as 2nd argument",
type);
}
if (j->wantedlines > 0 && j->wantedlines <= MAX_JOURNAL_LINES) {
if (args > 1) {
if (strcmp(tmp.get(), "system") == 0) {
j->flags |= SD_JOURNAL_SYSTEM;
#ifdef SD_JOURNAL_CURRENT_USER // not present in older version of systemd
} else if (strcmp(tmp.get(), "user") == 0) {
j->flags |= SD_JOURNAL_CURRENT_USER;
#endif /* SD_JOURNAL_CURRENT_USER */
} else {
free_journal(obj);
CRIT_ERR_FREE(obj, free_at_crash,
"invalid arg for %s, type must be 'system' or 'user'",
type);
}
} else {
NORM_ERR("You should type a 'user' or 'system' as an argument");
}
} else {
free_journal(obj);
CRIT_ERR_FREE(
obj, free_at_crash,
"invalid arg for %s, number of lines must be between 1 and %d", type,
MAX_JOURNAL_LINES);
}
obj->data.opaque = j;
}
static int print_field(sd_journal *jh, const char *field, char spacer,
size_t *read, char *p, unsigned int p_max_size) {
const void *get;
size_t length;
size_t fieldlen = strlen(field) + 1;
int ret = sd_journal_get_data(jh, field, &get, &length);
if (ret == -ENOENT) goto out;
if (ret < 0 || length + *read > p_max_size) return -1;
memcpy(p + *read, (const char *)get + fieldlen, length - fieldlen);
*read += length - fieldlen;
out:
if (spacer) {
if (p_max_size < *read) {
*read = p_max_size - 1;
} else {
p[(*read)++] = spacer;
}
}
return length ? length - fieldlen : 0;
}
bool read_log(size_t *read, size_t *length, time_t *time, uint64_t *timestamp,
sd_journal *jh, char *p, unsigned int p_max_size) {
struct tm tm;
if (sd_journal_get_realtime_usec(jh, timestamp) < 0) return false;
*time = *timestamp / 1000000;
localtime_r(time, &tm);
if ((*length =
strftime(p + *read, p_max_size - *read, "%b %d %H:%M:%S", &tm)) <= 0)
return false;
*read += *length;
if (p_max_size < *read) {
*read = p_max_size - 1;
return false;
}
p[*read++] = ' ';
if (print_field(jh, "_HOSTNAME", ' ', read, p, p_max_size) < 0) return false;
if (print_field(jh, "SYSLOG_IDENTIFIER", '[', read, p, p_max_size) < 0)
return false;
if (print_field(jh, "_PID", ']', read, p, p_max_size) < 0) return false;
if (p_max_size < *read) {
*read = p_max_size - 1;
return false;
}
p[*read++] = ':';
if (p_max_size < *read) {
*read = p_max_size - 1;
return false;
}
p[*read++] = ' ';
if (print_field(jh, "MESSAGE", '\n', read, p, p_max_size) < 0) return false;
return true;
}
void print_journal(struct text_object *obj, char *p, unsigned int p_max_size) {
journal *j = (journal *)obj->data.opaque;
sd_journal *jh = nullptr;
size_t read = 0;
size_t length;
time_t time;
uint64_t timestamp;
if (sd_journal_open(&jh, j->flags) != 0) {
NORM_ERR("unable to open journal");
goto out;
}
if (sd_journal_seek_tail(jh) < 0) {
NORM_ERR("unable to seek to end of journal");
goto out;
}
if (sd_journal_previous_skip(jh, j->wantedlines) < 0) {
NORM_ERR("unable to seek back %d lines", j->wantedlines);
goto out;
}
while (read_log(&read, &length, &time, ×tamp, jh, p, p_max_size) &&
sd_journal_next(jh))
;
out:
if (jh) sd_journal_close(jh);
p[read] = '\0';
}
| 5,496
|
C++
|
.cc
| 170
| 28.205882
| 80
| 0.630238
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,581
|
conky.cc
|
brndnmtthws_conky/src/conky.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "conky.h"
#include "config.h"
#include <algorithm>
#include <cerrno>
#include <climits>
#include <clocale>
#include <cmath>
#include <cstdarg>
#include <ctime>
#include <filesystem>
#include <iostream>
#include <memory>
#include <sstream>
#include <string>
#include <vector>
#include <fcntl.h>
#include <getopt.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#ifdef HAVE_SYS_INOTIFY_H
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wc99-extensions"
#include <sys/inotify.h>
#pragma clang diagnostic pop
#endif /* HAVE_SYS_INOTIFY_H */
#ifdef HAVE_DIRENT_H
#include <dirent.h>
#endif /* HAVE_DIRENT_H */
#include "common.h"
#include "text_object.h"
#ifdef BUILD_WAYLAND
#include "wl.h"
#endif /* BUILD_WAYLAND */
#ifdef BUILD_X11
#include "x11-settings.h"
#include "x11.h"
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wvariadic-macros"
#include <X11/Xutil.h>
#pragma GCC diagnostic pop
#ifdef BUILD_XDAMAGE
#include <X11/extensions/Xdamage.h>
#endif
#ifdef BUILD_IMLIB2
#include "conky-imlib2.h"
#endif /* BUILD_IMLIB2 */
#endif /* BUILD_X11 */
#ifdef BUILD_NCURSES
#include <ncurses.h>
#endif /* BUILD_NCURSES */
#ifdef BUILD_CURL
#include <curl/curl.h>
#endif /* BUILD_CURL */
#ifdef BUILD_RSS
#include <libxml/parser.h>
#endif /* BUILD_RSS */
/* local headers */
#include "colours.h"
#include "core.h"
#include "diskio.h"
#include "exec.h"
#ifdef BUILD_GUI
#include "fonts.h"
#include "gui.h"
#endif /* BUILD_GUI */
#include "fs.h"
#ifdef BUILD_ICONV
#include "iconv_tools.h"
#endif /* BUILD_ICONV */
#include "llua.h"
#include "logging.h"
#include "mail.h"
#include "nc.h"
#include "net_stat.h"
#include "specials.h"
#include "temphelper.h"
#include "template.h"
#include "timeinfo.h"
#include "top.h"
#ifdef BUILD_MYSQL
#include "mysql.h"
#endif /* BUILD_MYSQL */
#ifdef BUILD_NVIDIA
#include "nvidia.h"
#endif /* BUILD_NVIDIA */
#ifdef BUILD_CURL
#include "ccurl_thread.h"
#endif /* BUILD_CURL */
#include "display-output.hh"
#include "lua-config.hh"
#include "setting.hh"
/* check for OS and include appropriate headers */
#if defined(__linux__)
#include "linux.h"
#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
#include "freebsd.h"
#elif defined(__DragonFly__)
#include "dragonfly.h"
#elif defined(__OpenBSD__)
#include "openbsd.h"
#endif /* __OpenBSD__ */
#include "gradient.h"
#ifdef BUILD_OLD_CONFIG
#include "convertconf.h"
#endif /* BUILD_OLD_CONFIG */
#ifdef BUILD_BUILTIN_CONFIG
#include "defconfig.h"
namespace {
const char builtin_config_magic[] = "==builtin==";
} // namespace
#endif /* BUILD_BUILTIN_CONFIG */
#ifndef S_ISSOCK
#define S_ISSOCK(x) ((x & S_IFMT) == S_IFSOCK)
#endif
#define MAX_IF_BLOCK_DEPTH 5
// #define SIGNAL_BLOCKING
#undef SIGNAL_BLOCKING
/* debugging level, used by logging.h */
int global_debug_level = 0;
/* disable inotify auto reload feature if desired */
static conky::simple_config_setting<bool> disable_auto_reload(
"disable_auto_reload", false, false);
/* two strings for internal use */
static char *tmpstring1, *tmpstring2;
enum spacer_state { NO_SPACER = 0, LEFT_SPACER, RIGHT_SPACER };
template <>
conky::lua_traits<spacer_state>::Map conky::lua_traits<spacer_state>::map = {
{"none", NO_SPACER}, {"left", LEFT_SPACER}, {"right", RIGHT_SPACER}};
static conky::simple_config_setting<spacer_state> use_spacer("use_spacer",
NO_SPACER, false);
/* variables holding various config settings */
static conky::simple_config_setting<bool> short_units("short_units", false,
true);
static conky::simple_config_setting<bool> format_human_readable(
"format_human_readable", true, true);
conky::simple_config_setting<std::string> units_spacer("units_spacer", "",
false);
conky::simple_config_setting<bool> out_to_stdout("out_to_console",
// Default value is false, unless we are building without X
#ifdef BUILD_GUI
false,
#else
true,
#endif
false);
conky::simple_config_setting<bool> out_to_stderr("out_to_stderr", false, false);
int top_cpu, top_mem, top_time;
#ifdef BUILD_IOSTATS
int top_io;
#endif
int top_running;
/* Update interval */
conky::range_config_setting<double> update_interval(
"update_interval", 0.0, std::numeric_limits<double>::infinity(), 3.0, true);
conky::range_config_setting<double> update_interval_on_battery(
"update_interval_on_battery", 0.0, std::numeric_limits<double>::infinity(),
NOBATTERY, true);
conky::simple_config_setting<std::string> detect_battery("detect_battery",
std::string("BAT0"),
false);
static bool on_battery = false;
double active_update_interval() {
return (on_battery ? update_interval_on_battery : update_interval)
.get(*state);
}
void music_player_interval_setting::lua_setter(lua::state &l, bool init) {
lua::stack_sentry s(l, -2);
if (l.isnil(-2)) {
l.checkstack(1);
l.pushnumber(update_interval.get(l));
l.replace(-3);
}
Base::lua_setter(l, init);
++s;
}
music_player_interval_setting music_player_interval;
void *global_cpu = nullptr;
static conky::range_config_setting<unsigned int> max_text_width(
"max_text_width", 0, std::numeric_limits<unsigned int>::max(), 0, true);
#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
extern kvm_t *kd;
#endif
/* prototypes for internally used functions */
static void signal_handler(int /*sig*/);
static void reload_config();
static const char *suffixes[] = {_nop("B"), _nop("KiB"), _nop("MiB"),
_nop("GiB"), _nop("TiB"), _nop("PiB"),
""};
#ifdef BUILD_GUI
/* text size */
conky::vec2i text_start; /* text start position in window */
conky::vec2i text_offset; /* offset for start position */
conky::vec2i text_size =
conky::vec2i::One(); /* initially 1 so no zero-sized window is created */
#endif /* BUILD_GUI */
/* struct that has all info to be shared between
* instances of the same text object */
struct information info;
/* path to config file */
std::filesystem::path current_config;
/* set to 1 if you want all text to be in uppercase */
static conky::simple_config_setting<bool> stuff_in_uppercase("uppercase", false,
true);
static conky::simple_config_setting<bool> stuff_in_lowercase("lowercase", false,
true);
/* Run how many times? */
static conky::range_config_setting<unsigned long> total_run_times(
"total_run_times", 0, std::numeric_limits<unsigned long>::max(), 0, true);
/* fork? */
static conky::simple_config_setting<bool> fork_to_background("background",
false, false);
/* set to 0 after the first time conky is run, so we don't fork again after the
* first forking */
int first_pass = 1;
int argc_copy;
char **argv_copy;
conky::range_config_setting<int> cpu_avg_samples("cpu_avg_samples", 1, 14, 2,
true);
conky::range_config_setting<int> net_avg_samples("net_avg_samples", 1, 14, 2,
true);
conky::range_config_setting<int> diskio_avg_samples("diskio_avg_samples", 1, 14,
2, true);
#ifdef BUILD_GUI
/* graph */
conky::simple_config_setting<bool> show_graph_scale("show_graph_scale", false,
false);
conky::simple_config_setting<bool> show_graph_range("show_graph_range", false,
false);
enum gradient_state { RGB_GRADIENT = 0, HSV_GRADIENT, HCL_GRADIENT };
template <>
conky::lua_traits<gradient_state>::Map conky::lua_traits<gradient_state>::map =
{{"rgb", RGB_GRADIENT}, {"hsv", HSV_GRADIENT}, {"hcl", HCL_GRADIENT}};
static conky::simple_config_setting<gradient_state> graph_gradient_mode(
"graph_gradient_mode", RGB_GRADIENT, false);
/* Position on the screen */
conky::simple_config_setting<int> gap_x("gap_x", 5, true);
conky::simple_config_setting<int> gap_y("gap_y", 60, true);
/* border */
conky::simple_config_setting<bool> draw_borders("draw_borders", false, false);
conky::simple_config_setting<bool> draw_graph_borders("draw_graph_borders",
true, false);
conky::range_config_setting<char> stippled_borders(
"stippled_borders", 0, std::numeric_limits<char>::max(), 0, true);
conky::simple_config_setting<bool> draw_shades("draw_shades", true, false);
conky::simple_config_setting<bool> draw_outline("draw_outline", false, false);
#ifdef OWN_WINDOW
/* fixed size/pos is set if wm/user changes them */
int fixed_size = 0, fixed_pos = 0;
#endif
conky::range_config_setting<int> minimum_height("minimum_height", 0,
std::numeric_limits<int>::max(),
5, true);
conky::range_config_setting<int> minimum_width("minimum_width", 0,
std::numeric_limits<int>::max(),
5, true);
conky::range_config_setting<int> maximum_width("maximum_width", 0,
std::numeric_limits<int>::max(),
0, true);
static bool isutf8(const char *envvar) {
char *s = getenv(envvar);
if (s != nullptr) {
std::string temp = s;
std::transform(temp.begin(), temp.end(), temp.begin(), ::tolower);
if ((temp.find("utf-8") != std::string::npos) ||
(temp.find("utf8") != std::string::npos)) {
return true;
}
}
return false;
}
/* UTF-8 */
conky::simple_config_setting<bool> utf8_mode("override_utf8_locale",
isutf8("LC_ALL") ||
isutf8("LC_CTYPE") ||
isutf8("LANG"),
false);
#endif /* BUILD_GUI */
/* maximum size of config TEXT buffer, i.e. below TEXT line. */
conky::range_config_setting<unsigned int> max_user_text(
"max_user_text", 47, std::numeric_limits<unsigned int>::max(),
MAX_USER_TEXT_DEFAULT, false);
/* maximum size of individual text buffers, ie $exec buffer size */
conky::range_config_setting<unsigned int> text_buffer_size(
"text_buffer_size", DEFAULT_TEXT_BUFFER_SIZE,
std::numeric_limits<unsigned int>::max(), DEFAULT_TEXT_BUFFER_SIZE, false);
/* pad percentages to decimals? */
static conky::simple_config_setting<int> pad_percents("pad_percents", 0, false);
static char *global_text = nullptr;
char *get_global_text() { return global_text; }
long global_text_lines;
static int total_updates;
static int updatereset;
std::unique_ptr<lua::state> state;
void set_updatereset(int i) { updatereset = i; }
int get_updatereset() { return updatereset; }
int get_total_updates() { return total_updates; }
int calc_text_width(const char *s) {
if (display_output()) return display_output()->calc_text_width(s);
size_t slen = strlen(s);
return slen;
}
#ifdef BUILD_GUI
conky::gradient_factory *create_gradient_factory(int width, Colour first_colour,
Colour last_colour) {
switch (graph_gradient_mode.get(*state)) {
case RGB_GRADIENT:
return new conky::rgb_gradient_factory(width, first_colour, last_colour);
case HSV_GRADIENT:
return new conky::hsv_gradient_factory(width, first_colour, last_colour);
case HCL_GRADIENT:
return new conky::hcl_gradient_factory(width, first_colour, last_colour);
}
return nullptr;
}
#endif /* BUILD_GUI */
/* formatted text to render on screen, generated in generate_text(),
* drawn in draw_stuff() */
static char *text_buffer;
/* quite boring functions */
static inline void for_each_line(char *b, int f(char *, int)) {
char *ps, *pe;
int special_index = 0; /* specials index */
if (b == nullptr) { return; }
for (ps = b, pe = b; *pe != 0; pe++) {
if (*pe == '\n') {
*pe = '\0';
special_index = f(ps, special_index);
*pe = '\n';
ps = pe + 1;
}
}
if (ps < pe) { f(ps, special_index); }
}
static void convert_escapes(char *buf) {
char *p = buf, *s = buf;
while (*s != 0) {
if (*s == '\\') {
s++;
if (*s == 'n') {
*p++ = '\n';
} else if (*s == '\\') {
*p++ = '\\';
}
s++;
} else {
*p++ = *s++;
}
}
*p = '\0';
}
/* Prints anything normally printed with snprintf according to the current value
* of use_spacer. Actually slightly more flexible than snprintf, as you can
* safely specify the destination buffer as one of your inputs. */
int spaced_print(char *buf, int size, const char *format, int width, ...) {
int len = 0;
va_list argp;
char *tempbuf;
if (size < 1) { return 0; }
tempbuf = new char[size];
// Passes the varargs along to vsnprintf
va_start(argp, width);
vsnprintf(tempbuf, size, format, argp);
va_end(argp);
switch (use_spacer.get(*state)) {
case NO_SPACER:
len = snprintf(buf, size, "%s", tempbuf);
break;
case LEFT_SPACER:
len = snprintf(buf, size, "%*s", width, tempbuf);
break;
case RIGHT_SPACER:
len = snprintf(buf, size, "%-*s", width, tempbuf);
break;
}
delete[] tempbuf;
return len;
}
/* print percentage values
*
* - i.e., unsigned values between 0 and 100
* - respect the value of pad_percents */
int percent_print(char *buf, int size, unsigned value) {
return spaced_print(buf, size, "%u", pad_percents.get(*state), value);
}
/* converts from bytes to human readable format (K, M, G, T)
*
* The algorithm always divides by 1024, as unit-conversion of byte
* counts suggests. But for output length determination we need to
* compare with 1000 here, as we print in decimal form. */
void human_readable(long long num, char *buf, int size) {
const char **suffix = suffixes;
float fnum;
int precision;
int width;
const char *format;
/* Possibly just output as usual, for example for stdout usage */
if (!format_human_readable.get(*state)) {
spaced_print(buf, size, "%lld", 6, num);
return;
}
if (short_units.get(*state)) {
width = 5;
format = "%.*f%s%.1s";
} else {
width = 7;
format = "%.*f%s%-.3s";
}
width += strlen(units_spacer.get(*state).c_str());
if (llabs(num) < 1000LL) {
spaced_print(buf, size, format, width, 0, static_cast<float>(num),
units_spacer.get(*state).c_str(), _(*suffix));
return;
}
while (llabs(num / 1024) >= 1000LL && (**(suffix + 2) != 0)) {
num /= 1024;
suffix++;
}
suffix++;
fnum = num / 1024.0;
/* fnum should now be < 1000, so looks like 'AAA.BBBBB'
*
* The goal is to always have a significance of 3, by
* adjusting the decimal part of the number. Sample output:
* 123MiB
* 23.4GiB
* 5.12B
* so the point of alignment resides between number and unit. The
* upside of this is that there is minimal padding necessary, though
* there should be a way to make alignment take place at the decimal
* dot (then with fixed width decimal part).
*
* Note the repdigits below: when given a precision value, printf()
* rounds the float to it, not just cuts off the remaining digits. So
* e.g. 99.95 with a precision of 1 gets 100.0, which again should be
* printed with a precision of 0. Yay. */
precision = 0; /* print 100-999 without decimal part */
if (fnum < 99.95) { precision = 1; /* print 10-99 with one decimal place */ }
if (fnum < 9.995) { precision = 2; /* print 0-9 with two decimal places */ }
spaced_print(buf, size, format, width, precision, fnum,
units_spacer.get(*state).c_str(), _(*suffix));
}
/* global object list root element */
static struct text_object global_root_object;
static Colour current_text_color;
void set_current_text_color(Colour colour) { current_text_color = colour; }
Colour get_current_text_color() { return current_text_color; }
static void extract_variable_text(const char *p) {
free_text_objects(&global_root_object);
delete_block_and_zero(tmpstring1);
delete_block_and_zero(tmpstring2);
delete_block_and_zero(text_buffer);
extract_variable_text_internal(&global_root_object, p);
}
void parse_conky_vars(struct text_object *root, const char *txt, char *p,
int p_max_size) {
extract_variable_text_internal(root, txt);
generate_text_internal(p, p_max_size, *root);
}
/* IFBLOCK jumping algorithm
*
* This is easier as it looks like:
* - each IF checks it's condition
* - on FALSE: jump
* - on TRUE: don't care
* - each ELSE jumps unconditionally
* - each ENDIF is silently being ignored
*
* Why this works (or: how jumping works):
* Jumping means to overwrite the "obj" variable of the loop and set it to the
* target (i.e. the corresponding ELSE or ENDIF). After that, the for-loop does
* the rest: as regularly, "obj" is being updated to point to obj->next, so
* object parsing continues right after the corresponding ELSE or ENDIF. This
* means that if we find an ELSE, it's corresponding IF must not have jumped,
* so we need to jump always. If we encounter an ENDIF, it's corresponding IF
* or ELSE has not jumped, and there is nothing to do.
*/
void generate_text_internal(char *p, int p_max_size, struct text_object root) {
struct text_object *obj;
size_t a;
if (p == nullptr) { return; }
#ifdef BUILD_ICONV
char *buff_in;
buff_in = new char[p_max_size];
memset(buff_in, 0, p_max_size);
#endif /* BUILD_ICONV */
p[0] = 0;
obj = root.next;
while ((obj != nullptr) && p_max_size > 0) {
/* check callbacks for existence and act accordingly */
if (obj->callbacks.print != nullptr) {
(*obj->callbacks.print)(obj, p, p_max_size);
} else if (obj->callbacks.iftest != nullptr) {
if ((*obj->callbacks.iftest)(obj) == 0) {
DBGP2("jumping");
if (obj->ifblock_next != nullptr) { obj = obj->ifblock_next; }
}
} else if (obj->callbacks.barval != nullptr) {
new_bar(obj, p, p_max_size, (*obj->callbacks.barval)(obj));
} else if (obj->callbacks.gaugeval != nullptr) {
new_gauge(obj, p, p_max_size, (*obj->callbacks.gaugeval)(obj));
#ifdef BUILD_GUI
} else if (obj->callbacks.graphval != nullptr) {
new_graph(obj, p, p_max_size, (*obj->callbacks.graphval)(obj));
#endif /* BUILD_GUI */
} else if (obj->callbacks.percentage != nullptr) {
percent_print(p, p_max_size, (*obj->callbacks.percentage)(obj));
}
a = strlen(p);
#ifdef BUILD_ICONV
iconv_convert(&a, buff_in, p, p_max_size);
#endif /* BUILD_ICONV */
p += a;
p_max_size -= a;
(*p) = 0;
obj = obj->next;
}
#ifdef BUILD_GUI
/* load any new fonts we may have had */
load_fonts(utf8_mode.get(*state));
#endif /* BUILD_GUI */
#ifdef BUILD_ICONV
delete[] buff_in;
#endif /* BUILD_ICONV */
}
void evaluate(const char *text, char *p, int p_max_size) {
struct text_object subroot {};
/**
* Consider expressions like: ${execp echo '${execp echo hi}'}
* These would require run extract_variable_text_internal() before
* callbacks and generate_text_internal() after callbacks.
*/
extract_variable_text_internal(&subroot, text);
generate_text_internal(p, p_max_size, subroot);
DBGP2("evaluated '%s' to '%s'", text, p);
free_text_objects(&subroot);
}
double current_update_time, next_update_time, last_update_time;
static void generate_text() {
char *p;
unsigned int i, j, k;
special_count = 0;
current_update_time = get_time();
/* clears netstats info, calls conky::run_all_callbacks(), and changes
* some info.mem entries */
update_stuff();
/* populate the text buffer; generate_text_internal() iterates through
* global_root_object (an instance of the text_object struct) and calls
* any callbacks that were set on startup by construct_text_object(). */
p = text_buffer;
generate_text_internal(p, max_user_text.get(*state), global_root_object);
unsigned int mw = max_text_width.get(*state);
unsigned int tbs = text_buffer_size.get(*state);
if (mw > 0) {
for (i = 0, j = 0; p[i] != 0; i++) {
if (p[i] == '\n') {
j = 0;
} else if (j == mw) {
k = i + strlen(p + i) + 1;
if (k < tbs) {
while (k != i) {
p[k] = p[k - 1];
k--;
}
p[k] = '\n';
j = 0;
} else {
NORM_ERR(
"The end of the text_buffer is reached, increase "
"\"text_buffer_size\"");
}
} else {
j++;
}
}
}
if (stuff_in_uppercase.get(*state)) {
char *tmp_p;
tmp_p = text_buffer;
while (*tmp_p != 0) {
*tmp_p = toupper(static_cast<unsigned char>(*tmp_p));
tmp_p++;
}
} else if (stuff_in_lowercase.get(*state)) {
char *tmp_p;
tmp_p = text_buffer;
while (*tmp_p != 0) {
*tmp_p = tolower(static_cast<unsigned char>(*tmp_p));
tmp_p++;
}
}
double ui = active_update_interval();
double time = get_time();
next_update_time += ui;
if (next_update_time < time || next_update_time > time + ui) {
next_update_time = time - fmod(time, ui) + ui;
}
last_update_time = current_update_time;
total_updates++;
}
int get_string_width(const char *s) { return *s != 0 ? calc_text_width(s) : 0; }
#ifdef BUILD_GUI
int get_border_total() {
return dpi_scale(border_inner_margin.get(*state)) +
dpi_scale(border_outer_margin.get(*state)) +
dpi_scale(border_width.get(*state));
}
void remove_first_char(char *s) { memmove(s, s + 1, strlen(s)); }
static int get_string_width_special(char *s, int special_index) {
char *p, *final;
special_node *current = specials;
int width = 0;
long i;
if (s == nullptr) { return 0; }
if (display_output() == nullptr || !display_output()->graphical()) {
return strlen(s);
}
p = strndup(s, text_buffer_size.get(*state));
final = p;
for (i = 0; i <= special_index; i++) { current = current->next; }
while (*p != 0) {
if (*p == SPECIAL_CHAR) {
/* shift everything over by 1 so that the special char
* doesn't mess up the size calculation */
remove_first_char(p);
/*for (i = 0; i < static_cast<long>(strlen(p)); i++) {
*(p + i) = *(p + i + 1);
}*/
if (current->type == text_node_t::GRAPH ||
current->type == text_node_t::GAUGE ||
current->type == text_node_t::BAR) {
width += current->width;
}
if (current->type == text_node_t::FONT) {
// put all following text until the next fontchange/stringend in
// influenced_by_font but do not include specials
char *influenced_by_font = strdup(p);
special_node *current_after_font = current;
// influenced_by_font gets special chars removed, so after this loop i
// counts the number of letters (not special chars) influenced by font
for (i = 0; influenced_by_font[i] != 0; i++) {
if (influenced_by_font[i] == SPECIAL_CHAR) {
// remove specials and stop at fontchange
current_after_font = current_after_font->next;
if (current_after_font->type == text_node_t::FONT) {
influenced_by_font[i] = 0;
break;
}
remove_first_char(&influenced_by_font[i]);
}
}
// add the length of influenced_by_font in the new font to width
int orig_font = selected_font;
selected_font = current->font_added;
width += calc_text_width(influenced_by_font);
selected_font = orig_font;
free(influenced_by_font);
// make sure the chars counted in the new font are not again counted
// in the old font
int specials_skipped = 0;
while (i > 0) {
if (p[specials_skipped] != SPECIAL_CHAR) {
remove_first_char(&p[specials_skipped]);
// i only counts non-special chars, so only decrement it for those
i--;
} else {
specials_skipped++;
}
}
}
current = current->next;
} else {
p++;
}
}
if (strlen(final) > 1) { width += calc_text_width(final); }
free(final);
return width;
}
static int text_size_updater(char *s, int special_index);
int last_font_height;
void update_text_area() {
conky::vec2i xy;
if (display_output() == nullptr || !display_output()->graphical()) { return; }
/* update text size if it isn't fixed */
#ifdef OWN_WINDOW
if (fixed_size == 0)
#endif
{
text_size = conky::vec2i(dpi_scale(minimum_width.get(*state)), 0);
last_font_height = font_height();
for_each_line(text_buffer, text_size_updater);
text_size = text_size.max(conky::vec2i(text_size.x() + 1, dpi_scale(minimum_height.get(*state))));
int mw = dpi_scale(maximum_width.get(*state));
if (mw > 0) text_size = text_size.min(conky::vec2i(mw, text_size.y()));
}
alignment align = text_alignment.get(*state);
/* get text position on workarea */
switch (vertical_alignment(align)) {
case axis_align::START:
xy.set_y(workarea.y() + dpi_scale(gap_y.get(*state)));
break;
case axis_align::END:
default:
xy.set_y(workarea.end_y() - text_size.y() - dpi_scale(gap_y.get(*state)));
break;
case axis_align::MIDDLE:
xy.set_y(workarea.y() + workarea.height() / 2 - text_size.y() / 2 -
dpi_scale(gap_y.get(*state)));
break;
}
switch (horizontal_alignment(align)) {
case axis_align::START:
default:
xy.set_x(workarea.x() + dpi_scale(gap_x.get(*state)));
break;
case axis_align::END:
xy.set_x(workarea.end_x() - text_size.x() - dpi_scale(gap_x.get(*state)));
break;
case axis_align::MIDDLE:
xy.set_x(workarea.x() + workarea.width() / 2 - text_size.x() / 2 -
dpi_scale(gap_x.get(*state)));
break;
}
#ifdef OWN_WINDOW
if (align == alignment::NONE) { // Let the WM manage the window
xy = window.geometry.pos();
fixed_pos = 1;
fixed_size = 1;
}
#endif /* OWN_WINDOW */
#ifdef OWN_WINDOW
if (own_window.get(*state) && (fixed_pos == 0)) {
int border_total = get_border_total();
text_start = conky::vec2i::uniform(border_total);
window.geometry.set_pos(xy - text_start);
} else
#endif
{
text_start = xy;
}
/* update lua window globals */
llua_update_window_table(conky::rect<int>(text_start, text_size));
}
/* drawing stuff */
static int cur_x, cur_y; /* current x and y for drawing */
#endif
// draw_mode also without BUILD_GUI because we only need to print to stdout with
// FG
static draw_mode_t draw_mode; /* FG, BG or OUTLINE */
#ifdef BUILD_GUI
/*static*/ Colour current_color;
static int text_size_updater(char *s, int special_index) {
int w = 0;
char *p;
special_node *current = specials;
for (int i = 0; i < special_index; i++) { current = current->next; }
if (display_output() == nullptr || !display_output()->graphical()) {
return 0;
}
/* get string widths and skip specials */
p = s;
while (*p != 0) {
if (*p == SPECIAL_CHAR) {
*p = '\0';
w += get_string_width(s);
*p = SPECIAL_CHAR;
if (current->type == text_node_t::BAR ||
current->type == text_node_t::GAUGE ||
current->type == text_node_t::GRAPH) {
w += current->width;
if (current->height > last_font_height) {
last_font_height = current->height;
last_font_height += font_height();
}
} else if (current->type == text_node_t::OFFSET) {
if (current->arg > 0) { w += current->arg; }
} else if (current->type == text_node_t::VOFFSET) {
last_font_height += current->arg;
} else if (current->type == text_node_t::GOTO) {
if (current->arg > cur_x) { w = static_cast<int>(current->arg); }
} else if (current->type == text_node_t::TAB) {
int start = current->arg;
int step = current->width;
if ((step == 0) || step < 0) { step = 10; }
w += step - (cur_x - text_start.x() - start) % step;
} else if (current->type == text_node_t::FONT) {
selected_font = current->font_added;
if (font_height() > last_font_height) {
last_font_height = font_height();
}
}
special_index++;
current = current->next;
s = p + 1;
}
p++;
}
w += get_string_width(s);
if (w > text_size.x()) { text_size.set_x(w); }
int mw = dpi_scale(maximum_width.get(*state));
if (mw > 0) { text_size.set_x(std::min(mw, text_size.x())); }
text_size += conky::vec2i(0, last_font_height);
last_font_height = font_height();
return special_index;
}
#endif /* BUILD_GUI */
static inline void set_foreground_color(Colour c) {
for (auto output : display_outputs()) output->set_foreground_color(c);
}
static inline void draw_graph_bars(special_node *current, std::unique_ptr<Colour[]>& tmpcolour,
conky::vec2i& text_offset, int i, int &j, int w,
int colour_idx, int cur_x, int by, int h) {
double graphheight = current->graph[j] * (h - 1) / current->scale;
/* Check if graphheight is less than the minheight threshold, if so we must change it to the threshold */
if(graphheight > 0 && current->minheight - graphheight > 0) {
current->graph[j] = current->minheight * current->scale / (h - 1);
}
if (current->colours_set) {
if (current->tempgrad != 0) {
set_foreground_color(tmpcolour[static_cast<int>(
static_cast<float>(w - 2) -
current->graph[j] * (w - 2) /
std::max(static_cast<float>(current->scale),
1.0F))]);
} else {
set_foreground_color(tmpcolour[colour_idx++]);
}
}
/* Handle the case where y axis is to be inverted */
int offsety1 = current->inverty ? by : by + h;
int offsety2 = current->inverty ? by + current->graph[j] * (h - 1) / current->scale
: round_to_positive_int(static_cast<double>(by) + h -
current->graph[j] * (h - 1) /
current->scale);
/* this is mugfugly, but it works */
if (display_output()) {
display_output()->draw_line(
text_offset.x() + cur_x + i + 1, text_offset.y() + offsety1,
text_offset.x() + cur_x + i + 1, text_offset.y() + offsety2);
}
++j;
}
static void draw_string(const char *s) {
int i;
int i2;
int pos;
#ifdef BUILD_GUI
int width_of_s;
#endif /* BUILD_GUI */
int max = 0;
int added;
if (s[0] == '\0') { return; }
#ifdef BUILD_GUI
width_of_s = get_string_width(s);
#endif /* BUILD_GUI */
if (draw_mode == draw_mode_t::FG) {
for (auto output : display_outputs())
if (!output->graphical()) output->draw_string(s, 0);
}
int tbs = text_buffer_size.get(*state);
memset(tmpstring1, 0, tbs);
memset(tmpstring2, 0, tbs);
strncpy(tmpstring1, s, tbs - 1);
pos = 0;
added = 0;
#ifdef BUILD_GUI
if (display_output() && display_output()->graphical()) {
max = ((text_size.x() - width_of_s) / std::max(1, get_string_width(" ")));
}
#endif /* BUILD_GUI */
/* This code looks for tabs in the text and coverts them to spaces.
* The trick is getting the correct number of spaces, and not going
* over the window's size without forcing the window larger. */
for (i = 0; i < tbs; i++) {
if (tmpstring1[i] == '\t') {
i2 = 0;
for (i2 = 0; i2 < (8 - (1 + pos) % 8) && added <= max; i2++) {
/* guard against overrun */
tmpstring2[std::min(pos + i2, tbs - 1)] = ' ';
added++;
}
pos += i2;
} else {
/* guard against overrun */
tmpstring2[std::min(pos, tbs - 1)] = tmpstring1[i];
pos++;
}
}
#ifdef BUILD_GUI
if (display_output() && display_output()->graphical()) {
int mw = dpi_scale(maximum_width.get(*state));
if (text_size.x() == mw) {
/* this means the text is probably pushing the limit,
* so we'll chop it */
}
}
#endif /* BUILD_GUI */
s = tmpstring2;
#ifdef BUILD_GUI
if (display_output() && display_output()->graphical()) {
display_output()->draw_string_at(text_offset.x() + cur_x,
text_offset.y() + cur_y, s, strlen(s));
cur_x += width_of_s;
}
#endif /* BUILD_GUI */
memcpy(tmpstring1, s, tbs);
}
#if defined(BUILD_MATH) && defined(BUILD_GUI)
/// Format \a size as a real followed by closest SI unit, with \a prec
/// number of digits after the decimal point.
static std::string formatSizeWithUnits(double size, int prec = 1) {
int div = 0;
double rem = 0;
while (size >= 1024.0 &&
static_cast<size_t>(div) < (sizeof suffixes / sizeof *suffixes)) {
rem = fmod(size, 1024.0);
div++;
size /= 1024.0;
}
double size_d = size + rem / 1024.0;
std::ostringstream result;
result.setf(std::ios::fixed, std::ios::floatfield);
result.precision(prec);
result << size_d;
result << " ";
if (short_units.get(*state)) {
result << suffixes[div][0];
} else {
result << suffixes[div];
}
return result.str();
}
#endif /* BUILD_MATH && BUILD_GUI */
int draw_each_line_inner(char *s, int special_index, int last_special_applied) {
#ifndef BUILD_GUI
static int cur_x, cur_y; /* current x and y for drawing */
(void)cur_y;
#endif
#ifdef BUILD_GUI
int font_h = 0;
int cur_y_add = 0;
int mw = dpi_scale(maximum_width.get(*state));
#endif /* BUILD_GUI */
char *p = s;
int orig_special_index = special_index;
#ifdef BUILD_GUI
if (display_output() && display_output()->graphical()) {
font_h = font_height();
cur_y += font_ascent();
}
cur_x = text_start.x();
#endif /* BUILD_GUI */
while (*p != 0) {
if (*p == SPECIAL_CHAR || last_special_applied > -1) {
#ifdef BUILD_GUI
int w = 0;
#endif /* BUILD_GUI */
/* draw string before special, unless we're dealing multiline
* specials */
if (last_special_applied > -1) {
special_index = last_special_applied;
} else {
*p = '\0';
draw_string(s);
*p = SPECIAL_CHAR;
s = p + 1;
}
/* draw special */
special_node *current = specials;
for (int i = 0; i < special_index; i++) { current = current->next; }
switch (current->type) {
#ifdef BUILD_GUI
case text_node_t::HORIZONTAL_LINE:
if (display_output() && display_output()->graphical()) {
int h = current->height;
int mid = font_ascent() / 2;
w = text_start.x() + text_size.x() - cur_x;
if (display_output()) {
display_output()->set_line_style(h, true);
display_output()->draw_line(text_offset.x() + cur_x,
text_offset.y() + cur_y - mid / 2,
text_offset.x() + cur_x + w,
text_offset.y() + cur_y - mid / 2);
}
}
break;
case text_node_t::STIPPLED_HR:
if (display_output() && display_output()->graphical()) {
int h = current->height;
char tmp_s = current->arg;
int mid = font_ascent() / 2;
char ss[2] = {tmp_s, tmp_s};
w = text_start.x() + text_size.x() - cur_x - 1;
if (display_output()) {
display_output()->set_line_style(h, false);
display_output()->set_dashes(ss);
display_output()->draw_line(text_offset.x() + cur_x,
text_offset.y() + cur_y - mid / 2,
text_offset.x() + cur_x + w,
text_offset.x() + cur_y - mid / 2);
}
}
break;
case text_node_t::BAR:
if (display_output() && display_output()->graphical()) {
int h, by;
double bar_usage, scale;
if (cur_x - text_start.x() > mw && mw > 0) { break; }
h = current->height;
bar_usage = current->arg;
scale = current->scale;
by = cur_y - (font_ascent() / 2) - 1;
if (h < font_h) { by -= h / 2 - 1; }
w = current->width;
if (w == 0) { w = text_start.x() + text_size.x() - cur_x - 1; }
if (w < 0) { w = 0; }
if (display_output()) {
display_output()->set_line_style(dpi_scale(1), true);
display_output()->draw_rect(text_offset.x() + cur_x,
text_offset.y() + by, w, h);
display_output()->fill_rect(text_offset.x() + cur_x,
text_offset.y() + by,
w * bar_usage / scale, h);
}
if (h > cur_y_add && h > font_h) { cur_y_add = h; }
}
break;
case text_node_t::GAUGE: /* new GAUGE */
if (display_output() && display_output()->graphical()) {
int h, by = 0;
Colour last_colour = current_color;
#ifdef BUILD_MATH
float angle, px, py;
double usage, scale;
#endif /* BUILD_MATH */
if (cur_x - text_start.x() > mw && mw > 0) { break; }
h = current->height;
by = cur_y - (font_ascent() / 2) - 1;
if (h < font_h) { by -= h / 2 - 1; }
w = current->width;
if (w == 0) { w = text_start.x() + text_size.x() - cur_x - 1; }
if (w < 0) { w = 0; }
if (display_output()) {
display_output()->set_line_style(1, true);
display_output()->draw_arc(text_offset.x() + cur_x,
text_offset.y() + by, w, h * 2, 0,
180 * 64);
}
#ifdef BUILD_MATH
usage = current->arg;
scale = current->scale;
angle = M_PI * usage / scale;
px = static_cast<float>(cur_x + (w / 2.)) -
static_cast<float>(w / 2.) * cos(angle);
py = static_cast<float>(by + (h)) -
static_cast<float>(h) * sin(angle);
if (display_output()) {
display_output()->draw_line(
text_offset.x() + cur_x + (w / 2.),
text_offset.y() + by + (h),
text_offset.x() + static_cast<int>(px),
text_offset.y() + static_cast<int>(py));
}
#endif /* BUILD_MATH */
if (h > cur_y_add && h > font_h) { cur_y_add = h; }
set_foreground_color(last_colour);
}
break;
case text_node_t::GRAPH:
if (display_output() && display_output()->graphical()) {
int h, by, i = 0, j = 0;
int colour_idx = 0;
Colour last_colour = current_color;
if (cur_x - text_start.x() > mw && mw > 0) { break; }
h = current->height;
by = cur_y - (font_ascent() / 2) - 1;
if (h < font_h) { by -= h / 2 - 1; }
w = current->width;
if (w == 0) {
w = text_start.x() + text_size.x() - cur_x - 1;
current->graph_width = std::max(w - 1, 0);
if (current->graph_width != current->graph_allocated) {
w = current->graph_allocated + 1;
}
}
if (w < 0) { w = 0; }
if (draw_graph_borders.get(*state)) {
if (display_output()) {
display_output()->set_line_style(dpi_scale(1), true);
display_output()->draw_rect(text_offset.x() + cur_x,
text_offset.y() + by, w, h);
}
}
if (display_output()) display_output()->set_line_style(1, true);
/* in case we don't have a graph yet */
if (current->graph != nullptr) {
std::unique_ptr<Colour[]> tmpcolour;
if (current->colours_set) {
auto factory = create_gradient_factory(w, current->last_colour,
current->first_colour);
tmpcolour = factory->create_gradient();
delete factory;
}
colour_idx = 0;
if(current->invertx){
for (i = 0; i <= w - 2; i++) {
draw_graph_bars(current, tmpcolour, text_offset,
i, j, w, colour_idx, cur_x, by, h);
}
}
else{
for (i = w - 2; i > -1; i--) {
draw_graph_bars(current, tmpcolour, text_offset,
i, j, w, colour_idx, cur_x, by, h);
}
}
}
if (h > cur_y_add && h > font_h) { cur_y_add = h; }
if (show_graph_range.get(*state)) {
int tmp_x = cur_x;
int tmp_y = cur_y;
unsigned short int seconds = active_update_interval() * w;
char *tmp_day_str;
char *tmp_hour_str;
char *tmp_min_str;
char *tmp_sec_str;
char *tmp_str;
unsigned short int timeunits;
if (seconds != 0) {
timeunits = seconds / 86400;
seconds %= 86400;
if (timeunits <= 0 ||
asprintf(&tmp_day_str, _("%dd"), timeunits) == -1) {
tmp_day_str = strdup("");
}
timeunits = seconds / 3600;
seconds %= 3600;
if (timeunits <= 0 ||
asprintf(&tmp_hour_str, _("%dh"), timeunits) == -1) {
tmp_hour_str = strdup("");
}
timeunits = seconds / 60;
seconds %= 60;
if (timeunits <= 0 ||
asprintf(&tmp_min_str, _("%dm"), timeunits) == -1) {
tmp_min_str = strdup("");
}
if (seconds <= 0 ||
asprintf(&tmp_sec_str, _("%ds"), seconds) == -1) {
tmp_sec_str = strdup("");
}
if (asprintf(&tmp_str, "%s%s%s%s", tmp_day_str, tmp_hour_str,
tmp_min_str, tmp_sec_str) == -1) {
tmp_str = strdup("");
}
free(tmp_day_str);
free(tmp_hour_str);
free(tmp_min_str);
free(tmp_sec_str);
} else {
tmp_str = strdup(
_("Range not possible")); // should never happen, but
// better safe then sorry
}
cur_x += (w / 2) - (font_ascent() * (strlen(tmp_str) / 2));
cur_y += font_h / 2;
draw_string(tmp_str);
free(tmp_str);
cur_x = tmp_x;
cur_y = tmp_y;
}
#ifdef BUILD_MATH
if (show_graph_scale.get(*state) && (current->show_scale == 1)) {
// Set the foreground colour to the first colour, ensures the scale text is always drawn in the same colour
set_foreground_color(current->first_colour);
int tmp_x = cur_x;
int tmp_y = cur_y;
cur_x += font_ascent() / 2;
cur_y += font_h / 2;
std::string tmp_str = formatSizeWithUnits(
current->scale_log != 0 ? std::pow(10.0, current->scale)
: current->scale);
draw_string(tmp_str.c_str());
cur_x = tmp_x;
cur_y = tmp_y;
}
#endif
set_foreground_color(last_colour);
}
break;
case text_node_t::FONT:
if (display_output() && display_output()->graphical()) {
int old = font_ascent();
cur_y -= font_ascent();
selected_font = current->font_added;
set_font();
if (cur_y + font_ascent() < cur_y + old) {
cur_y += old;
} else {
cur_y += font_ascent();
}
font_h = font_height();
}
break;
#endif /* BUILD_GUI */
case text_node_t::FG:
if (draw_mode == draw_mode_t::FG) {
set_foreground_color(Colour::from_argb32(current->arg));
}
break;
#ifdef BUILD_GUI
case text_node_t::BG:
if (draw_mode == draw_mode_t::BG) {
set_foreground_color(Colour::from_argb32(current->arg));
}
break;
case text_node_t::OUTLINE:
if (draw_mode == draw_mode_t::OUTLINE) {
set_foreground_color(Colour::from_argb32(current->arg));
}
break;
case text_node_t::OFFSET:
w += current->arg;
break;
case text_node_t::VOFFSET:
cur_y += current->arg;
break;
case text_node_t::SAVE_COORDINATES:
#ifdef BUILD_IMLIB2
saved_coordinates[static_cast<int>(current->arg)] =
std::array<int, 2>{cur_x - text_start.x(),
cur_y - text_start.y() - last_font_height};
#endif /* BUILD_IMLIB2 */
break;
case text_node_t::TAB: {
int start = current->arg;
int step = current->width;
if ((step == 0) || step < 0) { step = 10; }
w = step - (cur_x - text_start.x() - start) % step;
break;
}
case text_node_t::ALIGNR: {
/* TODO: add back in "+ window.border_inner_margin" to the end of
* this line? */
int pos_x = text_start.x() + text_size.x() -
get_string_width_special(s, special_index);
/* printf("pos_x %i text_start.x %i text_size.x %i cur_x %i "
"get_string_width(p) %i gap_x %i "
"current->arg %i window.border_inner_margin %i "
"window.border_width %i\n", pos_x, text_start.x, text_size.x,
cur_x, get_string_width_special(s), gap_x,
current->arg, window.border_inner_margin,
window.border_width); */
cur_x = pos_x - current->arg;
break;
}
case text_node_t::ALIGNC: {
int pos_x = text_size.x() / 2 -
get_string_width_special(s, special_index) / 2 -
(cur_x - text_start.x());
/* int pos_x = text_start_x + text_size.x / 2 -
get_string_width_special(s) / 2; */
/* printf("pos_x %i text_start.x %i text_size.x %i cur_x %i "
"get_string_width(p) %i gap_x %i "
"current->arg %i\n", pos_x, text_start.x,
text_size.x, cur_x, get_string_width(s), gap_x,
current->arg); */
if (pos_x > current->arg) { w = pos_x - current->arg; }
break;
}
#endif /* BUILD_GUI */
case text_node_t::GOTO:
if (current->arg >= 0) {
#ifdef BUILD_GUI
cur_x = static_cast<int>(current->arg);
// make sure shades are 1 pixel to the right of the text
if (draw_mode == draw_mode_t::BG) { cur_x++; }
#endif /* BUILD_GUI */
cur_x = static_cast<int>(current->arg);
for (auto output : display_outputs()) output->gotox(cur_x);
}
break;
default:
// do nothing; not a special node or support not enabled
break;
}
#ifdef BUILD_GUI
cur_x += w;
#endif /* BUILD_GUI */
if (special_index != last_special_applied) {
special_index++;
} else {
special_index = orig_special_index;
last_special_applied = -1;
}
}
p++;
}
#ifdef BUILD_GUI
cur_y += cur_y_add;
#endif /* BUILD_GUI */
draw_string(s);
for (auto output : display_outputs()) output->line_inner_done();
#ifdef BUILD_GUI
if (display_output() && display_output()->graphical()) {
cur_y += font_descent();
}
#endif /* BUILD_GUI */
return special_index;
}
static int draw_line(char *s, int special_index) {
if (display_output() && display_output()->draw_line_inner_required()) {
return draw_each_line_inner(s, special_index, -1);
}
draw_string(s);
UNUSED(special_index);
return 0;
}
static void draw_text() {
for (auto output : display_outputs()) output->begin_draw_text();
#ifdef BUILD_GUI
// XXX:only works if inside set_display_output()
for (auto output : display_outputs()) {
if (output && output->graphical()) {
cur_y = text_start.y();
int bw = dpi_scale(border_width.get(*state));
/* draw borders */
if (draw_borders.get(*state) && bw > 0) {
if (stippled_borders.get(*state) != 0) {
char ss[2] = {(char)dpi_scale(stippled_borders.get(*state)),
(char)dpi_scale(stippled_borders.get(*state))};
output->set_line_style(bw, false);
output->set_dashes(ss);
} else {
output->set_line_style(bw, true);
}
int offset = dpi_scale(border_inner_margin.get(*state)) + bw;
output->draw_rect(text_offset.x() + text_start.x() - offset,
text_offset.y() + text_start.y() - offset,
text_size.x() + 2 * offset,
text_size.y() + 2 * offset);
}
/* draw text */
}
}
setup_fonts();
#endif /* BUILD_GUI */
for_each_line(text_buffer, draw_line);
for (auto output : display_outputs()) output->end_draw_text();
}
void draw_stuff() {
for (auto output : display_outputs()) output->begin_draw_stuff();
#ifdef BUILD_GUI
llua_draw_pre_hook();
#ifdef BUILD_IMLIB2
text_offset = conky::vec2i::Zero();
cimlib_render(text_start.x(), text_start.y(), window.geometry.width(),
window.geometry.height(),
imlib_cache_flush_interval.get(*state),
imlib_draw_blended.get(*state));
#endif /* BUILD_IMLIB2 */
for (auto output : display_outputs()) {
if (!output->graphical()) continue;
// XXX: we assume a single graphical display
set_display_output(output);
selected_font = 0;
if (draw_shades.get(*state) && !draw_outline.get(*state)) {
text_offset = conky::vec2i::One();
set_foreground_color(default_shade_color.get(*state));
draw_mode = draw_mode_t::BG;
draw_text();
text_offset = conky::vec2i::Zero();
}
if (draw_outline.get(*state)) {
selected_font = 0;
for (int ix = -1; ix < 2; ix++) {
for (int iy = -1; iy < 2; iy++) {
if (ix == 0 && iy == 0) { continue; }
text_offset = conky::vec2i(ix, iy);
set_foreground_color(default_outline_color.get(*state));
draw_mode = draw_mode_t::OUTLINE;
draw_text();
}
}
text_offset = conky::vec2i::Zero();
}
selected_font = 0;
set_foreground_color(default_color.get(*state));
unset_display_output();
}
#endif /* BUILD_GUI */
// always draw text
draw_mode = draw_mode_t::FG;
draw_text();
#ifdef BUILD_GUI
llua_draw_post_hook();
#endif /* BUILD_GUI */
for (auto output : display_outputs()) output->end_draw_stuff();
}
int need_to_update;
/* update_text() generates new text and clears old text area */
void update_text() {
#ifdef BUILD_IMLIB2
cimlib_cleanup();
#endif /* BUILD_IMLIB2 */
generate_text();
#ifdef BUILD_GUI
for (auto output : display_outputs()) {
if (output->graphical()) output->clear_text(1);
}
#endif /* BUILD_GUI */
need_to_update = 1;
llua_update_info(&info, active_update_interval());
}
#ifdef HAVE_SYS_INOTIFY_H
int inotify_fd = -1;
#endif
template <typename Out>
void split(const std::string &s, char delim, Out result) {
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim)) { *(result++) = item; }
}
std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
split(s, delim, std::back_inserter(elems));
return elems;
}
bool is_on_battery() { // checks if at least one battery specified in
// "detect_battery" is discharging
char buf[64];
std::vector<std::string> b_items = split(detect_battery.get(*state), ',');
for (auto const &value : b_items) {
get_battery_short_status(buf, 64, value.c_str());
if (buf[0] == 'D') { return true; }
}
return false;
}
volatile sig_atomic_t g_sigterm_pending, g_sighup_pending, g_sigusr2_pending;
void log_system_details() {
char *session_ty = getenv("XDG_SESSION_TYPE");
char *session = getenv("GDMSESSION");
char *desktop = getenv("XDG_CURRENT_DESKTOP");
if (desktop != nullptr || session != nullptr) {
NORM_ERR("'%s' %s session running '%s' desktop", session, session_ty,
desktop);
}
}
void main_loop() {
int terminate = 0;
#ifdef SIGNAL_BLOCKING
sigset_t newmask, oldmask;
#endif
#ifdef BUILD_GUI
double t;
#endif /* BUILD_GUI */
#ifdef HAVE_SYS_INOTIFY_H
int inotify_config_wd = -1;
#define INOTIFY_EVENT_SIZE (sizeof(struct inotify_event))
#define INOTIFY_BUF_LEN (20 * (INOTIFY_EVENT_SIZE + 16)) + 1
char inotify_buff[INOTIFY_BUF_LEN];
#endif /* HAVE_SYS_INOTIFY_H */
#ifdef SIGNAL_BLOCKING
sigemptyset(&newmask);
sigaddset(&newmask, SIGINT);
sigaddset(&newmask, SIGTERM);
sigaddset(&newmask, SIGUSR1);
#endif
log_system_details();
last_update_time = 0.0;
next_update_time = get_time() - fmod(get_time(), active_update_interval());
info.looped = 0;
while (terminate == 0 && (total_run_times.get(*state) == 0 ||
info.looped < total_run_times.get(*state))) {
if ((update_interval_on_battery.get(*state) != NOBATTERY)) {
on_battery = is_on_battery();
}
info.looped++;
#ifdef SIGNAL_BLOCKING
/* block signals. we will inspect for pending signals later */
if (sigprocmask(SIG_BLOCK, &newmask, &oldmask) < 0) {
CRIT_ERR("unable to sigprocmask()");
}
#endif
#ifdef BUILD_GUI
if (display_output() && display_output()->graphical()) {
t = next_update_time - get_time();
display_output()->main_loop_wait(t);
} else {
#endif /* BUILD_GUI */
struct timespec req, rem;
auto time_to_sleep = next_update_time - get_time();
auto seconds = static_cast<time_t>(std::floor(time_to_sleep));
auto nanos = (time_to_sleep - seconds) * 1000000000L;
req.tv_sec = seconds;
req.tv_nsec = nanos;
nanosleep(&req, &rem);
update_text();
draw_stuff();
for (auto output : display_outputs()) output->flush();
#ifdef BUILD_GUI
}
#endif /* BUILD_GUI */
#ifdef SIGNAL_BLOCKING
/* unblock signals of interest and let handler fly */
if (sigprocmask(SIG_SETMASK, &oldmask, nullptr) < 0) {
CRIT_ERR("unable to sigprocmask()");
}
#endif
if (g_sighup_pending != 0) {
g_sighup_pending = 0;
NORM_ERR("received SIGUSR1. reloading the config file.");
reload_config();
}
if (g_sigusr2_pending != 0) {
g_sigusr2_pending = 0;
// refresh view;
NORM_ERR("received SIGUSR2. refreshing.");
update_text();
draw_stuff();
for (auto output : display_outputs()) output->flush();
}
if (g_sigterm_pending != 0) {
g_sigterm_pending = 0;
NORM_ERR("received SIGHUP, SIGINT, or SIGTERM to terminate. bye!");
terminate = 1;
for (auto output : display_outputs()) output->sigterm_cleanup();
}
#ifdef HAVE_SYS_INOTIFY_H
if (!disable_auto_reload.get(*state) && inotify_fd != -1 &&
inotify_config_wd == -1 && !current_config.empty()) {
inotify_config_wd =
inotify_add_watch(inotify_fd, current_config.c_str(), IN_MODIFY);
}
if (!disable_auto_reload.get(*state) && inotify_fd != -1 &&
inotify_config_wd != -1 && !current_config.empty()) {
int len = 0, idx = 0;
fd_set descriptors;
struct timeval time_to_wait;
FD_ZERO(&descriptors);
FD_SET(inotify_fd, &descriptors);
time_to_wait.tv_sec = time_to_wait.tv_usec = 0;
select(inotify_fd + 1, &descriptors, nullptr, NULL, &time_to_wait);
if (FD_ISSET(inotify_fd, &descriptors)) {
/* process inotify events */
len = read(inotify_fd, inotify_buff, INOTIFY_BUF_LEN - 1);
inotify_buff[len] = 0;
while (len > 0 && idx < len) {
struct inotify_event *ev = (struct inotify_event *)&inotify_buff[idx];
if (ev->wd == inotify_config_wd &&
(ev->mask & IN_MODIFY || ev->mask & IN_IGNORED)) {
/* current_config should be reloaded */
NORM_ERR("'%s' modified, reloading...", current_config.c_str());
reload_config();
if (ev->mask & IN_IGNORED) {
/* for some reason we get IN_IGNORED here
* sometimes, so we need to re-add the watch */
inotify_config_wd = inotify_add_watch(
inotify_fd, current_config.c_str(), IN_MODIFY);
}
break;
} else {
llua_inotify_query(ev->wd, ev->mask);
}
idx += INOTIFY_EVENT_SIZE + ev->len;
}
}
} else if (disable_auto_reload.get(*state) && inotify_fd != -1) {
inotify_rm_watch(inotify_fd, inotify_config_wd);
close(inotify_fd);
inotify_fd = inotify_config_wd = -1;
}
#endif /* HAVE_SYS_INOTIFY_H */
llua_update_info(&info, active_update_interval());
}
clean_up();
#ifdef HAVE_SYS_INOTIFY_H
if (inotify_fd != -1) {
inotify_rm_watch(inotify_fd, inotify_config_wd);
close(inotify_fd);
inotify_fd = inotify_config_wd = -1;
}
#endif /* HAVE_SYS_INOTIFY_H */
}
/* reload the config file */
static void reload_config() {
struct stat sb {};
if ((stat(current_config.c_str(), &sb) != 0) ||
(!S_ISREG(sb.st_mode) && !S_ISLNK(sb.st_mode))) {
NORM_ERR(_("Config file '%s' is gone, continuing with config from "
"memory.\nIf you recreate this file sent me a SIGUSR1 to tell "
"me about it. ( kill -s USR1 %d )"),
current_config.c_str(), getpid());
return;
}
clean_up();
state = std::make_unique<lua::state>();
conky::export_symbols(*state);
sleep(1); /* slight pause */
initialisation(argc_copy, argv_copy);
}
void free_specials(special_node *¤t) {
if (current != nullptr) {
free_specials(current->next);
if (current->type == text_node_t::GRAPH) { free(current->graph); }
delete current;
current = nullptr;
}
clear_stored_graphs();
}
void clean_up(void) {
/* free_update_callbacks(); XXX: some new equivalent of this? */
free_and_zero(info.cpu_usage);
for (auto output : display_outputs()) output->cleanup();
conky::shutdown_display_outputs();
#ifdef BUILD_GUI
if (!display_output() || !display_output()->graphical()) {
fonts.clear(); // in set_default_configurations a font is set but not
// loaded
selected_font = 0;
}
#endif /* BUILD_GUI */
if (info.first_process != nullptr) {
free_all_processes();
info.first_process = nullptr;
}
free_text_objects(&global_root_object);
delete_block_and_zero(tmpstring1);
delete_block_and_zero(tmpstring2);
delete_block_and_zero(text_buffer);
free_and_zero(global_text);
#ifdef BUILD_PORT_MONITORS
tcp_portmon_clear();
#endif
llua_shutdown_hook();
#if defined BUILD_RSS
xmlCleanupParser();
#endif
free_specials(specials);
clear_net_stats();
clear_fs_stats();
clear_diskio_stats();
free_and_zero(global_cpu);
conky::cleanup_config_settings(*state);
state.reset();
}
static void set_default_configurations() {
update_uname();
info.memmax = 0;
top_cpu = 0;
top_mem = 0;
top_time = 0;
#ifdef BUILD_IOSTATS
top_io = 0;
#endif
top_running = 0;
#ifdef BUILD_XMMS2
info.xmms2.artist = nullptr;
info.xmms2.album = nullptr;
info.xmms2.title = nullptr;
info.xmms2.genre = nullptr;
info.xmms2.comment = nullptr;
info.xmms2.url = nullptr;
info.xmms2.status = nullptr;
info.xmms2.playlist = nullptr;
#endif /* BUILD_XMMS2 */
/* Enable a single output by default based on what was enabled at build-time */
#ifdef BUILD_WAYLAND
state->pushboolean(true);
out_to_wayland.lua_set(*state);
#else
#ifdef BUILD_X11
state->pushboolean(true);
out_to_x.lua_set(*state);
#else
state->pushboolean(true);
out_to_stdout.lua_set(*state);
#endif
#endif
info.users.number = 1;
}
void load_config_file() {
DBGP(_("reading contents from config file '%s'"), current_config.c_str());
lua::state &l = *state;
lua::stack_sentry s(l);
l.checkstack(2);
// Extend lua package.path so scripts can use relative paths
{
struct stat file_stat {};
std::string path_ext;
// add XDG directory to lua path
auto xdg_path =
std::filesystem::path(to_real_path(XDG_CONFIG_FILE)).parent_path();
if (stat(xdg_path.c_str(), &file_stat) == 0) {
path_ext.push_back(';');
path_ext.append(xdg_path);
path_ext.append("/?.lua");
}
auto parent_path = current_config.parent_path();
if (xdg_path != parent_path && stat(path_ext.c_str(), &file_stat) == 0) {
path_ext.push_back(';');
path_ext.append(parent_path);
path_ext.append("/?.lua");
}
l.getglobal("package");
l.getfield(-1, "path");
auto path = l.tostring(-1);
path.append(path_ext);
l.pop();
l.pushstring(path.c_str());
l.setfield(-2, "path");
l.pop();
}
try {
#ifdef BUILD_BUILTIN_CONFIG
if (current_config == builtin_config_magic) {
l.loadstring(defconfig);
} else {
#endif
l.loadfile(current_config.c_str());
#ifdef BUILD_BUILTIN_CONFIG
}
#endif
} catch (lua::syntax_error &e) {
#define SYNTAX_ERR_READ_CONF "Syntax error (%s) while reading config file. "
#ifdef BUILD_OLD_CONFIG
NORM_ERR(_(SYNTAX_ERR_READ_CONF), e.what());
NORM_ERR(_("Assuming it's in old syntax and attempting conversion."));
// the strchr thingy skips the first line (#! /usr/bin/lua)
l.loadstring(strchr(convertconf, '\n'));
l.pushstring(current_config.c_str());
l.call(1, 1);
#else
char *syntaxerr;
if (asprintf(&syntaxerr, _(SYNTAX_ERR_READ_CONF), e.what())) {
std::string syntaxerrobj(syntaxerr);
free(syntaxerr);
throw conky::error(syntaxerrobj);
}
#endif
}
l.call(0, 0);
l.getglobal("conky");
l.getfield(-1, "text");
l.replace(-2);
if (l.type(-1) != lua::TSTRING) {
throw conky::error(_("missing text block in configuration"));
}
/* Remove \\-\n. */
l.gsub(l.tocstring(-1), "\\\n", "");
l.replace(-2);
global_text = strdup(l.tocstring(-1));
l.pop();
}
inline void reset_optind() {
#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || \
defined(__OpenBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
optind = optreset = 1;
#else
optind = 0;
#endif
}
void set_current_config() {
/* load current_config, CONFIG_FILE or SYSTEM_CONFIG_FILE */
struct stat s {};
if (current_config.empty()) {
/* Try to use personal config file first */
std::string buf = to_real_path(XDG_CONFIG_FILE);
if (stat(buf.c_str(), &s) == 0) { current_config = buf; }
}
if (current_config.empty()) {
/* Try to use personal config file first */
std::string buf = to_real_path(CONFIG_FILE);
if (stat(buf.c_str(), &s) == 0) { current_config = buf; }
}
/* Try to use system config file if personal config does not exist */
if (current_config.empty() && (stat(SYSTEM_CONFIG_FILE, &s) == 0)) {
current_config = SYSTEM_CONFIG_FILE;
}
/* No readable config found */
if (current_config.empty()) {
#define NOCFGFILEFOUND "no personal or system-wide config file found"
#ifdef BUILD_BUILTIN_CONFIG
current_config = builtin_config_magic;
NORM_ERR(NOCFGFILEFOUND ", using builtin default");
#else
throw conky::error(NOCFGFILEFOUND);
#endif
}
// "-" stands for "read from stdin"
if (current_config == "-") { current_config = "/dev/stdin"; }
}
/* : means that character before that takes an argument */
const char *getopt_string =
"vVqdDSs:t:u:i:hc:p:"
#if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
"U"
#endif /* Linux || FreeBSD */
#ifdef BUILD_X11
"x:y:w:a:X:m:f:"
#ifdef OWN_WINDOW
"o"
#endif
"b"
#endif /* BUILD_X11 */
#ifdef BUILD_BUILTIN_CONFIG
"C"
#endif
;
const struct option longopts[] = {
{"help", 0, nullptr, 'h'}, {"version", 0, nullptr, 'v'},
{"short-version", 0, nullptr, 'V'}, {"quiet", 0, nullptr, 'q'},
{"debug", 0, nullptr, 'D'}, {"config", 1, nullptr, 'c'},
#ifdef BUILD_BUILTIN_CONFIG
{"print-config", 0, nullptr, 'C'},
#endif
{"daemonize", 0, nullptr, 'd'},
#ifdef BUILD_X11
{"alignment", 1, nullptr, 'a'}, {"display", 1, nullptr, 'X'},
{"xinerama-head", 1, nullptr, 'm'}, {"font", 1, nullptr, 'f'},
#ifdef OWN_WINDOW
{"own-window", 0, nullptr, 'o'},
#endif
{"double-buffer", 0, nullptr, 'b'}, {"window-id", 1, nullptr, 'w'},
#endif /* BUILD_X11 */
{"text", 1, nullptr, 't'}, {"interval", 1, nullptr, 'u'},
{"pause", 1, nullptr, 'p'},
#if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
{"unique", 0, nullptr, 'U'},
#endif /* Linux || FreeBSD */
{nullptr, 0, nullptr, 0}
};
void setup_inotify() {
#ifdef HAVE_SYS_INOTIFY_H
// the file descriptor will be automatically closed on exit
inotify_fd = inotify_init();
if (inotify_fd != -1) {
fcntl(inotify_fd, F_SETFL, fcntl(inotify_fd, F_GETFL) | O_NONBLOCK);
fcntl(inotify_fd, F_SETFD, fcntl(inotify_fd, F_GETFD) | FD_CLOEXEC);
}
#endif /* HAVE_SYS_INOTIFY_H */
}
void initialisation(int argc, char **argv) {
struct sigaction act {
}, oact{};
clear_net_stats();
set_default_configurations();
set_current_config();
load_config_file();
/* handle other command line arguments */
reset_optind();
#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
if ((kd = kvm_open("/dev/null", "/dev/null", "/dev/null", O_RDONLY,
"kvm_open")) == nullptr) {
CRIT_ERR("cannot read kvm");
}
#endif
while (1) {
int c = getopt_long(argc, argv, getopt_string, longopts, nullptr);
int startup_pause;
char *conv_end;
if (c == -1) { break; }
switch (c) {
case 'd':
state->pushboolean(true);
fork_to_background.lua_set(*state);
break;
#ifdef BUILD_X11
case 'f':
state->pushstring(optarg);
font.lua_set(*state);
break;
case 'a':
state->pushstring(optarg);
text_alignment.lua_set(*state);
break;
case 'm':
state->pushinteger(strtol(optarg, &conv_end, 10));
if (*conv_end != 0) {
CRIT_ERR("'%s' is a wrong xinerama-head index", optarg);
}
head_index.lua_set(*state);
break;
case 'X':
state->pushstring(optarg);
display_name.lua_set(*state);
break;
#ifdef OWN_WINDOW
case 'o':
state->pushboolean(true);
own_window.lua_set(*state);
break;
#endif
#ifdef BUILD_XDBE
case 'b':
state->pushboolean(true);
use_xdbe.lua_set(*state);
break;
#else
case 'b':
state->pushboolean(true);
use_xpmdb.lua_set(*state);
break;
#endif
#endif /* BUILD_X11 */
case 't':
free_and_zero(global_text);
global_text = strndup(optarg, max_user_text.get(*state));
convert_escapes(global_text);
break;
case 'u':
state->pushnumber(strtod(optarg, &conv_end));
if (*conv_end != 0) {
CRIT_ERR("'%s' is an invalid update interval", optarg);
}
update_interval.lua_set(*state);
break;
case 'i':
state->pushinteger(strtol(optarg, &conv_end, 10));
if (*conv_end != 0) {
CRIT_ERR("'%s' is an invalid number of update times", optarg);
}
total_run_times.lua_set(*state);
break;
#ifdef BUILD_X11
case 'x':
state->pushinteger(strtol(optarg, &conv_end, 10));
if (*conv_end != 0) {
CRIT_ERR("'%s' is an invalid value for the X-position", optarg);
}
gap_x.lua_set(*state);
break;
case 'y':
state->pushinteger(strtol(optarg, &conv_end, 10));
if (*conv_end != 0) {
CRIT_ERR("'%s' is a wrong value for the Y-position", optarg);
}
gap_y.lua_set(*state);
break;
#endif /* BUILD_X11 */
case 'p':
if (first_pass != 0) {
startup_pause = strtol(optarg, nullptr, 10);
sleep(startup_pause);
}
break;
case '?':
throw unknown_arg_throw();
}
}
conky::set_config_settings(*state);
#ifdef BUILD_GUI
if (display_output() && display_output()->graphical()) {
current_text_color = default_color.get(*state);
}
#endif
/* generate text and get initial size */
extract_variable_text(global_text);
free_and_zero(global_text);
/* fork */
if (fork_to_background.get(*state) && (first_pass != 0)) {
int pid = fork();
switch (pid) {
case -1:
NORM_ERR(PACKAGE_NAME ": couldn't fork() to background: %s",
strerror(errno));
break;
case 0:
/* child process */
usleep(25000);
fprintf(stderr, "\n");
fflush(stderr);
break;
default:
/* parent process */
fprintf(stderr, PACKAGE_NAME ": forked to background, pid is %d\n",
pid);
fflush(stderr);
throw fork_throw();
}
}
text_buffer = new char[max_user_text.get(*state)];
memset(text_buffer, 0, max_user_text.get(*state));
tmpstring1 = new char[text_buffer_size.get(*state)];
memset(tmpstring1, 0, text_buffer_size.get(*state));
tmpstring2 = new char[text_buffer_size.get(*state)];
memset(tmpstring2, 0, text_buffer_size.get(*state));
if (!conky::initialize_display_outputs()) {
CRIT_ERR("initialize_display_outputs() failed.");
}
#ifdef BUILD_GUI
/* setup lua window globals */
llua_setup_window_table(conky::rect<int>(text_start, text_size));
#endif /* BUILD_GUI */
llua_setup_info(&info, active_update_interval());
/* Set signal handlers */
act.sa_handler = signal_handler;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
#ifdef SA_RESTART
act.sa_flags |= SA_RESTART;
#endif
if (sigaction(SIGINT, &act, &oact) < 0 ||
sigaction(SIGALRM, &act, &oact) < 0 ||
sigaction(SIGUSR1, &act, &oact) < 0 ||
sigaction(SIGUSR2, &act, &oact) < 0 ||
sigaction(SIGHUP, &act, &oact) < 0 ||
sigaction(SIGTERM, &act, &oact) < 0) {
NORM_ERR("error setting signal handler: %s", strerror(errno));
}
llua_startup_hook();
}
static void signal_handler(int sig) {
/* signal handler is light as a feather, as it should be.
* we will poll g_signal_pending with each loop of conky
* and do any signal processing there, NOT here */
switch (sig) {
case SIGHUP:
case SIGINT:
case SIGTERM:
g_sigterm_pending = 1;
break;
case SIGUSR1:
g_sighup_pending = 1;
break;
case SIGUSR2:
g_sigusr2_pending = 1;
default:
/* Reaching here means someone set a signal
* (SIGXXXX, signal_handler), but didn't write any code
* to deal with it.
* If you don't want to handle a signal, don't set a handler on
* it in the first place.
* We cannot print debug messages from a sighandler, so simply ignore.
*/
break;
}
}
| 73,367
|
C++
|
.cc
| 2,070
| 28.672947
| 121
| 0.581686
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,582
|
intel_backlight.cc
|
brndnmtthws_conky/src/intel_backlight.cc
|
/*
*
* Conky, a system monitor, based on torsmo.
*
* Any original torsmo code is licensed under the BSD license.
* All code written since the fork of torsmo is licensed under the GPL.
* Please see COPYING for details.
*
* Copyright (c) 2021 Rogier Reerink
* (See AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
#include "intel_backlight.h"
#include "logging.h"
#define FS_BRIGHTNESS_MAX "/sys/class/backlight/intel_backlight/max_brightness"
#define FS_BRIGHTNESS_CURRENT "/sys/class/backlight/intel_backlight/brightness"
struct backlight {
FILE *fp_max;
unsigned max;
FILE *fp_current;
unsigned current;
};
void open_backlight(struct backlight *bl) {
bl->fp_max = fopen(FS_BRIGHTNESS_MAX, "r");
if (bl->fp_max == NULL) {
NORM_ERR("Failed to open file: '" FS_BRIGHTNESS_MAX "'.");
}
bl->fp_current = fopen(FS_BRIGHTNESS_CURRENT, "r");
if (bl->fp_current == NULL) {
NORM_ERR("Failed to open file: '" FS_BRIGHTNESS_CURRENT "'.");
}
}
void read_backlight(struct backlight *bl) {
FILE *fp_max, *fp_current;
fp_max = bl->fp_max;
if (fp_max != NULL) {
rewind(fp_max);
fflush(fp_max);
if (fscanf(fp_max, "%u", &(bl->max)) < 0) {
NORM_ERR("Failed to read maximum brightness.");
}
} else {
bl->max = 0;
}
fp_current = bl->fp_current;
if (fp_current != NULL) {
rewind(fp_current);
fflush(fp_current);
if (fscanf(fp_current, "%u", &(bl->current)) < 0) {
NORM_ERR("Failed to read current brightness.");
}
} else {
bl->current = 0;
}
}
unsigned get_backlight_percent(struct backlight *bl) {
read_backlight(bl);
if (bl->max == 0) {
return 0;
} else {
return bl->current * 100.0 / bl->max + 0.5;
}
}
void close_backlight(struct backlight *bl) {
if (bl->fp_max != NULL) { fclose(bl->fp_max); }
if (bl->fp_current != NULL) { fclose(bl->fp_current); }
}
void init_intel_backlight(struct text_object *obj) {
struct backlight *bl = (struct backlight *)malloc(sizeof(struct backlight));
open_backlight(bl);
obj->data.opaque = bl;
}
void free_intel_backlight(struct text_object *obj) {
struct backlight *bl = (struct backlight *)obj->data.opaque;
close_backlight(bl);
free(bl);
}
void print_intel_backlight(struct text_object *obj, char *p,
unsigned int p_max_size) {
struct backlight *bl = (struct backlight *)obj->data.opaque;
unsigned percent = get_backlight_percent(bl);
snprintf(p, p_max_size, "%d", percent);
}
| 3,118
|
C++
|
.cc
| 97
| 29.113402
| 79
| 0.682935
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,583
|
freebsd.cc
|
brndnmtthws_conky/src/freebsd.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "config.h"
#include <sys/dkstat.h>
#include <sys/ioctl.h>
#include <sys/param.h>
#include <sys/resource.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/sysctl.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/user.h>
#include <net/if.h>
#include <net/if_media.h>
#include <net/if_mib.h>
#include <net/if_var.h>
#include <devstat.h>
#include <ifaddrs.h>
#include <limits.h>
#include <paths.h>
#include <unistd.h>
#include <dev/acpica/acpiio.h>
#if 0
#include <dev/wi/if_wavelan_ieee.h>
#endif
#include <mutex>
#include "conky.h"
#include "diskio.h"
#include "freebsd.h"
#include "logging.h"
#include "net_stat.h"
#include "text_object.h"
#include "top.h"
#define GETSYSCTL(name, var) getsysctl(name, &(var), sizeof(var))
#define KELVTOC(x) ((x - 2732) / 10.0)
#define MAXSHOWDEVS 16
#if 0
#define FREEBSD_DEBUG
#endif
kvm_t *kd;
std::mutex kvm_proc_mutex;
__attribute__((gnu_inline)) inline void proc_find_top(struct process **cpu,
struct process **mem,
struct process **time);
static short conky_cpu_setup = 0;
static int getsysctl(const char *name, void *ptr, size_t len) {
size_t nlen = len;
if (sysctlbyname(name, ptr, &nlen, nullptr, 0) == -1) { return -1; }
if (nlen != len && errno == ENOMEM) { return -1; }
return 0;
}
struct ifmibdata *data = nullptr;
size_t len = 0;
static int swapmode(unsigned long *retavail, unsigned long *retfree) {
int n;
unsigned long pagesize = getpagesize();
struct kvm_swap swapary[1];
*retavail = 0;
*retfree = 0;
#define CONVERT(v) ((quad_t)(v) * (pagesize / 1024))
n = kvm_getswapinfo(kd, swapary, 1, 0);
if (n < 0 || swapary[0].ksw_total == 0) { return 0; }
*retavail = CONVERT(swapary[0].ksw_total);
*retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
n = (int)((double)swapary[0].ksw_used * 100.0 / (double)swapary[0].ksw_total);
return n;
}
void prepare_update(void) {}
int update_uptime(void) {
int mib[2] = {CTL_KERN, KERN_BOOTTIME};
struct timeval boottime;
time_t now;
size_t size = sizeof(boottime);
if ((sysctl(mib, 2, &boottime, &size, nullptr, 0) != -1) &&
(boottime.tv_sec != 0)) {
time(&now);
info.uptime = now - boottime.tv_sec;
} else {
fprintf(stderr, "Could not get uptime\n");
info.uptime = 0;
}
return 0;
}
int check_mount(struct text_object *obj) {
struct statfs *mntbuf;
int i, mntsize;
if (!obj->data.s) return 0;
mntsize = getmntinfo(&mntbuf, MNT_NOWAIT);
for (i = mntsize - 1; i >= 0; i--) {
if (strcmp(mntbuf[i].f_mntonname, obj->data.s) == 0) { return 1; }
}
return 0;
}
int update_meminfo(void) {
u_int total_pages, inactive_pages, free_pages, wire_pages, active_pages,
bufferspace, laundry_pages;
unsigned long swap_avail, swap_free;
int pagesize = getpagesize();
if (GETSYSCTL("vm.stats.vm.v_page_count", total_pages)) {
fprintf(stderr, "Cannot read sysctl \"vm.stats.vm.v_page_count\"\n");
}
if (GETSYSCTL("vm.stats.vm.v_free_count", free_pages)) {
fprintf(stderr, "Cannot read sysctl \"vm.stats.vm.v_free_count\"\n");
}
if (GETSYSCTL("vm.stats.vm.v_inactive_count", inactive_pages)) {
fprintf(stderr, "Cannot read sysctl \"vm.stats.vm.v_inactive_count\"\n");
}
if (GETSYSCTL("vm.stats.vm.v_wire_count", wire_pages)) {
fprintf(stderr, "Cannot read sysctl \"vm.stats.vm.v_wire_count\"\n");
}
if (GETSYSCTL("vm.stats.vm.v_active_count", active_pages)) {
fprintf(stderr, "Cannot read sysctl \"vm.stats.vm.v_active_count\"\n");
}
if (GETSYSCTL("vfs.bufspace", bufferspace)) {
fprintf(stderr, "Cannot read sysctl \"vfs.bufspace\"\n");
}
if (GETSYSCTL("vm.stats.vm.v_laundry_count", laundry_pages)) {
fprintf(stderr, "Cannot read sysctl \"vm.stats.vm.v_laundry_count\"\n");
}
info.memmax = total_pages * (pagesize >> 10);
info.mem = (total_pages - free_pages - inactive_pages) * (pagesize >> 10);
info.memwithbuffers = info.mem;
info.memeasyfree = info.memmax - info.mem;
info.memfree = free_pages * (pagesize >> 10);
info.legacymem = info.mem;
info.memwired = wire_pages * (pagesize >> 10);
info.memactive = active_pages * (pagesize >> 10);
info.meminactive = inactive_pages * (pagesize >> 10);
info.memlaundry = laundry_pages * (pagesize >> 10);
info.buffers = bufferspace / 1024;
if ((swapmode(&swap_avail, &swap_free)) >= 0) {
info.swapmax = swap_avail;
info.swap = (swap_avail - swap_free);
info.swapfree = swap_free;
} else {
info.swapmax = 0;
info.swap = 0;
info.swapfree = 0;
}
return 0;
}
int update_net_stats(void) {
struct net_stat *ns;
double delta;
long long r, t, last_recv, last_trans;
struct ifaddrs *ifap, *ifa;
struct if_data *ifd;
/* get delta */
delta = current_update_time - last_update_time;
if (delta <= 0.0001) { return 0; }
if (getifaddrs(&ifap) < 0) { return 0; }
for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
ns = get_net_stat((const char *)ifa->ifa_name, nullptr, NULL);
if (ifa->ifa_flags & IFF_UP) {
struct ifaddrs *iftmp;
ns->up = 1;
last_recv = ns->recv;
last_trans = ns->trans;
if (ifa->ifa_addr->sa_family != AF_LINK) { continue; }
for (iftmp = ifa->ifa_next;
iftmp != nullptr && strcmp(ifa->ifa_name, iftmp->ifa_name) == 0;
iftmp = iftmp->ifa_next) {
if (iftmp->ifa_addr->sa_family == AF_INET) {
memcpy(&(ns->addr), iftmp->ifa_addr, iftmp->ifa_addr->sa_len);
}
}
ifd = (struct if_data *)ifa->ifa_data;
r = ifd->ifi_ibytes;
t = ifd->ifi_obytes;
if (r < ns->last_read_recv) {
ns->recv += ((long long)4294967295U - ns->last_read_recv) + r;
} else {
ns->recv += (r - ns->last_read_recv);
}
ns->last_read_recv = r;
if (t < ns->last_read_trans) {
ns->trans += ((long long)4294967295U - ns->last_read_trans) + t;
} else {
ns->trans += (t - ns->last_read_trans);
}
ns->last_read_trans = t;
/* calculate speeds */
ns->recv_speed = (ns->recv - last_recv) / delta;
ns->trans_speed = (ns->trans - last_trans) / delta;
} else {
ns->up = 0;
}
}
freeifaddrs(ifap);
return 0;
}
int update_total_processes(void) {
int n_processes;
std::lock_guard<std::mutex> guard(kvm_proc_mutex);
kvm_getprocs(kd, KERN_PROC_ALL, 0, &n_processes);
info.procs = n_processes;
return 0;
}
int update_running_processes(void) {
struct kinfo_proc *p;
int n_processes;
int i, cnt = 0;
std::lock_guard<std::mutex> guard(kvm_proc_mutex);
p = kvm_getprocs(kd, KERN_PROC_ALL, 0, &n_processes);
for (i = 0; i < n_processes; i++) {
if (p[i].ki_stat == SRUN) { cnt++; }
}
info.run_procs = cnt;
return 0;
}
void get_cpu_count(void) {
int cpu_count = 0;
if (GETSYSCTL("hw.ncpu", cpu_count) == 0) {
info.cpu_count = cpu_count;
} else {
fprintf(stderr, "Cannot get hw.ncpu\n");
info.cpu_count = 0;
}
info.cpu_usage = (float *)malloc((info.cpu_count + 1) * sizeof(float));
if (info.cpu_usage == nullptr) { CRIT_ERR("malloc"); }
}
struct cpu_info {
long oldtotal;
long oldused;
};
int update_cpu_usage(void) {
int i, j = 0;
long used, total;
long *cp_time = nullptr;
size_t cp_len;
static struct cpu_info *cpu = nullptr;
unsigned int malloc_cpu_size = 0;
extern void *global_cpu;
/* add check for !info.cpu_usage since that mem is freed on a SIGUSR1 */
if ((conky_cpu_setup == 0) || (!info.cpu_usage)) {
get_cpu_count();
conky_cpu_setup = 1;
}
if (!global_cpu) {
malloc_cpu_size = (info.cpu_count + 1) * sizeof(struct cpu_info);
cpu = (cpu_info *)malloc(malloc_cpu_size);
memset(cpu, 0, malloc_cpu_size);
global_cpu = cpu;
}
/* cpu[0] is overall stats, get it from separate sysctl */
cp_len = CPUSTATES * sizeof(long);
cp_time = (long int *)malloc(cp_len);
if (sysctlbyname("kern.cp_time", cp_time, &cp_len, nullptr, 0) < 0) {
fprintf(stderr, "Cannot get kern.cp_time\n");
}
total = 0;
for (j = 0; j < CPUSTATES; j++) total += cp_time[j];
used = total - cp_time[CP_IDLE];
if ((total - cpu[0].oldtotal) != 0) {
info.cpu_usage[0] =
((double)(used - cpu[0].oldused)) / (double)(total - cpu[0].oldtotal);
} else {
info.cpu_usage[0] = 0;
}
cpu[0].oldused = used;
cpu[0].oldtotal = total;
free(cp_time);
/* per-core stats */
cp_len = CPUSTATES * sizeof(long) * info.cpu_count;
cp_time = (long int *)malloc(cp_len);
/* on e.g. i386 SMP we may have more values than actual cpus; this will just
* drop extra values */
if (sysctlbyname("kern.cp_times", cp_time, &cp_len, nullptr, 0) < 0 &&
errno != ENOMEM) {
fprintf(stderr, "Cannot get kern.cp_times\n");
}
for (i = 0; i < (int)info.cpu_count; i++) {
total = 0;
for (j = 0; j < CPUSTATES; j++) total += cp_time[i * CPUSTATES + j];
used = total - cp_time[i * CPUSTATES + CP_IDLE];
if ((total - cpu[i + 1].oldtotal) != 0) {
info.cpu_usage[i + 1] = ((double)(used - cpu[i + 1].oldused)) /
(double)(total - cpu[i + 1].oldtotal);
} else {
info.cpu_usage[i + 1] = 0;
}
cpu[i + 1].oldused = used;
cpu[i + 1].oldtotal = total;
}
free(cp_time);
return 0;
}
void free_cpu(struct text_object *) { /* no-op */
}
int update_load_average(void) {
double v[3];
getloadavg(v, 3);
info.loadavg[0] = (double)v[0];
info.loadavg[1] = (double)v[1];
info.loadavg[2] = (double)v[2];
return 0;
}
double get_acpi_temperature(int fd) {
int temp;
(void)fd;
if (GETSYSCTL("hw.acpi.thermal.tz0.temperature", temp) == 0) {
return KELVTOC(temp);
} else if (GETSYSCTL("dev.cpu.0.temperature", temp) == 0) {
return KELVTOC(temp);
} else if (GETSYSCTL("dev.amdtemp.0.core0.sensor0", temp) == 0) {
return KELVTOC(temp);
}
fprintf(stderr, "Cannot get temperature from sysctl\n");
return 0.0;
}
// If a leaf MIB in the sysctl tree returns ENOENT, that means the entry does
// not exist. On the contrary, if a non-leaf entry *does exist*, then EISDIR
// errno is returned, meaning it exists, but it is an array/directory with
// more elements hanging from it.
static int sysctl_mib_exists(const char *mib)
{
size_t len;
void *p = NULL;
sysctlbyname(mib, p, &len, NULL, 0);
return !(errno == ENOENT);
}
static void get_battery_stats(int *battime, int *batcapacity, int *batstate,
int *ac) {
int battery_present = sysctl_mib_exists("hw.acpi.battery");
int ac_present = sysctl_mib_exists("hw.acpi.acline");
if (!battery_present && !ac_present) {
// According to acpi(4), hw.acpi.acline is optional and only present
// if supported by the hardware. If no battery and acline is detected,
// for sure we are running on an AC line.
*ac = 1;
*batstate = 7;
return;
}
if (battery_present) {
if (battime && GETSYSCTL("hw.acpi.battery.time", *battime)) {
NORM_ERR("Cannot read sysctl \"hw.acpi.battery.time\"");
}
if (batcapacity && GETSYSCTL("hw.acpi.battery.life", *batcapacity)) {
NORM_ERR("Cannot read sysctl \"hw.acpi.battery.life\"");
}
if (batstate && GETSYSCTL("hw.acpi.battery.state", *batstate)) {
NORM_ERR("Cannot read sysctl \"hw.acpi.battery.state\"");
}
}
if (ac_present && ac && GETSYSCTL("hw.acpi.acline", *ac)) {
NORM_ERR("Cannot read sysctl \"hw.acpi.acline\"");
}
}
void get_battery_stuff(char *buf, unsigned int n, const char *bat, int item) {
int battime = 0, batcapacity = 0, batstate = 0, ac = 0;
(void)bat;
get_battery_stats(&battime, &batcapacity, &batstate, &ac);
if (batstate != 1 && batstate != 2 && batstate != 0 && batstate != 7)
fprintf(stderr, "Unknown battery state %d!\n", batstate);
else if (batstate != 1 && ac == 0)
fprintf(stderr, "Battery charging while not on AC!\n");
else if (batstate == 1 && ac == 1)
fprintf(stderr, "Battery discharing while on AC!\n");
switch (item) {
case BATTERY_TIME:
if (batstate == 1 && battime != -1)
snprintf(buf, n, "%d:%2.2d", battime / 60, battime % 60);
break;
case BATTERY_STATUS:
if (batstate == 1) // Discharging
snprintf(buf, n, "remaining (%d%%)", batcapacity);
else
snprintf(buf, n,
batstate == 2
? "charging (%d%%)"
: (batstate == 7 ? "absent/on AC" : "charged (%d%%)"),
batcapacity);
break;
default:
fprintf(stderr, "Unknown requested battery stat %d\n", item);
}
}
int get_battery_perct(const char *) {
int batcapacity;
get_battery_stats(nullptr, &batcapacity, NULL, NULL);
return batcapacity;
}
void get_battery_power_draw(char *buffer, unsigned int n, const char *bat) {
int rate = 0;
double ret = 0;
/*
* hw.acpi.battery.rate returns battery discharge rate in mW,
* or -1 (according to docs, but also 0 in practice) when not discharging.
*
* ref. acpi_battery(4)
*/
if (GETSYSCTL("hw.acpi.battery.rate", rate)) {
fprintf(stderr, "Cannot read sysctl \"hw.acpi.battery.rate\"\n");
}
if (rate > 0) { ret = (double)rate / (double)1000; }
snprintf(buffer, n, "%.1f", ret);
}
double get_battery_perct_bar(struct text_object *obj) {
int batperct = get_battery_perct(obj->data.s);
return batperct;
}
int open_acpi_temperature(const char *name) {
(void)name;
/* Not applicable for FreeBSD. */
return 0;
}
void get_acpi_ac_adapter(char *p_client_buffer, size_t client_buffer_size,
const char *adapter) {
int state;
(void)adapter; // only linux uses this
if (!p_client_buffer || client_buffer_size <= 0) { return; }
if (GETSYSCTL("hw.acpi.acline", state)) {
fprintf(stderr, "Cannot read sysctl \"hw.acpi.acline\"\n");
return;
}
if (state) {
strncpy(p_client_buffer, "Running on AC Power", client_buffer_size);
} else {
strncpy(p_client_buffer, "Running on battery", client_buffer_size);
}
}
void get_acpi_fan(char *p_client_buffer, size_t client_buffer_size) {
/* not implemented */
if (p_client_buffer && client_buffer_size > 0) {
memset(p_client_buffer, 0, client_buffer_size);
}
}
/* void */
char get_freq(char *p_client_buffer, size_t client_buffer_size,
const char *p_format, int divisor, unsigned int cpu) {
int freq;
char freq_sysctl[16] = {0};
if (!p_client_buffer || client_buffer_size <= 0 || !p_format ||
divisor <= 0) {
return 0;
}
snprintf(freq_sysctl, sizeof(freq_sysctl), "dev.cpu.%d.freq", (cpu - 1));
if (GETSYSCTL(freq_sysctl, freq) == 0) {
snprintf(p_client_buffer, client_buffer_size, p_format,
(float)freq / divisor);
} else {
snprintf(p_client_buffer, client_buffer_size, p_format, 0.0f);
}
return 1;
}
#if 0
void update_wifi_stats(void)
{
struct ifreq ifr; /* interface stats */
struct wi_req wireq;
struct net_stat *ns;
struct ifaddrs *ifap, *ifa;
struct ifmediareq ifmr;
int s;
/* Get iface table */
if (getifaddrs(&ifap) < 0) {
return;
}
for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
ns = get_net_stat((const char *) ifa->ifa_name, nullptr, NULL);
s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
/* Get media type */
bzero(&ifmr, sizeof(ifmr));
strlcpy(ifmr.ifm_name, ifa->ifa_name, IFNAMSIZ);
if (ioctl(s, SIOCGIFMEDIA, (caddr_t) &ifmr) < 0) {
close(s);
return;
}
/* We can monitor only wireless interfaces
* which are not in hostap mode */
if ((ifmr.ifm_active & IFM_IEEE80211)
&& !(ifmr.ifm_active & IFM_IEEE80211_HOSTAP)) {
/* Get wi status */
bzero(&ifr, sizeof(ifr));
strlcpy(ifr.ifr_name, ifa->ifa_name, IFNAMSIZ);
wireq.wi_type = WI_RID_COMMS_QUALITY;
wireq.wi_len = WI_MAX_DATALEN;
ifr.ifr_data = (void *) &wireq;
if (ioctl(s, SIOCGWAVELAN, (caddr_t) &ifr) < 0) {
perror("ioctl (getting wi status)");
exit(1);
}
/* wi_val[0] = quality
* wi_val[1] = signal
* wi_val[2] = noise */
ns->linkstatus = (int) wireq.wi_val[1];
}
cleanup:
close(s);
}
}
#endif
int update_diskio(void) {
int devs_count, num_selected, num_selections, dn;
struct device_selection *dev_select = nullptr;
long select_generation;
static struct statinfo statinfo_cur;
char device_name[DEFAULT_TEXT_BUFFER_SIZE];
struct diskio_stat *cur;
unsigned int reads, writes;
unsigned int total_reads = 0, total_writes = 0;
memset(&statinfo_cur, 0, sizeof(statinfo_cur));
statinfo_cur.dinfo = (struct devinfo *)calloc(1, sizeof(struct devinfo));
stats.current = stats.current_read = stats.current_write = 0;
if (devstat_getdevs(nullptr, &statinfo_cur) < 0) {
free(statinfo_cur.dinfo);
return 0;
}
devs_count = statinfo_cur.dinfo->numdevs;
if (devstat_selectdevs(&dev_select, &num_selected, &num_selections,
&select_generation, statinfo_cur.dinfo->generation,
statinfo_cur.dinfo->devices, devs_count, nullptr, 0,
NULL, 0, DS_SELECT_ONLY, MAXSHOWDEVS, 1) >= 0) {
for (dn = 0; dn < devs_count; dn++) {
int di;
struct devstat *dev;
di = dev_select[dn].position;
dev = &statinfo_cur.dinfo->devices[di];
snprintf(device_name, DEFAULT_TEXT_BUFFER_SIZE, "%s%d",
dev_select[dn].device_name, dev_select[dn].unit_number);
total_reads += (reads = dev->bytes[DEVSTAT_READ] / 512);
total_writes += (writes = dev->bytes[DEVSTAT_WRITE] / 512);
for (cur = stats.next; cur; cur = cur->next) {
if (cur->dev && !strcmp(device_name, cur->dev)) {
update_diskio_values(cur, reads, writes);
break;
}
}
}
update_diskio_values(&stats, total_reads, total_writes);
free(dev_select);
}
if (statinfo_cur.dinfo->mem_ptr) { free(statinfo_cur.dinfo->mem_ptr); }
free(statinfo_cur.dinfo);
return 0;
}
/* While topless is obviously better, top is also not bad. */
void get_top_info(void) {
struct kinfo_proc *p;
struct process *proc;
int n_processes;
int i;
std::lock_guard<std::mutex> guard(kvm_proc_mutex);
p = kvm_getprocs(kd, KERN_PROC_PROC, 0, &n_processes);
for (i = 0; i < n_processes; i++) {
if (!(p[i].ki_flag & P_SYSTEM)) {
proc = get_process(p[i].ki_pid);
proc->time_stamp = g_time;
proc->name = strndup(p[i].ki_comm, text_buffer_size.get(*state));
proc->basename = strndup(p[i].ki_comm, text_buffer_size.get(*state));
proc->amount = 100.0 * p[i].ki_pctcpu / FSCALE;
proc->vsize = p[i].ki_size;
proc->rss = (p[i].ki_rssize * getpagesize());
/* ki_runtime is in microseconds, total_cpu_time in centiseconds.
* Therefore we divide by 10000. */
proc->total_cpu_time = p[i].ki_runtime / 10000;
}
}
}
void get_battery_short_status(char *buffer, unsigned int n, const char *bat) {
get_battery_stuff(buffer, n, bat, BATTERY_STATUS);
if (0 == strncmp("charging", buffer, 8)) {
buffer[0] = 'C';
memmove(buffer + 1, buffer + 8, n - 8);
} else if (0 == strncmp("remaining", buffer, 9)) {
buffer[0] = 'D';
memmove(buffer + 1, buffer + 9, n - 9);
} else if (0 == strncmp("charged", buffer, 7)) {
buffer[0] = 'F';
memmove(buffer + 1, buffer + 7, n - 7);
} else if (0 == strncmp("absent/on AC", buffer, 12)) {
buffer[0] = 'N';
memmove(buffer + 1, buffer + 12, n - 12);
}
}
int get_entropy_avail(unsigned int *val) {
/* Not applicable for FreeBSD as it uses the yarrow prng. */
(void)val;
return 1;
}
int get_entropy_poolsize(unsigned int *val) {
/* Not applicable for FreeBSD as it uses the yarrow prng. */
(void)val;
return 1;
}
void print_sysctlbyname(struct text_object *obj, char *p,
unsigned int p_max_size) {
u_int val[3] = {0};
char buf[256] = {""};
size_t len = sizeof(val);
size_t len2 = sizeof(buf);
if (0 == strcmp(obj->data.s, "")) {
snprintf(p, p_max_size, "%s", "sysctlbyname takes an argument");
return;
}
if (0 != sysctlbyname(obj->data.s, &val, &len, NULL, 0)) {
if (0 != sysctlbyname(obj->data.s, &buf, &len2, NULL, 0)) {
snprintf(p, p_max_size, "%s", "");
return;
}
}
if (0 != strcmp(buf, "")) {
snprintf(p, p_max_size, "%s", buf);
} else {
snprintf(p, p_max_size, "%lu", (unsigned long)val[0]);
}
}
/******************************************
* Check if more than one conky process *
* is running *
******************************************/
bool is_conky_already_running(void) {
kvm_t *kd;
struct kinfo_proc *kp;
char errbuf[_POSIX2_LINE_MAX];
int entries = -1;
int instances = 0;
kd = kvm_openfiles(NULL, _PATH_DEVNULL, NULL, O_RDONLY, errbuf);
if (kd == NULL) {
NORM_ERR("%s\n", errbuf);
return false;
}
kp = kvm_getprocs(kd, KERN_PROC_ALL, 0, &entries);
if ((kp == NULL && errno != ESRCH) || (kp != NULL && entries < 0)) {
NORM_ERR("%s\n", kvm_geterr(kd));
goto cleanup;
}
for (int i = 0; i < entries && instances < 2; ++i) {
if (!strcmp("conky", kp[i].ki_comm)) {
++instances;
}
}
cleanup:
kvm_close(kd);
return instances > 1;
}
| 22,310
|
C++
|
.cc
| 662
| 29.453172
| 80
| 0.625291
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
22,584
|
lua-config.cc
|
brndnmtthws_conky/src/lua-config.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Please see COPYING for details
*
* Copyright (C) 2010 Pavel Labath et al.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <config.h>
#include "lua-config.hh"
#include "data-source.hh"
#include "setting.hh"
namespace conky {
void export_symbols(lua::state &l) {
lua::stack_sentry s(l);
l.checkstack(3);
l.newtable();
{
export_data_sources(l);
l.newtable();
l.rawsetfield(-2, "config");
}
l.setglobal("conky");
}
} // namespace conky
| 1,135
|
C++
|
.cc
| 38
| 27.552632
| 72
| 0.72594
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
22,585
|
gradient.cc
|
brndnmtthws_conky/src/gradient.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "gradient.h"
#include "colours.h"
#include "conky.h"
#include "logging.h"
namespace conky {
gradient_factory::gradient_factory(int width, Colour first_colour,
Colour last_colour) {
// Make sure the width is always at least 2
this->width = std::max(2, width);
this->first_colour = first_colour;
this->last_colour = last_colour;
}
void gradient_factory::convert_from_rgb(Colour original, long *array) {
long scaled[3];
scaled[0] = original.red * SCALE;
scaled[1] = original.green * SCALE;
scaled[2] = original.blue * SCALE;
convert_from_scaled_rgb(scaled, array);
}
Colour gradient_factory::convert_to_rgb(long *const array) {
long scaled_rgb[3];
Colour c;
convert_to_scaled_rgb(array, scaled_rgb);
c.red = scaled_rgb[0] / SCALE;
c.green = scaled_rgb[1] / SCALE;
c.blue = scaled_rgb[2] / SCALE;
c.alpha = 255;
return c;
}
gradient_factory::colour_array gradient_factory::create_gradient() {
colour_array colours(new Colour[width]);
long first_converted[3];
long last_converted[3];
long diff[3], delta[3];
colours[0] = first_colour;
colours[width - 1] = last_colour;
convert_from_rgb(first_colour, first_converted);
convert_from_rgb(last_colour, last_converted);
for (int i = 0; i < 3; i++) {
diff[i] = last_converted[i] - first_converted[i];
}
fix_diff(diff);
for (int i = 0; i < 3; i++) { delta[i] = diff[i] / (width - 1); }
for (int i = 1; i < width - 1; i++) {
for (int k = 0; k < 3; k++) { first_converted[k] += delta[k]; }
colours[i] = convert_to_rgb(first_converted);
}
return colours;
}
long gradient_factory::get_hue(long *const rgb, long chroma, long value) {
if (chroma == 0) { return 0; }
long diff, offset;
if (rgb[0] == value) {
diff = rgb[1] - rgb[2];
offset = 0;
} else if (rgb[1] == value) {
diff = rgb[2] - rgb[0];
offset = SCALE2;
} else {
diff = rgb[0] - rgb[1];
offset = SCALE4;
}
long h = (SCALE * diff) / chroma + offset;
return 60L * ((SCALE6 + h) % SCALE6);
}
long gradient_factory::get_intermediate(long hue, long chroma) {
long h = hue / 60L;
long multiplier = SCALE - std::abs(h % SCALE2 - SCALE);
return (chroma * multiplier) / SCALE;
}
/* rgb_gradient_factory */
void rgb_gradient_factory::convert_from_scaled_rgb(long *const scaled,
long *target) {
target[0] = scaled[0] * 360L;
target[1] = scaled[1] * 360L;
target[2] = scaled[2] * 360L;
}
void rgb_gradient_factory::convert_to_scaled_rgb(long *const target,
long *scaled) {
scaled[0] = target[0] / 360L;
scaled[1] = target[1] / 360L;
scaled[2] = target[2] / 360L;
}
/* rgb_gradient_factory */
namespace {
long get_value(long *const rgb) {
if (rgb[0] > rgb[1]) { return std::max(rgb[0], rgb[2]); }
return std::max(rgb[1], rgb[2]);
}
long get_minimum(long *const rgb) {
if (rgb[0] < rgb[1]) { return std::min(rgb[0], rgb[2]); }
return std::min(rgb[1], rgb[2]);
}
} // namespace
/* hsv_gradient_factory */
void hsv_gradient_factory::fix_diff(long *diff) {
if (diff[0] > SCALE180) {
diff[0] -= SCALE360;
} else if (diff[0] < -SCALE180) {
diff[0] += SCALE360;
}
}
void hsv_gradient_factory::convert_from_scaled_rgb(long *const scaled,
long *target) {
auto value = get_value(scaled);
auto minimum = get_minimum(scaled);
auto chroma = value - minimum;
long saturation = (SCALE360 * (uint64_t)chroma) / value;
target[0] = get_hue(scaled, chroma, value);
target[1] = saturation;
target[2] = value * 360L;
}
void hsv_gradient_factory::convert_to_scaled_rgb(long *const target,
long *scaled) {
auto hue = target[0] % SCALE360;
auto saturation = target[1] / 360L;
auto value = target[2] / 360L;
auto chroma = (saturation * value) / SCALE;
auto x = get_intermediate(hue, chroma);
scaled[0] = scaled[1] = scaled[2] = (value - chroma);
if (hue < SCALE60) {
scaled[0] += chroma;
scaled[1] += x;
} else if (hue < SCALE120) {
scaled[0] += x;
scaled[1] += chroma;
} else if (hue < SCALE180) {
scaled[1] += chroma;
scaled[2] += x;
} else if (hue < SCALE240) {
scaled[1] += x;
scaled[2] += chroma;
} else if (hue < SCALE300) {
scaled[2] += chroma;
scaled[0] += x;
} else {
scaled[2] += x;
scaled[0] += chroma;
}
}
/* hsv_gradient_factory */
namespace {
// Using Rec.2020 color space
// Y' = 0.2627 x R + 0.6780 x G + 0.0593 x B
long get_luma(long *const rgb) {
return 360L * (uint64_t)(2627L * rgb[0] + 6780L * rgb[1] + 593L * rgb[2]) /
10000L;
}
// Using Rec.2020 color space
// m = Y' - (0.2627 x R + 0.6780 x G + 0.0593 x B)
long get_minimum_from_luma(long luma, long r, long g, long b) {
return luma - (2627L * r + 6780L * g + 593L * b) / 10000L;
}
} // namespace
/* hcl_gradient_factory */
void hcl_gradient_factory::fix_diff(long *diff) {
if (diff[0] > SCALE180) {
diff[0] -= SCALE360;
} else if (diff[0] < -SCALE180) {
diff[0] += SCALE360;
}
}
void hcl_gradient_factory::convert_from_scaled_rgb(long *const scaled,
long *target) {
auto value = get_value(scaled);
auto minimum = get_minimum(scaled);
auto luma = get_luma(scaled);
auto chroma = value - minimum;
target[0] = get_hue(scaled, chroma, value);
target[1] = chroma * 360L;
target[2] = luma;
}
void hcl_gradient_factory::convert_to_scaled_rgb(long *const target,
long *scaled) {
auto hue = target[0] % SCALE360;
auto chroma = target[1] / 360L;
auto luma = target[2] / 360L;
auto x = get_intermediate(hue, chroma);
long m;
if (hue < SCALE60) {
m = get_minimum_from_luma(luma, chroma, x, 0);
scaled[0] = scaled[1] = scaled[2] = m;
scaled[0] += chroma;
scaled[1] += x;
} else if (hue < SCALE120) {
m = get_minimum_from_luma(luma, x, chroma, 0);
scaled[0] = scaled[1] = scaled[2] = m;
scaled[0] += x;
scaled[1] += chroma;
} else if (hue < SCALE180) {
m = get_minimum_from_luma(luma, 0, chroma, x);
scaled[0] = scaled[1] = scaled[2] = m;
scaled[1] += chroma;
scaled[2] += x;
} else if (hue < SCALE240) {
m = get_minimum_from_luma(luma, 0, x, chroma);
scaled[0] = scaled[1] = scaled[2] = m;
scaled[1] += x;
scaled[2] += chroma;
} else if (hue < SCALE300) {
m = get_minimum_from_luma(luma, x, 0, chroma);
scaled[0] = scaled[1] = scaled[2] = m;
scaled[2] += chroma;
scaled[0] += x;
} else {
m = get_minimum_from_luma(luma, chroma, 0, x);
scaled[0] = scaled[1] = scaled[2] = m;
scaled[2] += x;
scaled[0] += chroma;
}
}
/* hcl_gradient_factory */
} // namespace conky
| 7,924
|
C++
|
.cc
| 241
| 28.547718
| 77
| 0.617366
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,586
|
mboxscan.cc
|
brndnmtthws_conky/src/mboxscan.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2006 Marco Candrian <mac@calmar.ws>
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <sys/stat.h>
#include <sys/time.h>
#include <cerrno>
#include <memory>
#include "conky.h"
#include "logging.h"
#include "mail.h"
#include "text_object.h"
#define FROM_WIDTH 10
#define SUBJECT_WIDTH 22
#define PRINT_MAILS 5
#define TIME_DELAY 5
struct ring_list {
char *from;
char *subject;
struct ring_list *previous;
struct ring_list *next;
};
static time_t last_ctime; /* needed for mutt at least */
static time_t last_mtime; /* not sure what to test: testing both now */
static double last_update;
static int args_ok = 0;
static int from_width;
static int subject_width;
static int print_num_mails;
static int time_delay;
static char mbox_mail_spool[DEFAULT_TEXT_BUFFER_SIZE];
static void mbox_scan(char *args, char *output, size_t max_len) {
int i, u, flag;
int force_rescan = 0;
std::unique_ptr<char[]> buf_(new char[text_buffer_size.get(*state)]);
char *buf = buf_.get();
struct stat statbuf {};
struct ring_list *curr = nullptr, *prev = nullptr, *startlist = nullptr;
FILE *fp;
/* output was set to 1 after malloc'ing in conky.c */
/* -> being able to test it here for catching SIGUSR1 */
if (output[0] == 1) {
force_rescan = 1;
output[0] = '\0';
}
if ((args_ok == 0) || (force_rescan != 0)) {
char *substr = strstr(args, "-n");
if (substr != nullptr) {
if (sscanf(substr, "-n %i", &print_num_mails) != 1) {
print_num_mails = PRINT_MAILS;
}
} else {
print_num_mails = PRINT_MAILS;
}
if (print_num_mails < 1) { print_num_mails = 1; }
substr = strstr(args, "-t");
if (substr != nullptr) {
if (sscanf(substr, "-t %i", &time_delay) != 1) {
time_delay = TIME_DELAY;
}
} else {
time_delay = TIME_DELAY;
}
substr = strstr(args, "-fw");
if (substr != nullptr) {
if (sscanf(substr, "-fw %i", &from_width) != 1) {
from_width = FROM_WIDTH;
}
} else {
from_width = FROM_WIDTH;
}
substr = strstr(args, "-sw");
if (substr != nullptr) {
if (sscanf(substr, "-sw %i", &subject_width) != 1) {
subject_width = SUBJECT_WIDTH;
}
} else {
subject_width = SUBJECT_WIDTH;
}
/* encapsulated with "'s find first occurrence of " */
if (args[strlen(args) - 1] == '"') {
char *start;
strncpy(mbox_mail_spool, args, DEFAULT_TEXT_BUFFER_SIZE);
start = strchr(mbox_mail_spool, '"') + 1;
start[(strrchr(mbox_mail_spool, '"') - start)] = '\0';
strncpy(mbox_mail_spool, start, DEFAULT_TEXT_BUFFER_SIZE);
} else {
char *copy_args = strndup(args, text_buffer_size.get(*state));
char *tmp = strtok(copy_args, " ");
char *start = tmp;
while (tmp != nullptr) {
tmp = strtok(nullptr, " ");
if (tmp != nullptr) { start = tmp; }
}
if (start != nullptr) {
strncpy(mbox_mail_spool, start, DEFAULT_TEXT_BUFFER_SIZE);
}
free(copy_args);
}
if (strlen(mbox_mail_spool) < 1) {
CRIT_ERR(
"Usage: ${mboxscan [-n <number of messages to print>] "
"[-fw <from width>] [-sw <subject width>] "
"[-t <delay in sec> mbox]}");
}
/* allowing $MAIL in the config */
if (strcmp(mbox_mail_spool, "$MAIL") == 0) {
strncpy(mbox_mail_spool, current_mail_spool.get(*state).c_str(),
DEFAULT_TEXT_BUFFER_SIZE);
}
if (stat(mbox_mail_spool, &statbuf) != 0) {
CRIT_ERR("can't stat %s: %s", mbox_mail_spool, strerror(errno));
}
args_ok = 1; /* args-computing necessary only once */
}
/* if time_delay not yet reached, then return */
if (current_update_time - last_update < time_delay && (force_rescan == 0)) {
return;
}
last_update = current_update_time;
/* mbox still exists? and get stat-infos */
if (stat(mbox_mail_spool, &statbuf) != 0) {
NORM_ERR("can't stat %s: %s", mbox_mail_spool, strerror(errno));
output[0] = '\0'; /* delete any output */
return;
}
/* modification time has not changed, so skip scanning the box */
if (statbuf.st_ctime == last_ctime && statbuf.st_mtime == last_mtime &&
(force_rescan == 0)) {
return;
}
last_ctime = statbuf.st_ctime;
last_mtime = statbuf.st_mtime;
/* build up double-linked ring-list to hold data, while scanning down the
* mbox */
for (i = 0; i < print_num_mails; i++) {
curr = static_cast<struct ring_list *>(malloc(sizeof(struct ring_list)));
curr->from = static_cast<char *>(malloc(from_width + 1));
curr->subject = static_cast<char *>(malloc(subject_width + 1));
curr->from[0] = '\0';
curr->subject[0] = '\0';
if (i == 0) { startlist = curr; }
if (i > 0) {
curr->previous = prev;
prev->next = curr;
}
prev = curr;
}
if (startlist == nullptr) { return; }
/* connect end to start for an endless loop-ring */
startlist->previous = curr;
curr->next = startlist;
/* mbox */
fp = fopen(mbox_mail_spool, "re");
if (fp == nullptr) { return; }
/* first find a "From " to set it to 0 for header-sarchings */
flag = 1;
while (feof(fp) == 0) {
if (fgets(buf, text_buffer_size.get(*state), fp) == nullptr) { break; }
if (strncmp(buf, "From ", 5) == 0) {
curr = curr->next;
/* skip until \n */
while (strchr(buf, '\n') == nullptr && (feof(fp) == 0)) {
if (fgets(buf, text_buffer_size.get(*state), fp) == nullptr) { break; }
}
flag = 0; /* in the headers now */
continue;
}
if (flag == 1) { /* in the body, so skip */
continue;
}
if (buf[0] == '\n') {
/* beyond the headers now (empty line), skip until \n */
/* then search for new mail ("From ") */
while (strchr(buf, '\n') == nullptr && (feof(fp) == 0)) {
if (fgets(buf, text_buffer_size.get(*state), fp) == nullptr) { break; }
}
flag = 1; /* in the body now */
continue;
}
if ((strncmp(buf, "X-Status: ", 10) == 0) ||
(strncmp(buf, "Status: R", 9) == 0)) {
/* Mail was read or something, so skip that message */
flag = 1; /* search for next From */
curr->subject[0] = '\0';
curr->from[0] = '\0';
/* (will get current again on new 'From ' finding) */
curr = curr->previous;
/* Skip until \n */
while (strchr(buf, '\n') == nullptr && (feof(fp) == 0)) {
if (fgets(buf, text_buffer_size.get(*state), fp) == nullptr) { break; }
}
continue;
}
/* that covers ^From: and ^from: ^From:<tab> */
if (strncmp(buf + 1, "rom:", 4) == 0) {
i = 0;
u = 6; /* no "From: " string needed, so skip */
while (1) {
if (buf[u] == '"') { /* no quotes around names */
u++;
continue;
}
/* some are: From: <foo@bar.com> */
if (buf[u] == '<' && i > 1) {
curr->from[i] = '\0';
/* skip until \n */
while (strchr(buf, '\n') == nullptr && (feof(fp) == 0)) {
if (fgets(buf, text_buffer_size.get(*state), fp) == nullptr) {
break;
}
}
break;
}
if (buf[u] == '\n') {
curr->from[i] = '\0';
break;
}
if (buf[u] == '\0') {
curr->from[i] = '\0';
break;
}
if (i >= from_width) {
curr->from[i] = '\0';
/* skip until \n */
while (strchr(buf, '\n') == nullptr && (feof(fp) == 0)) {
if (fgets(buf, text_buffer_size.get(*state), fp) == nullptr) {
break;
}
}
break;
}
/* nothing special so just set it */
curr->from[i++] = buf[u++];
}
}
/* that covers ^Subject: and ^subject: and ^Subjec:<tab> */
if (strncmp(buf + 1, "ubject:", 7) == 0) {
i = 0;
u = 9; /* no "Subject: " string needed, so skip */
while (1) {
if (buf[u] == '\n') {
curr->subject[i] = '\0';
break;
}
if (buf[u] == '\0') {
curr->subject[i] = '\0';
break;
}
if (i >= subject_width) {
curr->subject[i] = '\0';
/* skip until \n */
while (strchr(buf, '\n') == nullptr && (feof(fp) == 0)) {
if (fgets(buf, text_buffer_size.get(*state), fp) == nullptr) {
break;
}
}
break;
}
/* nothing special so just set it */
curr->subject[i++] = buf[u++];
}
}
}
fclose(fp);
output[0] = '\0';
i = print_num_mails;
while (i != 0) {
struct ring_list *tmp;
if (curr->from[0] != '\0') {
if (i != print_num_mails) {
snprintf(buf, text_buffer_size.get(*state), "\nF: %-*s S: %-*s",
from_width, curr->from, subject_width, curr->subject);
} else { /* first time - no \n in front */
snprintf(buf, text_buffer_size.get(*state), "F: %-*s S: %-*s",
from_width, curr->from, subject_width, curr->subject);
}
} else {
snprintf(buf, text_buffer_size.get(*state), "%s", "\n");
}
strncat(output, buf, max_len - strlen(output));
tmp = curr->previous;
free(curr->from);
free(curr->subject);
free(curr);
curr = tmp;
i--;
}
}
struct mboxscan_data {
char *args;
char *output;
};
void parse_mboxscan_arg(struct text_object *obj, const char *arg) {
struct mboxscan_data *msd;
msd = static_cast<mboxscan_data *>(malloc(sizeof(struct mboxscan_data)));
memset(msd, 0, sizeof(struct mboxscan_data));
msd->args = strndup(arg, text_buffer_size.get(*state));
msd->output = static_cast<char *>(malloc(text_buffer_size.get(*state)));
/* if '1' (in mboxscan.c) then there was SIGUSR1, hmm */
msd->output[0] = 1;
obj->data.opaque = msd;
}
void print_mboxscan(struct text_object *obj, char *p, unsigned int p_max_size) {
auto *msd = static_cast<mboxscan_data *>(obj->data.opaque);
if (msd == nullptr) { return; }
mbox_scan(msd->args, msd->output, text_buffer_size.get(*state));
snprintf(p, p_max_size, "%s", msd->output);
}
void free_mboxscan(struct text_object *obj) {
auto *msd = static_cast<mboxscan_data *>(obj->data.opaque);
if (msd == nullptr) { return; }
free_and_zero(msd->args);
free_and_zero(msd->output);
free_and_zero(obj->data.opaque);
}
| 11,374
|
C++
|
.cc
| 340
| 27.7
| 80
| 0.565415
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
22,587
|
entropy.cc
|
brndnmtthws_conky/src/entropy.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <inttypes.h>
#include <time.h>
#include "config.h"
#include "conky.h"
#include "text_object.h"
/* check for OS and include appropriate headers */
#if defined(__linux__)
#include "linux.h"
#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
#include "freebsd.h"
#elif defined(__DragonFly__)
#include "dragonfly.h"
#elif defined(__OpenBSD__)
#include "openbsd.h"
#elif defined(__sun)
#include "solaris.h"
#elif defined(__HAIKU__)
#include "haiku.h"
#elif defined(__APPLE__) && defined(__MACH__)
#include "darwin.h"
#endif
struct _entropy {
_entropy() = default;
unsigned int avail{0};
unsigned int poolsize{0};
};
static _entropy entropy;
int update_entropy() {
get_entropy_avail(&entropy.avail);
get_entropy_poolsize(&entropy.poolsize);
return 0;
}
void print_entropy_avail(struct text_object *obj, char *p,
unsigned int p_max_size) {
(void)obj;
snprintf(p, p_max_size, "%u", entropy.avail);
}
uint8_t entropy_percentage(struct text_object *obj) {
(void)obj;
return round_to_positive_int(static_cast<double>(entropy.avail) * 100.0 /
static_cast<double>(entropy.poolsize));
}
void print_entropy_poolsize(struct text_object *obj, char *p,
unsigned int p_max_size) {
(void)obj;
snprintf(p, p_max_size, "%u", entropy.poolsize);
}
double entropy_barval(struct text_object *obj) {
(void)obj;
return static_cast<double>(entropy.avail) / entropy.poolsize;
}
void print_password(struct text_object *obj, char *p, unsigned int p_max_size) {
time_t t;
static const char letters[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789~!@#$%^&*("
")_";
static const int len = static_cast<int>(sizeof(letters)) - 1;
uintmax_t x = strtoumax(obj->data.s, (char **)NULL, 10);
uintmax_t z = 0;
if (-1 == (t = time(NULL))) { return; }
srandom(static_cast<unsigned int>(t));
for (; z < x && p_max_size - 1 > z; z++) { *p++ = letters[random() % len]; }
*p = '\0';
}
| 3,079
|
C++
|
.cc
| 92
| 30.48913
| 80
| 0.694015
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,588
|
haiku.cc
|
brndnmtthws_conky/src/haiku.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <OS.h>
#include "conky.h"
#include "haiku.h"
#include "net_stat.h"
#include "top.h"
static short cpu_setup = 0;
void prepare_update() {}
int update_uptime() {
info.uptime = (double)system_time() / 1000000.0;
return 0;
}
int check_mount(struct text_object *obj) {
/* stub */
(void)obj;
return 0;
}
int update_meminfo() {
system_info si;
if (get_system_info(&si) != B_OK) {
fprintf(stderr, "Cannot get_system_info\n");
return 1;
}
info.memmax = si.max_pages * (B_PAGE_SIZE >> 10);
info.mem = si.used_pages * (B_PAGE_SIZE >> 10);
// TODO: we have some more info...
info.memwithbuffers = info.mem;
info.memeasyfree = info.memfree = info.memmax - info.mem;
info.legacymem = info.mem;
info.swapmax = si.max_swap_pages * (B_PAGE_SIZE >> 10);
info.swapfree = si.free_swap_pages * (B_PAGE_SIZE >> 10);
info.swap = (info.swapmax - info.swapfree);
return 0;
}
int update_net_stats() {
// TODO
return 1;
}
int update_total_processes() {
// TODO
return 0;
}
int update_running_processes() {
// TODO
return 1;
}
void get_cpu_count(void) {
system_info si;
if (get_system_info(&si) != B_OK) {
fprintf(stderr, "Cannot get_system_info\n");
info.cpu_count = 0;
return;
}
info.cpu_count = si.cpu_count;
info.cpu_usage = (float *)malloc((info.cpu_count + 1) * sizeof(float));
if (info.cpu_usage == nullptr) { CRIT_ERR("malloc"); }
}
int update_cpu_usage() {
// TODO
static bigtime_t prev = 0;
static cpu_info *prev_cpuinfo = nullptr;
bigtime_t now;
cpu_info *cpuinfo;
/* add check for !info.cpu_usage since that mem is freed on a SIGUSR1 */
if ((cpu_setup == 0) || (!info.cpu_usage)) {
get_cpu_count();
cpu_setup = 1;
}
int malloc_cpu_size = sizeof(cpu_info) * (info.cpu_count + 1);
if (!prev_cpuinfo) {
prev_cpuinfo = (cpu_info *)malloc(malloc_cpu_size);
if (prev_cpuinfo == nullptr) { CRIT_ERR("malloc"); }
memset(prev_cpuinfo, 0, malloc_cpu_size);
}
cpuinfo = (cpu_info *)malloc(malloc_cpu_size);
memset(cpuinfo, 0, malloc_cpu_size);
if (cpuinfo == nullptr) { CRIT_ERR("malloc"); }
now = system_time();
if (get_cpu_info(0, info.cpu_count, &cpuinfo[1]) == B_OK) {
for (int i = 1; i <= info.cpu_count; i++)
cpuinfo[0].active_time += cpuinfo[i].active_time;
cpuinfo[0].active_time /= info.cpu_count;
for (int i = 0; i <= info.cpu_count; i++) {
double period = (double)(now - prev);
info.cpu_usage[i] =
((double)(cpuinfo[i].active_time - prev_cpuinfo[i].active_time)) /
period;
}
}
memcpy(prev_cpuinfo, cpuinfo, malloc_cpu_size);
prev = now;
free(cpuinfo);
return 1;
}
void free_cpu(struct text_object *) { /* no-op */
}
int update_load_average() {
// TODO
return 1;
}
double get_acpi_temperature(int fd) { return -1; }
void get_battery_stuff(char *buf, unsigned int n, const char *bat, int item) {
// TODO
}
int get_battery_perct(const char *bat) {
/*
int batcapacity;
get_battery_stats(nullptr, &batcapacity, NULL, NULL);
return batcapacity;
*/
// TODO
return 0;
}
double get_battery_perct_bar(struct text_object *obj) {
int batperct = get_battery_perct(obj->data.s);
return batperct;
}
void get_battery_power_draw(char *buffer, unsigned int n, const char *bat) {
// TODO
}
int open_acpi_temperature(const char *name) { return -1; }
void get_acpi_ac_adapter(char *p_client_buffer, size_t client_buffer_size,
const char *adapter) {
(void)adapter; // only linux uses this
if (!p_client_buffer || client_buffer_size <= 0) { return; }
/* not implemented */
memset(p_client_buffer, 0, client_buffer_size);
}
/* char *get_acpi_fan() */
void get_acpi_fan(char *p_client_buffer, size_t client_buffer_size) {
if (!p_client_buffer || client_buffer_size <= 0) { return; }
/* not implemented */
memset(p_client_buffer, 0, client_buffer_size);
}
/* void */
char get_freq(char *p_client_buffer, size_t client_buffer_size,
const char *p_format, int divisor, unsigned int cpu) {
int freq;
char *freq_sysctl;
if (!p_client_buffer || client_buffer_size <= 0 || !p_format ||
divisor <= 0) {
return 0;
}
return 0;
// TODO
// return 1;
}
int update_diskio(void) { return 1; }
void get_top_info(void) {
int32 tmcookie = 0;
team_info tm;
struct process *proc;
while (get_next_team_info(&tmcookie, &tm) == B_NO_ERROR) {
team_usage_info ti;
if (get_team_usage_info(tm.team, B_TEAM_USAGE_SELF, &ti) != B_OK) continue;
proc = get_process(tm.team);
proc->time_stamp = g_time;
proc->name = strndup(tm.args, sizeof(tm.args));
proc->basename = strndup(tm.args, sizeof(tm.args));
// proc->amount = 100.0 * p[i].ki_pctcpu / FSCALE;
proc->vsize = 0;
proc->rss = 0;
/* bigtime_t is in microseconds, total_cpu_time in centiseconds.
* Therefore we divide by 10000. */
proc->total_cpu_time = (ti.user_time + ti.kernel_time) / 10000;
}
}
void get_battery_short_status(char *buffer, unsigned int n, const char *bat) {
// TODO
}
int get_entropy_avail(unsigned int *val) { return 1; }
int get_entropy_poolsize(unsigned int *val) { return 1; }
| 6,254
|
C++
|
.cc
| 199
| 28.231156
| 79
| 0.666112
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,589
|
display-wayland.cc
|
brndnmtthws_conky/src/display-wayland.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Please see COPYING for details
*
* Copyright (C) 2018-2021 François Revol et al.
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "display-wayland.hh"
#include <wayland-client.h>
// #include "wayland.h"
#include <cairo.h>
#include <fontconfig/fontconfig.h>
#include <pango/pangocairo.h>
#include <pango/pangofc-fontmap.h>
#include <fcntl.h>
#include <sys/epoll.h>
#include <sys/mman.h>
#include <sys/timerfd.h>
#include <unistd.h>
#include <wayland-client-protocol.h>
#include <wlr-layer-shell-client-protocol.h>
#include <xdg-shell-client-protocol.h>
#include <cstdint>
#include <iostream>
#include <sstream>
#include "conky.h"
#include "display-output.hh"
#include "geometry.h"
#include "gui.h"
#include "llua.h"
#include "logging.h"
#include "fonts.h"
#ifdef BUILD_MOUSE_EVENTS
#include <array>
#include <map>
#include "mouse-events.h"
#endif
#pragma GCC diagnostic ignored "-Wunused-parameter"
static int set_cloexec_or_close(int fd) {
long flags;
if (fd == -1) return -1;
flags = fcntl(fd, F_GETFD);
if (flags == -1) goto err;
if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1) goto err;
return fd;
err:
close(fd);
return -1;
}
static int create_tmpfile_cloexec(char *tmpname) {
int fd;
#ifdef HAVE_MKOSTEMP
fd = mkostemp(tmpname, O_CLOEXEC);
if (fd >= 0) unlink(tmpname);
#else
fd = mkstemp(tmpname);
if (fd >= 0) {
fd = set_cloexec_or_close(fd);
unlink(tmpname);
}
#endif
return fd;
}
/*
* Create a new, unique, anonymous file of the given size, and
* return the file descriptor for it. The file descriptor is set
* CLOEXEC. The file is immediately suitable for mmap()'ing
* the given size at offset zero.
*
* The file should not have a permanent backing store like a disk,
* but may have if XDG_RUNTIME_DIR is not properly implemented in OS.
*
* The file name is deleted from the file system.
*
* The file is suitable for buffer sharing between processes by
* transmitting the file descriptor over Unix sockets using the
* SCM_RIGHTS methods.
*
* If the C library implements posix_fallocate(), it is used to
* guarantee that disk space is available for the file at the
* given size. If disk space is insufficent, errno is set to ENOSPC.
* If posix_fallocate() is not supported, program may receive
* SIGBUS on accessing mmap()'ed file contents instead.
*/
static int os_create_anonymous_file(off_t size) {
static const char templ[] = "/weston-shared-XXXXXX";
const char *path;
char *name;
int fd;
int ret;
path = getenv("XDG_RUNTIME_DIR");
if (!path) {
errno = ENOENT;
return -1;
}
name = static_cast<char *>(malloc(strlen(path) + sizeof(templ)));
if (!name) return -1;
strcpy(name, path);
strcat(name, templ);
fd = create_tmpfile_cloexec(name);
free(name);
if (fd < 0) return -1;
ret = posix_fallocate(fd, 0, size);
if (ret != 0) {
close(fd);
errno = ret;
return -1;
}
return fd;
}
// TODO: cleanup externs (move to conky.h ?)
#ifdef OWN_WINDOW
extern int fixed_size, fixed_pos;
#endif
extern conky::vec2i text_start; /* text start position in window */
extern conky::vec2i text_offset; /* offset for start position */
extern conky::vec2i
text_size; /* initially 1 so no zero-sized window is created */
extern double current_update_time, next_update_time, last_update_time;
void update_text();
extern int need_to_update;
int get_border_total();
extern conky::range_config_setting<int> maximum_width;
extern Colour current_color;
/* for pango_fonts */
struct pango_font {
PangoFontDescription *desc;
struct {
uint32_t ascent;
uint32_t descent;
} metrics;
int font_alpha;
pango_font() : desc(nullptr), metrics({0, 0}), font_alpha(0xffff) {}
};
static std::vector<pango_font> pango_fonts; /* indexed by selected_font */
namespace {
class textalpha_setting : public conky::simple_config_setting<float> {
using Base = conky::simple_config_setting<float>;
protected:
void lua_setter(lua::state &l, bool init) override {
lua::stack_sentry s(l, -2);
Base::lua_setter(l, init);
if (init) {
pango_fonts.resize(std::max(1, static_cast<int>(fonts.size())));
pango_fonts[0].desc = nullptr;
pango_fonts[0].font_alpha = do_convert(l, -1).first * 0xffff;
}
++s;
}
public:
textalpha_setting() : Base("textalpha", 1.0, false) {}
};
textalpha_setting textalpha;
} // namespace
static void wayland_create_window();
static void wayland_create_window() {
setup_fonts();
load_fonts(utf8_mode.get(*state));
update_text_area(); /* to position text/window on screen */
#ifdef OWN_WINDOW
if (own_window.get(*state)) {
if (fixed_pos == 0) {
// XMoveWindow(display, window.window, window.x, window.y);
// TODO
}
// set_transparent_background(window.window);
}
#endif
selected_font = 0;
update_text_area(); /* to get initial size of the window */
}
namespace conky {
namespace {
conky::display_output_wayland wayland_output;
} // namespace
template <>
void register_output<output_t::WAYLAND>(display_outputs_t &outputs) {
outputs.push_back(&wayland_output);
}
display_output_wayland::display_output_wayland()
: display_output_base("wayland") {
is_graphical = true;
priority = 2;
}
bool display_output_wayland::detect() {
if (out_to_wayland.get(*state)) {
DBGP2("Wayland display output '%s' enabled in config.", name.c_str());
return true;
}
return false;
}
static int epoll_fd;
static struct epoll_event ep[1];
static struct window *global_window;
static wl_display *global_display;
struct window {
struct rect<size_t> rectangle;
struct wl_shm *shm;
struct wl_surface *surface;
struct zwlr_layer_surface_v1 *layer_surface;
int scale, pending_scale;
cairo_surface_t *cairo_surface;
cairo_t *cr;
PangoLayout *layout;
PangoContext *pango_context;
};
struct {
struct wl_registry *registry;
struct wl_compositor *compositor;
struct wl_shm *shm;
struct wl_surface *surface;
struct wl_seat *seat;
struct wl_pointer *pointer;
struct wl_output *output;
struct xdg_wm_base *shell;
struct zwlr_layer_shell_v1 *layer_shell;
} wl_globals;
static void xdg_wm_base_ping(void *data, struct xdg_wm_base *shell,
uint32_t serial) {
xdg_wm_base_pong(shell, serial);
}
static const struct xdg_wm_base_listener xdg_wm_base_listener = {
/*.ping =*/&xdg_wm_base_ping,
};
static void output_geometry(void *data, struct wl_output *wl_output, int32_t x,
int32_t y, int32_t physical_width,
int32_t physical_height, int32_t subpixel,
const char *make, const char *model,
int32_t transform) {
// TODO: Add support for proper output management through:
// - xdg-output-unstable-v1
// Maybe also support (if XDG protocol not reported):
// - kde-output-management(-v2)
// - wlr-output-management-unstable-v1
workarea = absolute_rect<int>(
vec2i(x, y),
vec2i(x + physical_width,
y + physical_height)); // TODO: use xdg_output.logical_position
}
static void output_mode(void *data, struct wl_output *wl_output, uint32_t flags,
int32_t width, int32_t height, int32_t refresh) {}
#ifdef WL_OUTPUT_DONE_SINCE_VERSION
static void output_done(void *data, struct wl_output *wl_output) {}
#endif
#ifdef WL_OUTPUT_SCALE_SINCE_VERSION
void output_scale(void *data, struct wl_output *wl_output, int32_t factor) {
/* For now, assume we have one output and adopt its scale unconditionally. */
/* We should also re-render immediately when scale changes. */
global_window->pending_scale = factor;
}
#endif
#ifdef WL_OUTPUT_NAME_SINCE_VERSION
static void output_name(void *data, struct wl_output *wl_output,
const char *name) {}
#endif
#ifdef WL_OUTPUT_DESCRIPTION_SINCE_VERSION
static void output_description(void *data, struct wl_output *wl_output,
const char *description) {}
#endif
const struct wl_output_listener output_listener = {
/*.geometry =*/output_geometry,
/*.mode =*/output_mode,
#ifdef WL_OUTPUT_DONE_SINCE_VERSION
/*.done =*/output_done,
#endif
#ifdef WL_OUTPUT_SCALE_SINCE_VERSION
/*.scale =*/&output_scale,
#endif
#ifdef WL_OUTPUT_NAME_SINCE_VERSION
/*.name =*/&output_name,
#endif
#ifdef WL_OUTPUT_DESCRIPTION_SINCE_VERSION
/*.description =*/&output_description,
#endif
};
void registry_handle_global(void *data, struct wl_registry *registry,
uint32_t name, const char *interface,
uint32_t version) {
if (strcmp(interface, "wl_compositor") == 0) {
wl_globals.compositor = static_cast<wl_compositor *>(
wl_registry_bind(registry, name, &wl_compositor_interface, 3));
} else if (strcmp(interface, "wl_shm") == 0) {
wl_globals.shm = static_cast<wl_shm *>(
wl_registry_bind(registry, name, &wl_shm_interface, 1));
} else if (strcmp(interface, "wl_seat") == 0) {
wl_globals.seat = static_cast<wl_seat *>(
wl_registry_bind(registry, name, &wl_seat_interface, 1));
} else if (strcmp(interface, "wl_output") == 0) {
wl_globals.output = static_cast<wl_output *>(
wl_registry_bind(registry, name, &wl_output_interface, 2));
wl_output_add_listener(wl_globals.output, &output_listener, nullptr);
} else if (strcmp(interface, "xdg_wm_base") == 0) {
wl_globals.shell = static_cast<xdg_wm_base *>(
wl_registry_bind(registry, name, &xdg_wm_base_interface, 1));
xdg_wm_base_add_listener(wl_globals.shell, &xdg_wm_base_listener, nullptr);
} else if (strcmp(interface, "zwlr_layer_shell_v1") == 0) {
wl_globals.layer_shell = static_cast<zwlr_layer_shell_v1 *>(
wl_registry_bind(registry, name, &zwlr_layer_shell_v1_interface, 1));
}
}
void registry_handle_global_remove(void *data, struct wl_registry *registry,
uint32_t name) {}
static const struct wl_registry_listener registry_listener = {
registry_handle_global, registry_handle_global_remove};
static void layer_surface_configure(void *data,
struct zwlr_layer_surface_v1 *layer_surface,
uint32_t serial, uint32_t width,
uint32_t height) {
zwlr_layer_surface_v1_ack_configure(layer_surface, serial);
}
static void layer_surface_closed(void *data,
struct zwlr_layer_surface_v1 *layer_surface) {}
static const struct zwlr_layer_surface_v1_listener layer_surface_listener = {
/*.configure =*/&layer_surface_configure,
/*.closed =*/&layer_surface_closed,
};
struct window *window_create(struct wl_surface *surface, struct wl_shm *shm,
int width, int height);
void window_resize(struct window *window, int width, int height);
void window_allocate_buffer(struct window *window);
void window_destroy(struct window *window);
void window_commit_buffer(struct window *window);
void window_get_width_height(struct window *window, int *w, int *h);
void window_layer_surface_set_size(struct window *window) {
zwlr_layer_surface_v1_set_size(global_window->layer_surface,
global_window->rectangle.width(),
global_window->rectangle.height());
}
#ifdef BUILD_MOUSE_EVENTS
static std::map<wl_pointer *, vec2<size_t>> last_known_positions{};
static void on_pointer_enter(void *data, wl_pointer *pointer,
std::uint32_t serial, wl_surface *surface,
wl_fixed_t surface_x, wl_fixed_t surface_y) {
auto w = reinterpret_cast<struct window *>(data);
auto pos =
vec2d(wl_fixed_to_double(surface_x), wl_fixed_to_double(surface_y));
last_known_positions[pointer] = pos;
auto pos_abs = w->rectangle.pos() + pos;
mouse_crossing_event event{mouse_event_t::AREA_ENTER, pos, pos_abs};
llua_mouse_hook(event);
}
static void on_pointer_leave(void *data, struct wl_pointer *pointer,
std::uint32_t serial, struct wl_surface *surface) {
auto w = reinterpret_cast<struct window *>(data);
auto pos = last_known_positions[pointer];
auto pos_abs = w->rectangle.pos() + pos;
mouse_crossing_event event{mouse_event_t::AREA_LEAVE, pos, pos_abs};
llua_mouse_hook(event);
}
static void on_pointer_motion(void *data, struct wl_pointer *pointer,
std::uint32_t _time, wl_fixed_t surface_x,
wl_fixed_t surface_y) {
auto w = reinterpret_cast<struct window *>(data);
auto pos =
vec2d(wl_fixed_to_double(surface_x), wl_fixed_to_double(surface_y));
last_known_positions[pointer] = pos;
auto pos_abs = w->rectangle.pos() + pos;
mouse_move_event event{pos, pos_abs};
llua_mouse_hook(event);
}
static void on_pointer_button(void *data, struct wl_pointer *pointer,
std::uint32_t serial, std::uint32_t time,
std::uint32_t button, std::uint32_t state) {
auto w = reinterpret_cast<struct window *>(data);
auto pos = last_known_positions[pointer];
auto pos_abs = w->rectangle.pos() + pos;
mouse_button_event event{
mouse_event_t::RELEASE,
pos,
pos_abs,
static_cast<mouse_button_t>(button),
};
switch (static_cast<wl_pointer_button_state>(state)) {
case WL_POINTER_BUTTON_STATE_RELEASED:
// pass; default is MOUSE_RELEASE
break;
case WL_POINTER_BUTTON_STATE_PRESSED:
event.type = mouse_event_t::PRESS;
break;
default:
return;
}
llua_mouse_hook(event);
}
void on_pointer_axis(void *data, struct wl_pointer *pointer, std::uint32_t time,
std::uint32_t axis, wl_fixed_t value) {
if (value == 0) return;
auto w = reinterpret_cast<struct window *>(data);
auto pos = last_known_positions[pointer];
auto pos_abs = w->rectangle.pos() + pos;
mouse_scroll_event event{
pos,
pos_abs,
scroll_direction_t::UP,
};
switch (static_cast<wl_pointer_axis>(axis)) {
case WL_POINTER_AXIS_VERTICAL_SCROLL:
event.direction =
value > 0 ? scroll_direction_t::DOWN : scroll_direction_t::UP;
break;
case WL_POINTER_AXIS_HORIZONTAL_SCROLL:
event.direction =
value > 0 ? scroll_direction_t::RIGHT : scroll_direction_t::LEFT;
break;
default:
return;
}
llua_mouse_hook(event);
}
static void seat_capability_listener(void *data, wl_seat *seat,
uint32_t capability_int) {
wl_seat_capability capabilities =
static_cast<wl_seat_capability>(capability_int);
if (wl_globals.seat == seat) {
if ((capabilities & WL_SEAT_CAPABILITY_POINTER) > 0) {
wl_globals.pointer = wl_seat_get_pointer(seat);
static wl_pointer_listener listener{
.enter = on_pointer_enter,
.leave = on_pointer_leave,
.motion = on_pointer_motion,
.button = on_pointer_button,
.axis = on_pointer_axis,
};
wl_pointer_add_listener(wl_globals.pointer, &listener, data);
}
}
}
static void seat_name_listener(void *data, struct wl_seat *wl_seat,
const char *name) {}
#endif /* BUILD_MOUSE_EVENTS */
bool display_output_wayland::initialize() {
epoll_fd = epoll_create1(0);
if (epoll_fd < 0) {
perror("conky: epoll_create");
return false;
}
global_display = wl_display_connect(NULL);
if (!global_display) {
perror("conky: wl_display_connect");
return false;
}
wl_globals.registry = wl_display_get_registry(global_display);
wl_registry_add_listener(wl_globals.registry, ®istry_listener, NULL);
wl_display_roundtrip(global_display);
if (wl_globals.layer_shell == nullptr) {
// TODO: Implement OWN_WINDOW and XDG Shell support
CRIT_ERR(
"Compositor doesn't support wlr-layer-shell-unstable-v1. Can't run "
"conky.");
}
struct wl_surface *surface =
wl_compositor_create_surface(wl_globals.compositor);
global_window = window_create(surface, wl_globals.shm, 1, 1);
window_allocate_buffer(global_window);
global_window->layer_surface = zwlr_layer_shell_v1_get_layer_surface(
wl_globals.layer_shell, global_window->surface, nullptr,
ZWLR_LAYER_SHELL_V1_LAYER_BOTTOM, "conky_namespace");
window_layer_surface_set_size(global_window);
zwlr_layer_surface_v1_add_listener(global_window->layer_surface,
&layer_surface_listener, nullptr);
#ifdef BUILD_MOUSE_EVENTS
wl_seat_listener listener{
.capabilities = seat_capability_listener,
.name = seat_name_listener,
};
wl_seat_add_listener(wl_globals.seat, &listener, global_window);
#endif /* BUILD_MOUSE_EVENTS */
wl_surface_commit(global_window->surface);
wl_display_roundtrip(global_display);
wayland_create_window();
return true;
}
typedef void (*display_global_handler_t)(struct display *display, uint32_t name,
const char *interface,
uint32_t version, void *data);
typedef void (*display_output_handler_t)(struct output *output, void *data);
bool display_output_wayland::shutdown() { return false; }
#define ARRAY_LENGTH(x) (sizeof(x) / sizeof(x[0]))
static bool added = false;
bool display_output_wayland::main_loop_wait(double t) {
while (wl_display_prepare_read(global_display) != 0)
wl_display_dispatch_pending(global_display);
wl_display_flush(global_display);
if (t < 0.0) { t = 0.0; }
int ms = t * 1000;
/* add fd to epoll set the first time around */
if (!added) {
ep[0].events = EPOLLIN | EPOLLERR | EPOLLHUP | EPOLLET;
ep[0].data.ptr = nullptr;
if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, wl_display_get_fd(global_display),
&ep[0]) == -1) {
perror("conky: epoll_ctl: add");
return false;
}
added = true;
}
/* wait for Wayland event or timeout */
int ep_count = epoll_wait(epoll_fd, ep, ARRAY_LENGTH(ep), ms);
if (ep_count > 0) {
if (ep[0].events & (EPOLLERR | EPOLLHUP)) {
NORM_ERR("output closed");
exit(1);
return false;
}
}
wl_display_read_events(global_display);
wl_display_dispatch_pending(global_display);
wl_display_flush(global_display);
/* timeout */
if (ep_count == 0) { update_text(); }
if (need_to_update != 0) {
need_to_update = 0;
selected_font = 0;
update_text_area();
int changed = 0;
int border_total = get_border_total();
int width, height;
window_get_width_height(global_window, &width, &height);
int fixed_size = 0;
bool scale_changed = global_window->scale != global_window->pending_scale;
/* resize window if it isn't right size */
if ((fixed_size == 0) &&
(text_size.x() + 2 * border_total != width ||
text_size.y() + 2 * border_total != height || scale_changed)) {
/* clamp text_width to configured maximum */
if (maximum_width.get(*state)) {
int mw = global_window->scale * maximum_width.get(*state);
if (mw > 0) { text_size.set_x(std::min(mw, text_size.x())); }
}
/* pending scale will be applied by resizing the window */
global_window->scale = global_window->pending_scale;
width = text_size.x() + 2 * border_total;
height = text_size.y() + 2 * border_total;
window_resize(global_window, width, height); /* resize window */
changed++;
/* update lua window globals */
llua_update_window_table(conky::rect<int>(text_start, text_size));
}
/* move window if it isn't in right position */
#ifdef POSITION
if ((fixed_pos == 0) && (window.x != wx || window.y != wy)) {
// XMoveWindow(display, window.window, window.x, window.y);
changed++;
}
#endif
/* update struts */
if (changed != 0) {
int anchor = 0;
DBGP("%s", _(PACKAGE_NAME ": defining struts\n"));
fflush(stderr);
alignment text_align = text_alignment.get(*state);
switch (vertical_alignment(text_align)) {
case axis_align::START:
anchor |= ZWLR_LAYER_SURFACE_V1_ANCHOR_TOP;
break;
case axis_align::END:
anchor |= ZWLR_LAYER_SURFACE_V1_ANCHOR_BOTTOM;
break;
default:
break;
}
switch (horizontal_alignment(text_align)) {
case axis_align::START:
anchor |= ZWLR_LAYER_SURFACE_V1_ANCHOR_LEFT;
break;
case axis_align::END:
anchor |= ZWLR_LAYER_SURFACE_V1_ANCHOR_RIGHT;
break;
default:
break;
}
// middle anchor alignment is the default and requires no special
// handling.
if (anchor != -1) {
zwlr_layer_surface_v1_set_anchor(global_window->layer_surface, anchor);
zwlr_layer_surface_v1_set_margin(global_window->layer_surface,
gap_y.get(*state), gap_x.get(*state),
gap_y.get(*state), gap_x.get(*state));
}
}
clear_text(1);
draw_stuff();
}
wl_display_flush(global_display);
#ifdef INPUT
#ifdef X_EVENT
case ButtonPress:
if (own_window.get(*state)) {
/* if an ordinary window with decorations */
if ((own_window_type.get(*state) == TYPE_NORMAL &&
!TEST_HINT(own_window_hints.get(*state), HINT_UNDECORATED)) ||
own_window_type.get(*state) == TYPE_DESKTOP) {
/* allow conky to hold input focus. */
break;
}
/* forward the click to the desktop window */
XUngrabPointer(display, ev.xbutton.time);
ev.xbutton.window = window.desktop;
ev.xbutton.x = ev.xbutton.x_root;
ev.xbutton.y = ev.xbutton.y_root;
XSendEvent(display, ev.xbutton.window, False, ButtonPressMask, &ev);
XSetInputFocus(display, ev.xbutton.window, RevertToParent,
ev.xbutton.time);
}
break;
case ButtonRelease:
if (own_window.get(*state)) {
/* if an ordinary window with decorations */
if ((own_window_type.get(*state) == TYPE_NORMAL) &&
!TEST_HINT(own_window_hints.get(*state), HINT_UNDECORATED)) {
/* allow conky to hold input focus. */
break;
}
/* forward the release to the desktop window */
ev.xbutton.window = window.desktop;
ev.xbutton.x = ev.xbutton.x_root;
ev.xbutton.y = ev.xbutton.y_root;
XSendEvent(display, ev.xbutton.window, False, ButtonReleaseMask, &ev);
}
break;
#endif /*X_EVENT*/
#endif /*INPUT*/
// handled
return true;
}
void display_output_wayland::sigterm_cleanup() {}
void display_output_wayland::cleanup() {
if (global_window != nullptr) {
window_destroy(global_window);
global_window = nullptr;
}
free_fonts(utf8_mode.get(*state));
}
void display_output_wayland::set_foreground_color(Colour c) {
current_color = c;
#ifdef BUILD_ARGB
current_color.alpha = own_window_argb_value.get(*state);
#endif /* BUILD_ARGB */
if (global_window->cr) {
cairo_set_source_rgba(global_window->cr, current_color.red / 255.0,
current_color.green / 255.0,
current_color.blue / 255.0,
current_color.alpha / 255.0);
}
}
int display_output_wayland::calc_text_width(const char *s) {
struct window *window = global_window;
size_t slen = strlen(s);
pango_layout_set_text(window->layout, s, slen);
PangoRectangle margin_rect;
pango_layout_set_font_description(window->layout,
pango_fonts[selected_font].desc);
pango_layout_get_pixel_extents(window->layout, nullptr, &margin_rect);
return margin_rect.width;
}
static void adjust_coords(int &x, int &y) {
x -= text_start.x();
y -= text_start.y();
int border = get_border_total();
x += border;
y += border;
}
void display_output_wayland::draw_string_at(int x, int y, const char *s,
int w) {
struct window *window = global_window;
y -= pango_fonts[selected_font].metrics.ascent;
adjust_coords(x, y);
pango_layout_set_text(window->layout, s, strlen(s));
cairo_save(window->cr);
uint8_t r = current_color.red;
uint8_t g = current_color.green;
uint8_t b = current_color.blue;
unsigned int a = pango_fonts[selected_font].font_alpha;
cairo_set_source_rgba(global_window->cr, r / 255.0, g / 255.0, b / 255.0,
a / 65535.);
cairo_move_to(window->cr, x, y);
pango_cairo_show_layout(window->cr, window->layout);
cairo_restore(window->cr);
}
void display_output_wayland::set_line_style(int w, bool solid) {
struct window *window = global_window;
static double dashes[2] = {1.0, 1.0};
if (solid)
cairo_set_dash(window->cr, nullptr, 0, 0);
else
cairo_set_dash(window->cr, dashes, 2, 0);
cairo_set_line_width(window->cr, w);
}
void display_output_wayland::set_dashes(char *s) {
struct window *window = global_window;
size_t len = strlen(s);
double *dashes = new double[len];
for (size_t i = 0; i < len; i++) { dashes[i] = s[i]; }
cairo_set_dash(window->cr, dashes, len, 0);
delete[] dashes;
}
void display_output_wayland::draw_line(int x1, int y1, int x2, int y2) {
struct window *window = global_window;
adjust_coords(x1, y1);
adjust_coords(x2, y2);
cairo_save(window->cr);
cairo_move_to(window->cr, x1 - 0.5, y1 - 0.5);
cairo_line_to(window->cr, x2 - 0.5, y2 - 0.5);
cairo_stroke(window->cr);
cairo_restore(window->cr);
}
static void do_rect(int x, int y, int w, int h, bool fill) {
struct window *window = global_window;
adjust_coords(x, y);
cairo_save(window->cr);
if (fill) {
/* Note that cairo interprets fill and stroke coordinates differently,
so here we don't add 0.5 to move between centers and corners of pixels. */
cairo_rectangle(window->cr, x, y, w - 1, h - 1);
cairo_fill(window->cr);
} else {
cairo_rectangle(window->cr, x - 0.5, y - 0.5, w, h);
cairo_stroke(window->cr);
}
cairo_restore(window->cr);
}
void display_output_wayland::draw_rect(int x, int y, int w, int h) {
do_rect(x, y, w, h, false);
}
void display_output_wayland::fill_rect(int x, int y, int w, int h) {
do_rect(x, y, w, h, true);
}
void display_output_wayland::draw_arc(int x, int y, int w, int h, int a1,
int a2) {
struct window *window = global_window;
adjust_coords(x, y);
cairo_save(window->cr);
cairo_translate(window->cr, x + w / 2. - 0.5, y + h / 2. - 0.5);
cairo_scale(window->cr, w / 2., h / 2.);
cairo_set_line_width(window->cr, 2. / (w + h));
double mult = M_PI / (180. * 64.);
cairo_arc_negative(window->cr, 0., 0., 1., a1 * mult, a2 * mult);
cairo_stroke(window->cr);
cairo_restore(window->cr);
}
void display_output_wayland::move_win(int x, int y) {
// window.x = x;
// window.y = y;
// TODO
}
float display_output_wayland::get_dpi_scale() { return 1.0; }
void display_output_wayland::end_draw_stuff() {
window_commit_buffer(global_window);
}
void display_output_wayland::clear_text(int exposures) {
struct window *window = global_window;
cairo_save(window->cr);
Colour color;
if (set_transparent.get(*state)) {
color.alpha = 0;
} else {
color = background_colour.get(*state);
color.alpha = own_window_argb_value.get(*state);
}
cairo_set_source_rgba(window->cr, color.red / 255.0, color.green / 255.0,
color.blue / 255.0, color.alpha / 255.0);
cairo_set_operator(window->cr, CAIRO_OPERATOR_SOURCE);
cairo_paint(window->cr);
cairo_restore(window->cr);
}
int display_output_wayland::font_height(unsigned int f) {
if (pango_fonts.size() == 0) { return 2; }
assert(f < pango_fonts.size());
return pango_fonts[f].metrics.ascent + pango_fonts[f].metrics.descent;
}
int display_output_wayland::font_ascent(unsigned int f) {
if (pango_fonts.size() == 0) { return 1; }
assert(f < pango_fonts.size());
return pango_fonts[f].metrics.ascent;
}
int display_output_wayland::font_descent(unsigned int f) {
if (pango_fonts.size() == 0) { return 1; }
assert(f < pango_fonts.size());
return pango_fonts[f].metrics.descent;
}
void display_output_wayland::setup_fonts(void) { /* Nothing to do here */
}
void display_output_wayland::set_font(unsigned int f) {
assert(f < pango_fonts.size());
if (pango_fonts.size() > f && pango_fonts[f].desc != nullptr) {
pango_layout_set_font_description(global_window->layout,
pango_fonts[f].desc);
}
}
void display_output_wayland::free_fonts(bool utf8) {
for (auto &font : pango_fonts) {
if (font.desc != nullptr) {
pango_font_description_free(font.desc);
font.desc = nullptr;
}
}
pango_fonts.clear();
}
void display_output_wayland::load_fonts(bool utf8) {
free_fonts(utf8);
pango_fonts.resize(fonts.size());
for (unsigned int i = 0; i < fonts.size(); i++) {
auto &font = fonts[i];
auto &pango_font_entry = pango_fonts[i];
FcPattern *fc_pattern =
FcNameParse(reinterpret_cast<const unsigned char *>(font.name.c_str()));
// pango_fc_font_description_from_pattern requires a FAMILY to be set,
// so set an empty one if none is present.
FcValue dummy;
if (FcPatternGet(fc_pattern, FC_FAMILY, 0, &dummy) != FcResultMatch) {
FcPatternAddString(fc_pattern, FC_FAMILY, (FcChar8 *)"");
}
pango_font_entry.desc =
pango_fc_font_description_from_pattern(fc_pattern, true);
// Handle pixel size ourselves because
// pango_fc_font_description_from_pattern does not
double pixel_size = -1;
if (FcPatternGetDouble(fc_pattern, FC_PIXEL_SIZE, 0, &pixel_size) ==
FcResultMatch) {
pango_font_description_set_absolute_size(pango_font_entry.desc,
pixel_size * PANGO_SCALE);
}
FcPatternDestroy(fc_pattern);
PangoFont *pango_font = pango_context_load_font(
global_window->pango_context, pango_font_entry.desc);
PangoFontMetrics *font_metrics =
pango_font_get_metrics(pango_font, nullptr);
auto ascent = pango_font_metrics_get_ascent(font_metrics) / PANGO_SCALE;
auto descent = pango_font_metrics_get_descent(font_metrics) / PANGO_SCALE;
pango_font_metrics_unref(font_metrics);
g_object_unref(pango_font);
pango_font_entry.metrics.ascent = ascent;
pango_font_entry.metrics.descent = descent;
}
}
struct shm_pool {
struct wl_shm_pool *pool;
size_t size;
size_t used;
void *data;
};
struct shm_surface_data {
struct wl_buffer *buffer;
struct shm_pool *pool;
};
static const cairo_user_data_key_t shm_surface_data_key = {0};
struct wl_buffer *get_buffer_from_cairo_surface(cairo_surface_t *surface) {
struct shm_surface_data *data;
data = static_cast<struct shm_surface_data *>(
cairo_surface_get_user_data(surface, &shm_surface_data_key));
return data->buffer;
}
static void shm_pool_destroy(struct shm_pool *pool);
static void shm_surface_data_destroy(void *p) {
struct shm_surface_data *data = static_cast<struct shm_surface_data *>(p);
wl_buffer_destroy(data->buffer);
if (data->pool) shm_pool_destroy(data->pool);
delete data;
}
static struct wl_shm_pool *make_shm_pool(struct wl_shm *shm, int size,
void **data) {
struct wl_shm_pool *pool;
int fd;
fd = os_create_anonymous_file(size);
if (fd < 0) {
fprintf(stderr, "creating a buffer file for %d B failed: %m\n", size);
return NULL;
}
*data = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
if (*data == MAP_FAILED) {
fprintf(stderr, "mmap failed: %m\n");
close(fd);
return NULL;
}
pool = wl_shm_create_pool(shm, fd, size);
close(fd);
return pool;
}
static struct shm_pool *shm_pool_create(struct wl_shm *shm, size_t size) {
struct shm_pool *pool = new struct shm_pool;
if (!pool) return NULL;
pool->pool = make_shm_pool(shm, size, &pool->data);
if (!pool->pool) {
delete pool;
return NULL;
}
pool->size = size;
pool->used = 0;
return pool;
}
static void *shm_pool_allocate(struct shm_pool *pool, size_t size,
int *offset) {
if (pool->used + size > pool->size) return NULL;
*offset = pool->used;
pool->used += size;
return (char *)pool->data + *offset;
}
/* destroy the pool. this does not unmap the memory though */
static void shm_pool_destroy(struct shm_pool *pool) {
munmap(pool->data, pool->size);
wl_shm_pool_destroy(pool->pool);
delete pool;
}
static int stride_for_shm_surface(rect<size_t> *rect, int scale) {
return cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32,
rect->width() * scale);
}
static int data_length_for_shm_surface(rect<size_t> *rect, int scale) {
int stride;
stride = stride_for_shm_surface(rect, scale);
return stride * rect->height() * scale;
}
static cairo_surface_t *create_shm_surface_from_pool(void *none,
rect<size_t> *rectangle,
struct shm_pool *pool,
int scale) {
struct shm_surface_data *data;
uint32_t format;
cairo_surface_t *surface;
cairo_format_t cairo_format;
int stride, length, offset;
void *map;
data = new struct shm_surface_data;
if (data == NULL) return NULL;
cairo_format = CAIRO_FORMAT_ARGB32; /*or CAIRO_FORMAT_RGB16_565 who knows??*/
stride = stride_for_shm_surface(rectangle, scale);
length = data_length_for_shm_surface(rectangle, scale);
data->pool = NULL;
map = shm_pool_allocate(pool, length, &offset);
if (!map) {
delete data;
return NULL;
}
auto scaled = rectangle->size() * scale;
surface = cairo_image_surface_create_for_data(
static_cast<unsigned char *>(map), cairo_format, scaled.x(), scaled.y(),
stride);
cairo_surface_set_user_data(surface, &shm_surface_data_key, data,
shm_surface_data_destroy);
format = WL_SHM_FORMAT_ARGB8888; /*or WL_SHM_FORMAT_RGB565*/
data->buffer = wl_shm_pool_create_buffer(pool->pool, offset, scaled.x(),
scaled.y(), stride, format);
return surface;
}
void window_allocate_buffer(struct window *window) {
assert(window->shm != nullptr);
int scale = window->pending_scale;
struct shm_pool *pool;
pool = shm_pool_create(
window->shm, data_length_for_shm_surface(&window->rectangle, scale));
if (!pool) {
fprintf(stderr, "could not allocate shm pool\n");
return;
}
window->cairo_surface = create_shm_surface_from_pool(
window->shm, &window->rectangle, pool, scale);
cairo_surface_set_device_scale(window->cairo_surface, scale, scale);
if (!window->cairo_surface) {
shm_pool_destroy(pool);
return;
}
window->cr = cairo_create(window->cairo_surface);
window->layout = pango_cairo_create_layout(window->cr);
window->pango_context = pango_cairo_create_context(window->cr);
/* make sure we destroy the pool when the surface is destroyed */
struct shm_surface_data *data;
data = static_cast<struct shm_surface_data *>(cairo_surface_get_user_data(
window->cairo_surface, &shm_surface_data_key));
data->pool = pool;
}
struct window *window_create(struct wl_surface *surface, struct wl_shm *shm,
int width, int height) {
struct window *window;
window = new struct window;
window->rectangle.set_pos(vec2<size_t>::Zero());
window->rectangle.set_size(width, height);
window->scale = 0;
window->pending_scale = 1;
window->surface = surface;
window->shm = shm;
window->cairo_surface = nullptr;
window->cr = nullptr;
window->layout = nullptr;
window->pango_context = nullptr;
return window;
}
void window_free_buffer(struct window *window) {
cairo_surface_destroy(window->cairo_surface);
cairo_destroy(window->cr);
g_object_unref(window->layout);
g_object_unref(window->pango_context);
window->cairo_surface = nullptr;
window->cr = nullptr;
window->layout = nullptr;
window->pango_context = nullptr;
}
void window_destroy(struct window *window) {
window_free_buffer(window);
zwlr_layer_surface_v1_destroy(window->layer_surface);
wl_surface_attach(window->surface, nullptr, 0, 0);
wl_surface_commit(window->surface);
wl_display_roundtrip(global_display);
wl_surface_destroy(window->surface);
wl_shm_destroy(window->shm);
delete window;
}
void window_resize(struct window *window, int width, int height) {
window_free_buffer(window);
window->rectangle.set_size(width, height);
window_allocate_buffer(window);
window_layer_surface_set_size(window);
}
void window_commit_buffer(struct window *window) {
assert(window->cairo_surface != nullptr);
wl_surface_set_buffer_scale(global_window->surface,
global_window->pending_scale);
wl_surface_attach(window->surface,
get_buffer_from_cairo_surface(window->cairo_surface), 0, 0);
/* repaint all the pixels in the surface, change size to only repaint changed
* area*/
wl_surface_damage(window->surface, window->rectangle.x(),
window->rectangle.y(), window->rectangle.width(),
window->rectangle.height());
wl_surface_commit(window->surface);
}
void window_get_width_height(struct window *window, int *w, int *h) {
*w = window->rectangle.width();
*h = window->rectangle.height();
}
} // namespace conky
| 38,557
|
C++
|
.cc
| 1,048
| 31.486641
| 80
| 0.658077
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,590
|
rss.cc
|
brndnmtthws_conky/src/rss.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Please see COPYING for details
*
* Copyright (c) 2007 Toni Spets
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <assert.h>
#include <time.h>
#include <cmath>
#include <mutex>
#include "ccurl_thread.h"
#include "conky.h"
#include "logging.h"
#include "prss.h"
#include "text_object.h"
struct rss_data {
char uri[128];
char action[64];
int act_par;
float interval;
unsigned int nrspaces;
};
namespace {
class rss_cb : public curl_callback<std::shared_ptr<PRSS>> {
typedef curl_callback<std::shared_ptr<PRSS>> Base;
protected:
virtual void process_data() {
try {
std::shared_ptr<PRSS> tmp(new PRSS(data));
std::unique_lock<std::mutex> lock(Base::result_mutex);
Base::result = tmp;
} catch (std::runtime_error &e) { NORM_ERR("%s", e.what()); }
}
public:
rss_cb(uint32_t period, const std::string &uri)
: Base(period, Base::Tuple(uri)) {}
};
} // namespace
static void rss_process_info(char *p, int p_max_size, const std::string &uri,
char *action, int act_par, int interval,
unsigned int nrspaces) {
char *str;
uint32_t period = std::max(lround(interval / active_update_interval()), 1l);
auto cb = conky::register_cb<rss_cb>(period, uri);
assert(act_par >= 0 && action);
std::shared_ptr<PRSS> data = cb->get_result_copy();
if (!data || data->item_count < 1) {
*p = 0;
} else {
/*
* XXX: Refactor this so that we can retrieve any of the fields in the
* PRSS struct (in prss.h).
*/
if (strcmp(action, "feed_title") == EQUAL) {
str = data->title;
if (str && strlen(str) > 0) {
// remove trailing new line if one exists
if (str[strlen(str) - 1] == '\n') { str[strlen(str) - 1] = 0; }
snprintf(p, p_max_size, "%s", str);
}
} else if (strcmp(action, "item_title") == EQUAL) {
if (act_par < data->item_count) {
str = data->items[act_par].title;
// remove trailing new line if one exists
if (str && strlen(str) > 0) {
if (str[strlen(str) - 1] == '\n') { str[strlen(str) - 1] = 0; }
snprintf(p, p_max_size, "%s", str);
}
}
} else if (strcmp(action, "item_desc") == EQUAL) {
if (act_par < data->item_count) {
str = data->items[act_par].description;
// remove trailing new line if one exists
if (str && strlen(str) > 0) {
if (str[strlen(str) - 1] == '\n') { str[strlen(str) - 1] = 0; }
snprintf(p, p_max_size, "%s", str);
}
}
} else if (strcmp(action, "item_titles") == EQUAL) {
if (data->item_count > 0) {
int itmp;
int show;
//'tmpspaces' is a string with spaces too be placed in front of each
// title
char *tmpspaces = (char *)malloc(nrspaces + 1);
memset(tmpspaces, ' ', nrspaces);
tmpspaces[nrspaces] = 0;
if (act_par > data->item_count) {
show = data->item_count;
} else {
show = act_par;
}
for (itmp = 0; itmp < show; itmp++) {
PRSS_Item *item = &data->items[itmp];
str = item->title;
if (str) {
// don't add new line before first item
if (itmp > 0) { strncat(p, "\n", p_max_size); }
/* remove trailing new line if one exists,
* we have our own */
if (strlen(str) > 0 && str[strlen(str) - 1] == '\n') {
str[strlen(str) - 1] = 0;
}
strncat(p, tmpspaces, p_max_size);
strncat(p, str, p_max_size);
}
}
free(tmpspaces);
}
} else {
NORM_ERR("rss: Invalid action '%s'", action);
}
}
}
void rss_scan_arg(struct text_object *obj, const char *arg) {
int argc;
struct rss_data *rd;
rd = (struct rss_data *)malloc(sizeof(struct rss_data));
memset(rd, 0, sizeof(struct rss_data));
argc = sscanf(arg, "%127s %f %63s %d %u", rd->uri, &rd->interval, rd->action,
&rd->act_par, &rd->nrspaces);
if (argc < 3) {
NORM_ERR("wrong number of arguments for $rss");
free(rd);
return;
}
obj->data.opaque = rd;
}
void rss_print_info(struct text_object *obj, char *p, unsigned int p_max_size) {
struct rss_data *rd = (struct rss_data *)obj->data.opaque;
if (!rd) {
NORM_ERR("error processing RSS data");
return;
}
rss_process_info(p, p_max_size, rd->uri, rd->action, rd->act_par,
rd->interval, rd->nrspaces);
}
void rss_free_obj_info(struct text_object *obj) {
free_and_zero(obj->data.opaque);
}
| 5,381
|
C++
|
.cc
| 158
| 28.246835
| 80
| 0.590429
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
22,591
|
users.cc
|
brndnmtthws_conky/src/users.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <time.h>
#include <unistd.h>
#include <utmp.h>
#include "conky.h"
#define BUFLEN 512
static void user_name(char *ptr) {
const struct utmp *usr = 0;
setutent();
while ((usr = getutent()) != nullptr) {
if (usr->ut_type == USER_PROCESS) {
memcpy(ptr, usr->ut_name, UT_NAMESIZE);
ptr[UT_NAMESIZE] = 0;
}
}
}
static void user_num(int *ptr) {
const struct utmp *usr;
int users_num = 0;
setutent();
while ((usr = getutent()) != nullptr) {
if (usr->ut_type == USER_PROCESS) { ++users_num; }
}
*ptr = users_num;
}
static void user_term(char *ptr) {
const struct utmp *usr;
setutent();
while ((usr = getutent()) != nullptr) {
if (usr->ut_type == USER_PROCESS) {
memcpy(ptr, usr->ut_line, UT_LINESIZE);
ptr[UT_LINESIZE] = 0;
}
}
}
static void user_time(char *ptr) {
const struct utmp *usr;
time_t log_in, real, diff;
char buf[BUFLEN] = "";
setutent();
while ((usr = getutent()) != nullptr) {
if (usr->ut_type == USER_PROCESS) {
log_in = usr->ut_time;
time(&real);
diff = difftime(real, log_in);
format_seconds(buf, BUFLEN, diff);
if (strlen(ptr) + strlen(buf) + 1 <= BUFLEN) {
strncat(ptr, buf, BUFLEN - strlen(ptr) - 1);
}
}
}
}
static void tty_user_time(char *ptr, char *tty) {
time_t real, diff, log_in;
char buf[BUFLEN] = "";
struct utmp *usr, line;
setutent();
strncpy(line.ut_line, tty, UT_LINESIZE);
usr = getutline(&line);
if (usr == nullptr) { return; }
log_in = usr->ut_time;
time(&real);
diff = difftime(real, log_in);
format_seconds(buf, BUFLEN, diff);
strncpy(ptr, buf, BUFLEN - 1);
}
static void users_alloc(struct information *ptr) {
if (ptr->users.names == nullptr) {
ptr->users.names = (char *)malloc(text_buffer_size.get(*state));
}
if (ptr->users.terms == nullptr) {
ptr->users.terms = (char *)malloc(text_buffer_size.get(*state));
}
if (ptr->users.times == nullptr) {
ptr->users.times = (char *)malloc(text_buffer_size.get(*state));
}
}
static void update_user_time(char *tty) {
struct information *current_info = &info;
char temp[BUFLEN] = "";
if (current_info->users.ctime == nullptr) {
current_info->users.ctime = (char *)malloc(text_buffer_size.get(*state));
}
tty_user_time(temp, tty);
if (*temp != 0) {
free_and_zero(current_info->users.ctime);
current_info->users.ctime = (char *)malloc(text_buffer_size.get(*state));
strncpy(current_info->users.ctime, temp, text_buffer_size.get(*state));
} else {
free_and_zero(current_info->users.ctime);
current_info->users.ctime = (char *)malloc(text_buffer_size.get(*state));
strncpy(current_info->users.ctime, "broken", text_buffer_size.get(*state));
}
}
int update_users(void) {
struct information *current_info = &info;
char temp[BUFLEN] = "";
int t;
users_alloc(current_info);
user_name(temp);
if (*temp != 0) {
free_and_zero(current_info->users.names);
current_info->users.names = (char *)malloc(text_buffer_size.get(*state));
strncpy(current_info->users.names, temp, text_buffer_size.get(*state));
} else {
free_and_zero(current_info->users.names);
current_info->users.names = (char *)malloc(text_buffer_size.get(*state));
strncpy(current_info->users.names, "broken", text_buffer_size.get(*state));
}
user_num(&t);
if (t != 0) {
if (current_info->users.number) { current_info->users.number = 0; }
current_info->users.number = t;
} else {
current_info->users.number = 0;
}
temp[0] = 0;
user_term(temp);
if (*temp != 0) {
free_and_zero(current_info->users.terms);
current_info->users.terms = (char *)malloc(text_buffer_size.get(*state));
strncpy(current_info->users.terms, temp, text_buffer_size.get(*state));
} else {
free_and_zero(current_info->users.terms);
current_info->users.terms = (char *)malloc(text_buffer_size.get(*state));
strncpy(current_info->users.terms, "broken", text_buffer_size.get(*state));
}
user_time(temp);
if (*temp != 0) {
free_and_zero(current_info->users.times);
current_info->users.times = (char *)malloc(text_buffer_size.get(*state));
strncpy(current_info->users.times, temp, text_buffer_size.get(*state));
} else {
free_and_zero(current_info->users.times);
current_info->users.times = (char *)malloc(text_buffer_size.get(*state));
strncpy(current_info->users.times, "broken", text_buffer_size.get(*state));
}
return 0;
}
void print_user_names(struct text_object *obj, char *p,
unsigned int p_max_size) {
(void)obj;
snprintf(p, p_max_size, "%s", info.users.names);
}
void print_user_terms(struct text_object *obj, char *p,
unsigned int p_max_size) {
(void)obj;
snprintf(p, p_max_size, "%s", info.users.terms);
}
void print_user_times(struct text_object *obj, char *p,
unsigned int p_max_size) {
(void)obj;
snprintf(p, p_max_size, "%s", info.users.times);
}
void print_user_time(struct text_object *obj, char *p,
unsigned int p_max_size) {
update_user_time(obj->data.s);
snprintf(p, p_max_size, "%s", info.users.ctime);
}
void print_user_number(struct text_object *obj, char *p,
unsigned int p_max_size) {
(void)obj;
snprintf(p, p_max_size, "%d", info.users.number);
}
void free_user_names(struct text_object *obj) {
(void)obj;
free_and_zero(info.users.names);
}
void free_user_terms(struct text_object *obj) {
(void)obj;
free_and_zero(info.users.terms);
}
void free_user_times(struct text_object *obj) {
(void)obj;
free_and_zero(info.users.times);
}
void free_user_time(struct text_object *obj) {
free_and_zero(info.users.ctime);
free_and_zero(obj->data.s);
}
| 6,838
|
C++
|
.cc
| 207
| 29.352657
| 79
| 0.660863
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
22,592
|
gui.cc
|
brndnmtthws_conky/src/gui.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "gui.h"
#include "colour-settings.h"
#include "common.h"
#include "config.h"
#include "conky.h"
#include "logging.h"
#ifdef BUILD_X11
#include "x11-settings.h"
#endif /* BUILD_X11 */
#ifdef BUILD_WAYLAND
#include "wl.h"
#endif /* BUILD_WAYLAND */
// #ifdef BUILD_IMLIB2
// #include "conky-imlib2.h"
// #endif /* BUILD_IMLIB2 */
#ifndef OWN_WINDOW
#include <iostream>
#endif
/* workarea where window / text is aligned (from _NET_WORKAREA on X11) */
conky::absolute_rect<int> workarea;
/* Window stuff */
char window_created = 0;
/* local prototypes */
#ifdef BUILD_X11
void x11_init_window(lua::state &l, bool own);
#endif /*BUILD_X11*/
/********************* <SETTINGS> ************************/
bool out_to_gui(lua::state &l) {
bool to_gui = false;
#ifdef BUILD_X11
to_gui |= out_to_x.get(l);
#endif /* BUILD_X11 */
#ifdef BUILD_WAYLAND
to_gui |= out_to_wayland.get(l);
#endif /* BUILD_WAYLAND */
return to_gui;
}
namespace priv {
void own_window_setting::lua_setter(lua::state &l, bool init) {
lua::stack_sentry s(l, -2);
Base::lua_setter(l, init);
if (init) {
if (do_convert(l, -1).first) {
#ifndef OWN_WINDOW
std::cerr << "Support for the own_window setting has been "
"disabled during compilation\n";
l.pop();
l.pushboolean(false);
#endif
}
if (out_to_gui(l)) {
#ifdef BUILD_X11
x11_init_window(l, do_convert(l, -1).first);
#endif /*BUILD_X11*/
} else {
// own_window makes no sense when not drawing to X
l.pop();
l.pushboolean(false);
}
}
++s;
}
} // namespace priv
template <>
conky::lua_traits<alignment>::Map conky::lua_traits<alignment>::map = {
{"top_left", alignment::TOP_LEFT},
{"top_right", alignment::TOP_RIGHT},
{"top_middle", alignment::TOP_MIDDLE},
{"top", alignment::TOP_MIDDLE},
{"bottom_left", alignment::BOTTOM_LEFT},
{"bottom_right", alignment::BOTTOM_RIGHT},
{"bottom_middle", alignment::BOTTOM_MIDDLE},
{"bottom", alignment::BOTTOM_MIDDLE},
{"middle_left", alignment::MIDDLE_LEFT},
{"left", alignment::MIDDLE_LEFT},
{"middle_middle", alignment::MIDDLE_MIDDLE},
{"center", alignment::MIDDLE_MIDDLE},
{"middle_right", alignment::MIDDLE_RIGHT},
{"right", alignment::MIDDLE_RIGHT},
{"tl", alignment::TOP_LEFT},
{"tr", alignment::TOP_RIGHT},
{"tm", alignment::TOP_MIDDLE},
{"bl", alignment::BOTTOM_LEFT},
{"br", alignment::BOTTOM_RIGHT},
{"bm", alignment::BOTTOM_MIDDLE},
{"ml", alignment::MIDDLE_LEFT},
{"mm", alignment::MIDDLE_MIDDLE},
{"mr", alignment::MIDDLE_RIGHT},
{"none", alignment::NONE}};
#ifdef OWN_WINDOW
template <>
conky::lua_traits<window_type>::Map conky::lua_traits<window_type>::map = {
{"normal", window_type::NORMAL}, {"dock", window_type::DOCK},
{"panel", window_type::PANEL}, {"desktop", window_type::DESKTOP},
{"utility", window_type::UTILITY}, {"override", window_type::OVERRIDE}};
template <>
conky::lua_traits<window_hints>::Map conky::lua_traits<window_hints>::map = {
{"undecorated", window_hints::UNDECORATED},
{"below", window_hints::BELOW},
{"above", window_hints::ABOVE},
{"sticky", window_hints::STICKY},
{"skip_taskbar", window_hints::SKIP_TASKBAR},
{"skip_pager", window_hints::SKIP_PAGER}};
std::pair<uint16_t, bool> window_hints_traits::convert(
lua::state &l, int index, const std::string &name) {
lua::stack_sentry s(l);
l.checkstack(1);
std::string hints = l.tostring(index);
// add a sentinel to simplify the following loop
hints += ',';
size_t pos = 0;
size_t newpos;
uint16_t ret = 0;
while ((newpos = hints.find_first_of(", ", pos)) != std::string::npos) {
if (newpos > pos) {
l.pushstring(hints.substr(pos, newpos - pos));
auto t = conky::lua_traits<window_hints>::convert(l, -1, name);
if (!t.second) { return {0, false}; }
SET_HINT(ret, t.first);
l.pop();
}
pos = newpos + 1;
}
return {ret, true};
}
#endif
#ifdef OWN_WINDOW
namespace {
// used to set the default value for own_window_title
std::string gethostnamecxx() {
update_uname();
return info.uname_s.nodename;
}
} // namespace
#endif /* OWN_WINDOW */
/*
* The order of these settings cannot be completely arbitrary. Some of them
* depend on others, and the setters are called in the order in which they are
* defined. The order should be: x11_display_name -> out_to_x -> everything
* colour related -> border_*, own_window_*, etc -> own_window -> double_buffer
* -> imlib_cache_size.
*
* The settings order can be modified with the settings_ordering vector in
* setting.cc.
*/
conky::simple_config_setting<alignment> text_alignment("alignment",
alignment::BOTTOM_LEFT,
false);
priv::colour_setting default_shade_color("default_shade_color", black_argb32);
priv::colour_setting default_outline_color("default_outline_color",
black_argb32);
conky::range_config_setting<int> border_inner_margin(
"border_inner_margin", 0, std::numeric_limits<int>::max(), 3, true);
conky::range_config_setting<int> border_outer_margin(
"border_outer_margin", 0, std::numeric_limits<int>::max(), 1, true);
conky::range_config_setting<int> border_width("border_width", 0,
std::numeric_limits<int>::max(),
1, true);
#ifdef OWN_WINDOW
conky::simple_config_setting<std::string> own_window_title(
"own_window_title", PACKAGE_NAME " (" + gethostnamecxx() + ")", false);
conky::simple_config_setting<window_type> own_window_type("own_window_type",
window_type::NORMAL,
false);
conky::simple_config_setting<std::string> own_window_class("own_window_class",
PACKAGE_NAME, false);
#endif /* OWN_WINDOW */
#if defined(OWN_WINDOW) && defined(BUILD_X11)
conky::simple_config_setting<uint16_t, window_hints_traits> own_window_hints(
"own_window_hints", 0, false);
#endif /* OWN_WINDOW && BUILD_X11 */
#if defined(OWN_WINDOW) || defined(BUILD_WAYLAND)
priv::colour_setting background_colour("own_window_colour", 0);
conky::simple_config_setting<bool> set_transparent("own_window_transparent",
false, false);
#endif /* OWN_WINDOW || BUILD_WAYLAND */
#if defined(BUILD_ARGB) || defined(BUILD_WAYLAND)
conky::simple_config_setting<bool> use_argb_visual("own_window_argb_visual",
false, false);
conky::range_config_setting<int> own_window_argb_value("own_window_argb_value",
0, 255, 255, false);
#endif /* BUILD_ARGB || BUILD_WAYLAND */
priv::own_window_setting own_window;
/******************** </SETTINGS> ************************/
| 8,123
|
C++
|
.cc
| 212
| 32.787736
| 80
| 0.6325
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,593
|
main.cc
|
brndnmtthws_conky/src/main.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <getopt.h>
#include <cstdio>
#include <iostream>
#include "build.h"
#include "config.h"
#include "conky.h"
#include "display-output.hh"
#include "lua-config.hh"
#ifdef BUILD_X11
#include "x11.h"
#endif /* BUILD_X11 */
#ifdef BUILD_CURL
#include "ccurl_thread.h"
#endif /* BUILD_CURL */
#if defined(__linux__)
#include "linux.h"
#endif /* Linux */
#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
#include "freebsd.h"
#endif /* FreeBSD */
#ifdef BUILD_BUILTIN_CONFIG
#include "defconfig.h"
#ifdef BUILD_OLD_CONFIG
#include "convertconf.h"
#endif /* BUILD_OLD_CONFIG */
#endif /* BUILD_BUILTIN_CONFIG */
static void print_short_version() { std::cout << VERSION << std::endl; }
static void print_version() {
std::cout << _(PACKAGE_NAME " " VERSION " compiled for " BUILD_ARCH
"\n"
"\nCompiled in features:\n\n"
"System config file: " SYSTEM_CONFIG_FILE
"\n"
"Package library path: " PACKAGE_LIBDIR "\n\n")
<< _("\n General:\n")
#ifdef HAVE_OPENMP
<< _(" * OpenMP\n")
#endif /* HAVE_OPENMP */
#ifdef BUILD_MATH
<< _(" * math\n")
#endif /* BUILD_MATH */
#ifdef BUILD_HDDTEMP
<< _(" * hddtemp\n")
#endif /* BUILD_HDDTEMP */
#ifdef BUILD_PORT_MONITORS
<< _(" * portmon\n")
#endif /* BUILD_PORT_MONITORS */
#ifdef BUILD_HTTP
<< _(" * HTTP\n")
#endif /* BUILD_HTTP */
#ifdef BUILD_IPV6
<< _(" * IPv6\n")
#endif /* BUILD_IPV6 */
#ifdef BUILD_IRC
<< _(" * IRC\n")
#endif
#ifdef BUILD_CURL
<< _(" * Curl\n")
#endif /* BUILD_CURL */
#ifdef BUILD_RSS
<< _(" * RSS\n")
#endif /* BUILD_RSS */
#ifdef BUILD_ICAL
<< _(" * ICal\n")
#endif /* BUILD_ICAL */
#ifdef BUILD_ICONV
<< _(" * iconv\n")
#endif /* BUILD_ICONV */
#ifdef BUILD_MYSQL
<< _(" * MySQL\n")
#endif /* BUILD_MYSQL */
#ifdef BUILD_WLAN
<< _(" * wireless\n")
#endif /* BUILD_WLAN */
#ifdef BUILD_IBM
<< _(" * support for IBM/Lenovo notebooks\n")
#endif /* BUILD_IBM */
#ifdef BUILD_NVIDIA
<< _(" * nvidia\n")
#endif /* BUILD_NVIDIA */
#ifdef BUILD_BUILTIN_CONFIG
<< _(" * builtin default configuration\n")
#endif /* BUILD_BUILTIN_CONFIG */
#ifdef BUILD_OLD_CONFIG
<< _(" * old configuration syntax\n")
#endif /* BUILD_OLD_CONFIG */
#ifdef BUILD_IMLIB2
<< _(" * Imlib2\n")
#endif /* BUILD_IMLIB2 */
#ifdef HAVE_SOME_SOUNDCARD_H
<< _(" * OSS mixer support\n")
#endif /* HAVE_SOME_SOUNDCARD_H */
#ifdef BUILD_MIXER_ALSA
<< _(" * ALSA mixer support\n")
#endif /* BUILD_MIXER_ALSA */
#ifdef BUILD_APCUPSD
<< _(" * apcupsd\n")
#endif /* BUILD_APCUPSD */
#ifdef BUILD_IOSTATS
<< _(" * iostats\n")
#endif /* BUILD_IOSTATS */
#ifdef BUILD_NCURSES
<< _(" * ncurses\n")
#endif /* BUILD_NCURSES */
#ifdef BUILD_I18N
<< _(" * Internationalization support\n")
#endif
#ifdef BUILD_PULSEAUDIO
<< _(" * PulseAudio\n")
#endif /* BUIL_PULSEAUDIO */
#ifdef DEBUG
<< _(" * Debugging extensions\n")
#endif
#if defined BUILD_LUA_CAIRO || defined BUILD_LUA_IMLIB2 || BUILD_LUA_RSVG
<< _("\n Lua bindings:\n")
#endif
#ifdef BUILD_LUA_CAIRO
<< _(" * Cairo\n")
#endif /* BUILD_LUA_CAIRO */
#ifdef BUILD_LUA_IMLIB2
<< _(" * Imlib2\n")
#endif /* BUILD_LUA_IMLIB2 */
#ifdef BUILD_LUA_RSVG
<< _(" * RSVG\n")
#endif /* BUILD_LUA_RSVG */
#ifdef BUILD_X11
<< _(" X11:\n")
#ifdef BUILD_XDAMAGE
<< _(" * Xdamage extension\n")
#endif /* BUILD_XDAMAGE */
#ifdef BUILD_XINERAMA
<< _(" * Xinerama extension (virtual display)\n")
#endif /* BUILD_XINERAMA */
#ifdef BUILD_XSHAPE
<< _(" * Xshape extension (click through)\n")
#endif /* BUILD_XSHAPE */
#ifdef BUILD_XDBE
<< _(" * XDBE (double buffer extension)\n")
#endif /* BUILD_XDBE */
#ifdef BUILD_XFT
<< _(" * Xft\n")
#endif /* BUILD_XFT */
#ifdef BUILD_XINPUT
<< _(" * Xinput\n")
#endif /* BUILD_XINPUT */
#ifdef BUILD_ARGB
<< _(" * ARGB visual\n")
#endif /* BUILD_ARGB */
#ifdef OWN_WINDOW
<< _(" * Own window\n")
#endif
#ifdef BUILD_MOUSE_EVENTS
<< _(" * Mouse events\n")
#endif /* BUILD_MOUSE_EVENTS */
#endif /* BUILD_X11 */
#ifdef BUILD_WAYLAND
<< _(" Wayland:\n")
#ifdef BUILD_ARGB
<< _(" * ARGB visual\n")
#endif /* BUILD_ARGB */
#ifdef BUILD_MOUSE_EVENTS
<< _(" * Mouse events\n")
#endif /* BUILD_MOUSE_EVENTS */
#endif /* BUILD_WAYLAND */
#if defined BUILD_AUDACIOUS || defined BUILD_CMUS || defined BUILD_MPD || \
defined BUILD_MOC || defined BUILD_XMMS2
<< _("\n Music detection:\n")
#endif
#ifdef BUILD_AUDACIOUS
<< _(" * Audacious\n")
#endif /* BUILD_AUDACIOUS */
#ifdef BUILD_CMUS
<< _(" * CMUS\n")
#endif /* BUILD_CMUS */
#ifdef BUILD_MPD
<< _(" * MPD\n")
#endif /* BUILD_MPD */
#ifdef BUILD_MOC
<< _(" * MOC\n")
#endif /* BUILD_MOC */
#ifdef BUILD_XMMS2
<< _(" * XMMS2\n")
#endif /* BUILD_XMMS2 */
<< _("\n Default values:\n") << " * Netdevice: " DEFAULTNETDEV "\n"
<< " * Local configfile: " CONFIG_FILE "\n"
#ifdef BUILD_I18N
<< " * Localedir: " LOCALE_DIR "\n"
#endif /* BUILD_I18N */
#ifdef BUILD_HTTP
<< " * HTTP-port: " << HTTPPORT << "\n"
#endif /* BUILD_HTTP */
<< " * Maximum netdevices: " << MAX_NET_INTERFACES << "\n"
<< " * Maximum text size: " << MAX_USER_TEXT_DEFAULT << "\n"
<< " * Size text buffer: " << DEFAULT_TEXT_BUFFER_SIZE << "\n";
}
static void print_help(const char *prog_name) {
printf("Usage: %s [OPTION]...\n" PACKAGE_NAME
" is a system monitor that renders text on desktop or to own "
"transparent\n"
"window. Command line options will override configurations defined in "
"config\n"
"file.\n"
" -v, --version version with build details\n"
" -V, --short-version short version\n"
" -q, --quiet quiet mode\n"
" -D, --debug increase debugging output, ie. -DD for "
"more debugging\n"
" -c, --config=FILE config file to load\n"
#ifdef BUILD_BUILTIN_CONFIG
" -C, --print-config print the builtin default config to "
"stdout\n"
" e.g. 'conky -C > ~/.conkyrc' will "
"create a new default config\n"
#endif
" -d, --daemonize daemonize, fork to background\n"
" -h, --help help\n"
#ifdef BUILD_X11
" -a, --alignment=ALIGNMENT text alignment on screen, "
"{top,bottom,middle}_{left,right,middle}\n"
" -X, --display=DISPLAY X11 display to use\n"
" -m, --xinerama-head=N Xinerama monitor index (0=first)\n"
" -f, --font=FONT font to use\n"
#ifdef OWN_WINDOW
" -o, --own-window create own window to draw\n"
#endif
" -b, --double-buffer double buffer (prevents flickering)\n"
" -w, --window-id=WIN_ID window id to draw\n"
" -x X x position\n"
" -y Y y position\n"
#endif /* BUILD_X11 */
" -t, --text=TEXT text to render, remember single quotes, "
"like -t '$uptime'\n"
" -u, --interval=SECS update interval\n"
" -i COUNT number of times to update " PACKAGE_NAME
" (and quit)\n"
" -p, --pause=SECS pause for SECS seconds at startup "
"before doing anything\n"
#if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
" -U, --unique only one conky process can be created\n"
#endif /* Linux || FreeBSD */
, prog_name);
}
inline void reset_optind() {
#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || \
defined(__OpenBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
optind = optreset = 1;
#else
optind = 0;
#endif
}
int main(int argc, char **argv) {
#ifdef BUILD_I18N
setlocale(LC_ALL, "");
bindtextdomain(PACKAGE_NAME, LOCALE_DIR);
textdomain(PACKAGE_NAME);
#endif
argc_copy = argc;
argv_copy = argv;
g_sigterm_pending = 0;
g_sighup_pending = 0;
g_sigusr2_pending = 0;
bool unique_process = false;
#ifdef BUILD_CURL
struct curl_global_initializer {
curl_global_initializer() {
if (curl_global_init(CURL_GLOBAL_ALL)) {
NORM_ERR(
"curl_global_init() failed, you may not be able to use curl "
"variables");
}
}
~curl_global_initializer() { curl_global_cleanup(); }
};
curl_global_initializer curl_global;
#endif
/* handle command line parameters that don't change configs */
#ifdef BUILD_X11
if (!setlocale(LC_CTYPE, "")) {
NORM_ERR("Can't set the specified locale!\nCheck LANG, LC_CTYPE, LC_ALL.");
}
#endif /* BUILD_X11 */
while (1) {
int c = getopt_long(argc, argv, getopt_string, longopts, nullptr);
if (c == -1) { break; }
switch (c) {
case 'D':
global_debug_level++;
break;
case 'v':
print_version();
return EXIT_SUCCESS;
case 'V':
print_short_version();
return EXIT_SUCCESS;
case 'c':
current_config = optarg;
break;
case 'q':
if (freopen("/dev/null", "w", stderr) == nullptr) {
CRIT_ERR("could not open /dev/null as stderr!");
}
break;
case 'h':
print_help(argv[0]);
return 0;
#ifdef BUILD_BUILTIN_CONFIG
case 'C':
std::cout << defconfig;
return 0;
#endif
#ifdef BUILD_X11
case 'w':
window.window = strtol(optarg, nullptr, 0);
break;
#endif /* BUILD_X11 */
#if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
case 'U':
unique_process = true;
break;
#endif /* Linux || FreeBSD */
case '?':
return EXIT_FAILURE;
}
}
#if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
if (unique_process && is_conky_already_running()) {
NORM_ERR("already running");
return 0;
}
#endif /* Linux || FreeBSD */
try {
set_current_config();
state = std::make_unique<lua::state>();
conky::export_symbols(*state);
setup_inotify();
initialisation(argc, argv);
first_pass = 0; /* don't ever call fork() again */
main_loop();
} catch (fork_throw &e) {
return EXIT_SUCCESS;
} catch (unknown_arg_throw &e) {
return EXIT_FAILURE;
} catch (obj_create_error &e) {
std::cerr << e.what() << std::endl;
clean_up();
return EXIT_FAILURE;
} catch (std::exception &e) {
std::cerr << PACKAGE_NAME ": " << e.what() << std::endl;
return EXIT_FAILURE;
}
conky::shutdown_display_outputs();
#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
kvm_close(kd);
#endif
#ifdef LEAKFREE_NCURSES
_nc_free_and_exit(0); // hide false memleaks
#endif
return 0;
}
| 12,368
|
C++
|
.cc
| 386
| 26.748705
| 80
| 0.568142
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,594
|
dragonfly.cc
|
brndnmtthws_conky/src/dragonfly.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2011 Andrea Magliano <masterblaster@tiscali.it>
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "config.h"
#include <kinfo_pcpu.h>
#include <sys/ioctl.h>
#include <sys/param.h>
#include <sys/resource.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/sysctl.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/user.h>
#include <net/if.h>
#include <net/if_media.h>
#include <net/if_mib.h>
#include <net/if_var.h>
#include <devstat.h>
#include <ifaddrs.h>
#include <limits.h>
#include <pthread.h>
#include <unistd.h>
#include <dev/acpica/acpiio.h>
#include "conky.h"
#include "diskio.h"
#include "dragonfly.h"
#include "logging.h"
#include "net_stat.h"
#include "top.h"
#define GETSYSCTL(name, var) getsysctl(name, &(var), sizeof(var))
#define KELVTOC(x) ((x - 2732) / 10.0)
#define MAXSHOWDEVS 16
static short cpu_setup = 0;
static int getsysctl(const char *name, void *ptr, size_t len) {
size_t nlen = len;
if (sysctlbyname(name, ptr, &nlen, nullptr, 0) == -1) {
fprintf(stderr, "getsysctl(): %s failed '%s'\n", name, strerror(errno));
return -1;
}
if (nlen != len && errno == ENOMEM) {
fprintf(stderr, "getsysctl(): %s failed %zu != %zu\n", name, nlen, len);
return -1;
}
return 0;
}
static int swapmode(unsigned long *retavail, unsigned long *retfree) {
int total, used;
size_t len = sizeof(int);
if (sysctlbyname("vm.swap_size", &total, &len, nullptr, 0) == -1)
perror("vm_swap_usage(): vm.swap_size");
else if (sysctlbyname("vm.swap_anon_use", &used, &len, nullptr, 0) == -1)
perror("vm_swap_usage(): vm.swap_anon_use");
else {
int size = getpagesize();
#define CONVERT(v) ((quad_t)(v) * (size / 1024))
*retavail = CONVERT(total);
*retfree = CONVERT(total - used);
return (int)((double)used * 100.0 / (double)total);
}
return 0;
}
void prepare_update(void) {}
int update_uptime(void) {
int mib[2] = {CTL_KERN, KERN_BOOTTIME};
struct timeval boottime;
time_t now;
size_t size = sizeof(boottime);
if ((sysctl(mib, 2, &boottime, &size, nullptr, 0) != -1) && boottime.tv_sec) {
time(&now);
info.uptime = now - boottime.tv_sec;
} else {
fprintf(stderr, "Could not get uptime\n");
info.uptime = 0;
}
return 0;
}
int check_mount(char *s) {
struct statfs *mntbuf;
int i, mntsize;
mntsize = getmntinfo(&mntbuf, MNT_NOWAIT);
for (i = mntsize - 1; i >= 0; i--) {
if (strcmp(mntbuf[i].f_mntonname, s) == 0) { return 1; }
}
return 0;
}
int update_meminfo(void) {
u_int total_pages, inactive_pages, free_pages;
unsigned long swap_avail, swap_free;
int pagesize = getpagesize();
if (GETSYSCTL("vm.stats.vm.v_page_count", total_pages)) {
fprintf(stderr, "Cannot read sysctl \"vm.stats.vm.v_page_count\"\n");
}
if (GETSYSCTL("vm.stats.vm.v_free_count", free_pages)) {
fprintf(stderr, "Cannot read sysctl \"vm.stats.vm.v_free_count\"\n");
}
if (GETSYSCTL("vm.stats.vm.v_inactive_count", inactive_pages)) {
fprintf(stderr, "Cannot read sysctl \"vm.stats.vm.v_inactive_count\"\n");
}
info.memmax = total_pages * (pagesize >> 10);
info.mem = (total_pages - free_pages - inactive_pages) * (pagesize >> 10);
info.memeasyfree = info.memfree = info.memmax - info.mem;
info.legacymem = info.mem;
if ((swapmode(&swap_avail, &swap_free)) >= 0) {
info.swapmax = swap_avail;
info.swap = (swap_avail - swap_free);
info.swapfree = swap_free;
} else {
info.swapmax = 0;
info.swap = 0;
info.swapfree = 0;
}
return 0;
}
int update_net_stats(void) {
struct net_stat *ns;
double delta;
long long r, t, last_recv, last_trans;
struct ifaddrs *ifap, *ifa;
struct if_data *ifd;
/* get delta */
delta = current_update_time - last_update_time;
if (delta <= 0.0001) { return 0; }
if (getifaddrs(&ifap) < 0) { return 0; }
for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
ns = get_net_stat((const char *)ifa->ifa_name, nullptr, NULL);
if (ifa->ifa_flags & IFF_UP) {
struct ifaddrs *iftmp;
ns->up = 1;
last_recv = ns->recv;
last_trans = ns->trans;
if (ifa->ifa_addr->sa_family != AF_LINK) { continue; }
for (iftmp = ifa->ifa_next;
iftmp != nullptr && strcmp(ifa->ifa_name, iftmp->ifa_name) == 0;
iftmp = iftmp->ifa_next) {
if (iftmp->ifa_addr->sa_family == AF_INET) {
memcpy(&(ns->addr), iftmp->ifa_addr, iftmp->ifa_addr->sa_len);
}
}
ifd = (struct if_data *)ifa->ifa_data;
r = ifd->ifi_ibytes;
t = ifd->ifi_obytes;
if (r < ns->last_read_recv) {
ns->recv += ((long long)4294967295U - ns->last_read_recv) + r;
} else {
ns->recv += (r - ns->last_read_recv);
}
ns->last_read_recv = r;
if (t < ns->last_read_trans) {
ns->trans += ((long long)4294967295U - ns->last_read_trans) + t;
} else {
ns->trans += (t - ns->last_read_trans);
}
ns->last_read_trans = t;
/* calculate speeds */
ns->recv_speed = (ns->recv - last_recv) / delta;
ns->trans_speed = (ns->trans - last_trans) / delta;
} else {
ns->up = 0;
}
}
freeifaddrs(ifap);
return 0;
}
static int kern_proc_all_n() {
size_t len = 0;
if (sysctlbyname("kern.proc.all_lwp", nullptr, &len, NULL, 0) == -1) {
perror("kern.proc.all_lwp");
return -1;
}
if (len % sizeof(struct kinfo_proc)) {
fprintf(stderr,
"kern_proc(): "
"len %% sizeof(struct kinfo_proc) != 0");
return -1;
}
return len / sizeof(struct kinfo_proc);
}
static struct kinfo_proc *kern_proc_all(size_t proc_n) {
if (proc_n > 0) {
size_t len = proc_n * sizeof(struct kinfo_proc);
struct kinfo_proc *kp = (struct kinfo_proc *)malloc(len);
if (kp) {
if (sysctlbyname("kern.proc.all_lwp", kp, &len, nullptr, 0) == -1)
perror("kern_proc(): kern.proc.all_lwp");
else
return kp;
free(kp);
} else
perror("malloc");
}
return nullptr;
}
void get_cpu_count(void) {
int cpu_count = 0;
if (GETSYSCTL("hw.ncpu", cpu_count) == 0) {
info.cpu_count = cpu_count;
} else {
fprintf(stderr, "Cannot get hw.ncpu\n");
info.cpu_count = 0;
}
info.cpu_usage = (float *)malloc((info.cpu_count + 1) * sizeof(float));
if (info.cpu_usage == nullptr) { CRIT_ERR("malloc"); }
}
struct cpu_info {
long oldtotal;
long oldused;
};
PCPU_STATISTICS_FUNC(cputime, struct kinfo_cputime, uint64_t);
static void stat_cpu(struct cpu_info *cpu, struct kinfo_cputime *percpu,
float *usage) {
long int used = (percpu->cp_user + percpu->cp_nice + percpu->cp_sys +
percpu->cp_intr),
total = used + percpu->cp_idle;
*usage = (total - cpu->oldtotal) && cpu->oldtotal
? ((float)(used - cpu->oldused)) / (total - cpu->oldtotal)
: 0;
cpu->oldused = used;
cpu->oldtotal = total;
}
int update_cpu_usage(void) {
static struct cpu_info *cpu = nullptr;
extern void *global_cpu;
/* add check for !info.cpu_usage since that mem is freed on a SIGUSR1 */
if ((cpu_setup == 0) || (!info.cpu_usage)) {
get_cpu_count();
cpu_setup = 1;
}
if (!global_cpu) {
if (!cpu)
cpu = (struct cpu_info *)calloc(sizeof(struct cpu_info),
info.cpu_count + 1);
global_cpu = cpu;
}
{
size_t percpu_n = info.cpu_count * sizeof(struct kinfo_cputime);
struct kinfo_cputime *percpu = (struct kinfo_cputime *)malloc(
info.cpu_count * sizeof(struct kinfo_cputime));
if (percpu) {
if (sysctlbyname("kern.cputime", percpu, &percpu_n, nullptr, 0) == -1 &&
errno != ENOMEM) {
printf("update_cpu_usage(): with %d cpu(s) ", info.cpu_count);
perror("kern.cputime");
} else {
struct kinfo_cputime total;
cputime_pcpu_statistics(&percpu[0], &total, info.cpu_count);
{
int i;
for (i = 0; i < info.cpu_count; i++)
stat_cpu(&cpu[i + 1], &percpu[i], &info.cpu_usage[i + 1]);
}
stat_cpu(&cpu[0], &total, &info.cpu_usage[0]);
}
free(percpu);
}
}
return 0;
}
void free_cpu(struct text_object *) { /* no-op */
}
int update_load_average(void) {
double v[3];
getloadavg(v, 3);
info.loadavg[0] = (double)v[0];
info.loadavg[1] = (double)v[1];
info.loadavg[2] = (double)v[2];
return 0;
}
double get_acpi_temperature(int fd) {
int temp;
(void)fd;
if (GETSYSCTL("hw.acpi.thermal.tz0.temperature", temp)) {
fprintf(stderr, "Cannot read sysctl \"hw.acpi.thermal.tz0.temperature\"\n");
return 0.0;
}
return KELVTOC(temp);
}
static void get_battery_stats(int *battime, int *batcapacity, int *batstate,
int *ac) {
if (battime && GETSYSCTL("hw.acpi.battery.time", *battime)) {
fprintf(stderr, "Cannot read sysctl \"hw.acpi.battery.time\"\n");
}
if (batcapacity && GETSYSCTL("hw.acpi.battery.life", *batcapacity)) {
fprintf(stderr, "Cannot read sysctl \"hw.acpi.battery.life\"\n");
}
if (batstate && GETSYSCTL("hw.acpi.battery.state", *batstate)) {
fprintf(stderr, "Cannot read sysctl \"hw.acpi.battery.state\"\n");
}
if (ac && GETSYSCTL("hw.acpi.acline", *ac)) {
fprintf(stderr, "Cannot read sysctl \"hw.acpi.acline\"\n");
}
}
void get_battery_stuff(char *buf, unsigned int n, const char *bat, int item) {
int battime, batcapacity, batstate, ac;
(void)bat;
get_battery_stats(&battime, &batcapacity, &batstate, &ac);
if (batstate != 1 && batstate != 2 && batstate != 0 && batstate != 7)
fprintf(stderr, "Unknown battery state %d!\n", batstate);
else if (batstate != 1 && ac == 0)
fprintf(stderr, "Battery charging while not on AC!\n");
else if (batstate == 1 && ac == 1)
fprintf(stderr, "Battery discharing while on AC!\n");
switch (item) {
case BATTERY_TIME:
if (batstate == 1 && battime != -1)
snprintf(buf, n, "%d:%2.2d", battime / 60, battime % 60);
break;
case BATTERY_STATUS:
if (batstate == 1) // Discharging
snprintf(buf, n, "remaining %d%%", batcapacity);
else
snprintf(buf, n,
batstate == 2
? "charging (%d%%)"
: (batstate == 7 ? "absent/on AC" : "charged (%d%%)"),
batcapacity);
break;
default:
fprintf(stderr, "Unknown requested battery stat %d\n", item);
}
}
static int check_bat(const char *bat) {
int batnum, numbatts;
char *endptr;
if (GETSYSCTL("hw.acpi.battery.units", numbatts)) {
fprintf(stderr, "Cannot read sysctl \"hw.acpi.battery.units\"\n");
return -1;
}
if (numbatts <= 0) {
fprintf(stderr, "No battery unit detected\n");
return -1;
}
if (!bat || (batnum = strtol(bat, &endptr, 10)) < 0 || bat == endptr ||
batnum > numbatts) {
fprintf(stderr, "Wrong battery unit %s requested\n", bat ? bat : "");
return -1;
}
return batnum;
}
int get_battery_perct(const char *bat) {
union acpi_battery_ioctl_arg battio;
int batnum, acpifd;
int designcap, lastfulcap, batperct;
if ((battio.unit = batnum = check_bat(bat)) < 0) return 0;
if ((acpifd = open("/dev/acpi", O_RDONLY)) < 0) {
fprintf(stderr, "Can't open ACPI device\n");
return 0;
}
if (ioctl(acpifd, ACPIIO_BATT_GET_BIF, &battio) == -1) {
fprintf(stderr, "Unable to get info for battery unit %d\n", batnum);
return 0;
}
close(acpifd);
designcap = battio.bif.dcap;
lastfulcap = battio.bif.lfcap;
batperct = (designcap > 0 && lastfulcap > 0)
? (((float)lastfulcap / designcap) * 100)
: 0;
return batperct > 100 ? 100 : batperct;
}
double get_battery_perct_bar(struct text_object *obj) {
int batperct = get_battery_perct(obj->data.s);
return batperct * 2.56 - 1;
}
int open_acpi_temperature(const char *name) {
(void)name;
/* Not applicable for FreeBSD. */
return 0;
}
void get_acpi_ac_adapter(char *p_client_buffer, size_t client_buffer_size,
const char *adapter) {
int state;
(void)adapter; // only linux uses this
if (!p_client_buffer || client_buffer_size <= 0) { return; }
if (GETSYSCTL("hw.acpi.acline", state)) {
fprintf(stderr, "Cannot read sysctl \"hw.acpi.acline\"\n");
return;
}
if (state) {
strncpy(p_client_buffer, "Running on AC Power", client_buffer_size);
} else {
strncpy(p_client_buffer, "Running on battery", client_buffer_size);
}
}
void get_acpi_fan(char *p_client_buffer, size_t client_buffer_size) {
/* not implemented */
if (p_client_buffer && client_buffer_size > 0) {
memset(p_client_buffer, 0, client_buffer_size);
}
}
/* void */
char get_freq(char *p_client_buffer, size_t client_buffer_size,
const char *p_format, int divisor, unsigned int cpu) {
int64_t freq;
if (p_client_buffer && client_buffer_size > 0 && p_format && divisor > 0) {
if (GETSYSCTL("hw.tsc_frequency", freq) == 0) {
snprintf(p_client_buffer, client_buffer_size, p_format,
(float)freq / (divisor * 1000000));
} else {
snprintf(p_client_buffer, client_buffer_size, p_format, 0.0f);
}
return 1;
}
return 0;
}
#if 0
void update_wifi_stats(void)
{
struct ifreq ifr; /* interface stats */
struct wi_req wireq;
struct net_stat *ns;
struct ifaddrs *ifap, *ifa;
struct ifmediareq ifmr;
int s;
/* Get iface table */
if (getifaddrs(&ifap) < 0) {
return;
}
for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
ns = get_net_stat((const char *) ifa->ifa_name, nullptr, NULL);
s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
/* Get media type */
bzero(&ifmr, sizeof(ifmr));
strlcpy(ifmr.ifm_name, ifa->ifa_name, IFNAMSIZ);
if (ioctl(s, SIOCGIFMEDIA, (caddr_t) &ifmr) < 0) {
close(s);
return;
}
/* We can monitor only wireless interfaces
* which are not in hostap mode */
if ((ifmr.ifm_active & IFM_IEEE80211)
&& !(ifmr.ifm_active & IFM_IEEE80211_HOSTAP)) {
/* Get wi status */
bzero(&ifr, sizeof(ifr));
strlcpy(ifr.ifr_name, ifa->ifa_name, IFNAMSIZ);
wireq.wi_type = WI_RID_COMMS_QUALITY;
wireq.wi_len = WI_MAX_DATALEN;
ifr.ifr_data = (void *) &wireq;
if (ioctl(s, SIOCGWAVELAN, (caddr_t) &ifr) < 0) {
perror("ioctl (getting wi status)");
exit(1);
}
/* wi_val[0] = quality
* wi_val[1] = signal
* wi_val[2] = noise */
ns->linkstatus = (int) wireq.wi_val[1];
}
cleanup:
close(s);
}
}
#endif
int update_diskio(void) {
int devs_count, num_selected, num_selections, dn;
struct device_selection *dev_select = nullptr;
long select_generation;
static struct statinfo statinfo_cur;
char device_name[DEFAULT_TEXT_BUFFER_SIZE];
struct diskio_stat *cur;
unsigned int reads, writes;
unsigned int total_reads = 0, total_writes = 0;
memset(&statinfo_cur, 0, sizeof(statinfo_cur));
statinfo_cur.dinfo = (struct devinfo *)calloc(1, sizeof(struct devinfo));
stats.current = stats.current_read = stats.current_write = 0;
if (getdevs(&statinfo_cur) < 0) {
free(statinfo_cur.dinfo);
return 0;
}
devs_count = statinfo_cur.dinfo->numdevs;
if (selectdevs(&dev_select, &num_selected, &num_selections,
&select_generation, statinfo_cur.dinfo->generation,
statinfo_cur.dinfo->devices, devs_count, nullptr, 0, NULL, 0,
DS_SELECT_ONLY, MAXSHOWDEVS, 1) >= 0) {
for (dn = 0; dn < devs_count; dn++) {
int di;
struct devstat *dev;
di = dev_select[dn].position;
dev = &statinfo_cur.dinfo->devices[di];
snprintf(device_name, DEFAULT_TEXT_BUFFER_SIZE, "%s%d",
dev_select[dn].device_name, dev_select[dn].unit_number);
total_reads += (reads = dev->bytes_read / 512);
total_writes += (writes = dev->bytes_written / 512);
for (cur = stats.next; cur; cur = cur->next) {
if (cur->dev && !strcmp(device_name, cur->dev)) {
update_diskio_values(cur, reads, writes);
break;
}
}
}
update_diskio_values(&stats, total_reads, total_writes);
free(dev_select);
}
free(statinfo_cur.dinfo);
return 0;
}
static int proc_rusage(struct kinfo_proc *p) {
struct kinfo_lwp *lwp = &p->kp_lwp;
struct rusage *cru = &p->kp_cru;
return (lwp->kl_uticks + lwp->kl_sticks + lwp->kl_iticks) +
(cru->ru_stime.tv_sec + cru->ru_utime.tv_sec) * 1000000;
}
static void proc_count(struct kinfo_proc *kp, size_t proc_n) {
size_t i, act = 0, run = 0;
for (i = 0; i < proc_n; i++) {
struct kinfo_proc *p = &kp[i];
if (!(p->kp_flags & P_SYSTEM)) {
struct kinfo_lwp *lwp = &p->kp_lwp;
if (!lwp->kl_tid) act++;
if (lwp->kl_stat == LSRUN) run++;
}
}
info.procs = act;
info.run_procs = run;
}
static void proc_fill(struct kinfo_proc *kp, size_t proc_n) {
size_t i, f = getpagesize();
static long prev_ticks = 0; /* safe as long as in same thread */
for (i = 0; i < proc_n; i++) {
struct kinfo_proc *p = &kp[i];
struct kinfo_lwp *lwp = &p->kp_lwp;
if (!(p->kp_flags & P_SYSTEM) && p->kp_comm &&
*p->kp_comm && /* just to be sure */
!lwp->kl_tid) { /* 'main' lwp, the real process (observed) */
struct process *my = get_process(p->kp_pid);
long ticks = proc_rusage(p);
my->time_stamp = g_time;
free_and_zero(my->name);
my->name = strdup(p->kp_comm);
my->amount = 100.0 * lwp->kl_pctcpu / FSCALE;
my->vsize = p->kp_vm_map_size;
my->rss = p->kp_vm_rssize * f;
my->total_cpu_time = ticks - prev_ticks;
prev_ticks = ticks;
// printf("\tmy[%p]: %s(%u) %d %d 0x%x 0x%x %f\n", p,
// my->name, my->pid, my->vsize, my->rss,
// p->kp_flags, lwp->kl_stat, my->amount);
}
}
}
void get_top_info(void) {
size_t proc_n = kern_proc_all_n();
struct kinfo_proc *kp = kern_proc_all(proc_n);
if (kp) {
proc_count(kp, proc_n);
proc_fill(kp, proc_n);
free(kp);
}
}
#if defined(i386) || defined(__i386__)
#define APMDEV "/dev/apm"
#define APM_UNKNOWN 255
int apm_getinfo(int fd, apm_info_t aip) {
if (ioctl(fd, APMIO_GETINFO, aip) == -1) { return -1; }
return 0;
}
char *get_apm_adapter(void) {
int fd;
struct apm_info a_info;
char *out;
out = (char *)calloc(16, sizeof(char));
fd = open(APMDEV, O_RDONLY);
if (fd < 0) {
strncpy(out, "ERR", 16);
return out;
}
if (apm_getinfo(fd, &a_info) != 0) {
close(fd);
strncpy(out, "ERR", 16);
return out;
}
close(fd);
switch (a_info.ai_acline) {
case 0:
strncpy(out, "off-line", 16);
return out;
break;
case 1:
if (a_info.ai_batt_stat == 3) {
strncpy(out, "charging", 16);
return out;
} else {
strncpy(out, "on-line", 16);
return out;
}
break;
default:
strncpy(out, "unknown", 16);
return out;
break;
}
}
char *get_apm_battery_life(void) {
int fd;
u_int batt_life;
struct apm_info a_info;
char *out;
out = (char *)calloc(16, sizeof(char));
fd = open(APMDEV, O_RDONLY);
if (fd < 0) {
strncpy(out, "ERR", 16);
return out;
}
if (apm_getinfo(fd, &a_info) != 0) {
close(fd);
strncpy(out, "ERR", 16);
return out;
}
close(fd);
batt_life = a_info.ai_batt_life;
if (batt_life == APM_UNKNOWN) {
strncpy(out, "unknown", 16);
} else if (batt_life <= 100) {
snprintf(out, 16, "%d%%", batt_life);
return out;
} else {
strncpy(out, "ERR", 16);
}
return out;
}
char *get_apm_battery_time(void) {
int fd;
int batt_time;
int h, m, s;
struct apm_info a_info;
char *out;
out = (char *)calloc(16, sizeof(char));
fd = open(APMDEV, O_RDONLY);
if (fd < 0) {
strncpy(out, "ERR", 16);
return out;
}
if (apm_getinfo(fd, &a_info) != 0) {
close(fd);
strncpy(out, "ERR", 16);
return out;
}
close(fd);
batt_time = a_info.ai_batt_time;
if (batt_time == -1) {
strncpy(out, "unknown", 16);
} else {
h = batt_time;
s = h % 60;
h /= 60;
m = h % 60;
h /= 60;
snprintf(out, 16, "%2d:%02d:%02d", h, m, s);
}
return out;
}
#endif
void get_battery_short_status(char *buffer, unsigned int n, const char *bat) {
get_battery_stuff(buffer, n, bat, BATTERY_STATUS);
if (0 == strncmp("charging", buffer, 8)) {
buffer[0] = 'C';
memmove(buffer + 1, buffer + 8, n - 8);
} else if (0 == strncmp("discharging", buffer, 11)) {
buffer[0] = 'D';
memmove(buffer + 1, buffer + 11, n - 11);
} else if (0 == strncmp("absent/on AC", buffer, 12)) {
buffer[0] = 'A';
memmove(buffer + 1, buffer + 12, n - 12);
}
}
int get_entropy_avail(unsigned int *val) {
/* Not applicable for FreeBSD as it uses the yarrow prng. */
(void)val;
return 1;
}
int get_entropy_poolsize(unsigned int *val) {
/* Not applicable for FreeBSD as it uses the yarrow prng. */
(void)val;
return 1;
}
| 21,880
|
C++
|
.cc
| 697
| 26.862267
| 80
| 0.612744
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
22,595
|
data-source.cc
|
brndnmtthws_conky/src/data-source.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Please see COPYING for details
*
* Copyright (C) 2010 Pavel Labath et al.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <config.h>
#include "data-source.hh"
#include <iostream>
#include <sstream>
#include <unordered_map>
namespace conky {
namespace {
/*
* Returned when there is no data available.
* An alternative would be to throw an exception, but if we don't want to react
* too aggressively when the user e.g. uses a nonexisting variable, then
* returning NaN will do just fine.
*/
float NaN = std::numeric_limits<float>::quiet_NaN();
typedef std::unordered_map<std::string, lua::cpp_function> data_sources_t;
/*
* We cannot construct this object statically, because order of object
* construction in different modules is not defined, so register_source could be
* called before this object is constructed. Therefore, we create it on the
* first call to register_source.
*/
data_sources_t *data_sources;
data_source_base &get_data_source(lua::state *l) {
if (l->gettop() != 1) {
throw std::runtime_error("Wrong number of parameters");
}
l->rawgetfield(lua::REGISTRYINDEX, priv::data_source_metatable);
if (!l->getmetatable(-2) || !l->rawequal(-1, -2)) {
throw std::runtime_error("Invalid parameter");
}
return *static_cast<data_source_base *>(l->touserdata(1));
}
int data_source_asnumber(lua::state *l) {
double x = get_data_source(l).get_number();
l->pushnumber(x);
return 1;
}
int data_source_astext(lua::state *l) {
std::string x = get_data_source(l).get_text();
l->pushstring(x);
return 1;
}
const char data_source__index[] =
"local table, key = ...;\n"
"if key == 'num' then\n"
" return conky.asnumber(table);\n"
"elseif key == 'text' then\n"
" return conky.astext(table);\n"
"else\n"
" print(string.format([[Invalid data source operation: '%s']], key));\n"
" return 0/0;\n"
"end\n";
} // namespace
namespace priv {
void do_register_data_source(const std::string &name,
const lua::cpp_function &fn) {
struct data_source_constructor {
data_source_constructor() { data_sources = new data_sources_t(); }
~data_source_constructor() {
delete data_sources;
data_sources = nullptr;
}
};
static data_source_constructor constructor;
bool inserted = data_sources->insert({name, fn}).second;
if (!inserted) {
throw std::logic_error("Data source with name '" + name +
"' already registered");
}
}
disabled_data_source::disabled_data_source(lua::state *l,
const std::string &name,
const std::string &setting)
: simple_numeric_source<float>(l, name, &NaN) {
// XXX some generic way of reporting errors? NORM_ERR?
std::cerr << "Support for variable '" << name
<< "' has been disabled during compilation. Please recompile with '"
<< setting << "'" << std::endl;
}
} // namespace priv
double data_source_base::get_number() const { return NaN; }
std::string data_source_base::get_text() const {
std::ostringstream s;
s << get_number();
return s.str();
}
register_disabled_data_source::register_disabled_data_source(
const std::string &name, const std::string &setting)
: register_data_source<priv::disabled_data_source>(name, setting) {}
// at least one data source should always be registered, so data_sources will
// not be null
void export_data_sources(lua::state &l) {
lua::stack_sentry s(l);
l.checkstack(2);
l.newmetatable(priv::data_source_metatable);
{
l.pushboolean(false);
l.rawsetfield(-2, "__metatable");
l.pushdestructor<data_source_base>();
l.rawsetfield(-2, "__gc");
l.loadstring(data_source__index);
l.rawsetfield(-2, "__index");
}
l.pop();
l.newtable();
{
for (auto &data_source : *data_sources) {
l.pushfunction(data_source.second);
l.rawsetfield(-2, data_source.first.c_str());
}
}
l.rawsetfield(-2, "variables");
l.pushfunction(data_source_asnumber);
l.rawsetfield(-2, "asnumber");
l.pushfunction(data_source_astext);
l.rawsetfield(-2, "astext");
}
} // namespace conky
/////////// example data sources, remove after real data sources are available
//////////
int asdf_ = 47;
conky::register_data_source<conky::simple_numeric_source<int>> asdf("asdf",
&asdf_);
conky::register_disabled_data_source zxcv("zxcv", "BUILD_ZXCV");
| 5,193
|
C++
|
.cc
| 145
| 31.413793
| 80
| 0.6666
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
22,596
|
xmms2.cc
|
brndnmtthws_conky/src/xmms2.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "conky.h"
xmmsc_connection_t *xmms2_conn;
#define CONN_INIT 0
#define CONN_OK 1
#define CONN_NO 2
static void xmms_alloc(struct information *ptr) {
if (ptr->xmms2.artist == nullptr) {
ptr->xmms2.artist = (char *)malloc(text_buffer_size.get(*state));
}
if (ptr->xmms2.album == nullptr) {
ptr->xmms2.album = (char *)malloc(text_buffer_size.get(*state));
}
if (ptr->xmms2.title == nullptr) {
ptr->xmms2.title = (char *)malloc(text_buffer_size.get(*state));
}
if (ptr->xmms2.genre == nullptr) {
ptr->xmms2.genre = (char *)malloc(text_buffer_size.get(*state));
}
if (ptr->xmms2.comment == nullptr) {
ptr->xmms2.comment = (char *)malloc(text_buffer_size.get(*state));
}
if (ptr->xmms2.url == nullptr) {
ptr->xmms2.url = (char *)malloc(text_buffer_size.get(*state));
}
if (ptr->xmms2.date == nullptr) {
ptr->xmms2.date = (char *)malloc(text_buffer_size.get(*state));
}
ptr->xmms2.artist[0] = '\0';
ptr->xmms2.album[0] = '\0';
ptr->xmms2.title[0] = '\0';
ptr->xmms2.genre[0] = '\0';
ptr->xmms2.comment[0] = '\0';
ptr->xmms2.url[0] = '\0';
ptr->xmms2.date[0] = '\0';
ptr->xmms2.tracknr = 0;
ptr->xmms2.id = 0;
ptr->xmms2.bitrate = 0;
ptr->xmms2.duration = 0;
ptr->xmms2.elapsed = 0;
ptr->xmms2.size = 0;
ptr->xmms2.progress = 0;
ptr->xmms2.timesplayed = -1;
}
void free_xmms2(struct text_object *obj) {
(void)obj;
free_and_zero(info.xmms2.artist);
free_and_zero(info.xmms2.album);
free_and_zero(info.xmms2.title);
free_and_zero(info.xmms2.genre);
free_and_zero(info.xmms2.comment);
free_and_zero(info.xmms2.url);
free_and_zero(info.xmms2.date);
free_and_zero(info.xmms2.status);
free_and_zero(info.xmms2.playlist);
}
void connection_lost(void *p) {
struct information *ptr = (struct information *)p;
ptr->xmms2.conn_state = CONN_NO;
fprintf(stderr, "XMMS2 connection failed. %s\n",
xmmsc_get_last_error(xmms2_conn));
xmms_alloc(ptr);
strncpy(ptr->xmms2.status, "Disconnected", text_buffer_size.get(*state) - 1);
ptr->xmms2.playlist[0] = '\0';
ptr->xmms2.id = 0;
}
int handle_curent_id(xmmsv_t *value, void *p) {
struct information *ptr = (struct information *)p;
xmmsv_t *val, *infos, *dict_entry;
xmmsc_result_t *res;
const char *errbuf;
int current_id;
const char *charval;
int intval;
if (xmmsv_get_error(value, &errbuf)) {
fprintf(stderr, "XMMS2 server error. %s\n", errbuf);
return TRUE;
}
if (xmmsv_get_int(value, ¤t_id) && current_id > 0) {
res = xmmsc_medialib_get_info(xmms2_conn, current_id);
xmmsc_result_wait(res);
val = xmmsc_result_get_value(res);
if (xmmsv_get_error(val, &errbuf)) {
fprintf(stderr, "XMMS2 server error. %s\n", errbuf);
return TRUE;
}
xmms_alloc(ptr);
ptr->xmms2.id = current_id;
infos = xmmsv_propdict_to_dict(val, nullptr);
if (xmmsv_dict_get(infos, "artist", &dict_entry) &&
xmmsv_get_string(dict_entry, &charval))
strncpy(ptr->xmms2.artist, charval, text_buffer_size.get(*state) - 1);
if (xmmsv_dict_get(infos, "title", &dict_entry) &&
xmmsv_get_string(dict_entry, &charval))
strncpy(ptr->xmms2.title, charval, text_buffer_size.get(*state) - 1);
if (xmmsv_dict_get(infos, "album", &dict_entry) &&
xmmsv_get_string(dict_entry, &charval))
strncpy(ptr->xmms2.album, charval, text_buffer_size.get(*state) - 1);
if (xmmsv_dict_get(infos, "genre", &dict_entry) &&
xmmsv_get_string(dict_entry, &charval))
strncpy(ptr->xmms2.genre, charval, text_buffer_size.get(*state) - 1);
if (xmmsv_dict_get(infos, "comment", &dict_entry) &&
xmmsv_get_string(dict_entry, &charval))
strncpy(ptr->xmms2.comment, charval, text_buffer_size.get(*state) - 1);
if (xmmsv_dict_get(infos, "url", &dict_entry) &&
xmmsv_get_string(dict_entry, &charval))
strncpy(ptr->xmms2.url, charval, text_buffer_size.get(*state) - 1);
if (xmmsv_dict_get(infos, "date", &dict_entry) &&
xmmsv_get_string(dict_entry, &charval))
strncpy(ptr->xmms2.date, charval, text_buffer_size.get(*state) - 1);
if (xmmsv_dict_get(infos, "tracknr", &dict_entry) &&
xmmsv_get_int(dict_entry, &intval))
ptr->xmms2.tracknr = intval;
if (xmmsv_dict_get(infos, "duration", &dict_entry) &&
xmmsv_get_int(dict_entry, &intval))
ptr->xmms2.duration = intval;
if (xmmsv_dict_get(infos, "bitrate", &dict_entry) &&
xmmsv_get_int(dict_entry, &intval))
ptr->xmms2.bitrate = intval / 1000;
if (xmmsv_dict_get(infos, "size", &dict_entry) &&
xmmsv_get_int(dict_entry, &intval))
ptr->xmms2.size = (float)intval / 1048576;
if (xmmsv_dict_get(infos, "timesplayed", &dict_entry) &&
xmmsv_get_int(dict_entry, &intval))
ptr->xmms2.timesplayed = intval;
xmmsv_unref(infos);
xmmsc_result_unref(res);
}
return TRUE;
}
int handle_playtime(xmmsv_t *value, void *p) {
struct information *ptr = (struct information *)p;
int play_time;
const char *errbuf;
if (xmmsv_get_error(value, &errbuf)) {
fprintf(stderr, "XMMS2 server error. %s\n", errbuf);
return TRUE;
}
if (xmmsv_get_int(value, &play_time)) {
ptr->xmms2.elapsed = play_time;
ptr->xmms2.progress = (float)play_time / ptr->xmms2.duration;
ptr->xmms2.percent = (int)(ptr->xmms2.progress * 100);
}
return TRUE;
}
int handle_playback_state_change(xmmsv_t *value, void *p) {
struct information *ptr = (struct information *)p;
int pb_state = 0;
const char *errbuf;
if (xmmsv_get_error(value, &errbuf)) {
fprintf(stderr, "XMMS2 server error. %s\n", errbuf);
return TRUE;
}
if (ptr->xmms2.status == nullptr) {
ptr->xmms2.status = (char *)malloc(text_buffer_size.get(*state));
ptr->xmms2.status[0] = '\0';
}
if (xmmsv_get_int(value, &pb_state)) {
switch (pb_state) {
case XMMS_PLAYBACK_STATUS_PLAY:
strncpy(ptr->xmms2.status, "Playing", text_buffer_size.get(*state) - 1);
break;
case XMMS_PLAYBACK_STATUS_PAUSE:
strncpy(ptr->xmms2.status, "Paused", text_buffer_size.get(*state) - 1);
break;
case XMMS_PLAYBACK_STATUS_STOP:
strncpy(ptr->xmms2.status, "Stopped", text_buffer_size.get(*state) - 1);
ptr->xmms2.elapsed = ptr->xmms2.progress = ptr->xmms2.percent = 0;
break;
default:
strncpy(ptr->xmms2.status, "Unknown", text_buffer_size.get(*state) - 1);
}
}
return TRUE;
}
int handle_playlist_loaded(xmmsv_t *value, void *p) {
struct information *ptr = (struct information *)p;
const char *c, *errbuf;
if (xmmsv_get_error(value, &errbuf)) {
fprintf(stderr, "XMMS2 server error. %s\n", errbuf);
return TRUE;
}
if (ptr->xmms2.playlist == nullptr) {
ptr->xmms2.playlist = (char *)malloc(text_buffer_size.get(*state));
ptr->xmms2.playlist[0] = '\0';
}
if (xmmsv_get_string(value, &c)) {
strncpy(ptr->xmms2.playlist, c, text_buffer_size.get(*state) - 1);
}
return TRUE;
}
int handle_medialib_changed(xmmsv_t *value, void *p) {
struct information *ptr = (struct information *)p;
const char *errbuf;
int current_id;
if (xmmsv_get_error(value, &errbuf)) {
fprintf(stderr, "XMMS2 server error. %s\n", errbuf);
return TRUE;
}
if (xmmsv_get_int(value, ¤t_id) && current_id > 0 &&
ptr->xmms2.id == (unsigned int)current_id) {
return handle_curent_id(value, ptr);
}
return TRUE;
}
int update_xmms2(void) {
struct information *current_info = &info;
/* initialize connection */
if (current_info->xmms2.conn_state == CONN_INIT) {
if (xmms2_conn == nullptr) { xmms2_conn = xmmsc_init(PACKAGE_NAME); }
/* did init fail? */
if (xmms2_conn == nullptr) {
fprintf(stderr, "XMMS2 init failed. %s\n",
xmmsc_get_last_error(xmms2_conn));
return 0;
}
/* init ok but not connected yet.. */
current_info->xmms2.conn_state = CONN_NO;
/* clear all values */
xmms_alloc(current_info);
}
/* connect */
if (current_info->xmms2.conn_state == CONN_NO) {
char *path = getenv("XMMS_PATH");
if (!xmmsc_connect(xmms2_conn, path)) {
fprintf(stderr, "XMMS2 connection failed. %s\n",
xmmsc_get_last_error(xmms2_conn));
current_info->xmms2.conn_state = CONN_NO;
return 0;
}
/* set callbacks */
xmmsc_disconnect_callback_set(xmms2_conn, connection_lost, current_info);
XMMS_CALLBACK_SET(xmms2_conn, xmmsc_broadcast_playback_current_id,
handle_curent_id, current_info);
XMMS_CALLBACK_SET(xmms2_conn, xmmsc_signal_playback_playtime,
handle_playtime, current_info);
XMMS_CALLBACK_SET(xmms2_conn, xmmsc_broadcast_playback_status,
handle_playback_state_change, current_info);
XMMS_CALLBACK_SET(xmms2_conn, xmmsc_broadcast_playlist_loaded,
handle_playlist_loaded, current_info);
XMMS_CALLBACK_SET(xmms2_conn, xmmsc_broadcast_medialib_entry_changed,
handle_medialib_changed, current_info);
/* get playback status, current id and active playlist */
XMMS_CALLBACK_SET(xmms2_conn, xmmsc_playback_current_id, handle_curent_id,
current_info);
XMMS_CALLBACK_SET(xmms2_conn, xmmsc_playback_status,
handle_playback_state_change, current_info);
XMMS_CALLBACK_SET(xmms2_conn, xmmsc_playlist_current_active,
handle_playlist_loaded, current_info);
/* everything seems to be ok */
current_info->xmms2.conn_state = CONN_OK;
}
/* handle callbacks */
if (current_info->xmms2.conn_state == CONN_OK) {
xmmsc_io_in_handle(xmms2_conn);
if (xmmsc_io_want_out(xmms2_conn)) xmmsc_io_out_handle(xmms2_conn);
}
return 0;
}
void print_xmms2_tracknr(struct text_object *obj, char *p,
unsigned int p_max_size) {
(void)obj;
if (info.xmms2.tracknr != -1) {
snprintf(p, p_max_size, "%i", info.xmms2.tracknr);
}
}
void print_xmms2_elapsed(struct text_object *obj, char *p,
unsigned int p_max_size) {
(void)obj;
snprintf(p, p_max_size, "%02d:%02d", info.xmms2.elapsed / 60000,
(info.xmms2.elapsed / 1000) % 60);
}
void print_xmms2_duration(struct text_object *obj, char *p,
unsigned int p_max_size) {
(void)obj;
snprintf(p, p_max_size, "%02d:%02d", info.xmms2.duration / 60000,
(info.xmms2.duration / 1000) % 60);
}
double xmms2_barval(struct text_object *obj) {
(void)obj;
return info.xmms2.progress;
}
void print_xmms2_smart(struct text_object *obj, char *p,
unsigned int p_max_size) {
(void)obj;
int artist_len = strlen(info.xmms2.artist);
int title_len = strlen(info.xmms2.title);
if (artist_len < 2 && title_len < 2) {
snprintf(p, p_max_size, "%s", info.xmms2.url);
} else if (artist_len < 1) {
snprintf(p, p_max_size, "%s", info.xmms2.title);
} else {
snprintf(p, p_max_size, "%s - %s", info.xmms2.artist, info.xmms2.title);
}
}
#define XMMS2_PRINT_GENERATOR(name, fmt) \
void print_xmms2_##name(struct text_object *obj, char *p, \
unsigned int p_max_size) { \
(void)obj; \
snprintf(p, p_max_size, fmt, info.xmms2.name); \
}
XMMS2_PRINT_GENERATOR(artist, "%s")
XMMS2_PRINT_GENERATOR(album, "%s")
XMMS2_PRINT_GENERATOR(title, "%s")
XMMS2_PRINT_GENERATOR(genre, "%s")
XMMS2_PRINT_GENERATOR(comment, "%s")
XMMS2_PRINT_GENERATOR(url, "%s")
XMMS2_PRINT_GENERATOR(status, "%s")
XMMS2_PRINT_GENERATOR(date, "%s")
XMMS2_PRINT_GENERATOR(bitrate, "%i")
XMMS2_PRINT_GENERATOR(id, "%u")
XMMS2_PRINT_GENERATOR(size, "%2.1f")
XMMS2_PRINT_GENERATOR(playlist, "%s")
XMMS2_PRINT_GENERATOR(timesplayed, "%i")
XMMS2_PRINT_GENERATOR(percent, "%i")
#undef XMMS2_PRINT_GENERATOR
int if_xmms2_connected(struct text_object *obj) {
(void)obj;
return info.xmms2.conn_state == CONN_OK;
}
| 13,072
|
C++
|
.cc
| 346
| 32.898844
| 80
| 0.649407
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
22,597
|
pulseaudio.cc
|
brndnmtthws_conky/src/pulseaudio.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "pulseaudio.h"
#include <math.h>
#include <unistd.h>
#include "common.h"
#include "config.h"
#include "conky.h"
#include "core.h"
#include "logging.h"
#include "specials.h"
#include "text_object.h"
struct pulseaudio_default_results get_result_copy();
const struct pulseaudio_default_results pulseaudio_result0 = {
std::string(),
std::string(),
std::string(),
std::string(),
0,
0,
0,
0,
std::string(),
PA_SOURCE_SUSPENDED,
0,
std::string(),
std::string(),
0};
pulseaudio_c *pulseaudio = nullptr;
void pa_sink_info_callback(pa_context *c, const pa_sink_info *i, int eol,
void *data) {
if (i != nullptr && data) {
struct pulseaudio_default_results *pdr =
(struct pulseaudio_default_results *)data;
pdr->sink_description.assign(i->description);
pdr->sink_mute = i->mute;
pdr->sink_card = i->card;
pdr->sink_index = i->index;
if (i->active_port != nullptr) {
pdr->sink_active_port_name.assign(i->active_port->name);
pdr->sink_active_port_description.assign(i->active_port->description);
} else {
pdr->sink_active_port_name.erase();
pdr->sink_active_port_description.erase();
}
pdr->sink_volume = round_to_positive_int(
100.0f * (float)pa_cvolume_avg(&(i->volume)) / (float)PA_VOLUME_NORM);
pa_threaded_mainloop_signal(pulseaudio->mainloop, 0);
}
(void)c;
++eol;
}
void pa_source_info_callback(pa_context *c, const pa_source_info *i, int eol,
void *data) {
if (i != nullptr && data) {
struct pulseaudio_default_results *pdr =
(struct pulseaudio_default_results *)data;
pdr->source_state = i->state;
pdr->source_mute = i->mute;
pa_threaded_mainloop_signal(pulseaudio->mainloop, 0);
}
(void)c;
++eol;
}
void pa_server_info_callback(pa_context *c, const pa_server_info *i,
void *userdata) {
if (i != nullptr) {
struct pulseaudio_default_results *pdr =
(struct pulseaudio_default_results *)userdata;
pdr->sink_name.assign(i->default_sink_name);
pdr->source_name.assign(i->default_source_name);
pa_threaded_mainloop_signal(pulseaudio->mainloop, 0);
}
(void)c;
}
void pa_server_sink_info_callback(pa_context *c, const pa_server_info *i,
void *userdata) {
if (i != nullptr) {
struct pulseaudio_default_results *pdr =
(struct pulseaudio_default_results *)userdata;
pdr->sink_name.assign(i->default_sink_name);
if (pdr->sink_name.empty()) return;
pa_operation *op;
if (!(op = pa_context_get_sink_info_by_name(c, pdr->sink_name.c_str(),
pa_sink_info_callback, pdr))) {
NORM_ERR("pa_context_get_sink_info_by_index() failed");
return;
}
pa_operation_unref(op);
}
(void)c;
}
void pa_card_info_callback(pa_context *c, const pa_card_info *card, int eol,
void *userdata) {
if (card) {
struct pulseaudio_default_results *pdr =
(struct pulseaudio_default_results *)userdata;
pdr->card_name.assign(card->name);
pdr->card_index = card->index;
pdr->card_active_profile_description.assign(
card->active_profile->description);
pa_threaded_mainloop_signal(pulseaudio->mainloop, 0);
}
(void)c;
eol++;
}
void context_state_cb(pa_context *c, void *userdata) {
pulseaudio_c *puau_int = static_cast<pulseaudio_c *>(userdata);
switch (pa_context_get_state(c)) {
case PA_CONTEXT_UNCONNECTED:
case PA_CONTEXT_CONNECTING:
case PA_CONTEXT_AUTHORIZING:
case PA_CONTEXT_SETTING_NAME:
break;
case PA_CONTEXT_READY: {
puau_int->cstate = PULSE_CONTEXT_READY;
break;
}
case PA_CONTEXT_FAILED:
case PA_CONTEXT_TERMINATED: {
puau_int->cstate = PULSE_CONTEXT_FINISHED;
break;
}
default:
return;
}
}
#define PULSEAUDIO_OP(command, error_msg) \
if (!(op = command)) { \
NORM_ERR(error_msg); \
return; \
} \
pa_operation_unref(op);
void subscribe_cb(pa_context *c, pa_subscription_event_type_t t, uint32_t index,
void *userdata) {
struct pulseaudio_default_results *res =
(struct pulseaudio_default_results *)userdata;
switch (t & PA_SUBSCRIPTION_EVENT_FACILITY_MASK) {
case PA_SUBSCRIPTION_EVENT_SINK: {
if (res->sink_name.empty()) return;
pa_operation *op;
PULSEAUDIO_OP(pa_context_get_sink_info_by_name(
c, res->sink_name.c_str(), pa_sink_info_callback, res),
"pa_context_get_sink_info_by_name failed");
} break;
case PA_SUBSCRIPTION_EVENT_SOURCE: {
if (res->source_name.empty()) return;
pa_operation *op;
PULSEAUDIO_OP(
pa_context_get_source_info_by_name(c, res->source_name.c_str(),
pa_source_info_callback, res),
"pa_context_get_source_info_by_name failed");
} break;
case PA_SUBSCRIPTION_EVENT_CARD:
if (index == res->card_index && res->card_index != (uint32_t)-1) {
pa_operation *op;
PULSEAUDIO_OP(pa_context_get_card_info_by_index(
c, index, pa_card_info_callback, res),
"pa_context_get_card_info_by_index() failed")
}
break;
case PA_SUBSCRIPTION_EVENT_SERVER: {
pa_operation *op;
PULSEAUDIO_OP(
pa_context_get_server_info(c, pa_server_sink_info_callback, res),
"pa_context_get_server_info() failed");
} break;
}
}
#define PULSEAUDIO_WAIT(COMMAND) \
{ \
op = COMMAND; \
while (pa_operation_get_state(op) == PA_OPERATION_RUNNING) { \
pa_threaded_mainloop_wait(pulseaudio->mainloop); \
} \
pa_operation_unref(op); \
}
void init_pulseaudio(struct text_object *obj) {
// already initialized
(void)obj;
if (pulseaudio != nullptr && pulseaudio->cstate == PULSE_CONTEXT_READY) {
pulseaudio->ninits++;
obj->data.opaque = (void *)pulseaudio;
return;
}
pulseaudio = new pulseaudio_c();
obj->data.opaque = (void *)pulseaudio;
pulseaudio->ninits++;
// Create a mainloop API and connection to the default server
pulseaudio->mainloop = pa_threaded_mainloop_new();
if (!pulseaudio->mainloop) NORM_ERR("Cannot create pulseaudio mainloop");
pulseaudio->mainloop_api = pa_threaded_mainloop_get_api(pulseaudio->mainloop);
if (!pulseaudio->mainloop_api) NORM_ERR("Cannot get mainloop api");
pulseaudio->context = pa_context_new(pulseaudio->mainloop_api, "Conky Infos");
// This function defines a callback so the server will tell us its state.
pa_context_set_state_callback(pulseaudio->context, context_state_cb,
pulseaudio);
// This function connects to the pulse server
if (pa_context_connect(pulseaudio->context, nullptr, (pa_context_flags_t)0,
nullptr) < 0) {
CRIT_ERR("Cannot connect to pulseaudio");
return;
}
pa_threaded_mainloop_start(pulseaudio->mainloop);
while (pulseaudio->cstate != PULSE_CONTEXT_READY) {
struct timespec req;
struct timespec rem;
req.tv_sec = 1;
req.tv_nsec = 200000;
nanosleep(&req, &rem);
}
// Initial parameters update
pa_operation *op;
PULSEAUDIO_WAIT(pa_context_get_server_info(
pulseaudio->context, pa_server_info_callback, &pulseaudio->result));
if (pulseaudio->result.sink_name.empty()) return;
PULSEAUDIO_WAIT(pa_context_get_sink_info_by_name(
pulseaudio->context, pulseaudio->result.sink_name.c_str(),
pa_sink_info_callback, &pulseaudio->result));
if (pulseaudio->result.sink_name.empty()) {
NORM_ERR("Incorrect pulseaudio sink information.");
return;
}
if (pulseaudio->result.source_name.empty()) return;
PULSEAUDIO_WAIT(pa_context_get_source_info_by_name(
pulseaudio->context, pulseaudio->result.source_name.c_str(),
pa_source_info_callback, &pulseaudio->result));
if (pulseaudio->result.source_name.empty()) {
NORM_ERR("Incorrect pulseaudio source information.");
return;
}
if (pulseaudio->result.sink_card != (uint32_t)-1)
PULSEAUDIO_WAIT(pa_context_get_card_info_by_index(
pulseaudio->context, pulseaudio->result.sink_card,
pa_card_info_callback, &pulseaudio->result));
// get notification when something changes in PA
pa_context_set_subscribe_callback(pulseaudio->context, subscribe_cb,
&pulseaudio->result);
if (!(op = pa_context_subscribe(
pulseaudio->context,
(pa_subscription_mask_t)(PA_SUBSCRIPTION_MASK_SINK |
PA_SUBSCRIPTION_MASK_SOURCE |
PA_SUBSCRIPTION_MASK_SERVER |
PA_SUBSCRIPTION_MASK_CARD),
nullptr, NULL))) {
NORM_ERR("pa_context_subscribe() failed");
return;
}
pa_operation_unref(op);
}
void free_pulseaudio(struct text_object *obj) {
pulseaudio_c *puau_int = static_cast<pulseaudio_c *>(obj->data.opaque);
if (!puau_int) return;
if (--puau_int->ninits > 0) {
obj->data.opaque = nullptr;
return;
}
puau_int->cstate = PULSE_CONTEXT_FINISHED;
if (puau_int->context) {
pa_context_set_state_callback(puau_int->context, nullptr, NULL);
pa_context_disconnect(puau_int->context);
pa_context_unref(puau_int->context);
}
if (puau_int->mainloop) {
pa_threaded_mainloop_stop(puau_int->mainloop);
pa_threaded_mainloop_free(puau_int->mainloop);
}
delete puau_int;
puau_int = nullptr;
}
struct pulseaudio_default_results get_pulseaudio(struct text_object *obj) {
pulseaudio_c *puau_int = static_cast<pulseaudio_c *>(obj->data.opaque);
if (puau_int && puau_int->cstate == PULSE_CONTEXT_READY)
return puau_int->result;
return pulseaudio_result0;
}
uint8_t puau_vol(struct text_object *obj) {
return get_pulseaudio(obj).sink_volume;
}
int puau_muted(struct text_object *obj) {
return get_pulseaudio(obj).sink_mute;
}
int puau_source_running(struct text_object *obj) {
return get_pulseaudio(obj).source_state == PA_SOURCE_RUNNING;
}
int puau_source_muted(struct text_object *obj) {
return get_pulseaudio(obj).source_mute;
}
void print_puau_sink_description(struct text_object *obj, char *p,
unsigned int p_max_size) {
snprintf(p, p_max_size, "%s", get_pulseaudio(obj).sink_description.c_str());
}
void print_puau_sink_active_port_name(struct text_object *obj, char *p,
unsigned int p_max_size) {
snprintf(p, p_max_size, "%s",
get_pulseaudio(obj).sink_active_port_name.c_str());
}
void print_puau_sink_active_port_description(struct text_object *obj, char *p,
unsigned int p_max_size) {
snprintf(p, p_max_size, "%s",
get_pulseaudio(obj).sink_active_port_description.c_str());
}
void print_puau_card_active_profile(struct text_object *obj, char *p,
unsigned int p_max_size) {
snprintf(p, p_max_size, "%s",
get_pulseaudio(obj).card_active_profile_description.c_str());
}
void print_puau_card_name(struct text_object *obj, char *p,
unsigned int p_max_size) {
snprintf(p, p_max_size, "%s", get_pulseaudio(obj).card_name.c_str());
}
double puau_volumebarval(struct text_object *obj) {
return get_pulseaudio(obj).sink_volume / 100.0f;
}
| 12,934
|
C++
|
.cc
| 340
| 31.932353
| 80
| 0.633312
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,598
|
diskio.cc
|
brndnmtthws_conky/src/diskio.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "diskio.h"
#include <sys/stat.h>
#include <cstdlib>
#include <vector>
#include "common.h"
#include "config.h"
#include "conky.h" /* text_buffer_size */
#include "core.h"
#include "logging.h"
#include "specials.h"
#include "text_object.h"
/* this is the root of all per disk stats,
* also containing the totals. */
struct diskio_stat stats;
void clear_diskio_stats() {
struct diskio_stat *cur;
while (stats.next != nullptr) {
cur = stats.next;
stats.next = stats.next->next;
free_and_zero(cur->dev);
delete cur;
}
}
struct diskio_stat *prepare_diskio_stat(const char *s) {
struct stat sb {};
std::vector<char> stat_name(text_buffer_size.get(*state)),
device_name(text_buffer_size.get(*state)),
device_s(text_buffer_size.get(*state));
struct diskio_stat *cur = &stats;
char *rpbuf;
char rpbuf2[256];
if (s == nullptr) { return &stats; }
if (strncmp(s, "label:", 6) == 0) {
snprintf(&(device_name[0]), text_buffer_size.get(*state),
"/dev/disk/by-label/%s", s + 6);
rpbuf = realpath(&(device_name[0]), nullptr);
} else if (0 == (strncmp(s, "partuuid:", 9))) {
snprintf(&(device_name[0]), text_buffer_size.get(*state),
"/dev/disk/by-partuuid/%s", s + 9);
rpbuf = realpath(&device_name[0], nullptr);
snprintf(rpbuf2, 255, "%s", rpbuf);
} else {
rpbuf = realpath(s, nullptr);
}
if (rpbuf != nullptr) {
strncpy(&device_s[0], rpbuf, text_buffer_size.get(*state));
free(rpbuf);
} else {
strncpy(&device_s[0], s, text_buffer_size.get(*state));
}
#if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__linux__)
if (strncmp(&device_s[0], "/dev/", 5) == 0) {
device_s.erase(device_s.begin(), device_s.begin() + 5);
}
#endif
strncpy(&(device_name[0]), &device_s[0], text_buffer_size.get(*state));
#if !defined(__sun)
/*
* On Solaris we currently don't use the name of disk's special file so
* this test is useless.
*/
if (strncmp(s, "label:", 6) == 0) {
snprintf(&(stat_name[0]), text_buffer_size.get(*state), "/dev/%s",
&(device_name[0]));
if ((stat(&(stat_name[0]), &sb) != 0) || !S_ISBLK(sb.st_mode)) {
NORM_ERR("diskio device '%s' does not exist", &device_s[0]);
}
} else if ((0 == (strncmp(s, "partuuid:", 9))) &&
((stat(rpbuf2, &sb) != 0) || !S_ISBLK(sb.st_mode))) {
NORM_ERR("diskio device '%s' does not exist", &device_s[0]);
}
#endif
/* lookup existing */
while (cur->next != nullptr) {
cur = cur->next;
if (strcmp(cur->dev, &(device_name[0])) == 0) { return cur; }
}
/* no existing found, make a new one */
cur->next = new diskio_stat;
cur = cur->next;
cur->dev = strndup(&(device_s[0]), text_buffer_size.get(*state));
cur->last = UINT_MAX;
cur->last_read = UINT_MAX;
cur->last_write = UINT_MAX;
return cur;
}
void parse_diskio_arg(struct text_object *obj, const char *arg) {
obj->data.opaque = prepare_diskio_stat(arg);
}
/* dir indicates the direction:
* -1: read
* 0: read + write
* 1: write
*/
static void print_diskio_dir(struct text_object *obj, int dir, char *p,
unsigned int p_max_size) {
auto *diskio = static_cast<struct diskio_stat *>(obj->data.opaque);
double val;
if (diskio == nullptr) { return; }
if (dir < 0) {
val = diskio->current_read;
} else if (dir == 0) {
val = diskio->current;
} else {
val = diskio->current_write;
}
/* TODO: move this correction from kB to kB/s elsewhere
* (or get rid of it??) */
human_readable(val / active_update_interval(), p, p_max_size);
}
void print_diskio(struct text_object *obj, char *p, unsigned int p_max_size) {
print_diskio_dir(obj, 0, p, p_max_size);
}
void print_diskio_read(struct text_object *obj, char *p,
unsigned int p_max_size) {
print_diskio_dir(obj, -1, p, p_max_size);
}
void print_diskio_write(struct text_object *obj, char *p,
unsigned int p_max_size) {
print_diskio_dir(obj, 1, p, p_max_size);
}
#ifdef BUILD_GUI
void parse_diskiograph_arg(struct text_object *obj, const char *arg) {
auto [buf, skip] = scan_command(arg);
scan_graph(obj, arg + skip, 0, FALSE);
obj->data.opaque = prepare_diskio_stat(dev_name(buf));
free_and_zero(buf);
}
double diskiographval(struct text_object *obj) {
auto *diskio = static_cast<struct diskio_stat *>(obj->data.opaque);
return (diskio != nullptr ? diskio->current : 0);
}
double diskiographval_read(struct text_object *obj) {
auto *diskio = static_cast<struct diskio_stat *>(obj->data.opaque);
return (diskio != nullptr ? diskio->current_read : 0);
}
double diskiographval_write(struct text_object *obj) {
auto *diskio = static_cast<struct diskio_stat *>(obj->data.opaque);
return (diskio != nullptr ? diskio->current_write : 0);
}
#endif /* BUILD_GUI */
void update_diskio_values(struct diskio_stat *ds, unsigned int reads,
unsigned int writes) {
int i;
double sum = 0, sum_r = 0, sum_w = 0;
if (reads < ds->last_read || writes < ds->last_write) {
/* counter overflow or reset - rebase to sane values */
ds->last = reads + writes;
ds->last_read = reads;
ds->last_write = writes;
}
/* since the values in /proc/diskstats are absolute, we have to subtract
* our last reading. The numbers stand for "sectors read", and we therefore
* have to divide by two to get KB */
ds->sample_read[0] = (reads - ds->last_read) / 2;
ds->sample_write[0] = (writes - ds->last_write) / 2;
ds->sample[0] = ds->sample_read[0] + ds->sample_write[0];
/* compute averages */
int samples = diskio_avg_samples.get(*state);
for (i = 0; i < samples; i++) {
sum += ds->sample[i] * 1024LL;
sum_r += ds->sample_read[i] * 1024LL;
sum_w += ds->sample_write[i] * 1024LL;
}
ds->current = sum / static_cast<double>(samples);
ds->current_read = sum_r / static_cast<double>(samples);
ds->current_write = sum_w / static_cast<double>(samples);
/* shift sample history */
for (i = samples - 1; i > 0; i--) {
ds->sample[i] = ds->sample[i - 1];
ds->sample_read[i] = ds->sample_read[i - 1];
ds->sample_write[i] = ds->sample_write[i - 1];
}
/* save last */
ds->last_read = reads;
ds->last_write = writes;
ds->last = ds->last_read + ds->last_write;
}
| 7,398
|
C++
|
.cc
| 206
| 32.257282
| 78
| 0.644544
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
22,599
|
display-output.cc
|
brndnmtthws_conky/src/display-output.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Please see COPYING for details
*
* Copyright (C) 2018 François Revol et al.
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <config.h>
#include "display-output.hh"
#include <algorithm>
#include <iostream>
#include <sstream>
#include <unordered_map>
namespace conky {
inline void log_missing(const char *name, const char *flag) {
DBGP(
"%s display output disabled. Enable by recompiling with '%s' "
"flag enabled.",
name, flag);
}
#ifndef BUILD_HTTP
template <>
void register_output<output_t::HTTP>(display_outputs_t &outputs) {
log_missing("HTTP", "BUILD_HTTP");
}
#endif
#ifndef BUILD_NCURSES
template <>
void register_output<output_t::NCURSES>(display_outputs_t &outputs) {
log_missing("ncurses", "BUILD_NCURSES");
}
#endif
#ifndef BUILD_WAYLAND
template <>
void register_output<output_t::WAYLAND>(display_outputs_t &outputs) {
log_missing("Wayland", "BUILD_WAYLAND");
}
#endif
#ifndef BUILD_X11
template <>
void register_output<output_t::X11>(display_outputs_t &outputs) {
log_missing("X11", "BUILD_X11");
}
#endif
/*
* The selected and active display output.
*/
std::vector<display_output_base *> active_display_outputs;
/*
* the list of the only current output, when inside draw_text,
* else we iterate over each active outputs.
*/
std::vector<conky::display_output_base *> current_display_outputs;
bool initialize_display_outputs() {
std::vector<display_output_base *> outputs;
outputs.reserve(static_cast<size_t>(output_t::OUTPUT_COUNT));
register_output<output_t::CONSOLE>(outputs);
register_output<output_t::NCURSES>(outputs);
register_output<output_t::FILE>(outputs);
register_output<output_t::HTTP>(outputs);
register_output<output_t::X11>(outputs);
register_output<output_t::WAYLAND>(outputs);
for (auto out : outputs) { NORM_ERR("FOUND: %s", out->name.c_str()); }
// Sort display outputs by descending priority, to try graphical ones first.
sort(outputs.begin(), outputs.end(), &display_output_base::priority_compare);
int graphical_count = 0;
for (auto output : outputs) {
if (output->priority < 0) continue;
DBGP2("Testing display output '%s'... ", output->name.c_str());
if (output->detect()) {
DBGP2("Detected display output '%s'... ", output->name.c_str());
if (graphical_count && output->graphical()) continue;
// X11 init needs to draw, so we must add it to the list first.
active_display_outputs.push_back(output);
if (output->initialize()) {
DBGP("Initialized display output '%s'... ", output->name.c_str());
output->is_active = true;
if (output->graphical()) graphical_count++;
/*
* We only support a single graphical display for now.
* More than one text display (ncurses + http, ...) should be ok.
*/
// if (graphical_count)
// return true;
} else {
// failed, so remove from list
active_display_outputs.pop_back();
}
}
}
if (active_display_outputs.size()) return true;
std::cerr << "Unable to find a usable display output." << std::endl;
return true;
}
bool shutdown_display_outputs() {
bool ret = true;
for (auto output : active_display_outputs) {
output->is_active = false;
ret = output->shutdown();
}
active_display_outputs.clear();
return ret;
}
} // namespace conky
| 4,195
|
C++
|
.cc
| 122
| 31.114754
| 79
| 0.698569
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,600
|
libtcp-portmon.cc
|
brndnmtthws_conky/src/libtcp-portmon.cc
|
/*
*
* libtcp-portmon.c: tcp port monitoring library.
*
* Copyright (C) 2005-2007 Philip Kovacs pkovacs@users.sourceforge.net
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA.
*
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "libtcp-portmon.h"
#include <cstdio>
#include <cstring>
#include <unordered_map>
#include <vector>
/* -------------------------------------------------------------------
* IMPLEMENTATION INTERFACE
*
* Implementation-specific interface begins here. Clients should not
* manipulate these structures directly, nor call the defined helper
* functions. Use the "Client interface" functions defined at bottom.
* ------------------------------------------------------------------- */
namespace {
/* ------------------------------------------------------------------------
* A single tcp connection
* ------------------------------------------------------------------------ */
struct tcp_connection_t {
/* connection's key in monitor hash */
struct in6_addr local_addr;
struct in6_addr remote_addr;
in_port_t local_port;
in_port_t remote_port;
};
/* hash function for tcp connections */
struct tcp_connection_hash {
size_t operator()(const tcp_connection_t &a) const {
size_t hash = 0;
size_t i;
hash = hash * 47 + a.local_port;
hash = hash * 47 + a.remote_port;
for (i = 0; i < sizeof(a.local_addr.s6_addr); ++i)
hash = hash * 47 + a.local_addr.s6_addr[i];
for (i = 0; i < sizeof(a.remote_addr.s6_addr); ++i)
hash = hash * 47 + a.remote_addr.s6_addr[i];
return hash;
}
};
/* comparison function for tcp connections */
bool operator==(const tcp_connection_t &a, const tcp_connection_t &b) {
return a.local_port == b.local_port && a.remote_port == b.remote_port &&
!std::memcmp(&a.local_addr, &b.local_addr, sizeof(a.local_addr)) &&
!std::memcmp(&a.remote_addr.s6_addr, &b.remote_addr,
sizeof(a.remote_addr));
}
/* ------------------------------------------------------------------------
* A hash table containing tcp connection
*
* The second parameter provides the mechanism for removing connections if
* they are not seen again in subsequent update cycles.
* ------------------------------------------------------------------------ */
typedef std::unordered_map<tcp_connection_t, int, tcp_connection_hash>
connection_hash_t;
/* start and end of port monitor range. Set start=end to monitor a single port
*/
typedef std::pair<in_port_t, in_port_t> port_range_t;
/* hash function for port ranges */
struct port_range_hash {
size_t operator()(const port_range_t &a) const {
return a.first * 47 + a.second;
}
};
typedef std::unordered_map<port_range_t, tcp_port_monitor_t, port_range_hash>
monitor_hash_t;
} // namespace
/* --------------
* A port monitor
* -------------- */
struct _tcp_port_monitor_t {
/* hash table of pointers into connection list */
connection_hash_t hash;
/* array of connection pointers for O(1) peeking
* these point into the hash table*/
std::vector<const tcp_connection_t *> p_peek;
_tcp_port_monitor_t(int max_connections)
: hash(),
p_peek(max_connections,
static_cast<const tcp_connection_t *>(nullptr)) {}
_tcp_port_monitor_t(const _tcp_port_monitor_t &other)
: hash(other.hash),
p_peek(other.p_peek.size(),
static_cast<const tcp_connection_t *>(nullptr)) {
// we must rebuild the peek table because the pointers are no longer valid
rebuild_peek_table();
}
void rebuild_peek_table() {
/* Run through the monitor's connections and rebuild the peek table of
* connection pointers. This is done so peeking into the monitor can be
* done in O(1) time instead of O(n) time for each peek. */
/* zero out the peek array */
std::fill(p_peek.begin(), p_peek.end(),
static_cast<tcp_connection_t *>(nullptr));
size_t i = 0;
for (connection_hash_t::iterator j = hash.begin(); j != hash.end();
++j, ++i) {
p_peek[i] = &j->first;
}
}
private:
// we don't need this atm
const _tcp_port_monitor_t &operator=(const _tcp_port_monitor_t &);
};
/* -----------------------------
* A tcp port monitor collection
* ----------------------------- */
struct _tcp_port_monitor_collection_t {
/* hash table of monitors */
monitor_hash_t hash;
};
namespace {
/* ---------------------------------------
* A port monitor utility function typedef
* --------------------------------------- */
typedef void (*tcp_port_monitor_function_ptr_t)(
monitor_hash_t::value_type &monitor, void *p_void);
void age_tcp_port_monitor(monitor_hash_t::value_type &monitor, void *p_void) {
/* Run through the monitor's connections and decrement the age variable.
* If the age goes negative, we remove the connection from the monitor.
* Function takes O(n) time on the number of connections. */
if (p_void) { /* p_void should be nullptr in this context */
return;
}
for (connection_hash_t::iterator i = monitor.second.hash.begin();
i != monitor.second.hash.end();) {
if (--i->second >= 0)
++i;
else {
/* connection is old. remove connection from the hash. */
/* erase shouldn't invalidate iterators */
monitor.second.hash.erase(i++);
}
}
}
void rebuild_tcp_port_monitor_peek_table(monitor_hash_t::value_type &monitor,
void *p_void) {
if (p_void) { /* p_void should be nullptr in this context */
return;
}
monitor.second.rebuild_peek_table();
}
void show_connection_to_tcp_port_monitor(monitor_hash_t::value_type &monitor,
void *p_void) {
/* The monitor gets to look at each connection to see if it falls within
* the monitor's port range of interest. Connections of interest are first
* looked up in the hash to see if they are already there. If they are, we
* reset the age of the connection so it is not deleted. If the connection
* is not in the hash, we add it, but only if we haven't exceeded the
* maximum connection limit for the monitor.
* The function takes O(1) time. */
tcp_connection_t *p_connection;
if (!p_void) { return; }
/* This p_connection is on caller's stack and not the heap.
* If we are interested, we will create a copy of the connection
* (on the heap) and add it to our list. */
p_connection = (tcp_connection_t *)p_void;
/* inspect the local port number of the connection to see if we're
* interested. */
if ((monitor.first.first <= p_connection->local_port) &&
(p_connection->local_port <= monitor.first.second)) {
/* the connection is in the range of the monitor. */
/* first check the hash to see if the connection is already there. */
connection_hash_t::iterator i = monitor.second.hash.find(*p_connection);
if (i != monitor.second.hash.end()) {
/* it's already in the hash. reset the age of the connection. */
i->second = TCP_CONNECTION_STARTING_AGE;
return;
}
/* Connection is not yet in the hash.
* Add it if max_connections not exceeded. */
if (monitor.second.hash.size() < monitor.second.p_peek.size()) {
monitor.second.hash.insert(connection_hash_t::value_type(
*p_connection, TCP_CONNECTION_STARTING_AGE));
}
}
}
/* ------------------------------------------------------------------------
* Apply a tcp_port_monitor_function_ptr_t function to each port monitor in
* the collection.
* ------------------------------------------------------------------------ */
void for_each_tcp_port_monitor_in_collection(
tcp_port_monitor_collection_t *p_collection,
tcp_port_monitor_function_ptr_t p_function, void *p_function_args) {
if (!p_collection || !p_function) { return; }
/* for each monitor in the collection */
for (monitor_hash_t::iterator i = p_collection->hash.begin();
i != p_collection->hash.end(); ++i) {
/* apply the function with the given arguments */
p_function(*i, p_function_args);
}
}
const unsigned char prefix_4on6[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0xff, 0xff};
union sockaddr_in46 {
struct sockaddr_in sa4;
struct sockaddr_in6 sa6;
struct sockaddr sa;
};
/* checks whether the address is a IPv4-mapped IPv6 address */
bool is_4on6(const struct in6_addr *addr) {
return !std::memcmp(&addr->s6_addr, prefix_4on6, sizeof(prefix_4on6));
}
/* converts the address to appropriate textual representation (IPv6, IPv4 or
* fqdn) */
void print_host(char *p_buffer, size_t buffer_size, const struct in6_addr *addr,
int fqdn) {
union sockaddr_in46 sa;
socklen_t slen;
std::memset(&sa, 0, sizeof(sa));
if (is_4on6(addr)) {
sa.sa4.sin_family = AF_INET;
std::memcpy(&sa.sa4.sin_addr.s_addr, &addr->s6_addr[12], 4);
slen = sizeof(sa.sa4);
} else {
sa.sa6.sin6_family = AF_INET6;
std::memcpy(&sa.sa6.sin6_addr, addr, sizeof(struct in6_addr));
slen = sizeof(sa.sa6);
}
getnameinfo(&sa.sa, slen, p_buffer, buffer_size, nullptr, 0,
fqdn ? 0 : NI_NUMERICHOST);
}
/* converts the textual representation of an IPv4 or IPv6 address to struct
* in6_addr */
void string_to_addr(struct in6_addr *addr, const char *p_buffer) {
size_t i;
if (std::strlen(p_buffer) < 32) { // IPv4 address
i = sizeof(prefix_4on6);
std::memcpy(addr->s6_addr, prefix_4on6, i);
} else {
i = 0;
}
for (; i < sizeof(addr->s6_addr); i += 4, p_buffer += 8) {
std::sscanf(p_buffer, "%8x", (unsigned *)&addr->s6_addr[i]);
}
}
/* adds connections from file to the collection */
void process_file(tcp_port_monitor_collection_t *p_collection,
const char *file) {
std::FILE *fp;
char buf[256];
char local_addr[40];
char remote_addr[40];
tcp_connection_t conn;
unsigned long inode, uid, state;
if ((fp = std::fopen(file, "r")) == nullptr) { return; }
/* ignore field name line */
if (std::fgets(buf, 255, fp) == nullptr) {
std::fclose(fp);
return;
}
/* read all tcp connections */
while (std::fgets(buf, sizeof(buf), fp) != nullptr) {
if (std::sscanf(buf,
"%*d: %39[0-9a-fA-F]:%hx %39[0-9a-fA-F]:%hx %lx %*x:%*x "
"%*x:%*x %*x %lu %*d %lu",
local_addr, &conn.local_port, remote_addr,
&conn.remote_port, (unsigned long *)&state,
(unsigned long *)&uid, (unsigned long *)&inode) != 7) {
std::fprintf(stderr, "%s: bad file format\n", file);
}
/** TCP_ESTABLISHED equals 1, but is not (always??) included **/
// if ((inode == 0) || (state != TCP_ESTABLISHED)) {
if ((inode == 0) || (state != 1)) { continue; }
string_to_addr(&conn.local_addr, local_addr);
string_to_addr(&conn.remote_addr, remote_addr);
/* show the connection to each port monitor. */
for_each_tcp_port_monitor_in_collection(
p_collection, &show_connection_to_tcp_port_monitor, (void *)&conn);
}
std::fclose(fp);
}
} // namespace
/* ----------------------------------------------------------------------
* CLIENT INTERFACE
*
* Clients should call only those functions below this line.
* ---------------------------------------------------------------------- */
/* ----------------------------------
* Client operations on port monitors
* ---------------------------------- */
/* Clients use this function to get connection data from the indicated
* port monitor.
* The requested monitor value is copied into a client-supplied char buffer.
* Returns 0 on success, -1 otherwise. */
int peek_tcp_port_monitor(const tcp_port_monitor_t *p_monitor, int item,
int connection_index, char *p_buffer,
size_t buffer_size) {
struct sockaddr_in sa;
if (!p_monitor || !p_buffer || connection_index < 0) { return -1; }
std::memset(p_buffer, 0, buffer_size);
std::memset(&sa, 0, sizeof(sa));
sa.sin_family = AF_INET;
/* if the connection index is out of range, we simply return with no error,
* having first cleared the client-supplied buffer. */
if ((item != COUNT) &&
(connection_index >= ssize_t(p_monitor->hash.size()))) {
return 0;
}
switch (item) {
case COUNT:
std::snprintf(p_buffer, buffer_size, "%u",
unsigned(p_monitor->hash.size()));
break;
case REMOTEIP:
print_host(p_buffer, buffer_size,
&p_monitor->p_peek[connection_index]->remote_addr, 0);
break;
case REMOTEHOST:
print_host(p_buffer, buffer_size,
&p_monitor->p_peek[connection_index]->remote_addr, 1);
break;
case REMOTEPORT:
std::snprintf(p_buffer, buffer_size, "%d",
p_monitor->p_peek[connection_index]->remote_port);
break;
case REMOTESERVICE:
sa.sin_port = htons(p_monitor->p_peek[connection_index]->remote_port);
getnameinfo((struct sockaddr *)&sa, sizeof(struct sockaddr_in), nullptr,
0, p_buffer, buffer_size, NI_NUMERICHOST);
break;
case LOCALIP:
print_host(p_buffer, buffer_size,
&p_monitor->p_peek[connection_index]->local_addr, 0);
break;
case LOCALHOST:
print_host(p_buffer, buffer_size,
&p_monitor->p_peek[connection_index]->local_addr, 1);
break;
case LOCALPORT:
std::snprintf(p_buffer, buffer_size, "%d",
p_monitor->p_peek[connection_index]->local_port);
break;
case LOCALSERVICE:
sa.sin_port = htons(p_monitor->p_peek[connection_index]->local_port);
getnameinfo((struct sockaddr *)&sa, sizeof(struct sockaddr_in), nullptr,
0, p_buffer, buffer_size, NI_NUMERICHOST);
break;
default:
return -1;
}
return 0;
}
/* --------------------------------
* Client operations on collections
* -------------------------------- */
/* Create a monitor collection. Do this one first. */
tcp_port_monitor_collection_t *create_tcp_port_monitor_collection(void) {
return new tcp_port_monitor_collection_t();
}
/* Destroy the monitor collection (and the monitors inside).
* Do this one last. */
void destroy_tcp_port_monitor_collection(
tcp_port_monitor_collection_t *p_collection) {
delete p_collection;
}
/* Updates the tcp statistics for all monitors within a collection */
void update_tcp_port_monitor_collection(
tcp_port_monitor_collection_t *p_collection) {
if (!p_collection) { return; }
process_file(p_collection, "/proc/net/tcp");
process_file(p_collection, "/proc/net/tcp6");
/* age the connections in all port monitors. */
for_each_tcp_port_monitor_in_collection(p_collection, &age_tcp_port_monitor,
nullptr);
/* rebuild the connection peek tables of all monitors
* so clients can peek in O(1) time */
for_each_tcp_port_monitor_in_collection(
p_collection, &rebuild_tcp_port_monitor_peek_table, nullptr);
}
/* Creation of redundant monitors is silently ignored */
int insert_new_tcp_port_monitor_into_collection(
tcp_port_monitor_collection_t *p_collection, in_port_t port_range_begin,
in_port_t port_range_end, tcp_port_monitor_args_t *p_creation_args) {
if (!p_collection) { return -1; }
p_collection->hash.insert(monitor_hash_t::value_type(
port_range_t(port_range_begin, port_range_end),
tcp_port_monitor_t(p_creation_args->max_port_monitor_connections)));
return 0;
}
/* Clients need a way to find monitors */
tcp_port_monitor_t *find_tcp_port_monitor(
tcp_port_monitor_collection_t *p_collection, in_port_t port_range_begin,
in_port_t port_range_end) {
if (!p_collection) { return nullptr; }
/* is monitor in hash? */
monitor_hash_t::iterator i =
p_collection->hash.find(port_range_t(port_range_begin, port_range_end));
return i == p_collection->hash.end() ? nullptr : &i->second;
}
| 16,748
|
C++
|
.cc
| 412
| 35.716019
| 80
| 0.616834
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
22,601
|
display-ncurses.cc
|
brndnmtthws_conky/src/display-ncurses.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Please see COPYING for details
*
* Copyright (C) 2018 François Revol et al.
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <config.h>
#include "colours.h"
#include "conky.h"
#include "display-ncurses.hh"
#include "gui.h"
#include "nc.h"
#include <iostream>
#include <sstream>
#include <unordered_map>
#include <ncurses.h>
extern WINDOW* ncurses_window;
namespace conky {
namespace {
conky::display_output_ncurses ncurses_output;
} // namespace
template <>
void register_output<output_t::NCURSES>(display_outputs_t& outputs) {
outputs.push_back(&ncurses_output);
}
// namespace priv {
//} // namespace priv
#define COLORS_BUILTIN 8
Colour ncurses_colors[COLORS_BUILTIN + COLORS_CUSTOM] = {
{0x00, 0x00, 0x00, 0xff}, // BLACK
{0xff, 0x00, 0x00, 0xff}, // RED
{0x00, 0xff, 0x00, 0xff}, // GREEN
{0xff, 0xff, 0x00, 0xff}, // YELLOW
{0x00, 0x00, 0xff, 0xff}, // BLUE
{0xff, 0x00, 0xff, 0xff}, // MAGENTA
{0x00, 0xff, 0xff, 0xff}, // CYAN
{0xff, 0xff, 0xff, 0xff}, // WHITE
};
// Find the nearest ncurses color.
int to_ncurses(const Colour& c) {
int mindiff = INT_MAX;
int best_nccolor = 0;
for (int nccolor = 0; nccolor < COLORS_BUILTIN + COLORS_CUSTOM; nccolor++) {
const Colour& other = ncurses_colors[nccolor];
int diff = abs(c.red - other.red) + abs(c.green - other.green) +
abs(c.blue - other.blue);
if (diff < mindiff) {
mindiff = diff;
best_nccolor = nccolor;
}
}
return best_nccolor;
}
Colour from_ncurses(int nccolor) {
if (nccolor >= 0 && nccolor < COLORS_BUILTIN + COLORS_CUSTOM) {
return ncurses_colors[nccolor];
}
return ERROR_COLOUR;
}
display_output_ncurses::display_output_ncurses()
: display_output_console("ncurses") {
priority = 1;
}
bool display_output_ncurses::detect() {
if (out_to_ncurses.get(*state)) {
DBGP2("Display output '%s' enabled in config.", name.c_str());
return true;
}
return false;
}
bool display_output_ncurses::initialize() {
for (int i = 0; i < COLORS_CUSTOM; i++) {
Colour c = color[i].get(*state);
init_color(COLORS_BUILTIN + i, (1000 * c.red) / 255, (1000 * c.green) / 255,
(1000 * c.blue) / 255);
ncurses_colors[COLORS_BUILTIN + i] = c;
}
is_active = ncurses_window != nullptr;
return is_active;
}
bool display_output_ncurses::shutdown() { return false; }
void display_output_ncurses::set_foreground_color(Colour c) {
int nccolor = to_ncurses(c);
init_pair(nccolor + 1, nccolor, COLOR_BLACK);
attron(COLOR_PAIR(nccolor + 1));
}
void display_output_ncurses::begin_draw_text() {
init_pair(COLOR_WHITE, COLOR_WHITE, COLOR_BLACK);
attron(COLOR_PAIR(COLOR_WHITE));
}
void display_output_ncurses::end_draw_text() {}
void display_output_ncurses::draw_string(const char* s, int) {
printw("%s", s);
}
void display_output_ncurses::line_inner_done() { printw("\n"); }
int display_output_ncurses::getx() {
int x, y;
getyx(ncurses_window, y, x);
(void)y;
return x;
}
int display_output_ncurses::gety() {
int x, y;
getyx(ncurses_window, y, x);
(void)x;
return y;
}
void display_output_ncurses::gotox(int x) {
int y, old_x;
getyx(ncurses_window, y, old_x);
(void)old_x;
move(y, x);
}
void display_output_ncurses::gotoy(int y) {
int x, old_y;
getyx(ncurses_window, old_y, x);
(void)old_y;
move(y, x);
}
void display_output_ncurses::gotoxy(int x, int y) { move(y, x); }
void display_output_ncurses::flush() {
refresh();
clear();
}
} // namespace conky
| 4,359
|
C++
|
.cc
| 144
| 27.513889
| 80
| 0.685858
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,602
|
template.cc
|
brndnmtthws_conky/src/template.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <cctype>
#include <cstdlib>
#include <string>
#include "conky.h"
#include "logging.h"
namespace {
conky::simple_config_setting<std::string> _template[10] = {
{"template0", std::string(), true}, {"template1", std::string(), true},
{"template2", std::string(), true}, {"template3", std::string(), true},
{"template4", std::string(), true}, {"template5", std::string(), true},
{"template6", std::string(), true}, {"template7", std::string(), true},
{"template8", std::string(), true}, {"template9", std::string(), true}};
} // namespace
/* backslash_escape - do the actual substitution task for template objects
*
* The field templates is used for substituting the \N occurrences. Set it to
* nullptr to leave them as they are.
*/
static char *backslash_escape(const char *src, char **templates,
unsigned int template_count) {
char *src_dup;
const char *p;
unsigned int dup_idx = 0, dup_len;
dup_len = strlen(src) + 1;
src_dup = static_cast<char *>(malloc(dup_len * sizeof(char)));
p = src;
while (*p != 0) {
switch (*p) {
case '\\':
if (*(p + 1) == 0) { break; }
if (*(p + 1) == '\\') {
src_dup[dup_idx++] = '\\';
p++;
} else if (*(p + 1) == ' ') {
src_dup[dup_idx++] = ' ';
p++;
} else if (*(p + 1) == 'n') {
src_dup[dup_idx++] = '\n';
p++;
} else if (templates != nullptr) {
unsigned int tmpl_num;
int digits;
if ((sscanf(p + 1, "%u%n", &tmpl_num, &digits) <= 0) ||
(tmpl_num > template_count)) {
break;
}
if (tmpl_num == 0) {
CRIT_ERR_FREE(
nullptr, nullptr,
"invalid template argument \\0; arguments must start at \\1");
}
dup_len += strlen(templates[tmpl_num - 1]);
src_dup =
static_cast<char *>(realloc(src_dup, dup_len * sizeof(char)));
snprintf(src_dup + dup_idx, dup_len - dup_idx, "%s",
templates[tmpl_num - 1]);
dup_idx += strlen(templates[tmpl_num - 1]);
p += digits;
}
break;
default:
src_dup[dup_idx++] = *p;
break;
}
p++;
}
src_dup[dup_idx++] = '\0';
src_dup = static_cast<char *>(realloc(src_dup, dup_idx * sizeof(char)));
return src_dup;
}
/* handle_template_object - core logic of the template object
*
* use config variables like this:
* template1 = "$\1\2"
* template2 = "\1: ${fs_bar 4,100 \2} ${fs_used \2} / ${fs_size \2}"
*
* and use them like this:
* ${template1 node name}
* ${template2 root /}
* ${template2 cdrom /mnt/cdrom}
*/
static char *handle_template(const char *tmpl, const char *args) {
char *args_dup = nullptr;
char *p, *p_old;
char **argsp = nullptr;
unsigned int argcnt = 0, template_idx, i;
char *eval_text;
if ((sscanf(tmpl, "template%u", &template_idx) != 1) ||
(template_idx >= MAX_TEMPLATES)) {
return nullptr;
}
if (args != nullptr) {
args_dup = strdup(args);
p = args_dup;
while (*p != 0) {
while ((*p != 0) && (*p == ' ' && (p == args_dup || *(p - 1) != '\\'))) {
p++;
}
if (p > args_dup && *(p - 1) == '\\') { p--; }
p_old = p;
while ((*p != 0) && (*p != ' ' || (p > args_dup && *(p - 1) == '\\'))) {
p++;
}
if (*p != 0) {
(*p) = '\0';
p++;
}
argsp = static_cast<char **>(realloc(argsp, ++argcnt * sizeof(char *)));
argsp[argcnt - 1] = p_old;
}
for (i = 0; i < argcnt; i++) {
char *tmp;
tmp = backslash_escape(argsp[i], nullptr, 0);
DBGP2("%s: substituted arg '%s' to '%s'", tmpl, argsp[i], tmp);
argsp[i] = tmp;
}
}
eval_text = backslash_escape(_template[template_idx].get(*state).c_str(),
argsp, argcnt);
DBGP("substituted %s, output is '%s'", tmpl, eval_text);
free(args_dup);
for (i = 0; i < argcnt; i++) { free(argsp[i]); }
free(argsp);
return eval_text;
}
/* Search inbuf and replace all found template object references
* with the substituted value. */
char *find_and_replace_templates(const char *inbuf) {
char *outbuf, *indup, *p, *o, *templ, *args, *tmpl_out;
int stack, outlen;
outlen = strlen(inbuf) + 1;
o = outbuf = static_cast<char *>(calloc(outlen, sizeof(char)));
memset(outbuf, 0, outlen * sizeof(char));
p = indup = strdup(inbuf);
while (*p != 0) {
while ((*p != 0) && *p != '$') { *(o++) = *(p++); }
if ((*p) == 0) { break; }
if ((static_cast<int>(strncmp(p, "$template", strlen("$template")) != 0) !=
0) &&
(strncmp(p, "${template", strlen("${template")) != 0)) {
*(o++) = *(p++);
continue;
}
if (*(p + 1) == '{') {
p += 2;
templ = p;
while ((*p != 0) && (isspace(static_cast<unsigned char>(*p)) == 0) &&
*p != '{' && *p != '}') {
p++;
}
if (*p == '}') {
args = nullptr;
} else {
args = p;
}
stack = 1;
while ((*p != 0) && stack > 0) {
if (*p == '{') {
stack++;
} else if (*p == '}') {
stack--;
}
p++;
}
if (stack == 0) {
// stack is empty. that means the previous char was }, so we zero it
*(p - 1) = '\0';
} else {
// we ran into the end of string without finding a closing }, bark
CRIT_ERR("cannot find a closing '}' in template expansion");
}
} else {
templ = p + 1;
p += strlen("$template");
while ((*p != 0) && (isdigit(static_cast<unsigned char>(*p)) != 0)) {
p++;
}
args = nullptr;
}
tmpl_out = handle_template(templ, args);
if (tmpl_out != nullptr) {
int len = strlen(tmpl_out);
outlen += len;
*o = '\0';
outbuf = static_cast<char *>(realloc(outbuf, outlen * sizeof(char)));
strcat(outbuf, tmpl_out);
free(tmpl_out);
o = outbuf + strlen(outbuf);
} else {
NORM_ERR("failed to handle template '%s' with args '%s'", templ, args);
}
}
*o = '\0';
outbuf =
static_cast<char *>(realloc(outbuf, (strlen(outbuf) + 1) * sizeof(char)));
free(indup);
return outbuf;
}
/* check text for any template object references */
int text_contains_templates(const char *text) {
if (strcasestr(text, "${template") != nullptr) { return 1; }
if (strcasestr(text, "$template") != nullptr) { return 1; }
return 0;
}
| 7,606
|
C++
|
.cc
| 232
| 27.025862
| 80
| 0.544306
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,603
|
misc.cc
|
brndnmtthws_conky/src/misc.cc
|
/* -*- mode: c; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: t -*-
* vim: ts=4 sw=4 noet ai cindent syntax=c
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2010 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "conky.h"
#include "core.h"
#include "logging.h"
#include "specials.h"
#include "text_object.h"
static inline void read_file(const char *data, char *buf, const int size) {
FILE *fp;
memset(buf, 0, size);
if (!data) return;
fp = fopen(data, "r");
if (fp) {
int length;
length = fread(buf, 1, size - 1, fp);
fclose(fp);
buf[length] = '\0';
if (length > 0 && buf[length - 1] == '\n') { buf[length - 1] = '\0'; }
} else {
buf[0] = '\0';
}
}
static inline unsigned int file_buffer_size(const char *data,
const unsigned int maxsize) {
struct stat buf;
if (stat(data, &buf)) return maxsize;
if (buf.st_size < 0 || buf.st_size > maxsize) return maxsize;
if (buf.st_size < 10) return 10;
return buf.st_size + 1;
}
void print_cat(struct text_object *obj, char *p, unsigned int p_max_size) {
read_file(obj->data.s, p, p_max_size);
}
void print_catp(struct text_object *obj, char *p, unsigned int p_max_size) {
const unsigned int sz =
file_buffer_size(obj->data.s, text_buffer_size.get(*state));
char *buf = new char[sz];
read_file(obj->data.s, buf, sz);
evaluate(buf, p, p_max_size);
delete[] buf;
}
void print_startcase(struct text_object *obj, char *p,
unsigned int p_max_size) {
evaluate(obj->data.s, p, p_max_size);
for (unsigned int x = 0, z = 0; x < p_max_size - 1 && p[x]; x++) {
if (isspace(p[x])) {
z = 0;
} else {
p[x] = z ? tolower(p[x]) : toupper(p[x]);
z++;
}
}
}
void print_lowercase(struct text_object *obj, char *p,
unsigned int p_max_size) {
evaluate(obj->data.s, p, p_max_size);
for (unsigned int x = 0; x < p_max_size - 1 && p[x]; x++)
p[x] = tolower(p[x]);
}
void print_uppercase(struct text_object *obj, char *p,
unsigned int p_max_size) {
evaluate(obj->data.s, p, p_max_size);
for (unsigned int x = 0; x < p_max_size - 1 && p[x]; x++)
p[x] = toupper(p[x]);
}
void strip_trailing_whitespace(struct text_object *obj, char *p,
unsigned int p_max_size) {
evaluate(obj->data.s, p, p_max_size);
for (unsigned int x = p_max_size - 2;; x--) {
if (p[x] && !isspace(p[x])) {
p[x + 1] = '\0';
break;
} else if (x == 0) {
p[x] = '\0';
break;
}
}
}
long long int apply_base_multiplier(const char *s, long long int num) {
long long int base = 1024LL;
if (*s && (0 == (strcmp(s, "si")))) { base = 1000LL; }
return (num * base);
}
| 3,848
|
C++
|
.cc
| 116
| 29.137931
| 76
| 0.626616
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,604
|
audacious.cc
|
brndnmtthws_conky/src/audacious.cc
|
/*
*
* audacious.c: conky support for audacious music player
*
* Copyright (C) 2005-2007 Philip Kovacs pkovacs@users.sourceforge.net
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA.
*
*/
#include <config.h>
#include <cmath>
#include <mutex>
#include "audacious.h"
#include "conky.h"
#include "logging.h"
#include "update-cb.hh"
#include <glib.h>
#ifdef NEW_AUDACIOUS_FOUND
#include <audacious/audctrl.h>
#include <audacious/dbus.h>
#include <glib-object.h>
#else /* NEW_AUDACIOUS_FOUND */
#include <audacious/beepctrl.h>
#define audacious_remote_is_running(x) xmms_remote_is_running(x)
#define audacious_remote_is_paused(x) xmms_remote_is_paused(x)
#define audacious_remote_is_playing(x) xmms_remote_is_playing(x)
#define audacious_remote_get_playlist_pos(x) xmms_remote_get_playlist_pos(x)
#define audacious_remote_get_playlist_title(x, y) \
xmms_remote_get_playlist_title(x, y)
#define audacious_remote_get_playlist_time(x, y) \
xmms_remote_get_playlist_time(x, y)
#define audacious_remote_get_output_time(x) xmms_remote_get_output_time(x)
#define audacious_remote_get_info(w, x, y, z) xmms_remote_get_info(w, x, y, z)
#define audacious_remote_get_playlist_file(x, y) \
xmms_remote_get_playlist_file(x, y)
#define audacious_remote_get_playlist_length(x) \
xmms_remote_get_playlist_length(x)
#endif /* NEW_AUDACIOUS_FOUND */
namespace {
enum aud_status { AS_NOT_RUNNING, AS_PAUSED, AS_PLAYING, AS_STOPPED };
const char *const as_message[] = {"Not running", "Paused", "Playing",
"Stopped"};
struct aud_result {
std::string title;
std::string filename;
int length; // in ms
int position; // in ms
int bitrate;
int frequency;
int channels;
int playlist_length;
int playlist_position;
int main_volume;
aud_status status;
aud_result()
: length(0),
position(0),
bitrate(0),
frequency(0),
channels(0),
playlist_length(0),
playlist_position(0),
main_volume(0),
status(AS_NOT_RUNNING) {}
};
class audacious_cb : public conky::callback<aud_result> {
typedef conky::callback<aud_result> Base;
#ifdef NEW_AUDACIOUS_FOUND
DBusGProxy *session;
#else
gint session;
#endif
protected:
virtual void work();
public:
audacious_cb(uint32_t period) : Base(period, false, Tuple()) {
#ifdef NEW_AUDACIOUS_FOUND
DBusGConnection *connection = dbus_g_bus_get(DBUS_BUS_SESSION, nullptr);
if (!connection)
throw std::runtime_error("unable to establish dbus connection");
session = dbus_g_proxy_new_for_name(connection, AUDACIOUS_DBUS_SERVICE,
AUDACIOUS_DBUS_PATH,
AUDACIOUS_DBUS_INTERFACE);
if (!session) throw std::runtime_error("unable to create dbus proxy");
#else
session = 0;
#endif /* NEW_AUDACIOUS_FOUND */
}
#ifdef NEW_AUDACIOUS_FOUND
~audacious_cb() {
/* release reference to dbus proxy */
g_object_unref(session);
}
#endif
};
/* ---------------------------------------------------
* Worker thread function for audacious data sampling.
* --------------------------------------------------- */
void audacious_cb::work() {
aud_result tmp;
gchar *psong, *pfilename;
psong = nullptr;
pfilename = nullptr;
do {
if (!audacious_remote_is_running(session)) {
tmp.status = AS_NOT_RUNNING;
break;
}
/* Player status */
if (audacious_remote_is_paused(session)) {
tmp.status = AS_PAUSED;
} else if (audacious_remote_is_playing(session)) {
tmp.status = AS_PLAYING;
} else {
tmp.status = AS_STOPPED;
}
/* Current song title */
tmp.playlist_position = audacious_remote_get_playlist_pos(session);
psong = audacious_remote_get_playlist_title(session, tmp.playlist_position);
if (psong) {
tmp.title = psong;
g_free(psong);
}
/* Current song length */
tmp.length =
audacious_remote_get_playlist_time(session, tmp.playlist_position);
/* Current song position */
tmp.position = audacious_remote_get_output_time(session);
/* Current song bitrate, frequency, channels */
audacious_remote_get_info(session, &tmp.bitrate, &tmp.frequency,
&tmp.channels);
/* Current song filename */
pfilename =
audacious_remote_get_playlist_file(session, tmp.playlist_position);
if (pfilename) {
tmp.filename = pfilename;
g_free(pfilename);
}
/* Length of the Playlist (number of songs) */
tmp.playlist_length = audacious_remote_get_playlist_length(session);
/* Main volume */
tmp.main_volume = audacious_remote_get_main_volume(session);
} while (0);
{
/* Deliver the refreshed items array to audacious_items. */
std::lock_guard<std::mutex> lock(result_mutex);
result = tmp;
}
}
aud_result get_res() {
uint32_t period = std::max(
lround(music_player_interval.get(*state) / active_update_interval()), 1l);
return conky::register_cb<audacious_cb>(period)->get_result_copy();
}
} // namespace
void print_audacious_status(struct text_object *, char *p,
unsigned int p_max_size) {
const aud_result &res = get_res();
snprintf(p, p_max_size, "%s", as_message[res.status]);
}
void print_audacious_title(struct text_object *obj, char *p,
unsigned int p_max_size) {
snprintf(p, std::min((unsigned int)obj->data.i, p_max_size), "%s",
get_res().title.c_str());
}
void print_audacious_filename(struct text_object *obj, char *p,
unsigned int p_max_size) {
snprintf(p, p_max_size, "%s",
get_res().filename.c_str());
}
double audacious_barval(struct text_object *) {
const aud_result &res = get_res();
return (double)res.position / res.length;
}
void print_audacious_length(struct text_object *, char *p,
unsigned int p_max_size) {
const aud_result &res = get_res();
int sec = res.length / 1000;
snprintf(p, p_max_size, "%d:%.2d", sec / 60, sec % 60);
}
void print_audacious_length_seconds(struct text_object *, char *p,
unsigned int p_max_size) {
snprintf(p, p_max_size, "%d", get_res().length);
}
void print_audacious_position(struct text_object *, char *p,
unsigned int p_max_size) {
const aud_result &res = get_res();
int sec = res.position / 1000;
snprintf(p, p_max_size, "%d:%.2d", sec / 60, sec % 60);
}
void print_audacious_position_seconds(struct text_object *, char *p,
unsigned int p_max_size) {
snprintf(p, p_max_size, "%d", get_res().position);
}
void print_audacious_bitrate(struct text_object *, char *p,
unsigned int p_max_size) {
snprintf(p, p_max_size, "%d", get_res().bitrate);
}
void print_audacious_frequency(struct text_object *, char *p,
unsigned int p_max_size) {
snprintf(p, p_max_size, "%d", get_res().frequency);
}
void print_audacious_channels(struct text_object *, char *p,
unsigned int p_max_size) {
snprintf(p, p_max_size, "%d", get_res().channels);
}
void print_audacious_playlist_length(struct text_object *, char *p,
unsigned int p_max_size) {
snprintf(p, p_max_size, "%d", get_res().playlist_length);
}
void print_audacious_playlist_position(struct text_object *, char *p,
unsigned int p_max_size) {
snprintf(p, p_max_size, "%d", get_res().playlist_position + 1);
}
void print_audacious_main_volume(struct text_object *, char *p,
unsigned int p_max_size) {
snprintf(p, p_max_size, "%d", get_res().main_volume);
}
| 8,506
|
C++
|
.cc
| 231
| 31.277056
| 80
| 0.646066
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
22,605
|
apcupsd.cc
|
brndnmtthws_conky/src/apcupsd.cc
|
/*
*
* apcupsd.c: conky module for APC UPS daemon monitoring
*
* Copyright (C) 2009 Jaromir Smrcek <jaromir.smrcek@zoner.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA.
*
*/
#include "apcupsd.h"
#include "conky.h"
#include "logging.h"
#include "text_object.h"
#include <netdb.h>
#include <netinet/in.h>
#include <sys/time.h>
#include <unistd.h>
#include <cerrno>
enum _apcupsd_items {
APCUPSD_NAME,
APCUPSD_MODEL,
APCUPSD_UPSMODE,
APCUPSD_CABLE,
APCUPSD_STATUS,
APCUPSD_LINEV,
APCUPSD_LOAD,
APCUPSD_CHARGE,
APCUPSD_TIMELEFT,
APCUPSD_TEMP,
APCUPSD_LASTXFER,
_APCUPSD_COUNT
};
/* type for data exchange with main thread */
#define APCUPSD_MAXSTR 32
typedef struct apcupsd_s {
char items[_APCUPSD_COUNT]
[APCUPSD_MAXSTR + 1]; /* e.g. items[APCUPSD_STATUS] */
char host[64];
int port;
} APCUPSD_S, *PAPCUPSD_S;
static APCUPSD_S apcupsd;
//
// encapsulated recv()
//
static int net_recv_ex(int sock, void *buf, int size, struct timeval *tv) {
fd_set fds;
int res;
// wait for some data to be read
do {
errno = 0;
FD_ZERO(&fds);
FD_SET(sock, &fds);
res = select(sock + 1, &fds, nullptr, nullptr, tv);
} while (res < 0 && errno == EINTR);
if (res < 0) { return 0; }
if (res == 0) {
// timeout
errno = ETIMEDOUT; // select was successful, errno is now 0
return 0;
}
// socket ready, read the data
do {
errno = 0;
res = recv(sock, static_cast<char *>(buf), size, 0);
} while (res < 0 && errno == EINTR);
if (res < 0) { return 0; }
if (res == 0) {
// orderly shutdown
errno = ENOTCONN;
return 0;
}
return res;
}
//
// read whole buffer or fail
//
static int net_recv(int sock, void *buf, int size) {
int todo = size;
int off = 0;
int len;
struct timeval tv = {0, 250000};
while (todo != 0) {
len = net_recv_ex(sock, static_cast<char *>(buf) + off, todo, &tv);
if (len == 0) { return 0; }
todo -= len;
off += len;
}
return 1;
}
//
// get one response line
//
static int get_line(int sock, char line[], short linesize) {
// get the line length
short sz;
if (net_recv(sock, &sz, sizeof(sz)) == 0) { return -1; }
sz = ntohs(sz);
if (sz == 0) { return 0; }
// get the line
while (sz >= linesize) {
// this is just a hack (being lazy), this should not happen anyway
net_recv(sock, line, linesize);
sz -= linesize;
}
if (net_recv(sock, line, sz) == 0) { return 0; }
line[sz] = 0;
return sz;
}
#define FILL(NAME, FIELD, FIRST) \
if (!strncmp(NAME, line, sizeof(NAME) - 1)) { \
strncpy(apc->items[FIELD], line + 11, APCUPSD_MAXSTR); \
/* remove trailing newline and assure termination */ \
apc->items[FIELD][len - 11 > APCUPSD_MAXSTR ? APCUPSD_MAXSTR : len - 12] = \
0; \
if (FIRST) { \
char *c; \
for (c = apc->items[FIELD]; *c; ++c) \
if (*c == ' ' && c > apc->items[FIELD] + 2) { \
*c = 0; \
break; \
} \
} \
}
//
// fills in the data received from a socket
//
static int fill_items(int sock, PAPCUPSD_S apc) {
char line[512];
int len;
while ((len = get_line(sock, line, sizeof(line))) != 0) {
// fill the right types in
FILL("UPSNAME", APCUPSD_NAME, FALSE);
FILL("MODEL", APCUPSD_MODEL, FALSE);
FILL("UPSMODE", APCUPSD_UPSMODE, FALSE);
FILL("CABLE", APCUPSD_CABLE, FALSE);
FILL("STATUS", APCUPSD_STATUS, TRUE);
FILL("LINEV", APCUPSD_LINEV, TRUE);
FILL("LOADPCT", APCUPSD_LOAD, TRUE);
FILL("BCHARGE", APCUPSD_CHARGE, TRUE);
FILL("TIMELEFT", APCUPSD_TIMELEFT, TRUE);
FILL("ITEMP", APCUPSD_TEMP, TRUE);
FILL("LASTXFER", APCUPSD_LASTXFER, FALSE);
}
return static_cast<int>(len == 0);
}
//
// Conky update function for apcupsd data
//
int update_apcupsd() {
int i;
APCUPSD_S apc;
int sock = -1;
for (i = 0; i < _APCUPSD_COUNT; ++i) {
memcpy(apc.items[i], "N/A", 4); // including \0
}
do {
struct addrinfo hints {};
struct addrinfo *ai, *rp;
int res;
short sz = 0;
char portbuf[8];
//
// connect to apcupsd daemon
//
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = 0;
hints.ai_protocol = 0;
snprintf(portbuf, 8, "%d", apcupsd.port);
res = getaddrinfo(apcupsd.host, portbuf, &hints, &ai);
if (res != 0) {
NORM_ERR("APCUPSD getaddrinfo: %s", gai_strerror(res));
break;
}
for (rp = ai; rp != nullptr; rp = rp->ai_next) {
sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (sock == -1) { continue; }
if (connect(sock, rp->ai_addr, rp->ai_addrlen) != -1) { break; }
close(sock);
sock = -1;
}
freeaddrinfo(ai);
if (rp == nullptr) {
// no error reporting, the daemon is probably not running
if (sock >= 0) { close(sock); }
break;
}
//
// send status request - "status" - 6B
//
sz = htons(6);
// no waiting to become writeable is really needed
if (send(sock, &sz, sizeof(sz), 0) != sizeof(sz) ||
send(sock, "status", 6, 0) != 6) {
perror("send");
close(sock);
break;
}
//
// read the lines of output and put them into the info structure
//
fill_items(sock, &apc);
close(sock);
} while (0);
//
// "atomically" copy the data into working set
//
memcpy(apcupsd.items, apc.items, sizeof(apcupsd.items));
return 0;
}
int apcupsd_scan_arg(const char *arg) {
char host[64];
int port;
if (sscanf(arg, "%63s %d", host, &port) != 2) { return 1; }
apcupsd.port = port;
strncpy(apcupsd.host, host, sizeof(apcupsd.host));
return 0;
}
double apcupsd_loadbarval(struct text_object *obj) {
(void)obj;
return atof(apcupsd.items[APCUPSD_LOAD]);
}
#define APCUPSD_PRINT_GENERATOR(name, idx) \
void print_apcupsd_##name(struct text_object *obj, char *p, \
unsigned int p_max_size) { \
(void)obj; \
snprintf(p, p_max_size, "%s", apcupsd.items[APCUPSD_##idx]); \
}
APCUPSD_PRINT_GENERATOR(name, NAME)
APCUPSD_PRINT_GENERATOR(model, MODEL)
APCUPSD_PRINT_GENERATOR(upsmode, UPSMODE)
APCUPSD_PRINT_GENERATOR(cable, CABLE)
APCUPSD_PRINT_GENERATOR(status, STATUS)
APCUPSD_PRINT_GENERATOR(linev, LINEV)
APCUPSD_PRINT_GENERATOR(load, LOAD)
APCUPSD_PRINT_GENERATOR(charge, CHARGE)
APCUPSD_PRINT_GENERATOR(timeleft, TIMELEFT)
APCUPSD_PRINT_GENERATOR(temp, TEMP)
APCUPSD_PRINT_GENERATOR(lastxfer, LASTXFER)
#undef APCUPSD_PRINT_GENERATOR
| 7,959
|
C++
|
.cc
| 254
| 27.661417
| 80
| 0.578111
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
22,606
|
update-cb.cc
|
brndnmtthws_conky/src/update-cb.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Please see COPYING for details
*
* Copyright (C) 2010 Pavel Labath et al.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "config.h"
#include "logging.h"
#include "update-cb.hh"
#include <unistd.h>
#include <typeinfo>
namespace conky {
namespace {
semaphore sem_wait;
enum { UNUSED_MAX = 5 };
} // namespace
namespace priv {
callback_base::~callback_base() { stop(); }
void callback_base::stop() {
if (thread != nullptr) {
done = true;
sem_start.post();
if (pipefd.second >= 0) {
if (write(pipefd.second, "X", 1) != 1) {
NORM_ERR("can't write 'X' to pipefd %d: %s", pipefd.second,
strerror(errno));
}
}
thread->join();
delete thread;
thread = nullptr;
}
if (pipefd.first >= 0) {
close(pipefd.first);
pipefd.first = -1;
}
if (pipefd.second >= 0) {
close(pipefd.second);
pipefd.second = -1;
}
}
inline size_t callback_base::get_hash(const handle &h) { return h->hash; }
inline bool callback_base::is_equal(const handle &a, const handle &b) {
if (a->hash != b->hash) { return false; }
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpotentially-evaluated-expression"
if (typeid(*a) != typeid(*b)) { return false; }
#pragma clang diagnostic pop
return *a == *b;
}
/*
* If a callback is not successfully inserted into the set, it must have
* the same hash as an existing callback. If this is so, merge the incoming
* callback with the one that prevented insertion. Keep the smaller of the
* two periods.
*/
void callback_base::merge(callback_base &&other) {
if (other.period < period) {
period = other.period;
remaining = 0;
}
assert(wait == other.wait);
unused = 0;
}
/*
* Register a callback (i.e. insert it into the callbacks set)
*/
callback_base::handle callback_base::do_register_cb(const handle &h) {
const auto &p = callbacks.insert(h);
/* insertion failed; callback already exists */
if (!p.second) { (*p.first)->merge(std::move(*h)); }
return *p.first;
}
void callback_base::run() {
if (thread == nullptr) {
thread = new std::thread(&callback_base::start_routine, this);
}
sem_start.post();
}
void callback_base::start_routine() {
for (;;) {
sem_start.wait();
if (done) { return; }
// clear any remaining posts in case the previous iteration was very slow
// (this should only happen if wait == false)
while (sem_start.trywait()) {
// do nothing
}
work();
if (wait) { sem_wait.post(); }
}
}
callback_base::Callbacks callback_base::callbacks(1, get_hash, is_equal);
} // namespace priv
void run_all_callbacks() {
using priv::callback_base;
size_t wait = 0;
for (auto i = callback_base::callbacks.begin();
i != callback_base::callbacks.end();) {
callback_base &cb = **i;
/* check whether enough update intervals have elapsed (up to period) */
if (cb.remaining-- == 0) {
/* run the callback as long as someone holds a pointer to it;
* if no one owns the callback, run it at most UNUSED_MAX times */
if (i->use_count() > 1 || ++cb.unused < UNUSED_MAX) {
cb.remaining = cb.period - 1;
cb.run();
if (cb.wait) { ++wait; }
}
}
if (cb.unused == UNUSED_MAX) {
auto t = i;
++i;
callback_base::callbacks.erase(t);
} else {
++i;
}
}
while (wait-- > 0) { sem_wait.wait(); }
}
} // namespace conky
| 4,105
|
C++
|
.cc
| 136
| 26.654412
| 77
| 0.655006
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,607
|
common.cc
|
brndnmtthws_conky/src/common.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <fcntl.h>
#include <net/if.h>
#include <netinet/in.h>
#include <pthread.h>
#include <semaphore.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <cctype>
#include <cerrno>
#include <ctime>
#include <vector>
#include <wordexp.h>
#include "config.h"
#include "conky.h"
#include "core.h"
#include "fs.h"
#include "logging.h"
#include "misc.h"
#include "net_stat.h"
#include "specials.h"
#include "temphelper.h"
#include "timeinfo.h"
#include "top.h"
/* check for OS and include appropriate headers */
#if defined(__linux__)
#include "linux.h"
#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
#include "freebsd.h"
#elif defined(__DragonFly__)
#include "dragonfly.h"
#elif defined(__OpenBSD__)
#include "openbsd.h"
#elif defined(__APPLE__) && defined(__MACH__)
#include "darwin.h" // strings.h
#endif
#include "update-cb.hh"
#ifdef BUILD_CURL
#include "ccurl_thread.h"
#endif /* BUILD_CURL */
/* folds a string over top of itself, like so:
*
* if start is "blah", and you call it with count = 1, the result will be "lah"
*/
void strfold(char *start, int count) {
char *curplace;
for (curplace = start + count; *curplace != 0; curplace++) {
*(curplace - count) = *curplace;
}
*(curplace - count) = 0;
}
#ifndef HAVE_STRNDUP
// use our own strndup() if it's not available
char *strndup(const char *s, size_t n) {
if (strlen(s) > n) {
char *ret = malloc(n + 1);
strncpy(ret, s, n);
ret[n] = 0;
return ret;
} else {
return strdup(s);
}
}
#endif /* HAVE_STRNDUP */
int update_uname() {
uname(&info.uname_s);
#if defined(__DragonFly__)
{
size_t desc_n;
char desc[256];
if (sysctlbyname("kern.version", nullptr, &desc_n, NULL, 0) == -1 ||
sysctlbyname("kern.version", desc, &desc_n, nullptr, 0) == -1)
perror("kern.version");
else {
char *start = desc;
strsep(&start, " ");
strcpy(info.uname_v, strsep(&start, " "));
}
if (errno == ENOMEM) printf("desc_n %zu\n", desc_n);
}
#endif
return 0;
}
double get_time() {
struct timespec tv {};
#ifdef _POSIX_MONOTONIC_CLOCK
clock_gettime(CLOCK_MONOTONIC, &tv);
#else
clock_gettime(CLOCK_REALTIME, &tv);
#endif
return tv.tv_sec + (tv.tv_nsec * 1e-9);
}
/* Converts '~/...' paths to '/home/blah/...'. It's similar to
* variable_substitute, works for any enviroment variable */
std::string to_real_path(const std::string &source) {
wordexp_t p;
char **w;
int i;
const char *csource = source.c_str();
if (wordexp(csource, &p, 0) != 0) {
return nullptr;
}
w = p.we_wordv;
const char *resolved_path = strdup(w[0]);
wordfree(&p);
return std::string(resolved_path);
}
int open_fifo(const char *file, int *reported) {
int fd = 0;
fd = open(file, O_RDONLY | O_NONBLOCK | O_CLOEXEC);
if (fd == -1) {
if ((reported == nullptr) || *reported == 0) {
NORM_ERR("can't open %s: %s", file, strerror(errno));
if (reported != nullptr) { *reported = 1; }
}
return -1;
}
return fd;
}
FILE *open_file(const char *file, int *reported) {
FILE *fp = nullptr;
fp = fopen(file, "re");
if (fp == nullptr) {
if ((reported == nullptr) || *reported == 0) {
NORM_ERR("can't open %s: %s", file, strerror(errno));
if (reported != nullptr) { *reported = 1; }
}
return nullptr;
}
return fp;
}
std::string variable_substitute(std::string s) {
std::string::size_type pos = 0;
while ((pos = s.find('$', pos)) != std::string::npos) {
if (pos + 1 >= s.size()) { break; }
if (s[pos + 1] == '$') {
s.erase(pos, 1);
++pos;
} else {
std::string var;
std::string::size_type l = 0;
if (isalpha(static_cast<unsigned char>(s[pos + 1])) != 0) {
l = 1;
while (pos + l < s.size() &&
(isalnum(static_cast<unsigned char>(s[pos + l])) != 0)) {
++l;
}
var = s.substr(pos + 1, l - 1);
} else if (s[pos + 1] == '{') {
l = s.find('}', pos);
if (l == std::string::npos) { break; }
l -= pos - 1;
var = s.substr(pos + 2, l - 3);
} else {
++pos;
}
if (l != 0u) {
s.erase(pos, l);
const char *val = getenv(var.c_str());
if (val != nullptr) {
s.insert(pos, val);
pos += strlen(val);
}
}
}
}
return s;
}
void format_seconds(char *buf, unsigned int n, long seconds) {
long days;
int hours, minutes;
if (times_in_seconds.get(*state)) {
snprintf(buf, n, "%ld", seconds);
return;
}
days = seconds / 86400;
seconds %= 86400;
hours = seconds / 3600;
seconds %= 3600;
minutes = seconds / 60;
seconds %= 60;
if (days > 0) {
snprintf(buf, n, "%ldd %dh %dm", days, hours, minutes);
} else {
snprintf(buf, n, "%dh %dm %lds", hours, minutes, seconds);
}
}
void format_seconds_short(char *buf, unsigned int n, long seconds) {
long days;
int hours, minutes;
if (times_in_seconds.get(*state)) {
snprintf(buf, n, "%ld", seconds);
return;
}
days = seconds / 86400;
seconds %= 86400;
hours = seconds / 3600;
seconds %= 3600;
minutes = seconds / 60;
seconds %= 60;
if (days > 0) {
snprintf(buf, n, "%ldd %dh", days, hours);
} else if (hours > 0) {
snprintf(buf, n, "%dh %dm", hours, minutes);
} else {
snprintf(buf, n, "%dm %lds", minutes, seconds);
}
}
conky::simple_config_setting<bool> no_buffers("no_buffers", true, true);
conky::simple_config_setting<std::string> bar_fill("console_bar_fill", "#",
false);
conky::simple_config_setting<std::string> bar_unfill("console_bar_unfill", ".",
false);
conky::simple_config_setting<std::string> github_token("github_token", "",
false);
void update_stuff() {
/* clear speeds, addresses and up status in case device was removed and
* doesn't get updated */
#ifdef HAVE_OPENMP
#pragma omp parallel for schedule(dynamic, 10)
#endif /* HAVE_OPENMP */
for (int i = 0; i < MAX_NET_INTERFACES; ++i) {
if (netstats[i].dev != nullptr) {
netstats[i].up = 0;
netstats[i].recv_speed = 0.0;
netstats[i].trans_speed = 0.0;
netstats[i].addr.sa_data[2] = 0;
netstats[i].addr.sa_data[3] = 0;
netstats[i].addr.sa_data[4] = 0;
netstats[i].addr.sa_data[5] = 0;
}
}
/* this is a stub on all platforms except solaris */
prepare_update();
/* if you registered a callback with conky::register_cb, this will run it */
conky::run_all_callbacks();
#if !defined(__linux__)
/* XXX: move the following into the update_meminfo() functions? */
if (no_buffers.get(*state)) {
info.mem -= info.bufmem;
info.memeasyfree += info.bufmem;
}
#endif
}
/* Ohkie to return negative values for temperatures */
int round_to_int_temp(float f) { return static_cast<int>(f); }
/* Don't return negative values for cpugraph, bar, gauge, percentage.
* Causes unreasonable numbers to show */
unsigned int round_to_positive_int(float f) {
if (f >= 0.0) { return static_cast<int>(f + 0.5); }
return 0;
}
void scan_loadavg_arg(struct text_object *obj, const char *arg) {
obj->data.i = 0;
if ((arg != nullptr) && (arg[1] == 0) &&
(isdigit(static_cast<unsigned char>(arg[0])) != 0)) {
obj->data.i = strtol(arg, nullptr, 10);
if (obj->data.i > 3 || obj->data.i < 1) {
NORM_ERR("loadavg arg needs to be in range (1,3)");
obj->data.i = 0;
}
}
/* convert to array index (or the default (-1)) */
obj->data.i--;
}
void print_loadavg(struct text_object *obj, char *p, unsigned int p_max_size) {
float *v = info.loadavg;
if (obj->data.i < 0) {
snprintf(p, p_max_size, "%.2f %.2f %.2f", v[0], v[1], v[2]);
} else {
snprintf(p, p_max_size, "%.2f", v[obj->data.i]);
}
}
void scan_no_update(struct text_object *obj, const char *arg) {
obj->data.s = static_cast<char *>(malloc(text_buffer_size.get(*state)));
evaluate(arg, obj->data.s, text_buffer_size.get(*state));
obj->data.s =
static_cast<char *>(realloc(obj->data.s, strlen(obj->data.s) + 1));
}
void free_no_update(struct text_object *obj) { free(obj->data.s); }
void print_no_update(struct text_object *obj, char *p,
unsigned int p_max_size) {
snprintf(p, p_max_size, "%s", obj->data.s);
}
#ifdef BUILD_GUI
void scan_loadgraph_arg(struct text_object *obj, const char *arg) {
scan_graph(obj, arg, 0, FALSE);
}
double loadgraphval(struct text_object *obj) {
(void)obj;
return info.loadavg[0];
}
#endif /* BUILD_GUI */
uint8_t cpu_percentage(struct text_object *obj) {
if (static_cast<unsigned int>(obj->data.i) > info.cpu_count) {
NORM_ERR("obj->data.i %i info.cpu_count %i", obj->data.i, info.cpu_count);
CRIT_ERR("attempting to use more CPUs than you have!");
}
if (info.cpu_usage != nullptr) {
return round_to_positive_int(info.cpu_usage[obj->data.i] * 100.0);
}
return 0;
}
double cpu_barval(struct text_object *obj) {
if (static_cast<unsigned int>(obj->data.i) > info.cpu_count) {
NORM_ERR("obj->data.i %i info.cpu_count %i", obj->data.i, info.cpu_count);
CRIT_ERR("attempting to use more CPUs than you have!");
}
if (info.cpu_usage != nullptr) { return info.cpu_usage[obj->data.i]; }
return 0.;
}
#define PRINT_HR_GENERATOR(name) \
void print_##name(struct text_object *obj, char *p, \
unsigned int p_max_size) { \
human_readable(apply_base_multiplier(obj->data.s, info.name), p, \
p_max_size); \
}
PRINT_HR_GENERATOR(mem)
PRINT_HR_GENERATOR(memwithbuffers)
PRINT_HR_GENERATOR(memeasyfree)
PRINT_HR_GENERATOR(legacymem)
PRINT_HR_GENERATOR(memactive)
PRINT_HR_GENERATOR(meminactive)
PRINT_HR_GENERATOR(memfree)
PRINT_HR_GENERATOR(memmax)
PRINT_HR_GENERATOR(memdirty)
PRINT_HR_GENERATOR(shmem)
PRINT_HR_GENERATOR(memavail)
PRINT_HR_GENERATOR(memwired)
PRINT_HR_GENERATOR(memlaundry)
PRINT_HR_GENERATOR(swap)
PRINT_HR_GENERATOR(swapfree)
PRINT_HR_GENERATOR(swapmax)
uint8_t mem_percentage(struct text_object *obj) {
(void)obj;
return (info.memmax != 0u
? round_to_positive_int(info.mem * 100 / info.memmax)
: 0);
}
double mem_barval(struct text_object *obj) {
(void)obj;
return info.memmax != 0u ? (static_cast<double>(info.mem) / info.memmax) : 0;
}
double mem_with_buffers_barval(struct text_object *obj) {
(void)obj;
return info.memmax != 0u
? (static_cast<double>(info.memwithbuffers) / info.memmax)
: 0;
}
uint8_t swap_percentage(struct text_object *obj) {
(void)obj;
return (info.swapmax != 0u
? round_to_positive_int(info.swap * 100 / info.swapmax)
: 0);
}
double swap_barval(struct text_object *obj) {
(void)obj;
return info.swapmax != 0u ? (static_cast<double>(info.swap) / info.swapmax)
: 0;
}
void print_kernel(struct text_object *obj, char *p, unsigned int p_max_size) {
(void)obj;
snprintf(p, p_max_size, "%s", info.uname_s.release);
}
void print_machine(struct text_object *obj, char *p, unsigned int p_max_size) {
(void)obj;
snprintf(p, p_max_size, "%s", info.uname_s.machine);
}
void print_nodename(struct text_object *obj, char *p, unsigned int p_max_size) {
(void)obj;
snprintf(p, p_max_size, "%s", info.uname_s.nodename);
}
void print_nodename_short(struct text_object *obj, char *p,
unsigned int p_max_size) {
(void)obj;
snprintf(p, p_max_size, "%s", info.uname_s.nodename);
for (int i = 0; p[i] != 0; i++) {
if (p[i] == '.') {
p[i] = 0;
break;
}
}
}
void print_sysname(struct text_object *obj, char *p, unsigned int p_max_size) {
(void)obj;
snprintf(p, p_max_size, "%s", info.uname_s.sysname);
}
#if defined(__DragonFly__)
void print_version(struct text_object *obj, char *p, unsigned int p_max_size) {
(void)obj;
snprintf(p, p_max_size, "%s", info.uname_v);
}
#endif
void print_uptime(struct text_object *obj, char *p, unsigned int p_max_size) {
(void)obj;
format_seconds(p, p_max_size, static_cast<int>(info.uptime));
}
void print_uptime_short(struct text_object *obj, char *p,
unsigned int p_max_size) {
(void)obj;
format_seconds_short(p, p_max_size, static_cast<int>(info.uptime));
}
void print_processes(struct text_object *obj, char *p,
unsigned int p_max_size) {
(void)obj;
spaced_print(p, p_max_size, "%hu", 4, info.procs);
}
void print_running_processes(struct text_object *obj, char *p,
unsigned int p_max_size) {
(void)obj;
spaced_print(p, p_max_size, "%hu", 4, info.run_procs);
}
void print_running_threads(struct text_object *obj, char *p,
unsigned int p_max_size) {
(void)obj;
spaced_print(p, p_max_size, "%hu", 4, info.run_threads);
}
void print_threads(struct text_object *obj, char *p, unsigned int p_max_size) {
(void)obj;
spaced_print(p, p_max_size, "%hu", 4, info.threads);
}
void print_buffers(struct text_object *obj, char *p, unsigned int p_max_size) {
human_readable(apply_base_multiplier(obj->data.s, info.buffers), p,
p_max_size);
}
void print_cached(struct text_object *obj, char *p, unsigned int p_max_size) {
human_readable(apply_base_multiplier(obj->data.s, info.cached), p,
p_max_size);
}
void print_free_bufcache(struct text_object *obj, char *p,
unsigned int p_max_size) {
human_readable(apply_base_multiplier(obj->data.s, info.free_bufcache), p,
p_max_size);
}
void print_free_cached(struct text_object *obj, char *p,
unsigned int p_max_size) {
human_readable(apply_base_multiplier(obj->data.s, info.free_cached), p,
p_max_size);
}
void print_evaluate(struct text_object *obj, char *p, unsigned int p_max_size) {
std::vector<char> buf(text_buffer_size.get(*state));
evaluate(obj->data.s, &buf[0], buf.size());
evaluate(&buf[0], p, p_max_size);
}
int if_empty_iftest(struct text_object *obj) {
std::vector<char> buf(max_user_text.get(*state));
int result = 1;
generate_text_internal(&(buf[0]), max_user_text.get(*state), *obj->sub);
if (strlen(&(buf[0])) != 0) { result = 0; }
return result;
}
static int check_contains(char *f, char *s) {
int ret = 0;
FILE *where = open_file(f, nullptr);
if (where != nullptr) {
char buf1[256];
while (fgets(buf1, 256, where) != nullptr) {
if (strstr(buf1, s) != nullptr) {
ret = 1;
break;
}
}
fclose(where);
} else {
NORM_ERR("Could not open the file");
}
return ret;
}
int if_existing_iftest(struct text_object *obj) {
char *spc;
int result = 0;
spc = strchr(obj->data.s, ' ');
if (spc != nullptr) { *spc = 0; }
if (access(obj->data.s, F_OK) == 0) {
if (spc == nullptr || (check_contains(obj->data.s, spc + 1) != 0)) {
result = 1;
}
}
if (spc != nullptr) { *spc = ' '; }
return result;
}
int if_running_iftest(struct text_object *obj) {
#ifdef __linux__
if (!get_process_by_name(obj->data.s)) {
#else
if (((obj->data.s) != nullptr) && (system(obj->data.s) != 0)) {
#endif
return 0;
}
return 1;
}
#ifndef __OpenBSD__
void print_acpitemp(struct text_object *obj, char *p, unsigned int p_max_size) {
temp_print(p, p_max_size, get_acpi_temperature(obj->data.i), TEMP_CELSIUS, 1);
}
void free_acpitemp(struct text_object *obj) { close(obj->data.i); }
#endif /* !__OpenBSD__ */
void print_freq(struct text_object *obj, char *p, unsigned int p_max_size) {
static int ok = 1;
if (ok != 0) { ok = get_freq(p, p_max_size, "%.0f", 1, obj->data.i); }
}
void print_freq_g(struct text_object *obj, char *p, unsigned int p_max_size) {
static int ok = 1;
if (ok != 0) {
#ifndef __OpenBSD__
ok = get_freq(p, p_max_size, "%'.2f", 1000, obj->data.i);
#else
/* OpenBSD has no such flag (SUSv2) */
ok = get_freq(p, p_max_size, "%.2f", 1000, obj->data.i);
#endif /* __OpenBSD */
}
}
#ifndef __OpenBSD__
void print_acpifan(struct text_object *obj, char *p, unsigned int p_max_size) {
(void)obj;
get_acpi_fan(p, p_max_size);
}
void print_acpiacadapter(struct text_object *obj, char *p,
unsigned int p_max_size) {
get_acpi_ac_adapter(p, p_max_size,
static_cast<const char *>(obj->data.opaque));
}
void print_battery(struct text_object *obj, char *p, unsigned int p_max_size) {
get_battery_stuff(p, p_max_size, obj->data.s, BATTERY_STATUS);
}
void print_battery_time(struct text_object *obj, char *p,
unsigned int p_max_size) {
get_battery_stuff(p, p_max_size, obj->data.s, BATTERY_TIME);
}
void battery_power_draw(struct text_object *obj, char *p,
unsigned int p_max_size) {
get_battery_power_draw(p, p_max_size, obj->data.s);
}
uint8_t battery_percentage(struct text_object *obj) {
return get_battery_perct(obj->data.s);
}
void print_battery_short(struct text_object *obj, char *p,
unsigned int p_max_size) {
get_battery_short_status(p, p_max_size, obj->data.s);
}
void print_battery_status(struct text_object *obj, char *p,
unsigned int p_max_size) {
get_battery_stuff(p, p_max_size, obj->data.s, BATTERY_STATUS);
if (0 == strncmp("charging", p, 8)) {
snprintf(p, p_max_size, "%s", "charging");
} else if (0 == strncmp("discharging", p, 11) ||
0 == strncmp("remaining", p, 9)) {
snprintf(p, p_max_size, "%s", "discharging");
} else if (0 == strncmp("charged", p, 7)) {
snprintf(p, p_max_size, "%s", "charged");
} else if (0 == strncmp("not present", p, 11) ||
0 == strncmp("absent/on AC", p, 12)) {
snprintf(p, p_max_size, "%s", "not present");
} else if (0 == strncmp("empty", p, 5)) {
snprintf(p, p_max_size, "%s", "empty");
} else if (0 == strncmp("unknown", p, 7)) {
snprintf(p, p_max_size, "%s", "unknown");
}
}
#endif /* !__OpenBSD__ */
void print_blink(struct text_object *obj, char *p, unsigned int p_max_size) {
// blinking like this can look a bit ugly if the chars in the font don't have
// the same width
std::vector<char> buf(max_user_text.get(*state));
static int visible = 1;
static int last_len = 0;
int i;
if (visible != 0) {
generate_text_internal(&(buf[0]), max_user_text.get(*state), *obj->sub);
last_len = strlen(&(buf[0]));
} else {
for (i = 0; i < last_len; i++) { buf[i] = ' '; }
}
snprintf(p, p_max_size, "%s", &(buf[0]));
visible = static_cast<int>(static_cast<int>(visible) == 0);
}
void print_include(struct text_object *obj, char *p, unsigned int p_max_size) {
std::vector<char> buf(max_user_text.get(*state));
if (obj->sub == nullptr) { return; }
generate_text_internal(&(buf[0]), max_user_text.get(*state), *obj->sub);
snprintf(p, p_max_size, "%s", &(buf[0]));
}
#ifdef BUILD_CURL
#define NEW_TOKEN \
"https://github.com/settings/tokens/" \
"new?scopes=notifications&description=conky-query-github\n"
static size_t read_github_data_cb(char *, size_t, size_t, char *);
static size_t read_github_data_cb(char *data, size_t size, size_t nmemb,
char *p) {
char *ptr = data;
size_t sz = nmemb * size;
size_t z = 0;
static size_t x = 0;
static unsigned int skip = 0U;
for (; *ptr; ptr++, z++) {
if (z + 4 < sz) { /* Verifying up to *(ptr+4) */
if ('u' == *ptr && 'n' == *(ptr + 1) && 'r' == *(ptr + 2) &&
'e' == *(ptr + 3)) { /* "unread" */
++x;
skip = 0U;
}
if ('m' == *ptr && 'e' == *(ptr + 1) && 's' == *(ptr + 2) &&
's' == *(ptr + 3) && z + 13 < sz) { /* "message": */
if ('B' == *(ptr + 10) && 'a' == *(ptr + 11) &&
'd' == *(ptr + 12)) { /* "Bad credentials" */
NORM_ERR("Bad credentials: generate a new token:\n" NEW_TOKEN);
snprintf(p, 80, "%s",
"GitHub: Bad credentials, generate a new token.");
skip = 1U;
break;
}
if ('M' == *(ptr + 10) && 'i' == *(ptr + 11) &&
's' == *(ptr + 12)) { /* Missing the 'notifications' scope. */
NORM_ERR(
"Missing 'notifications' scope. Generate a new "
"token\n" NEW_TOKEN);
snprintf(
p, 80, "%s",
"GitHub: Missing the notifications scope. Generate a new token.");
skip = 1U;
break;
}
}
}
}
if (0U == skip) { snprintf(p, 49, "%zu", x); }
return sz;
}
void print_github(struct text_object *obj, char *p, unsigned int p_max_size) {
(void)obj;
char github_url[256] = {""};
char user_agent[30] = {""};
static char cached_result[256] = {""};
static unsigned int last_update = 1U;
CURL *curl = nullptr;
CURLcode res;
if (0 == strcmp(github_token.get(*state).c_str(), "")) {
NORM_ERR(
"${github_notifications} requires token. "
"Go ahead and generate one " NEW_TOKEN
"Insert it in conky.config = { github_token='TOKEN_SHA' }\n");
snprintf(p, p_max_size, "%s",
"GitHub notifications requires token, generate a new one.");
return;
}
if (1U != last_update) {
--last_update;
snprintf(p, p_max_size, "%s", cached_result);
return;
}
snprintf(github_url, 255, "%s%s",
"https://api.github.com/notifications?access_token=",
github_token.get(*state).c_str());
/* unique string for each conky user, so we dont hit any query limits */
snprintf(user_agent, 29, "conky/%s", github_token.get(*state).c_str());
curl_global_init(CURL_GLOBAL_ALL);
if (nullptr == (curl = curl_easy_init())) { goto error; }
curl_easy_setopt(curl, CURLOPT_URL, github_url);
#if defined(CURLOPT_ACCEPT_ENCODING)
curl_easy_setopt(curl, CURLOPT_ACCEPT_ENCODING, "gzip");
#else /* defined(CURLOPT_ACCEPT_ENCODING) */
curl_easy_setopt(curl, CURLOPT_ENCODING, "gzip");
#endif /* defined(CURLOPT_ACCEPT_ENCODING) */
curl_easy_setopt(curl, CURLOPT_USERAGENT, user_agent);
curl_easy_setopt(curl, CURLOPT_USE_SSL, (long)CURLUSESSL_ALL);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 20L);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, read_github_data_cb);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, p);
res = curl_easy_perform(curl);
if (CURLE_OK != res) { goto error; }
snprintf(cached_result, 255, "%s", p);
last_update = 60U;
error:
if (nullptr != curl) { curl_easy_cleanup(curl); }
curl_global_cleanup();
if (!isdigit(static_cast<unsigned char>(*p))) { last_update = 1U; }
}
void print_stock(struct text_object *obj, char *p, unsigned int p_max_size) {
if (!obj->data.s) {
p[0] = 0;
return;
}
ccurl_process_info(p, p_max_size, obj->data.s, 1);
}
void free_stock(struct text_object *obj) { free(obj->data.s); }
#endif /* BUILD_CURL */
void print_to_bytes(struct text_object *obj, char *p, unsigned int p_max_size) {
std::vector<char> buf(max_user_text.get(*state));
long double bytes;
char unit[16]; // 16 because we can also have long names (like mega-bytes)
generate_text_internal(&(buf[0]), max_user_text.get(*state), *obj->sub);
if (sscanf(&(buf[0]), "%Lf%s", &bytes, unit) == 2 && strlen(unit) < 16) {
if (strncasecmp("b", unit, 1) == 0) {
snprintf(&(buf[0]), max_user_text.get(*state), "%Lf", bytes);
} else if (strncasecmp("k", unit, 1) == 0) {
snprintf(&(buf[0]), max_user_text.get(*state), "%Lf", bytes * 1024);
} else if (strncasecmp("m", unit, 1) == 0) {
snprintf(&(buf[0]), max_user_text.get(*state), "%Lf",
bytes * 1024 * 1024);
} else if (strncasecmp("g", unit, 1) == 0) {
snprintf(&(buf[0]), max_user_text.get(*state), "%Lf",
bytes * 1024 * 1024 * 1024);
} else if (strncasecmp("t", unit, 1) == 0) {
snprintf(&(buf[0]), max_user_text.get(*state), "%Lf",
bytes * 1024 * 1024 * 1024 * 1024);
}
}
snprintf(p, p_max_size, "%s", &(buf[0]));
}
void print_updates(struct text_object *obj, char *p, unsigned int p_max_size) {
(void)obj;
snprintf(p, p_max_size, "%d", get_total_updates());
}
int updatenr_iftest(struct text_object *obj) {
if (get_total_updates() % get_updatereset() != obj->data.i - 1) { return 0; }
return 1;
}
| 25,586
|
C++
|
.cc
| 744
| 29.880376
| 80
| 0.609394
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,608
|
temphelper.cc
|
brndnmtthws_conky/src/temphelper.cc
|
/*
*
* temphelper.c: aid in converting temperature units
*
* Copyright (C) 2008 Phil Sutter <Phil@nwl.cc>
*
* This library 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 2 of the License, or
* (at your option) any later version.
*
* This library 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 this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA.
*
*/
#include "temphelper.h"
#include <sys/types.h>
#include <cctype>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include "config.h"
#include "conky.h"
template <>
conky::lua_traits<TEMP_UNIT>::Map conky::lua_traits<TEMP_UNIT>::map = {
{"celsius", TEMP_CELSIUS}, {"fahrenheit", TEMP_FAHRENHEIT}};
static conky::simple_config_setting<TEMP_UNIT> output_unit("temperature_unit",
TEMP_CELSIUS, true);
static double fahrenheit_to_celsius(double n) { return ((n - 32) * 5 / 9); }
static double celsius_to_fahrenheit(double n) { return ((n * 9 / 5) + 32); }
static double convert_temp_output(double n, enum TEMP_UNIT input_unit) {
if (input_unit == output_unit.get(*state)) { return n; }
switch (output_unit.get(*state)) {
case TEMP_CELSIUS:
return fahrenheit_to_celsius(n);
case TEMP_FAHRENHEIT:
return celsius_to_fahrenheit(n);
}
/* NOT REACHED */
return 0.0;
}
int temp_print(char *p, size_t p_max_size, double n, enum TEMP_UNIT input_unit,
int to_int) {
int i_out = 0;
float f_out = 0.0;
size_t plen = 0;
if (1 == to_int) {
i_out = round_to_int_temp(convert_temp_output(n, input_unit));
plen = spaced_print(p, p_max_size, "%d", 3, i_out);
} else {
f_out = convert_temp_output(n, input_unit);
plen = spaced_print(p, p_max_size, "%.2f", 3, f_out);
}
return static_cast<int>(!(plen >= p_max_size));
}
| 2,287
|
C++
|
.cc
| 62
| 33.193548
| 79
| 0.67659
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
22,609
|
combine.cc
|
brndnmtthws_conky/src/combine.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <vector>
#include "core.h"
#include "logging.h"
#include "text_object.h"
struct combine_data {
char *left;
char *seperation;
char *right;
};
void parse_combine_arg(struct text_object *obj, const char *arg) {
struct combine_data *cd;
unsigned int i, j;
unsigned int indenting = 0; // vars can be used as args for other vars
int startvar[2];
int endvar[2];
startvar[0] = endvar[0] = startvar[1] = endvar[1] = -1;
j = 0;
for (i = 0; arg[i] != 0 && j < 2; i++) {
if (startvar[j] == -1) {
if (arg[i] == '$') { startvar[j] = i; }
} else if (endvar[j] == -1) {
if (arg[i] == '{') {
indenting++;
} else if (arg[i] == '}') {
indenting--;
}
if (indenting == 0 &&
arg[i + 1] < 48) { //<48 has 0, $, and the most used chars not used
// in varnames but not { or }
endvar[j] = i + 1;
j++;
}
}
}
if (startvar[0] >= 0 && endvar[0] >= 0 && startvar[1] >= 0 &&
endvar[1] >= 0) {
cd =
static_cast<struct combine_data *>(malloc(sizeof(struct combine_data)));
memset(cd, 0, sizeof(struct combine_data));
cd->left = static_cast<char *>(malloc(endvar[0] - startvar[0] + 1));
cd->seperation = static_cast<char *>(malloc(startvar[1] - endvar[0] + 1));
cd->right = static_cast<char *>(malloc(endvar[1] - startvar[1] + 1));
strncpy(cd->left, arg + startvar[0], endvar[0] - startvar[0]);
cd->left[endvar[0] - startvar[0]] = 0;
strncpy(cd->seperation, arg + endvar[0], startvar[1] - endvar[0]);
cd->seperation[startvar[1] - endvar[0]] = 0;
strncpy(cd->right, arg + startvar[1], endvar[1] - startvar[1]);
cd->right[endvar[1] - startvar[1]] = 0;
obj->sub =
static_cast<struct text_object *>(malloc(sizeof(struct text_object)));
extract_variable_text_internal(obj->sub, cd->left);
obj->sub->sub =
static_cast<struct text_object *>(malloc(sizeof(struct text_object)));
extract_variable_text_internal(obj->sub->sub, cd->right);
obj->data.opaque = cd;
} else {
throw combine_needs_2_args_error();
}
}
void print_combine(struct text_object *obj, char *p, unsigned int p_max_size) {
auto *cd = static_cast<struct combine_data *>(obj->data.opaque);
std::vector<std::vector<char>> buf;
buf.resize(2);
buf[0].resize(max_user_text.get(*state));
buf[1].resize(max_user_text.get(*state));
int i, j;
int p_len_remaining = p_max_size - 1;
long longest = 0;
int nextstart;
int nr_rows[2];
struct llrows {
char *row;
struct llrows *next;
};
struct llrows *ll_rows[2], *current[2];
struct text_object *objsub = obj->sub;
if ((cd == nullptr) || (p_max_size == 0)) { return; }
p[0] = 0;
for (i = 0; i < 2; i++) {
nr_rows[i] = 1;
nextstart = 0;
ll_rows[i] = static_cast<struct llrows *>(malloc(sizeof(struct llrows)));
current[i] = ll_rows[i];
for (j = 0; j < i; j++) { objsub = objsub->sub; }
generate_text_internal(&(buf[i][0]), max_user_text.get(*state), *objsub);
for (j = 0; buf[i][j] != 0; j++) {
if (buf[i][j] == '\t') { buf[i][j] = ' '; }
if (buf[i][j] == '\n') {
buf[i][j] = 0; // the vars inside combine may not have a \n at the end
}
if (buf[i][j] ==
2) { // \002 is used instead of \n to separate lines inside a var
buf[i][j] = 0;
current[i]->row = strdup(&(buf[i][0]) + nextstart);
if (i == 0 && static_cast<long>(strlen(current[i]->row)) > longest) {
longest = static_cast<long>(strlen(current[i]->row));
}
current[i]->next =
static_cast<struct llrows *>(malloc(sizeof(struct llrows)));
current[i] = current[i]->next;
nextstart = j + 1;
nr_rows[i]++;
}
}
current[i]->row = strdup(&(buf[i][0]) + nextstart);
if (i == 0 && static_cast<long>(strlen(current[i]->row)) > longest) {
longest = static_cast<long>(strlen(current[i]->row));
}
current[i]->next = nullptr;
current[i] = ll_rows[i];
}
for (j = 0; j < (nr_rows[0] > nr_rows[1] ? nr_rows[0] : nr_rows[1]); j++) {
if (current[0] != nullptr) {
strncat(p, current[0]->row, p_len_remaining);
p_len_remaining -= strlen(current[0]->row);
i = strlen(current[0]->row);
} else {
i = 0;
}
while (i < longest) {
strncat(p, " ", p_len_remaining);
p_len_remaining -= 2;
i++;
}
if (current[1] != nullptr) {
p_len_remaining -= strlen(cd->seperation);
strncat(p, cd->seperation, p_len_remaining);
p_len_remaining -= strlen(current[1]->row);
strncat(p, current[1]->row, p_len_remaining);
}
strncat(p, "\n", p_len_remaining);
p_len_remaining -= 2;
#ifdef HAVE_OPENMP
#pragma omp parallel for schedule(dynamic, 10)
#endif /* HAVE_OPENMP */
for (i = 0; i < 2; i++) {
if (current[i] != nullptr) { current[i] = current[i]->next; }
}
}
#ifdef HAVE_OPENMP
#pragma omp parallel for schedule(dynamic, 10)
#endif /* HAVE_OPENMP */
for (i = 0; i < 2; i++) {
while (ll_rows[i] != nullptr) {
current[i] = ll_rows[i];
free(current[i]->row);
ll_rows[i] = current[i]->next;
free(current[i]);
}
}
}
void free_combine(struct text_object *obj) {
auto *cd = static_cast<struct combine_data *>(obj->data.opaque);
if (cd == nullptr) { return; }
free(cd->left);
free(cd->seperation);
free(cd->right);
free_text_objects(obj->sub->sub);
free_and_zero(obj->sub->sub);
free_text_objects(obj->sub);
free_and_zero(obj->sub);
free_and_zero(obj->data.opaque);
}
| 6,668
|
C++
|
.cc
| 191
| 30.240838
| 80
| 0.598174
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
22,610
|
exec.cc
|
brndnmtthws_conky/src/exec.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "exec.h"
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <cmath>
#include <cstdio>
#include <mutex>
#include "conky.h"
#include "core.h"
#include "logging.h"
#include "specials.h"
#include "text_object.h"
#include "update-cb.hh"
struct execi_data {
float interval{0};
char *cmd{nullptr};
execi_data() = default;
};
static const int cmd_len = 256;
static char cmd[cmd_len];
static char *remove_excess_quotes(const char *);
static char *remove_excess_quotes(const char *command) {
char *cmd_ptr = cmd;
const char *command_ptr = command;
int skip = 0;
if ((cmd_len - 1) < (strlen(command) - 1)) {
snprintf(cmd, cmd_len - 1, "%s", command);
return cmd;
}
if (*command_ptr == '"' || *command_ptr == '\'') {
skip = 1;
command_ptr++;
}
for (; *command_ptr; command_ptr++) {
if ('\0' == *(command_ptr + 1) && 1 == skip &&
(*command_ptr == '"' || *command_ptr == '\'')) {
continue;
}
*cmd_ptr++ = *command_ptr;
}
*cmd_ptr = '\0';
return cmd;
}
// our own implementation of popen, the difference : the value of 'childpid'
// will be filled with the pid of the running 'command'. This is useful if want
// to kill it when it hangs while reading or writing to it. We have to kill it
// because pclose will wait until the process dies by itself
static FILE *pid_popen(const char *command, const char *mode, pid_t *child) {
int ends[2];
int parentend, childend;
// by running pipe after the strcmp's we make sure that we don't have to
// create a pipe and close the ends if mode is something illegal
if (strcmp(mode, "r") == 0) {
if (pipe(ends) != 0) { return nullptr; }
parentend = ends[0];
childend = ends[1];
} else if (strcmp(mode, "w") == 0) {
if (pipe(ends) != 0) { return nullptr; }
parentend = ends[1];
childend = ends[0];
} else {
return nullptr;
}
*child = fork();
if (*child == -1) {
close(parentend);
close(childend);
return nullptr;
}
if (*child > 0) {
close(childend);
waitpid(*child, nullptr, 0);
} else {
// don't read from both stdin and pipe or write to both stdout and pipe
if (childend == ends[0]) {
close(0);
} else {
close(1);
}
close(parentend);
// by dupping childend, the returned fd will have close-on-exec turned off
if (fcntl(childend, F_DUPFD, 0) == -1) { perror("fcntl()"); }
close(childend);
execl("/bin/sh", "sh", "-c", remove_excess_quotes(command),
(char *)nullptr);
_exit(EXIT_FAILURE); // child should die here, (normally execl will take
// care of this but it can fail)
}
return fdopen(parentend, mode);
}
/**
* Executes a command and stores the result
*
* This function is called automatically, either once every update
* interval, or at specific intervals in the case of execi commands.
* conky::run_all_callbacks() handles this. In order for this magic to
* happen, we must register a callback with conky::register_cb<exec_cb>()
* and store it somewhere, such as obj->exec_handle. To retrieve the
* results, use the stored callback to call get_result_copy(), which
* returns a std::string.
*/
void exec_cb::work() {
pid_t childpid;
std::string buf;
std::shared_ptr<FILE> fp;
char b[0x1000];
if (FILE *t = pid_popen(std::get<0>(tuple).c_str(), "r", &childpid)) {
fp.reset(t, fclose);
} else {
return;
}
while ((feof(fp.get()) == 0) && (ferror(fp.get()) == 0)) {
int length = fread(b, 1, sizeof b, fp.get());
buf.append(b, length);
}
if (*buf.rbegin() == '\n') { buf.resize(buf.size() - 1); }
std::lock_guard<std::mutex> l(result_mutex);
result = buf;
}
// remove backspaced chars, example: "dog^H^H^Hcat" becomes "cat"
// string has to end with \0 and it's length should fit in a int
#define BACKSPACE 8
static void remove_deleted_chars(char *string, unsigned int p_max_size) {
int i = 0;
while (string[i] != 0) {
if (string[i] == BACKSPACE) {
if (i != 0) {
strncpy(&(string[i - 1]), &(string[i + 1]),
strnlen(string, p_max_size) - i + 1);
i--;
} else {
strncpy(&(string[i]), &(string[i + 1]),
strnlen(string, p_max_size) -
i); // necessary for ^H's at the start of a string
}
} else {
i++;
}
}
}
/**
* Parses command output to find a number between 0.0 and 100.0.
* Used by ${exec[i]{bar,gauge,graph}}.
*
* @param[in] buf output of a command executed by an exec_cb object
* @return number between 0.0 and 100.0
*/
static inline double get_barnum(const char *buf) {
double barnum;
if (sscanf(buf, "%lf", &barnum) != 1) {
NORM_ERR(
"reading exec value failed (perhaps it's not the "
"correct format?)");
return 0.0;
}
if (barnum > 100.0 || barnum < 0.0) {
NORM_ERR(
"your exec value is not between 0 and 100, "
"therefore it will be ignored");
return 0.0;
}
return barnum;
}
/**
* Store command output in p. For execp objects, we process the output
* in case it contains special commands like ${color}
*
* @param[in] buffer the output of a command
* @param[in] obj text_object that specifies whether or not to parse
* @param[out] p the string in which we store command output
* @param[in] p_max_size the maximum size of p...
*/
void fill_p(const char *buffer, struct text_object *obj, char *p,
unsigned int p_max_size) {
if (obj->parse) {
evaluate(buffer, p, p_max_size);
} else {
snprintf(p, p_max_size, "%s", buffer);
}
remove_deleted_chars(p, p_max_size);
}
/**
* Parses arg to find the command to be run, as well as special options
* like height, width, color, and update interval
*
* @param[out] obj stores the command and an execi_data structure (if
* applicable)
* @param[in] arg the argument to an ${exec*} object
* @param[in] execflag bitwise flag used to specify the exec variant we need to
* process
*/
void scan_exec_arg(struct text_object *obj, const char *arg,
unsigned int execflag) {
const char *cmd = arg;
char *orig_cmd = nullptr;
struct execi_data *ed;
/* in case we have an execi object, we need to parse out the interval */
if ((execflag & EF_EXECI) != 0u) {
ed = new execi_data;
int n;
/* store the interval in ed->interval */
if (sscanf(arg, "%f %n", &ed->interval, &n) <= 0) {
NORM_ERR("missing execi interval: ${execi* <interval> command}");
delete ed;
ed = nullptr;
return;
}
/* set cmd to everything after the interval */
cmd = strndup(arg + n, text_buffer_size.get(*state));
orig_cmd = const_cast<char *>(cmd);
}
/* parse any special options for the graphical exec types */
if ((execflag & EF_BAR) != 0u) {
cmd = scan_bar(obj, cmd, 100);
#ifdef BUILD_GUI
} else if ((execflag & EF_GAUGE) != 0u) {
cmd = scan_gauge(obj, cmd, 100);
} else if ((execflag & EF_GRAPH) != 0u) {
auto [buf, skip] = scan_command(cmd);
scan_graph(obj, cmd + skip, 100, FALSE);
cmd = buf;
if (cmd == nullptr) {
NORM_ERR("error parsing arguments to execgraph object");
}
#endif /* BUILD_GUI */
}
/* finally, store the resulting command, or an empty string if something went
* wrong */
if ((execflag & EF_EXEC) != 0u) {
obj->data.s =
strndup(cmd != nullptr ? cmd : "", text_buffer_size.get(*state));
} else if ((execflag & EF_EXECI) != 0u) {
ed->cmd = strndup(cmd != nullptr ? cmd : "", text_buffer_size.get(*state));
obj->data.opaque = ed;
}
free_and_zero(orig_cmd);
}
/**
* Register an exec_cb object using the command that we have parsed
*
* @param[out] obj stores the callback handle
*/
void register_exec(struct text_object *obj) {
if ((obj->data.s != nullptr) && (obj->data.s[0] != 0)) {
obj->exec_handle = new conky::callback_handle<exec_cb>(
conky::register_cb<exec_cb>(1, true, obj->data.s));
} else {
DBGP("unable to register exec callback");
}
}
/**
* Register an exec_cb object using the command that we have parsed.
*
* This version takes care of execi intervals. Note that we depend on
* obj->thread, so be sure to run this function *after* setting obj->thread.
*
* @param[out] obj stores the callback handle
*/
void register_execi(struct text_object *obj) {
auto *ed = static_cast<struct execi_data *>(obj->data.opaque);
if ((ed != nullptr) && (ed->cmd != nullptr) && (ed->cmd[0] != 0)) {
uint32_t period =
std::max(lround(ed->interval / active_update_interval()), 1l);
obj->exec_handle = new conky::callback_handle<exec_cb>(
conky::register_cb<exec_cb>(period, !obj->thread, ed->cmd));
} else {
DBGP("unable to register execi callback");
}
}
/**
* Get the results of an exec_cb object (command output)
*
* @param[in] obj holds an exec_handle, assuming one was registered
* @param[out] p the string in which we store command output
* @param[in] p_max_size the maximum size of p...
*/
void print_exec(struct text_object *obj, char *p, unsigned int p_max_size) {
if (obj->exec_handle != nullptr) {
fill_p((*obj->exec_handle)->get_result_copy().c_str(), obj, p, p_max_size);
}
}
/**
* Get the results of a graphical (bar, gauge, graph) exec_cb object
*
* @param[in] obj hold an exec_handle, assuming one was registered
* @return a value between 0.0 and 100.0
*/
double execbarval(struct text_object *obj) {
if (obj->exec_handle != nullptr) {
return get_barnum((*obj->exec_handle)->get_result_copy().c_str());
}
return 0.0;
}
/**
* Free up any dynamically allocated data
*
* @param[in] obj holds the data that we need to free up
*/
void free_exec(struct text_object *obj) {
free_and_zero(obj->data.s);
delete obj->exec_handle;
obj->exec_handle = nullptr;
}
/**
* Free up any dynamically allocated data, specifically for execi objects
*
* @param[in] obj holds the data that we need to free up
*/
void free_execi(struct text_object *obj) {
auto *ed = static_cast<struct execi_data *>(obj->data.opaque);
/* if ed is nullptr, there is nothing to do */
if (ed == nullptr) { return; }
delete obj->exec_handle;
obj->exec_handle = nullptr;
free_and_zero(ed->cmd);
delete ed;
ed = nullptr;
obj->data.opaque = nullptr;
}
| 11,403
|
C++
|
.cc
| 348
| 29.25
| 79
| 0.648842
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,611
|
x11.cc
|
brndnmtthws_conky/src/x11.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "config.h"
#include "x11-settings.h"
#include "x11.h"
#include <X11/X.h>
#include <X11/Xlibint.h>
#undef min
#undef max
#include <sys/types.h>
#include "common.h"
#include "conky.h"
#include "geometry.h"
#include "gui.h"
#include "logging.h"
#ifdef BUILD_XINPUT
#include "mouse-events.h"
#include <vector>
#endif
#include <algorithm>
#include <array>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <numeric>
#include <string>
// #ifndef OWN_WINDOW
// #include <iostream>
// #endif
extern "C" {
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wvariadic-macros"
#pragma GCC diagnostic ignored "-Wregister"
#include <X11/XKBlib.h>
#pragma GCC diagnostic pop
#include <X11/Xatom.h>
#include <X11/Xlib.h>
#include <X11/Xmd.h>
#include <X11/Xutil.h>
#ifdef BUILD_IMLIB2
#include "conky-imlib2.h"
#endif /* BUILD_IMLIB2 */
#ifdef BUILD_XFT
#include <X11/Xft/Xft.h>
#endif
#ifdef BUILD_XINERAMA
#include <X11/extensions/Xinerama.h>
#endif
#ifdef BUILD_XSHAPE
#include <X11/extensions/shape.h>
#endif /* BUILD_XSHAPE */
#ifdef BUILD_XFIXES
#include <X11/extensions/Xfixes.h>
#endif /* BUILD_XFIXES */
#ifdef BUILD_XINPUT
#include <X11/extensions/XInput.h>
#include <X11/extensions/XInput2.h>
#endif /* BUILD_XINPUT */
#ifdef HAVE_XCB_ERRORS
#include <xcb/xcb.h>
#include <xcb/xcb_errors.h>
#endif
#include <X11/Xresource.h>
}
Display *display = nullptr;
int screen;
#ifdef HAVE_XCB_ERRORS
xcb_connection_t *xcb_connection;
xcb_errors_context_t *xcb_errors_ctx;
#endif
/* Window stuff */
struct conky_x11_window window;
bool have_argb_visual = false;
/* local prototypes */
static Window find_desktop_window(Window *p_root, Window *p_desktop);
static Window find_desktop_window_impl(Window win, int w, int h);
/* WARNING, this type not in Xlib spec */
static int x11_error_handler(Display *d, XErrorEvent *err) {
char *error_name = nullptr;
bool name_allocated = false;
char *code_description = nullptr;
bool code_allocated = false;
#ifdef HAVE_XCB_ERRORS
if (xcb_errors_ctx != nullptr) {
const char *extension;
const char *base_name = xcb_errors_get_name_for_error(
xcb_errors_ctx, err->error_code, &extension);
if (extension != nullptr) {
const std::size_t size = strlen(base_name) + strlen(extension) + 4;
error_name = new char[size];
snprintf(error_name, size, "%s (%s)", base_name, extension);
name_allocated = true;
} else {
error_name = const_cast<char *>(base_name);
}
const char *major =
xcb_errors_get_name_for_major_code(xcb_errors_ctx, err->request_code);
const char *minor = xcb_errors_get_name_for_minor_code(
xcb_errors_ctx, err->request_code, err->minor_code);
if (minor != nullptr) {
const std::size_t size = strlen(major) + strlen(minor) + 4;
code_description = new char[size];
snprintf(code_description, size, "%s - %s", major, minor);
code_allocated = true;
} else {
code_description = const_cast<char *>(major);
}
}
#endif
if (error_name == nullptr) {
if (err->error_code > 0 && err->error_code < 17) {
static std::array<std::string, 17> NAMES = {
"request", "value", "window", "pixmap", "atom",
"cursor", "font", "match", "drawable", "access",
"alloc", "colormap", "G context", "ID choice", "name",
"length", "implementation"};
error_name = const_cast<char *>(NAMES[err->error_code].c_str());
} else {
static char code_name_buffer[5];
error_name = reinterpret_cast<char *>(&code_name_buffer);
snprintf(error_name, 4, "%d", err->error_code);
}
}
if (code_description == nullptr) {
const std::size_t size = 37;
code_description = new char[size];
snprintf(code_description, size, "error code: [major: %i, minor: %i]",
err->request_code, err->minor_code);
code_allocated = true;
}
DBGP(
"X %s Error:\n"
"Display: %lx, XID: %li, Serial: %lu\n"
"%s",
error_name, reinterpret_cast<uint64_t>(err->display),
static_cast<int64_t>(err->resourceid), err->serial, code_description);
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wfree-nonheap-object"
// *_allocated takes care of avoiding freeing unallocated objects
if (name_allocated) delete[] error_name;
if (code_allocated) delete[] code_description;
#pragma GCC diagnostic pop
return 0;
}
__attribute__((noreturn)) static int x11_ioerror_handler(Display *d) {
CRIT_ERR("X IO Error: Display %lx\n", reinterpret_cast<uint64_t>(d));
}
/// @brief Function to get virtual root windows of screen.
///
/// Some WMs (swm, tvtwm, amiwm, enlightenment, etc.) use virtual roots to
/// manage workspaces. These are direct descendants of root and WMs reparent all
/// children to them.
///
/// @param screen screen to get the (current) virtual root of
/// @return the virtual root window of the screen
static Window VRootWindowOfScreen(Screen *screen) {
Window root = RootWindowOfScreen(screen);
Display *dpy = DisplayOfScreen(screen);
/* go look for a virtual root */
Atom _NET_VIRTUAL_ROOTS = XInternAtom(display, "_NET_VIRTUAL_ROOTS", True);
if (_NET_VIRTUAL_ROOTS == 0) return root;
auto vroots = x11_atom_window_list(dpy, root, _NET_VIRTUAL_ROOTS);
if (vroots.empty()) return root;
Atom _NET_CURRENT_DESKTOP =
XInternAtom(display, "_NET_CURRENT_DESKTOP", True);
if (_NET_CURRENT_DESKTOP == 0) return root;
Atom actual_type;
int actual_format;
unsigned long nitems, bytesafter;
int *cardinal;
XGetWindowProperty(dpy, root, _NET_CURRENT_DESKTOP, 0, 1, False, XA_CARDINAL,
&actual_type, &actual_format, &nitems, &bytesafter,
(unsigned char **)&cardinal);
if (vroots.size() > *cardinal) { root = vroots[*cardinal]; }
XFree(cardinal);
return root;
}
inline Window VRootWindow(Display *display, int screen) {
return VRootWindowOfScreen(ScreenOfDisplay(display, screen));
}
inline Window DefaultVRootWindow(Display *display) {
return VRootWindowOfScreen(DefaultScreenOfDisplay(display));
}
/* X11 initializer */
void init_x11() {
DBGP("enter init_x11()");
if (display == nullptr) {
const std::string &dispstr = display_name.get(*state);
// passing nullptr to XOpenDisplay should open the default display
const char *disp = static_cast<unsigned int>(!dispstr.empty()) != 0u
? dispstr.c_str()
: nullptr;
if ((display = XOpenDisplay(disp)) == nullptr) {
std::string err =
std::string("can't open display: ") + XDisplayName(disp);
#ifdef BUILD_WAYLAND
NORM_ERR(err.c_str());
return;
#else /* BUILD_WAYLAND */
throw std::runtime_error(err);
#endif /* BUILD_WAYLAND */
}
}
info.x11.monitor.number = 1;
info.x11.monitor.current = 0;
info.x11.desktop.current = 1;
info.x11.desktop.number = 1;
info.x11.desktop.all_names.clear();
info.x11.desktop.name.clear();
screen = DefaultScreen(display);
XSetErrorHandler(&x11_error_handler);
XSetIOErrorHandler(&x11_ioerror_handler);
update_x11_resource_db(true);
update_x11_workarea();
get_x11_desktop_info(display, 0);
#ifdef HAVE_XCB_ERRORS
auto connection = xcb_connect(NULL, NULL);
if (!xcb_connection_has_error(connection)) {
if (xcb_errors_context_new(connection, &xcb_errors_ctx) != 0) {
xcb_errors_ctx = nullptr;
}
}
#endif /* HAVE_XCB_ERRORS */
DBGP("leave init_x11()");
}
void deinit_x11() {
if (display) {
DBGP("deinit_x11()");
XCloseDisplay(display);
display = nullptr;
}
}
// Source: dunst
// https://github.com/bebehei/dunst/blob/1bc3237a359f37905426012c0cca90d71c4b3b18/src/x11/x.c#L463
void update_x11_resource_db(bool first_run) {
XrmDatabase db;
XTextProperty prop;
Window root;
XFlush(display);
root = RootWindow(display, screen);
XLockDisplay(display);
if (XGetTextProperty(display, root, &prop, XA_RESOURCE_MANAGER)) {
if (!first_run) {
db = XrmGetDatabase(display);
XrmDestroyDatabase(db);
}
// https://github.com/dunst-project/dunst/blob/master/src/x11/x.c#L499
display->db = NULL; // should be new or deleted
db = XrmGetStringDatabase((const char *)prop.value);
XrmSetDatabase(display, db);
}
XUnlockDisplay(display);
XFlush(display);
XSync(display, false);
}
void update_x11_workarea() {
/* default work area is display */
workarea = conky::absolute_rect<int>(
conky::vec2i::Zero(), conky::vec2i(DisplayWidth(display, screen),
DisplayHeight(display, screen)));
#ifdef BUILD_XINERAMA
/* if xinerama is being used, adjust workarea to the head's area */
int useless1, useless2;
if (XineramaQueryExtension(display, &useless1, &useless2) == 0) {
return; /* doesn't even have xinerama */
}
if (XineramaIsActive(display) == 0) {
return; /* has xinerama but isn't using it */
}
int heads = 0;
XineramaScreenInfo *si = XineramaQueryScreens(display, &heads);
if (si == nullptr) {
NORM_ERR(
"warning: XineramaQueryScreen returned nullptr, ignoring head "
"settings");
return; /* queryscreens failed? */
}
int i = head_index.get(*state);
if (i < 0 || i >= heads) {
NORM_ERR("warning: invalid head index, ignoring head settings");
return;
}
XineramaScreenInfo *ps = &si[i];
workarea.set_pos(ps->x_org, ps->y_org);
workarea.set_size(ps->width, ps->height);
XFree(si);
DBGP("Fixed xinerama area to: %d %d %d %d", workarea[0], workarea[1],
workarea[2], workarea[3]);
#endif
}
/* Find root window and desktop window.
* Return desktop window on success,
* and set root and desktop byref return values.
* Return 0 on failure. */
static Window find_desktop_window(Window root) {
Window desktop = root;
/* get subwindows from root */
int display_width = DisplayWidth(display, screen);
int display_height = DisplayHeight(display, screen);
desktop = find_desktop_window_impl(root, display_width, display_height);
update_x11_workarea();
desktop =
find_desktop_window_impl(desktop, workarea.width(), workarea.height());
if (desktop != root) {
NORM_ERR("desktop window (0x%lx) is subwindow of root window (0x%lx)",
desktop, root);
} else {
NORM_ERR("desktop window (0x%lx) is root window", desktop);
}
return desktop;
}
#ifdef OWN_WINDOW
#ifdef BUILD_ARGB
namespace {
/* helper function for set_transparent_background() */
void do_set_background(Window win, uint8_t alpha) {
Colour colour = background_colour.get(*state);
colour.alpha = alpha;
unsigned long xcolor =
colour.to_x11_color(display, screen, have_argb_visual, true);
XSetWindowBackground(display, win, xcolor);
}
} // namespace
#endif /* BUILD_ARGB */
/* if no argb visual is configured sets background to ParentRelative for the
Window and all parents, else real transparency is used */
void set_transparent_background(Window win) {
#ifdef BUILD_ARGB
if (have_argb_visual) {
// real transparency
do_set_background(win, set_transparent.get(*state)
? 0
: own_window_argb_value.get(*state));
return;
}
#endif /* BUILD_ARGB */
// pseudo transparency
if (set_transparent.get(*state)) {
Window parent = win;
unsigned int i;
for (i = 0; i < 50 && parent != RootWindow(display, screen); i++) {
Window r, *children;
unsigned int n;
XSetWindowBackgroundPixmap(display, parent, ParentRelative);
XQueryTree(display, parent, &r, &parent, &children, &n);
XFree(children);
}
return;
}
#ifdef BUILD_ARGB
do_set_background(win, 0);
#endif /* BUILD_ARGB */
}
#endif /* OWN_WINDOW */
#ifdef BUILD_ARGB
static int get_argb_visual(Visual **visual, int *depth) {
/* code from gtk project, gdk_screen_get_rgba_visual */
XVisualInfo visual_template;
XVisualInfo *visual_list;
int nxvisuals = 0, i;
visual_template.screen = screen;
visual_list =
XGetVisualInfo(display, VisualScreenMask, &visual_template, &nxvisuals);
for (i = 0; i < nxvisuals; i++) {
if (visual_list[i].depth == 32 && (visual_list[i].red_mask == 0xff0000 &&
visual_list[i].green_mask == 0x00ff00 &&
visual_list[i].blue_mask == 0x0000ff)) {
*visual = visual_list[i].visual;
*depth = visual_list[i].depth;
DBGP("Found ARGB Visual");
XFree(visual_list);
return 1;
}
}
// no argb visual available
DBGP("No ARGB Visual found");
XFree(visual_list);
return 0;
}
#endif /* BUILD_ARGB */
void destroy_window() {
#ifdef BUILD_XFT
if (window.xftdraw != nullptr) { XftDrawDestroy(window.xftdraw); }
#endif /* BUILD_XFT */
if (window.gc != nullptr) { XFreeGC(display, window.gc); }
memset(&window, 0, sizeof(struct conky_x11_window));
}
void x11_init_window(lua::state &l, bool own) {
DBGP("enter x11_init_window()");
// own is unused if OWN_WINDOW is not defined
(void)own;
window.root = VRootWindow(display, screen);
if (window.root == None) {
DBGP2("no desktop window found");
return;
}
window.desktop = find_desktop_window(window.root);
window.visual = DefaultVisual(display, screen);
window.colourmap = DefaultColormap(display, screen);
#ifdef OWN_WINDOW
if (own) {
int depth = 0, flags = CWOverrideRedirect | CWBackingStore;
Visual *visual = nullptr;
depth = CopyFromParent;
visual = CopyFromParent;
#ifdef BUILD_ARGB
if (use_argb_visual.get(l) && (get_argb_visual(&visual, &depth) != 0)) {
have_argb_visual = true;
window.visual = visual;
window.colourmap = XCreateColormap(display, DefaultRootWindow(display),
window.visual, AllocNone);
}
#endif /* BUILD_ARGB */
int b = border_inner_margin.get(l) + border_width.get(l) +
border_outer_margin.get(l);
/* Sanity check to avoid making an invalid 0x0 window */
if (b == 0) { b = 1; }
XClassHint classHint;
// class_name must be a named local variable, so that c_str() remains
// valid until we call XmbSetWMProperties() or XSetClassHint. We use
// const_cast because, for whatever reason, res_name is not declared as
// const char *. XmbSetWMProperties hopefully doesn't modify the value
// (hell, even their own example app assigns a literal string constant to
// the field)
const std::string &class_name = own_window_class.get(l);
classHint.res_name = const_cast<char *>(class_name.c_str());
classHint.res_class = classHint.res_name;
if (own_window_type.get(l) == window_type::OVERRIDE) {
/* An override_redirect True window.
* No WM hints or button processing needed. */
XSetWindowAttributes attrs = {ParentRelative,
0L,
0,
0L,
0,
0,
Always,
0L,
0L,
False,
StructureNotifyMask | ExposureMask,
0L,
True,
0,
0};
flags |= CWBackPixel;
if (have_argb_visual) {
attrs.colormap = window.colourmap;
flags &= ~CWBackPixel;
flags |= CWBorderPixel | CWColormap;
}
/* Parent is desktop window (which might be a child of root) */
window.window = XCreateWindow(
display, window.desktop, window.geometry.x(), window.geometry.y(), b,
b, 0, depth, InputOutput, visual, flags, &attrs);
XLowerWindow(display, window.window);
XSetClassHint(display, window.window, &classHint);
NORM_ERR("window type - override");
} else { /* own_window_type.get(l) != TYPE_OVERRIDE */
/* A window managed by the window manager.
* Process hints and buttons. */
XSetWindowAttributes attrs = {
ParentRelative,
0L,
0,
0L,
0,
0,
Always,
0L,
0L,
False,
StructureNotifyMask | ExposureMask | ButtonPressMask |
ButtonReleaseMask,
0L,
own_window_type.get(l) == window_type::UTILITY ? True : False,
0,
0};
XWMHints wmHint;
Atom xa;
flags |= CWBackPixel;
if (have_argb_visual) {
attrs.colormap = window.colourmap;
flags &= ~CWBackPixel;
flags |= CWBorderPixel | CWColormap;
}
if (own_window_type.get(l) == window_type::DOCK) {
window.geometry.set_pos(conky::vec2i::Zero());
}
/* Parent is root window so WM can take control */
window.window = XCreateWindow(display, window.root, window.geometry.x(),
window.geometry.y(), b, b, 0, depth,
InputOutput, visual, flags, &attrs);
uint16_t hints = own_window_hints.get(l);
wmHint.flags = InputHint | StateHint;
/* allow decorated windows to be given input focus by WM */
wmHint.input = TEST_HINT(hints, window_hints::UNDECORATED) ? False : True;
#ifdef BUILD_XSHAPE
#ifdef BUILD_XFIXES
if (own_window_type.get(l) == window_type::UTILITY) {
XRectangle rect;
XserverRegion region = XFixesCreateRegion(display, &rect, 1);
XFixesSetWindowShapeRegion(display, window.window, ShapeInput, 0, 0,
region);
XFixesDestroyRegion(display, region);
}
#endif /* BUILD_XFIXES */
if (!wmHint.input) {
/* allow only decorated windows to be given mouse input */
int major_version;
int minor_version;
if (XShapeQueryVersion(display, &major_version, &minor_version) == 0) {
NORM_ERR("Input shapes are not supported");
} else {
if (own_window.get(*state) &&
(own_window_type.get(*state) != window_type::NORMAL ||
((TEST_HINT(own_window_hints.get(*state),
window_hints::UNDECORATED)) != 0))) {
XShapeCombineRectangles(display, window.window, ShapeInput, 0, 0,
nullptr, 0, ShapeSet, Unsorted);
}
}
}
#endif /* BUILD_XSHAPE */
if (own_window_type.get(l) == window_type::DOCK ||
own_window_type.get(l) == window_type::PANEL) {
// Docks and panels MUST have WithdrawnState initially
// See: https://github.com/brndnmtthws/conky/issues/2046
wmHint.initial_state = WithdrawnState;
} else {
wmHint.initial_state = NormalState;
}
XmbSetWMProperties(display, window.window, nullptr, nullptr, argv_copy,
argc_copy, nullptr, &wmHint, &classHint);
XStoreName(display, window.window, own_window_title.get(l).c_str());
/* Sets an empty WM_PROTOCOLS property */
XSetWMProtocols(display, window.window, nullptr, 0);
/* Set window type */
if ((xa = ATOM(_NET_WM_WINDOW_TYPE)) != None) {
Atom prop;
switch (own_window_type.get(l)) {
case window_type::DESKTOP:
prop = ATOM(_NET_WM_WINDOW_TYPE_DESKTOP);
NORM_ERR("window type - desktop");
break;
case window_type::DOCK:
prop = ATOM(_NET_WM_WINDOW_TYPE_DOCK);
NORM_ERR("window type - dock");
break;
case window_type::PANEL:
prop = ATOM(_NET_WM_WINDOW_TYPE_DOCK);
NORM_ERR("window type - panel");
break;
case window_type::UTILITY:
prop = ATOM(_NET_WM_WINDOW_TYPE_UTILITY);
NORM_ERR("window type - utility");
break;
case window_type::NORMAL:
default:
prop = ATOM(_NET_WM_WINDOW_TYPE_NORMAL);
NORM_ERR("window type - normal");
break;
}
XChangeProperty(display, window.window, xa, XA_ATOM, 32,
PropModeReplace,
reinterpret_cast<unsigned char *>(&prop), 1);
}
/* Set desired hints */
/* Window decorations */
if (TEST_HINT(hints, window_hints::UNDECORATED)) {
DBGP("hint - undecorated");
xa = ATOM(_MOTIF_WM_HINTS);
if (xa != None) {
long prop[5] = {2, 0, 0, 0, 0};
XChangeProperty(display, window.window, xa, xa, 32, PropModeReplace,
reinterpret_cast<unsigned char *>(prop), 5);
}
}
/* Below other windows */
if (TEST_HINT(hints, window_hints::BELOW)) {
DBGP("hint - below");
xa = ATOM(_WIN_LAYER);
if (xa != None) {
long prop = 0;
XChangeProperty(display, window.window, xa, XA_CARDINAL, 32,
PropModeAppend,
reinterpret_cast<unsigned char *>(&prop), 1);
}
xa = ATOM(_NET_WM_STATE);
if (xa != None) {
Atom xa_prop = ATOM(_NET_WM_STATE_BELOW);
XChangeProperty(display, window.window, xa, XA_ATOM, 32,
PropModeAppend,
reinterpret_cast<unsigned char *>(&xa_prop), 1);
}
}
/* Above other windows */
if (TEST_HINT(hints, window_hints::ABOVE)) {
DBGP("hint - above");
xa = ATOM(_WIN_LAYER);
if (xa != None) {
long prop = 6;
XChangeProperty(display, window.window, xa, XA_CARDINAL, 32,
PropModeAppend,
reinterpret_cast<unsigned char *>(&prop), 1);
}
xa = ATOM(_NET_WM_STATE);
if (xa != None) {
Atom xa_prop = ATOM(_NET_WM_STATE_ABOVE);
XChangeProperty(display, window.window, xa, XA_ATOM, 32,
PropModeAppend,
reinterpret_cast<unsigned char *>(&xa_prop), 1);
}
}
/* Sticky */
if (TEST_HINT(hints, window_hints::STICKY)) {
DBGP("hint - sticky");
xa = ATOM(_NET_WM_DESKTOP);
if (xa != None) {
CARD32 xa_prop = 0xFFFFFFFF;
XChangeProperty(display, window.window, xa, XA_CARDINAL, 32,
PropModeAppend,
reinterpret_cast<unsigned char *>(&xa_prop), 1);
}
xa = ATOM(_NET_WM_STATE);
if (xa != None) {
Atom xa_prop = ATOM(_NET_WM_STATE_STICKY);
XChangeProperty(display, window.window, xa, XA_ATOM, 32,
PropModeAppend,
reinterpret_cast<unsigned char *>(&xa_prop), 1);
}
}
/* Skip taskbar */
if (TEST_HINT(hints, window_hints::SKIP_TASKBAR)) {
DBGP("hint - skip taskbar");
xa = ATOM(_NET_WM_STATE);
if (xa != None) {
Atom xa_prop = ATOM(_NET_WM_STATE_SKIP_TASKBAR);
XChangeProperty(display, window.window, xa, XA_ATOM, 32,
PropModeAppend,
reinterpret_cast<unsigned char *>(&xa_prop), 1);
}
}
/* Skip pager */
if (TEST_HINT(hints, window_hints::SKIP_PAGER)) {
DBGP("hint - skip pager");
xa = ATOM(_NET_WM_STATE);
if (xa != None) {
Atom xa_prop = ATOM(_NET_WM_STATE_SKIP_PAGER);
XChangeProperty(display, window.window, xa, XA_ATOM, 32,
PropModeAppend,
reinterpret_cast<unsigned char *>(&xa_prop), 1);
}
}
}
NORM_ERR("drawing to created window (0x%lx)", window.window);
XMapWindow(display, window.window);
} else
#endif /* OWN_WINDOW */
{
XWindowAttributes attrs;
if (window.window == None) { window.window = window.desktop; }
if (XGetWindowAttributes(display, window.window, &attrs) != 0) {
window.geometry.set_size(attrs.width, attrs.height);
}
NORM_ERR("drawing to desktop window");
}
/* Drawable is same as window. This may be changed by double buffering. */
window.drawable = window.window;
XFlush(display);
int64_t input_mask = ExposureMask | PropertyChangeMask;
#ifdef OWN_WINDOW
if (own_window.get(l)) {
input_mask |= StructureNotifyMask;
#if !defined(BUILD_XINPUT)
input_mask |= ButtonPressMask | ButtonReleaseMask;
#endif
}
#if defined(BUILD_MOUSE_EVENTS) || defined(BUILD_XINPUT)
bool xinput_ok = false;
#ifdef BUILD_XINPUT
// not a loop; substitutes goto with break - if checks fail
do {
int _ignored; // segfault if NULL
if (!XQueryExtension(display, "XInputExtension", &window.xi_opcode,
&_ignored, &_ignored)) {
// events will still ~work but let the user know why they're buggy
NORM_ERR("XInput extension is not supported by X11!");
break;
}
int major = 2, minor = 0;
int retval = XIQueryVersion(display, &major, &minor);
if (retval != 0) {
NORM_ERR("Error: XInput 2.0 is not supported!");
break;
}
const std::size_t mask_size = (XI_LASTEVENT + 7) / 8;
unsigned char mask_bytes[mask_size] = {0}; /* must be zeroed! */
XISetMask(mask_bytes, XI_HierarchyChanged);
#ifdef BUILD_MOUSE_EVENTS
XISetMask(mask_bytes, XI_Motion);
#endif /* BUILD_MOUSE_EVENTS */
// Capture click events for "override" window type
if (!own) {
XISetMask(mask_bytes, XI_ButtonPress);
XISetMask(mask_bytes, XI_ButtonRelease);
}
XIEventMask ev_masks[1];
ev_masks[0].deviceid = XIAllDevices;
ev_masks[0].mask_len = sizeof(mask_bytes);
ev_masks[0].mask = mask_bytes;
XISelectEvents(display, window.root, ev_masks, 1);
if (own) {
#ifdef BUILD_MOUSE_EVENTS
XIClearMask(mask_bytes, XI_Motion);
#endif /* BUILD_MOUSE_EVENTS */
XISetMask(mask_bytes, XI_ButtonPress);
XISetMask(mask_bytes, XI_ButtonRelease);
ev_masks[0].deviceid = XIAllDevices;
ev_masks[0].mask_len = sizeof(mask_bytes);
ev_masks[0].mask = mask_bytes;
XISelectEvents(display, window.window, ev_masks, 1);
}
// setup cache
int num_devices;
XDeviceInfo *info = XListInputDevices(display, &num_devices);
for (int i = 0; i < num_devices; i++) {
if (info[i].use == IsXPointer || info[i].use == IsXExtensionPointer) {
conky::device_info::from_xi_id(info[i].id, display);
}
}
XFreeDeviceList(info);
xinput_ok = true;
} while (false);
#endif /* BUILD_XINPUT */
// Fallback to basic X11 enter/leave events if xinput fails to init.
// It's not recommended to add event masks to special windows in X; causes a
// crash (thus own_window_type != TYPE_DESKTOP)
#ifdef BUILD_MOUSE_EVENTS
if (!xinput_ok && own && own_window_type.get(l) != window_type::DESKTOP) {
input_mask |= PointerMotionMask | EnterWindowMask | LeaveWindowMask;
}
#endif /* BUILD_MOUSE_EVENTS */
#endif /* BUILD_MOUSE_EVENTS || BUILD_XINPUT */
#endif /* OWN_WINDOW */
window.event_mask = input_mask;
XSelectInput(display, window.window, input_mask);
window_created = 1;
DBGP("leave x11_init_window()");
}
static Window find_desktop_window_impl(Window win, int w, int h) {
unsigned int i, j;
Window troot, parent, *children;
unsigned int n;
/* search subwindows with same size as display or work area */
for (i = 0; i < 10; i++) {
XQueryTree(display, win, &troot, &parent, &children, &n);
for (j = 0; j < n; j++) {
XWindowAttributes attrs;
if (XGetWindowAttributes(display, children[j], &attrs) != 0) {
/* Window must be mapped and same size as display or
* work space */
if (attrs.map_state == IsViewable && attrs.override_redirect == false &&
((attrs.width == w && attrs.height == h))) {
win = children[j];
break;
}
}
}
XFree(children);
if (j == n) { break; }
}
return win;
}
void create_gc() {
XGCValues values;
values.graphics_exposures = 0;
values.function = GXcopy;
window.gc = XCreateGC(display, window.drawable,
GCFunction | GCGraphicsExposures, &values);
}
// Get current desktop number
static inline void get_x11_desktop_current(Display *current_display,
Window root, Atom atom) {
Atom actual_type;
int actual_format;
unsigned long nitems;
unsigned long bytes_after;
unsigned char *prop = nullptr;
struct information *current_info = &info;
if (atom == None) { return; }
if ((XGetWindowProperty(current_display, root, atom, 0, 1L, False,
XA_CARDINAL, &actual_type, &actual_format, &nitems,
&bytes_after, &prop) == 0) &&
(actual_type == XA_CARDINAL) && (nitems == 1L) && (actual_format == 32)) {
current_info->x11.desktop.current = prop[0] + 1;
}
if (prop != nullptr) { XFree(prop); }
}
// Get total number of available desktops
static inline void get_x11_desktop_number(Display *current_display, Window root,
Atom atom) {
Atom actual_type;
int actual_format;
unsigned long nitems;
unsigned long bytes_after;
unsigned char *prop = nullptr;
struct information *current_info = &info;
if (atom == None) { return; }
if ((XGetWindowProperty(current_display, root, atom, 0, 1L, False,
XA_CARDINAL, &actual_type, &actual_format, &nitems,
&bytes_after, &prop) == 0) &&
(actual_type == XA_CARDINAL) && (nitems == 1L) && (actual_format == 32)) {
current_info->x11.desktop.number = prop[0];
}
if (prop != nullptr) { XFree(prop); }
}
// Get all desktop names
static inline void get_x11_desktop_names(Display *current_display, Window root,
Atom atom) {
Atom actual_type;
int actual_format;
unsigned long nitems;
unsigned long bytes_after;
unsigned char *prop = nullptr;
struct information *current_info = &info;
if (atom == None) { return; }
if ((XGetWindowProperty(current_display, root, atom, 0, (~0L), False,
ATOM(UTF8_STRING), &actual_type, &actual_format,
&nitems, &bytes_after, &prop) == 0) &&
(actual_type == ATOM(UTF8_STRING)) && (nitems > 0L) &&
(actual_format == 8)) {
current_info->x11.desktop.all_names.assign(
reinterpret_cast<const char *>(prop), nitems);
}
if (prop != nullptr) { XFree(prop); }
}
// Get current desktop name
static inline void get_x11_desktop_current_name(const std::string &names) {
struct information *current_info = &info;
unsigned int i = 0, j = 0;
int k = 0;
while (i < names.size()) {
if (names[i++] == '\0') {
if (++k == current_info->x11.desktop.current) {
current_info->x11.desktop.name.assign(names.c_str() + j);
break;
}
j = i;
}
}
}
void get_x11_desktop_info(Display *current_display, Atom atom) {
Window root;
static Atom atom_current, atom_number, atom_names;
struct information *current_info = &info;
XWindowAttributes window_attributes;
root = RootWindow(current_display, current_info->x11.monitor.current);
/* Check if we initialise else retrieve changed property */
if (atom == 0) {
atom_current = XInternAtom(current_display, "_NET_CURRENT_DESKTOP", True);
atom_number = XInternAtom(current_display, "_NET_NUMBER_OF_DESKTOPS", True);
atom_names = XInternAtom(current_display, "_NET_DESKTOP_NAMES", True);
get_x11_desktop_current(current_display, root, atom_current);
get_x11_desktop_number(current_display, root, atom_number);
get_x11_desktop_names(current_display, root, atom_names);
get_x11_desktop_current_name(current_info->x11.desktop.all_names);
/* Set the PropertyChangeMask on the root window, if not set */
XGetWindowAttributes(display, root, &window_attributes);
if ((window_attributes.your_event_mask & PropertyChangeMask) == 0) {
XSetWindowAttributes attributes;
attributes.event_mask =
window_attributes.your_event_mask | PropertyChangeMask;
XChangeWindowAttributes(display, root, CWEventMask, &attributes);
XGetWindowAttributes(display, root, &window_attributes);
}
} else {
if (atom == atom_current) {
get_x11_desktop_current(current_display, root, atom_current);
get_x11_desktop_current_name(current_info->x11.desktop.all_names);
} else if (atom == atom_number) {
get_x11_desktop_number(current_display, root, atom_number);
} else if (atom == atom_names) {
get_x11_desktop_names(current_display, root, atom_names);
get_x11_desktop_current_name(current_info->x11.desktop.all_names);
}
}
}
static const char NOT_IN_X[] = "Not running in X";
void print_monitor(struct text_object *obj, char *p, unsigned int p_max_size) {
(void)obj;
if (!out_to_x.get(*state)) {
strncpy(p, NOT_IN_X, p_max_size);
return;
}
snprintf(p, p_max_size, "%d", XDefaultScreen(display));
}
void print_monitor_number(struct text_object *obj, char *p,
unsigned int p_max_size) {
(void)obj;
if (!out_to_x.get(*state)) {
strncpy(p, NOT_IN_X, p_max_size);
return;
}
snprintf(p, p_max_size, "%d", XScreenCount(display));
}
void print_desktop(struct text_object *obj, char *p, unsigned int p_max_size) {
(void)obj;
if (!out_to_x.get(*state)) {
strncpy(p, NOT_IN_X, p_max_size);
return;
}
snprintf(p, p_max_size, "%d", info.x11.desktop.current);
}
void print_desktop_number(struct text_object *obj, char *p,
unsigned int p_max_size) {
(void)obj;
if (!out_to_x.get(*state)) {
strncpy(p, NOT_IN_X, p_max_size);
return;
}
snprintf(p, p_max_size, "%d", info.x11.desktop.number);
}
void print_desktop_name(struct text_object *obj, char *p,
unsigned int p_max_size) {
(void)obj;
if (!out_to_x.get(*state)) {
strncpy(p, NOT_IN_X, p_max_size);
} else {
strncpy(p, info.x11.desktop.name.c_str(), p_max_size);
}
}
#ifdef OWN_WINDOW
enum class x11_strut : size_t {
LEFT,
RIGHT,
TOP,
BOTTOM,
LEFT_START_Y,
LEFT_END_Y,
RIGHT_START_Y,
RIGHT_END_Y,
TOP_START_X,
TOP_END_X,
BOTTOM_START_X,
BOTTOM_END_X,
};
const size_t STRUT_COUNT = static_cast<size_t>(x11_strut::BOTTOM_END_X) + 1;
constexpr size_t operator*(x11_strut index) {
return static_cast<size_t>(index);
}
/* reserve window manager space */
void set_struts(alignment align) {
// Middle and none align don't have least significant bit set.
// Ensures either vertical or horizontal axis are start/end
if ((*align & 0b0101) == 0) return;
Atom strut = ATOM(_NET_WM_STRUT);
if (strut != None) {
long sizes[STRUT_COUNT] = {0};
int display_width = workarea.width();
int display_height = workarea.height();
switch (align) {
case alignment::TOP_LEFT:
case alignment::TOP_RIGHT:
case alignment::TOP_MIDDLE:
sizes[*x11_strut::TOP] = std::clamp(window.geometry.end_y(), 0, display_height);
sizes[*x11_strut::TOP_START_X] = std::clamp(window.geometry.x(), 0, display_width);
sizes[*x11_strut::TOP_END_X] = std::clamp(window.geometry.end_x(), 0, display_width);
break;
case alignment::BOTTOM_LEFT:
case alignment::BOTTOM_RIGHT:
case alignment::BOTTOM_MIDDLE:
sizes[*x11_strut::BOTTOM] = display_height - std::clamp(window.geometry.y(), 0, display_height);
sizes[*x11_strut::BOTTOM_START_X] = std::clamp(window.geometry.x(), 0, display_width);
sizes[*x11_strut::BOTTOM_END_X] = std::clamp(window.geometry.end_x(), 0, display_width);
break;
case alignment::MIDDLE_LEFT:
sizes[*x11_strut::LEFT] = std::clamp(window.geometry.end_x(), 0, display_width);
sizes[*x11_strut::LEFT_START_Y] = std::clamp(window.geometry.y(), 0, display_height);
sizes[*x11_strut::LEFT_END_Y] = std::clamp(window.geometry.end_y(), 0, display_height);
break;
case alignment::MIDDLE_RIGHT:
sizes[*x11_strut::RIGHT] = display_width - std::clamp(window.geometry.x(), 0, display_width);
sizes[*x11_strut::RIGHT_START_Y] = std::clamp(window.geometry.y(), 0, display_height);
sizes[*x11_strut::RIGHT_END_Y] = std::clamp(window.geometry.end_y(), 0, display_height);
break;
default:
// can't reserve space in middle of the screen
break;
}
XChangeProperty(display, window.window, strut, XA_CARDINAL, 32,
PropModeReplace, reinterpret_cast<unsigned char *>(&sizes),
4);
strut = ATOM(_NET_WM_STRUT_PARTIAL);
if (strut != None) {
XChangeProperty(display, window.window, strut, XA_CARDINAL, 32,
PropModeReplace,
reinterpret_cast<unsigned char *>(&sizes), 12);
}
}
}
#endif /* OWN_WINDOW */
#ifdef BUILD_XDBE
void xdbe_swap_buffers() {
if (use_xdbe.get(*state)) {
XdbeSwapInfo swap;
swap.swap_window = window.window;
swap.swap_action = XdbeBackground;
XdbeSwapBuffers(display, &swap, 1);
}
}
#else
void xpmdb_swap_buffers(void) {
if (use_xpmdb.get(*state)) {
XCopyArea(display, window.back_buffer, window.window, window.gc, 0, 0,
window.geometry.width(), window.geometry.height(), 0, 0);
XSetForeground(display, window.gc, 0);
XFillRectangle(display, window.drawable, window.gc, 0, 0, window.geometry.width(),
window.geometry.height());
XFlush(display);
}
}
#endif /* BUILD_XDBE */
void print_kdb_led(const int keybit, char *p, unsigned int p_max_size) {
XKeyboardState x;
XGetKeyboardControl(display, &x);
snprintf(p, p_max_size, "%s", (x.led_mask & keybit ? "On" : "Off"));
}
void print_key_caps_lock(struct text_object *obj, char *p,
unsigned int p_max_size) {
(void)obj;
print_kdb_led(1, p, p_max_size);
}
void print_key_num_lock(struct text_object *obj, char *p,
unsigned int p_max_size) {
(void)obj;
print_kdb_led(2, p, p_max_size);
}
void print_key_scroll_lock(struct text_object *obj, char *p,
unsigned int p_max_size) {
(void)obj;
print_kdb_led(4, p, p_max_size);
}
void print_keyboard_layout(struct text_object *obj, char *p,
unsigned int p_max_size) {
(void)obj;
char *group = NULL;
XkbStateRec state;
XkbDescPtr desc;
XkbGetState(display, XkbUseCoreKbd, &state);
desc = XkbGetKeyboard(display, XkbAllComponentsMask, XkbUseCoreKbd);
group = XGetAtomName(display, desc->names->groups[state.group]);
snprintf(p, p_max_size, "%s", (group != NULL ? group : "unknown"));
XFree(group);
XkbFreeKeyboard(desc, XkbGBN_AllComponentsMask, True);
}
void print_mouse_speed(struct text_object *obj, char *p,
unsigned int p_max_size) {
(void)obj;
int acc_num = 0;
int acc_denom = 0;
int threshold = 0;
XGetPointerControl(display, &acc_num, &acc_denom, &threshold);
snprintf(p, p_max_size, "%d%%", (110 - threshold));
}
/// @brief Returns a mask for the event_type
/// @param event_type Xlib event type
/// @return Xlib event mask
int ev_to_mask(int event_type, int button) {
switch (event_type) {
case KeyPress:
return KeyPressMask;
case KeyRelease:
return KeyReleaseMask;
case ButtonPress:
return ButtonPressMask;
case ButtonRelease:
switch (button) {
case 1:
return ButtonReleaseMask | Button1MotionMask;
case 2:
return ButtonReleaseMask | Button2MotionMask;
case 3:
return ButtonReleaseMask | Button3MotionMask;
case 4:
return ButtonReleaseMask | Button4MotionMask;
case 5:
return ButtonReleaseMask | Button5MotionMask;
default:
return ButtonReleaseMask;
}
case EnterNotify:
return EnterWindowMask;
case LeaveNotify:
return LeaveWindowMask;
case MotionNotify:
return PointerMotionMask;
default:
return NoEventMask;
}
}
#ifdef BUILD_XINPUT
void propagate_xinput_event(const conky::xi_event_data *ev) {
if (ev->evtype != XI_Motion && ev->evtype != XI_ButtonPress &&
ev->evtype != XI_ButtonRelease) {
return;
}
Window target = window.root;
Window child = None;
conky::vec2i target_pos = ev->pos;
{
std::vector<Window> below = query_x11_windows_at_pos(
display, ev->pos_absolute,
[](XWindowAttributes &a) { return a.map_state == IsViewable; });
auto it = std::remove_if(below.begin(), below.end(),
[](Window w) { return w == window.window; });
below.erase(it, below.end());
if (!below.empty()) {
target = below.back();
int read_x, read_y;
// Update event x and y coordinates to be target window relative
XTranslateCoordinates(display, window.desktop, ev->event,
ev->pos_absolute.x(), ev->pos_absolute.y(), &read_x,
&read_y, &child);
target_pos = conky::vec2i(read_x, read_y);
}
}
auto events = ev->generate_events(target, child, target_pos);
XUngrabPointer(display, CurrentTime);
for (auto it : events) {
auto ev = std::get<1>(it);
XSendEvent(display, target, True, std::get<0>(it), ev);
free(ev);
}
XFlush(display);
}
#endif
void propagate_x11_event(XEvent &ev, const void *cookie) {
bool focus = ev.type == ButtonPress;
// cookie must be allocated before propagation, and freed after
#ifdef BUILD_XINPUT
if (ev.type == GenericEvent && ev.xgeneric.extension == window.xi_opcode) {
if (cookie == nullptr) { return; }
return propagate_xinput_event(
reinterpret_cast<const conky::xi_event_data *>(cookie));
}
#endif
if (!(ev.type == KeyPress || ev.type == KeyRelease ||
ev.type == ButtonPress || ev.type == ButtonRelease ||
ev.type == MotionNotify || ev.type == EnterNotify ||
ev.type == LeaveNotify)) {
// Not a known input event; blindly propagating them causes loops and all
// sorts of other evil.
return;
}
// Note that using ev.xbutton is the same as using any of the above events.
// It's only important we don't access fields that are not common to all of
// them.
ev.xbutton.window = window.desktop;
ev.xbutton.x = ev.xbutton.x_root;
ev.xbutton.y = ev.xbutton.y_root;
ev.xbutton.time = CurrentTime;
/* forward the event to the window below conky (e.g. caja) or desktop */
{
std::vector<Window> below = query_x11_windows_at_pos(
display, conky::vec2i(ev.xbutton.x_root, ev.xbutton.y_root),
[](XWindowAttributes &a) { return a.map_state == IsViewable; });
auto it = std::remove_if(below.begin(), below.end(),
[](Window w) { return w == window.window; });
below.erase(it, below.end());
if (!below.empty()) {
ev.xbutton.window = below.back();
Window _ignore;
// Update event x and y coordinates to be target window relative
XTranslateCoordinates(display, window.root, ev.xbutton.window,
ev.xbutton.x_root, ev.xbutton.y_root, &ev.xbutton.x,
&ev.xbutton.y, &_ignore);
}
// drop below vector
}
int mask =
ev_to_mask(ev.type, ev.type == ButtonRelease ? ev.xbutton.button : 0);
XUngrabPointer(display, CurrentTime);
XSendEvent(display, ev.xbutton.window, True, mask, &ev);
if (focus) {
XSetInputFocus(display, ev.xbutton.window, RevertToParent, CurrentTime);
}
}
Window query_x11_top_parent(Display *display, Window child) {
Window root = DefaultVRootWindow(display);
if (child == None || child == root) return child;
Window ret_root, parent, *children;
std::uint32_t child_count;
Window current = child;
int i;
do {
if (XQueryTree(display, current, &ret_root, &parent, &children,
&child_count) == 0) {
break;
}
if (child_count != 0) XFree(children);
if (parent == root) break;
current = parent;
} while (true);
return current;
}
std::vector<Window> x11_atom_window_list(Display *display, Window window,
Atom atom) {
Atom actual_type;
int actual_format;
unsigned long nitems;
unsigned long bytes_after;
unsigned char *data = nullptr;
if (XGetWindowProperty(display, window, atom, 0, (~0L), False, XA_WINDOW,
&actual_type, &actual_format, &nitems, &bytes_after,
&data) == 0) {
if (actual_format == XA_WINDOW && nitems > 0) {
Window *wdata = reinterpret_cast<Window *>(data);
std::vector<Window> result(wdata, wdata + nitems);
XFree(data);
return result;
}
}
return std::vector<Window>{};
}
std::vector<Window> query_x11_windows(Display *display, bool eager) {
Window root = DefaultRootWindow(display);
std::vector<Window> result;
Atom clients_atom = XInternAtom(display, "_NET_CLIENT_LIST_STACKING", True);
if (clients_atom != 0) {
result = x11_atom_window_list(display, root, clients_atom);
if (!result.empty()) { return result; }
}
clients_atom = XInternAtom(display, "_NET_CLIENT_LIST", True);
if (clients_atom != 0) {
result = x11_atom_window_list(display, root, clients_atom);
if (!result.empty()) { return result; }
}
// slowest method
if (eager) {
std::vector<Window> queue = {DefaultVRootWindow(display)};
Window _ignored, *children;
std::uint32_t count;
const auto has_wm_hints = [&](Window window) {
auto hints = XGetWMHints(display, window);
bool result = hints != NULL;
if (result) XFree(hints);
return result;
};
while (!queue.empty()) {
Window current = queue.back();
queue.pop_back();
if (XQueryTree(display, current, &_ignored, &_ignored, &children,
&count)) {
for (size_t i = 0; i < count; i++) queue.push_back(children[i]);
if (has_wm_hints(current)) result.push_back(current);
if (count > 0) XFree(children);
}
}
}
return result;
}
Window query_x11_window_at_pos(Display *display, conky::vec2i pos) {
Window root = DefaultVRootWindow(display);
// these values are ignored but NULL can't be passed to XQueryPointer.
Window root_return;
int root_x_return, root_y_return, win_x_return, win_y_return;
unsigned int mask_return;
Window last = None;
XQueryPointer(display, window.root, &root_return, &last, &root_x_return,
&root_y_return, &win_x_return, &win_y_return, &mask_return);
if (last == 0) return root;
return last;
}
std::vector<Window> query_x11_windows_at_pos(
Display *display, conky::vec2i pos,
std::function<bool(XWindowAttributes &)> predicate, bool eager) {
std::vector<Window> result;
Window root = DefaultVRootWindow(display);
XWindowAttributes attr;
for (Window current : query_x11_windows(display, eager)) {
int pos_x, pos_y;
Window _ignore;
// Doesn't account for decorations. There's no sane way to do that.
XTranslateCoordinates(display, current, root, 0, 0, &pos_x, &pos_y,
&_ignore);
XGetWindowAttributes(display, current, &attr);
if (pos_x <= pos.x() && pos_y <= pos.y() && pos_x + attr.width >= pos.x() &&
pos_y + attr.height >= pos.y() && predicate(attr)) {
result.push_back(current);
}
}
return result;
}
| 48,885
|
C++
|
.cc
| 1,321
| 30.554883
| 104
| 0.628894
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,612
|
hddtemp.cc
|
brndnmtthws_conky/src/hddtemp.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <errno.h>
#include <fcntl.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <unistd.h>
#include "conky.h"
#include "logging.h"
#include "temphelper.h"
#include "text_object.h"
#define BUFLEN 512
static conky::simple_config_setting<std::string> hddtemp_host("hddtemp_host",
"localhost",
false);
static conky::simple_config_setting<std::string> hddtemp_port("hddtemp_port",
"7634", false);
class hdd_info {
public:
hdd_info() : next(0) {}
hdd_info *next;
char *dev;
short temp;
char unit;
void reset() {
next = 0;
dev = 0;
temp = 0;
unit = 0;
}
};
hdd_info hdd_info_head;
static void __free_hddtemp_info(hdd_info *hdi) {
if (hdi->next) __free_hddtemp_info(hdi->next);
free(hdi->dev);
delete hdi;
}
static void free_hddtemp_info(void) {
DBGP("free_hddtemp_info() called");
if (!hdd_info_head.next) return;
__free_hddtemp_info(hdd_info_head.next);
hdd_info_head.next = nullptr;
}
static void add_hddtemp_info(char *dev, short temp, char unit) {
hdd_info *hdi = &hdd_info_head;
DBGP("add_hddtemp_info(%s, %d, %c) being called", dev, temp, unit);
while (hdi->next) hdi = hdi->next;
hdi->next = new hdd_info;
hdi->next->reset();
hdi->next->dev = strdup(dev);
hdi->next->temp = temp;
hdi->next->unit = unit;
}
static char *fetch_hddtemp_output(void) {
int sockfd;
char *buf = nullptr;
int buflen, offset = 0, rlen;
struct addrinfo hints, *result, *rp;
int i;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET; /* XXX: hddtemp has no ipv6 support (yet?) */
hints.ai_socktype = SOCK_STREAM;
if ((i = getaddrinfo(hddtemp_host.get(*state).c_str(),
hddtemp_port.get(*state).c_str(), &hints, &result))) {
NORM_ERR("getaddrinfo(): %s", gai_strerror(i));
return nullptr;
}
for (rp = result; rp; rp = rp->ai_next) {
sockfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (sockfd == -1) continue;
if (connect(sockfd, rp->ai_addr, rp->ai_addrlen) != -1) break;
close(sockfd);
}
if (!rp) {
NORM_ERR("could not connect to hddtemp host");
goto GET_OUT;
}
buflen = 1024;
buf = (char *)malloc(buflen);
while ((rlen = recv(sockfd, buf + offset, buflen - offset - 1, 0)) > 0) {
offset += rlen;
if (buflen - offset < 1) {
buflen += 1024;
buf = (char *)realloc(buf, buflen);
}
}
if (rlen < 0) perror("recv");
buf[offset] = '\0';
close(sockfd);
GET_OUT:
freeaddrinfo(result);
return buf;
}
/* this is an iterator:
* set line to nullptr in consecutive calls to get the next field
* note that exhausing iteration is assumed - otherwise *saveptr
* is not being freed!
*/
static int read_hdd_val(const char *line, char **dev, short *val, char *unit,
char **saveptr) {
char *line_s, *cval, *endptr;
static char *p = 0;
if (line) {
*saveptr = strdup(line);
p = *saveptr;
}
line_s = *saveptr;
again:
if (!*p) goto out_fail;
/* read the device */
*dev = ++p;
if (!(p = strchr(p, line_s[0]))) goto out_fail;
*(p++) = '\0';
/* jump over the devname */
if (!(p = strchr(p, line_s[0]))) goto out_fail;
/* read the value */
cval = ++p;
if (!(p = strchr(p, line_s[0]))) goto out_fail;
*(p++) = '\0';
*unit = *(p++);
*val = strtol(cval, &endptr, 10);
if (*endptr) {
if (!(p = strchr(p, line_s[0]))) goto out_fail;
p++;
goto again;
}
/* preset p for next call */
p++;
return 0;
out_fail:
free(*saveptr);
return 1;
}
int update_hddtemp(void) {
char *data, *dev, unit, *saveptr;
short val;
static double last_hddtemp_update = 0.0;
/* limit tcp connection overhead */
if (current_update_time - last_hddtemp_update < 5) return 0;
last_hddtemp_update = current_update_time;
free_hddtemp_info();
if (!(data = fetch_hddtemp_output())) return 0;
if (read_hdd_val(data, &dev, &val, &unit, &saveptr)) {
free(data);
return 0;
}
do {
add_hddtemp_info(dev, val, unit);
} while (!read_hdd_val(nullptr, &dev, &val, &unit, &saveptr));
free(data);
return 0;
}
void free_hddtemp(struct text_object *obj) {
free_hddtemp_info();
free_and_zero(obj->data.s);
}
static int get_hddtemp_info(const char *dev, short *val, char *unit) {
hdd_info *hdi = hdd_info_head.next;
/* if no dev is given, just use hdd_info_head->next */
while (dev && hdi) {
if (!strcmp(dev, hdi->dev)) break;
hdi = hdi->next;
}
if (!hdi) return 1;
*val = hdi->temp;
*unit = hdi->unit;
return 0;
}
void print_hddtemp(struct text_object *obj, char *p, unsigned int p_max_size) {
short val;
char unit;
if (get_hddtemp_info(obj->data.s, &val, &unit)) {
snprintf(p, p_max_size, "%s", "N/A");
} else {
temp_print(p, p_max_size, (double)val,
(unit == 'C' ? TEMP_CELSIUS : TEMP_FAHRENHEIT), 1);
}
}
| 6,138
|
C++
|
.cc
| 206
| 25.728155
| 79
| 0.62767
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
22,613
|
text_object.cc
|
brndnmtthws_conky/src/text_object.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "text_object.h"
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include "config.h"
#include "conky.h"
#include "logging.h"
void gen_free_opaque(struct text_object *obj) {
free_and_zero(obj->data.opaque);
}
int gen_false_iftest(struct text_object *) { return 0; }
void gen_print_nothing(struct text_object *, char *, unsigned int) {
// literally does nothing
}
void gen_print_obj_data_s(struct text_object *obj, char *p,
unsigned int p_max_size) {
if (obj->data.s == nullptr) { return; }
snprintf(p, p_max_size, "%s", obj->data.s);
}
/* text_object_list
*
* this list is special. it looks like this:
* nullptr <-- obj1 <--> obj2 <--> ... <--> objN --> NULL
* ^-------root_object----------^
* directions are reversed here
*
* why this is cool:
* - root_object points both to the start and end of the list
* - while traversing, the end of the list is always a nullptr pointer
* (this works in BOTH directions)
*/
/* append an object or list of objects to the given root object's list */
int append_object(struct text_object *root, struct text_object *obj) {
struct text_object *end;
/* hook in start of list to append */
end = root->prev;
obj->prev = end;
/* update pointers of the list to append to */
if (end != nullptr) {
if (end->next != nullptr) { CRIT_ERR("Houston, we have lift-off"); }
end->next = obj;
} else {
root->next = obj;
}
/* find end of appended list to point root->prev there */
while (obj->next != nullptr) { obj = obj->next; }
root->prev = obj;
return 0;
}
/* ifblock handlers for the object list
*
* - each if points to it's else or endif
* - each else points to it's endif
*
*/
/* possible ifblock types
* only used internally, so no need to make this public
*/
enum ifblock_type { IFBLOCK_IF = 1, IFBLOCK_ELSE, IFBLOCK_ENDIF };
/* linked list of ifblock objects, building a stack
* only used internally, so no need to make this public
*/
struct ifblock_stack_obj {
enum ifblock_type type;
struct text_object *obj;
struct ifblock_stack_obj *next;
};
/* push an ifblock object onto the stack
* in fact, this does a lot more:
* - IFBLOCK_IF is just pushed onto the stack
* - IFBLOCK_ELSE updates the "next" pointer of the upmost
* object in the stack and is then pushed onto the stack
* - IFBLOCK_ENDIF updates the "next" pointer of the upmost
* object in the stack and then triggers stack popping of
* any optional IFBLOCK_ELSE along with it's IFBLOCK_IF
*/
static int push_ifblock(struct ifblock_stack_obj **ifblock_stack_top,
struct text_object *obj, enum ifblock_type type) {
struct ifblock_stack_obj *stackobj;
switch (type) {
case IFBLOCK_ENDIF:
if ((*ifblock_stack_top) == nullptr) {
CRIT_ERR("got an endif without matching if");
}
(*ifblock_stack_top)->obj->ifblock_next = obj;
/* if there's some else in between, remove and free it */
if ((*ifblock_stack_top)->type == IFBLOCK_ELSE) {
stackobj = *ifblock_stack_top;
*ifblock_stack_top = stackobj->next;
free(stackobj);
}
/* finally remove and free the if object */
stackobj = *ifblock_stack_top;
*ifblock_stack_top = stackobj->next;
free(stackobj);
break;
case IFBLOCK_ELSE:
if ((*ifblock_stack_top) == nullptr) {
CRIT_ERR("got an else without matching if");
}
(*ifblock_stack_top)->obj->ifblock_next = obj;
/* falls through */
case IFBLOCK_IF:
stackobj = static_cast<ifblock_stack_obj *>(
malloc(sizeof(struct ifblock_stack_obj)));
stackobj->type = type;
stackobj->obj = obj;
stackobj->next = *ifblock_stack_top;
*ifblock_stack_top = stackobj;
break;
default:
CRIT_ERR("push_ifblock() misuse detected!");
}
return 0;
}
/* public functions for client use */
int obj_be_ifblock_if(void **opaque, struct text_object *obj) {
return push_ifblock(reinterpret_cast<struct ifblock_stack_obj **>(opaque),
obj, IFBLOCK_IF);
}
int obj_be_ifblock_else(void **opaque, struct text_object *obj) {
return push_ifblock(reinterpret_cast<struct ifblock_stack_obj **>(opaque),
obj, IFBLOCK_ELSE);
}
int obj_be_ifblock_endif(void **opaque, struct text_object *obj) {
return push_ifblock(reinterpret_cast<struct ifblock_stack_obj **>(opaque),
obj, IFBLOCK_ENDIF);
}
/* check if ifblock stack is empty
* if so, return true (!= 0)
*/
int ifblock_stack_empty(void **opaque) {
return static_cast<int>(*opaque == nullptr);
}
void obj_be_plain_text(struct text_object *obj, const char *text) {
obj->data.s = strdup(text);
memset(&obj->callbacks, 0, sizeof(obj->callbacks));
obj->callbacks.print = &gen_print_obj_data_s;
obj->callbacks.free = &gen_free_opaque;
}
| 5,891
|
C++
|
.cc
| 167
| 31.497006
| 76
| 0.673036
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
22,614
|
cmus.cc
|
brndnmtthws_conky/src/cmus.cc
|
/*
*
* CMUS Conky integration
*
* Please see COPYING for details
*
* Copyright (c) 2008, Henri Häkkinen
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "conky.h"
#include "logging.h"
#include "text_object.h"
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cmath>
#include <mutex>
#include "update-cb.hh"
namespace {
struct cmus_result {
std::string state;
std::string file;
std::string title;
std::string artist;
std::string album;
std::string totaltime;
std::string curtime;
std::string random;
std::string repeat;
std::string aaa;
std::string track;
std::string genre;
std::string date;
float progress;
float timeleft;
};
class cmus_cb : public conky::callback<cmus_result> {
typedef conky::callback<cmus_result> Base;
protected:
virtual void work();
public:
explicit cmus_cb(uint32_t period) : Base(period, false, Tuple()) {}
};
void cmus_cb::work() {
cmus_result cmus;
FILE *fp;
fp = popen("cmus-remote -Q 2>/dev/null", "r");
if (!fp) {
cmus.state = "Can't run 'cmus-remote -Q'";
} else {
while (1) {
char line[255];
char *p;
/* Read a line from the pipe and strip the possible '\n'. */
if (!fgets(line, 255, fp)) break;
if ((p = strrchr(line, '\n'))) *p = '\0';
/* Parse infos. */
if (strncmp(line, "status ", 7) == 0) {
cmus.state = line + 7;
} else if (strncmp(line, "file ", 5) == 0) {
cmus.file = line + 5;
} else if (strncmp(line, "tag artist ", 11) == 0) {
cmus.artist = line + 11;
} else if (strncmp(line, "tag title ", 10) == 0) {
cmus.title = line + 10;
} else if (strncmp(line, "tag album ", 10) == 0) {
cmus.album = line + 10;
} else if (strncmp(line, "duration ", 9) == 0) {
cmus.totaltime = line + 9;
} else if (strncmp(line, "position ", 9) == 0) {
cmus.curtime = line + 9;
cmus.timeleft = strtol(cmus.totaltime.c_str(), nullptr, 10) -
strtol(cmus.curtime.c_str(), nullptr, 10);
if (cmus.curtime.size() > 0) {
cmus.progress =
static_cast<float>(strtol(cmus.curtime.c_str(), nullptr, 10)) /
strtol(cmus.totaltime.c_str(), nullptr, 10);
} else {
cmus.progress = 0;
}
}
else if (strncmp(line, "set shuffle ", 12) == 0) {
cmus.random = (strncmp(line + 12, "true", 4) == 0 ? "on" : "off");
} else if (strncmp(line, "set repeat ", 11) == 0) {
cmus.repeat = (strncmp((line + 11), "true", 4) == 0 ? "all" : "off");
} else if (strncmp(line, "set repeat_current ", 19) == 0) {
cmus.repeat =
(strncmp((line + 19), "true", 4) == 0 ? "song" : cmus.repeat);
} else if (strncmp(line, "set aaa_mode ", 13) == 0) {
cmus.aaa = line + 13;
} else if (strncmp(line, "tag tracknumber ", 16) == 0) {
cmus.track = line + 16;
} else if (strncmp(line, "tag genre ", 10) == 0) {
cmus.genre = line + 10;
} else if (strncmp(line, "tag date ", 9) == 0) {
cmus.date = line + 9;
}
}
}
pclose(fp);
std::lock_guard<std::mutex> l(result_mutex);
result = cmus;
}
} // namespace
#define CMUS_PRINT_GENERATOR(type, alt) \
void print_cmus_##type(struct text_object *obj, char *p, \
unsigned int p_max_size) { \
(void)obj; \
uint32_t period = std::max( \
lround(music_player_interval.get(*state) / active_update_interval()), \
1l); \
const cmus_result &cmus = \
conky::register_cb<cmus_cb>(period)->get_result_copy(); \
snprintf(p, p_max_size, "%s", \
(cmus.type.length() ? cmus.type.c_str() : alt)); \
}
CMUS_PRINT_GENERATOR(state, "Off")
CMUS_PRINT_GENERATOR(file, "no file")
CMUS_PRINT_GENERATOR(title, "no title")
CMUS_PRINT_GENERATOR(artist, "no artist")
CMUS_PRINT_GENERATOR(album, "no album")
CMUS_PRINT_GENERATOR(random, "")
CMUS_PRINT_GENERATOR(repeat, "")
CMUS_PRINT_GENERATOR(aaa, "all")
CMUS_PRINT_GENERATOR(track, "no track")
CMUS_PRINT_GENERATOR(genre, "")
CMUS_PRINT_GENERATOR(date, "")
uint8_t cmus_percent(struct text_object *obj) {
(void)obj;
uint32_t period = std::max(
lround(music_player_interval.get(*state) / active_update_interval()), 1l);
const cmus_result &cmus =
conky::register_cb<cmus_cb>(period)->get_result_copy();
return static_cast<uint8_t>(round(cmus.progress * 100.0f));
}
double cmus_progress(struct text_object *obj) {
(void)obj;
uint32_t period = std::max(
lround(music_player_interval.get(*state) / active_update_interval()), 1l);
const cmus_result &cmus =
conky::register_cb<cmus_cb>(period)->get_result_copy();
return static_cast<double>(cmus.progress);
}
void print_cmus_totaltime(struct text_object *obj, char *p,
unsigned int p_max_size) {
(void)obj;
uint32_t period = std::max(
lround(music_player_interval.get(*state) / active_update_interval()), 1l);
const cmus_result &cmus =
conky::register_cb<cmus_cb>(period)->get_result_copy();
format_seconds_short(p, p_max_size,
strtol(cmus.totaltime.c_str(), nullptr, 10));
}
void print_cmus_timeleft(struct text_object *obj, char *p,
unsigned int p_max_size) {
(void)obj;
uint32_t period = std::max(
lround(music_player_interval.get(*state) / active_update_interval()), 1l);
const cmus_result &cmus =
conky::register_cb<cmus_cb>(period)->get_result_copy();
format_seconds_short(p, p_max_size, static_cast<long>(cmus.timeleft));
}
void print_cmus_curtime(struct text_object *obj, char *p,
unsigned int p_max_size) {
(void)obj;
uint32_t period = std::max(
lround(music_player_interval.get(*state) / active_update_interval()), 1l);
const cmus_result &cmus =
conky::register_cb<cmus_cb>(period)->get_result_copy();
format_seconds_short(p, p_max_size,
strtol(cmus.curtime.c_str(), nullptr, 10));
}
#undef CMUS_PRINT_GENERATOR
| 7,091
|
C++
|
.cc
| 186
| 32.919355
| 80
| 0.585976
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
22,615
|
timeinfo.cc
|
brndnmtthws_conky/src/timeinfo.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "config.h"
#include "timeinfo.h"
#include <stdio.h>
#include <cerrno>
#include <clocale>
#include <cstring>
#include <ctime>
#include "conky.h"
#include "logging.h"
#include "text_object.h"
#include <memory>
struct tztime_s {
char *tz; /* timezone variable */
char *fmt; /* time display formatting */
};
conky::simple_config_setting<bool> times_in_seconds("times_in_seconds", false,
false);
void scan_time(struct text_object *obj, const char *arg) {
obj->data.opaque =
strndup(arg != nullptr ? arg : "%F %T", text_buffer_size.get(*state));
}
void scan_tztime(struct text_object *obj, const char *arg) {
char buf1[256], buf2[256], *fmt, *tz;
struct tztime_s *ts;
fmt = tz = nullptr;
if (arg != nullptr) {
int nArgs = sscanf(arg, "%255s %255[^\n]", buf1, buf2);
if (nArgs == 2) {
fmt = buf2;
tz = buf1;
} else if (nArgs == 1) {
tz = buf1;
}
}
ts = static_cast<tztime_s *>(malloc(sizeof(struct tztime_s)));
memset(ts, 0, sizeof(struct tztime_s));
ts->fmt =
strndup(fmt != nullptr ? fmt : "%F %T", text_buffer_size.get(*state));
ts->tz = tz != nullptr ? strndup(tz, text_buffer_size.get(*state)) : nullptr;
obj->data.opaque = ts;
}
void print_time(struct text_object *obj, char *p, unsigned int p_max_size) {
time_t t = time(nullptr);
struct tm *tm = localtime(&t);
setlocale(LC_TIME, "");
strftime(p, p_max_size, static_cast<char *>(obj->data.opaque), tm);
}
void print_utime(struct text_object *obj, char *p, unsigned int p_max_size) {
time_t t = time(nullptr);
struct tm *tm = gmtime(&t);
setlocale(LC_TIME, "");
strftime(p, p_max_size, static_cast<char *>(obj->data.opaque), tm);
}
void print_tztime(struct text_object *obj, char *p, unsigned int p_max_size) {
char *oldTZ = nullptr;
time_t t;
struct tm *tm;
auto *ts = static_cast<tztime_s *>(obj->data.opaque);
if (ts == nullptr) { return; }
if (ts->tz != nullptr) {
oldTZ = getenv("TZ");
setenv("TZ", ts->tz, 1);
tzset();
}
t = time(nullptr);
tm = localtime(&t);
setlocale(LC_TIME, "");
strftime(p, p_max_size, ts->fmt, tm);
if (oldTZ != nullptr) {
setenv("TZ", oldTZ, 1);
tzset();
} else {
unsetenv("TZ");
}
// Needless to free oldTZ since getenv gives ptr to static data
}
void free_time(struct text_object *obj) { free_and_zero(obj->data.opaque); }
void free_tztime(struct text_object *obj) {
auto *ts = static_cast<tztime_s *>(obj->data.opaque);
if (ts == nullptr) { return; }
free_and_zero(ts->tz);
free_and_zero(ts->fmt);
free_and_zero(obj->data.opaque);
}
/* a safer asprintf()
* - no need to check for errors
* - exit conky on memory allocation failure
* - XXX: no return value at all, otherwise this
* could be used globally */
#define safe_asprintf(bufp, ...) \
{ \
int __v; \
if ((__v = asprintf(bufp, __VA_ARGS__)) == -1) { \
fprintf(stderr, "%s: memory allocation failed\n", __func__); \
exit(__v); \
} \
}
// all chars after the ending " and between the seconds and the starting " are
// silently ignored, this is wanted behavior, not a bug, so don't "fix" this.
static void do_format_time(struct text_object *obj, char *p,
unsigned int p_max_size) {
double seconds;
char *currentchar, *temp;
unsigned int output_length = 0;
int minutes, hours, days, weeks;
char show_minutes = 0, show_hours = 0, show_days = 0, show_weeks = 0,
hidestring;
if (!times_in_seconds.get(*state)) {
NORM_ERR("Enable \"times_in_seconds\" to use $format_time");
return;
}
errno = 0;
seconds = strtod(obj->data.s, ¤tchar);
if (errno == 0 && obj->data.s != currentchar) {
while (*currentchar != 0 && *currentchar != '"') { currentchar++; }
if (*currentchar != 0) {
currentchar++;
minutes = seconds / 60;
seconds -= minutes * 60;
hours = minutes / 60;
minutes %= 60;
days = hours / 24;
hours %= 24;
weeks = days / 7;
days %= 7;
for (temp = currentchar; *temp != 0 && *temp != '"'; temp++) {
if (*temp == '\\') {
switch (*(temp + 1)) {
case '\\':
temp++;
break;
case 'w':
show_weeks = 1;
break;
case 'd':
show_days = 1;
break;
case 'h':
show_hours = 1;
break;
case 'm':
show_minutes = 1;
break;
}
}
}
if (show_weeks == 0) { days += weeks * 7; }
if (show_days == 0) { hours += days * 24; }
if (show_hours == 0) { minutes += hours * 60; }
if (show_minutes == 0) { seconds += minutes * 60; }
hidestring = 0;
while (output_length < p_max_size - 1) {
if (*currentchar != 0 && *currentchar != '"') {
temp = nullptr;
if (*currentchar == '\\' && hidestring == 0) {
currentchar++;
switch (*currentchar) {
case 'w':
safe_asprintf(&temp, "%d", weeks);
break;
case 'd':
safe_asprintf(&temp, "%d", days);
break;
case 'h':
safe_asprintf(&temp, "%d", hours);
break;
case 'm':
safe_asprintf(&temp, "%d", minutes);
break;
case 's':
safe_asprintf(&temp, "%d", (int)seconds);
break;
case 'S':
currentchar++;
if (*currentchar >= '0' && *currentchar <= '9') {
safe_asprintf(&temp, "%.*f", (*currentchar) - '0', seconds);
} else if (*currentchar == 'x') {
if (seconds == static_cast<int>(seconds)) {
safe_asprintf(&temp, "%d", (int)seconds);
} else {
safe_asprintf(&temp, "%.9f", seconds);
while (*(temp + strlen(temp) - 1) == '0' ||
*(temp + strlen(temp) - 1) == '.') {
*(temp + strlen(temp) - 1) = 0;
}
}
} else {
currentchar--;
NORM_ERR(
"$format_time needs a digit behind 'S' to specify "
"precision");
}
break;
case '\\':
case '(':
case ')':
p[output_length] = *currentchar;
output_length++;
break;
default:
NORM_ERR("$format_time doesn't have a special char '%c'",
*currentchar);
}
} else if (*currentchar == '(') {
for (temp = currentchar + 1; *temp != 0 && *temp != ')'; temp++) {
if (*(temp - 1) == '\\') {
switch (*temp) {
case 'w':
if (weeks == 0) { hidestring = 1; }
break;
case 'd':
if (days == 0) { hidestring = 1; }
break;
case 'h':
if (hours == 0) { hidestring = 1; }
break;
case 'm':
if (minutes == 0) { hidestring = 1; }
break;
case 's':
case 'S':
if (seconds == 0) { hidestring = 1; }
break;
}
}
}
temp = nullptr;
} else if (*currentchar == ')') {
hidestring = 0;
} else if (hidestring == 0) {
p[output_length] = *currentchar;
output_length++;
}
if (temp != nullptr) {
if (output_length + strlen(temp) < p_max_size - 1) {
strncpy(p + output_length, temp,
p_max_size - output_length + strlen(temp));
output_length += strlen(temp);
} else {
NORM_ERR("The format string for $format_time is too long");
}
free(temp);
}
currentchar++;
} else {
break;
}
}
p[output_length] = 0;
} else {
NORM_ERR(
"$format_time needs a output-format starting with a \"-char as 2nd "
"argument");
}
} else {
NORM_ERR("$format_time didn't receive a time in seconds as first argument");
}
}
void print_format_time(struct text_object *obj, char *p,
unsigned int p_max_size) {
std::unique_ptr<char[]> buf(new char[max_user_text.get(*state)]);
generate_text_internal(buf.get(), max_user_text.get(*state), *obj->sub);
obj->data.s = buf.get();
do_format_time(obj, p, p_max_size);
}
| 10,276
|
C++
|
.cc
| 293
| 26.34471
| 80
| 0.501457
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
22,616
|
openbsd.cc
|
brndnmtthws_conky/src/openbsd.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2007 Toni Spets
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <kvm.h>
#include <sys/dkstat.h>
#include <sys/ioctl.h>
#include <sys/malloc.h>
#include <sys/param.h>
#include <sys/resource.h>
#include <sys/sensors.h>
#include <sys/socket.h>
#include <sys/swap.h>
#include <sys/sysctl.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/user.h>
#include <sys/vmmeter.h>
#include <net/if.h>
#include <net/if_media.h>
#include <netinet/in.h>
#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <ifaddrs.h>
#include <limits.h>
#include <machine/apmvar.h>
#include <unistd.h>
#include <net80211/ieee80211.h>
#include <net80211/ieee80211_ioctl.h>
#include "conky.h"
#include "diskio.h"
#include "logging.h"
#include "net_stat.h"
#include "openbsd.h"
#include "top.h"
#define MAXSHOWDEVS 16
#define LOG1024 10
#define pagetok(size) ((size) << pageshift)
inline void proc_find_top(struct process **cpu, struct process **mem);
static short cpu_setup = 0;
static kvm_t *kd = 0;
struct ifmibdata *data = nullptr;
size_t len = 0;
int init_kvm = 0;
int init_sensors = 0;
static int kvm_init() {
if (init_kvm) { return 1; }
kd = kvm_open(nullptr, NULL, NULL, KVM_NO_FILES, NULL);
if (kd == nullptr) {
NORM_ERR("error opening kvm");
} else {
init_kvm = 1;
}
return 1;
}
/* note: swapmode taken from 'top' source */
/* swapmode is rewritten by Tobias Weingartner <weingart@openbsd.org>
* to be based on the new swapctl(2) system call. */
static int swapmode(int *used, int *total) {
struct swapent *swdev;
int nswap, rnswap, i;
nswap = swapctl(SWAP_NSWAP, 0, 0);
if (nswap == 0) { return 0; }
swdev = malloc(nswap * sizeof(*swdev));
if (swdev == nullptr) { return 0; }
rnswap = swapctl(SWAP_STATS, swdev, nswap);
if (rnswap == -1) {
free(swdev);
return 0;
}
/* if rnswap != nswap, then what? */
/* Total things up */
*total = *used = 0;
for (i = 0; i < nswap; i++) {
if (swdev[i].se_flags & SWF_ENABLE) {
*used += (swdev[i].se_inuse / (1024 / DEV_BSIZE));
*total += (swdev[i].se_nblks / (1024 / DEV_BSIZE));
}
}
free(swdev);
return 1;
}
int check_mount(struct text_object *obj) {
/* stub */
(void)obj;
return 0;
}
void update_uptime() {
int mib[2] = {CTL_KERN, KERN_BOOTTIME};
struct timeval boottime;
time_t now;
size_t size = sizeof(boottime);
if ((sysctl(mib, 2, &boottime, &size, nullptr, 0) != -1) &&
(boottime.tv_sec != 0)) {
time(&now);
info.uptime = now - boottime.tv_sec;
} else {
NORM_ERR("Could not get uptime");
info.uptime = 0;
}
}
void update_meminfo() {
static int mib[2] = {CTL_VM, VM_METER};
struct vmtotal vmtotal;
size_t size;
int pagesize, pageshift, swap_avail, swap_used;
pagesize = getpagesize();
pageshift = 0;
while (pagesize > 1) {
pageshift++;
pagesize >>= 1;
}
/* we only need the amount of log(2)1024 for our conversion */
pageshift -= LOG1024;
/* get total -- systemwide main memory usage structure */
size = sizeof(vmtotal);
if (sysctl(mib, 2, &vmtotal, &size, nullptr, 0) < 0) {
warn("sysctl failed");
bzero(&vmtotal, sizeof(vmtotal));
}
info.memmax = pagetok(vmtotal.t_rm) + pagetok(vmtotal.t_free);
info.mem = info.memwithbuffers = pagetok(vmtotal.t_rm);
info.memeasyfree = info.memfree = info.memmax - info.mem;
info.legacymem = info.mem;
if ((swapmode(&swap_used, &swap_avail)) >= 0) {
info.swapmax = swap_avail;
info.swap = swap_used;
info.swapfree = swap_avail - swap_used;
} else {
info.swapmax = 0;
info.swap = 0;
info.swapfree = 0;
}
}
void update_net_stats() {
struct net_stat *ns;
double delta;
long long r, t, last_recv, last_trans;
struct ifaddrs *ifap, *ifa;
struct if_data *ifd;
/* get delta */
delta = current_update_time - last_update_time;
if (delta <= 0.0001) { return; }
if (getifaddrs(&ifap) < 0) { return; }
for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
ns = get_net_stat((const char *)ifa->ifa_name, nullptr, NULL);
if (ifa->ifa_flags & IFF_UP) {
struct ifaddrs *iftmp;
ns->up = 1;
last_recv = ns->recv;
last_trans = ns->trans;
if (ifa->ifa_addr->sa_family != AF_LINK) { continue; }
for (iftmp = ifa->ifa_next;
iftmp != nullptr && strcmp(ifa->ifa_name, iftmp->ifa_name) == 0;
iftmp = iftmp->ifa_next) {
if (iftmp->ifa_addr->sa_family == AF_INET) {
memcpy(&(ns->addr), iftmp->ifa_addr, iftmp->ifa_addr->sa_len);
}
}
ifd = (struct if_data *)ifa->ifa_data;
r = ifd->ifi_ibytes;
t = ifd->ifi_obytes;
if (r < ns->last_read_recv) {
ns->recv += ((long long)4294967295U - ns->last_read_recv) + r;
} else {
ns->recv += (r - ns->last_read_recv);
}
ns->last_read_recv = r;
if (t < ns->last_read_trans) {
ns->trans += (long long)4294967295U - ns->last_read_trans + t;
} else {
ns->trans += (t - ns->last_read_trans);
}
ns->last_read_trans = t;
/* calculate speeds */
ns->recv_speed = (ns->recv - last_recv) / delta;
ns->trans_speed = (ns->trans - last_trans) / delta;
} else {
ns->up = 0;
}
}
freeifaddrs(ifap);
}
int update_total_processes() {
int n_processes;
kvm_init();
kvm_getprocs(kd, KERN_PROC_ALL, 0, &n_processes);
info.procs = n_processes;
return 0;
}
void update_running_processes() {
struct kinfo_proc2 *p;
int n_processes;
int i, cnt = 0;
kvm_init();
int max_size = sizeof(struct kinfo_proc2);
p = kvm_getproc2(kd, KERN_PROC_ALL, 0, max_size, &n_processes);
for (i = 0; i < n_processes; i++) {
if (p[i].p_stat == SRUN) { cnt++; }
}
info.run_procs = cnt;
}
/* new SMP code can be enabled by commenting the following line */
#define OLDCPU
#ifdef OLDCPU
struct cpu_load_struct {
unsigned long load[5];
};
struct cpu_load_struct fresh = {{0, 0, 0, 0, 0}};
long cpu_used, oldtotal, oldused;
#else
#include <assert.h>
int64_t *fresh = nullptr;
/* XXX is 8 enough? - What's the constant for MAXCPU? */
/* allocate this with malloc would be better */
int64_t oldtotal[8], oldused[8];
#endif
void get_cpu_count() {
int cpu_count = 1; /* default to 1 cpu */
#ifndef OLDCPU
int mib[2] = {CTL_HW, HW_NCPU};
size_t len = sizeof(cpu_count);
if (sysctl(mib, 2, &cpu_count, &len, nullptr, 0) != 0) {
NORM_ERR("error getting cpu count, defaulting to 1");
}
#endif
info.cpu_count = cpu_count;
info.cpu_usage = malloc(info.cpu_count * sizeof(float));
if (info.cpu_usage == nullptr) { CRIT_ERR("malloc"); }
#ifndef OLDCPU
assert(fresh == nullptr); /* XXX Is this leaking memory? */
/* XXX Where shall I free this? */
if (nullptr == (fresh = calloc(cpu_count, sizeof(int64_t) * CPUSTATES))) {
CRIT_ERR("calloc");
}
#endif
}
void update_cpu_usage() {
#ifdef OLDCPU
int mib[2] = {CTL_KERN, KERN_CPTIME};
long used, total;
long cp_time[CPUSTATES];
size_t len = sizeof(cp_time);
#else
size_t size;
unsigned int i;
#endif
/* add check for !info.cpu_usage since that mem is freed on a SIGUSR1 */
if ((cpu_setup == 0) || (!info.cpu_usage)) {
get_cpu_count();
cpu_setup = 1;
}
#ifdef OLDCPU
if (sysctl(mib, 2, &cp_time, &len, nullptr, 0) < 0) {
NORM_ERR("Cannot get kern.cp_time");
}
fresh.load[0] = cp_time[CP_USER];
fresh.load[1] = cp_time[CP_NICE];
fresh.load[2] = cp_time[CP_SYS];
fresh.load[3] = cp_time[CP_IDLE];
fresh.load[4] = cp_time[CP_IDLE];
used = fresh.load[0] + fresh.load[1] + fresh.load[2];
total = fresh.load[0] + fresh.load[1] + fresh.load[2] + fresh.load[3];
if ((total - oldtotal) != 0) {
info.cpu_usage[0] = ((double)(used - oldused)) / (double)(total - oldtotal);
} else {
info.cpu_usage[0] = 0;
}
oldused = used;
oldtotal = total;
#else
if (info.cpu_count > 1) {
size = CPUSTATES * sizeof(int64_t);
for (i = 0; i < info.cpu_count; i++) {
int cp_time_mib[] = {CTL_KERN, KERN_CPTIME2, i};
if (sysctl(cp_time_mib, 3, &(fresh[i * CPUSTATES]), &size, nullptr, 0) <
0) {
NORM_ERR("sysctl kern.cp_time2 failed");
}
}
} else {
int cp_time_mib[] = {CTL_KERN, KERN_CPTIME};
long cp_time_tmp[CPUSTATES];
size = sizeof(cp_time_tmp);
if (sysctl(cp_time_mib, 2, cp_time_tmp, &size, nullptr, 0) < 0) {
NORM_ERR("sysctl kern.cp_time failed");
}
for (i = 0; i < CPUSTATES; i++) { fresh[i] = (int64_t)cp_time_tmp[i]; }
}
/* XXX Do sg with this int64_t => long => double ? float hell. */
for (i = 0; i < info.cpu_count; i++) {
int64_t used, total;
int at = i * CPUSTATES;
used = fresh[at + CP_USER] + fresh[at + CP_NICE] + fresh[at + CP_SYS];
total = used + fresh[at + CP_IDLE];
if ((total - oldtotal[i]) != 0) {
info.cpu_usage[i] =
((double)(used - oldused[i])) / (double)(total - oldtotal[i]);
} else {
info.cpu_usage[i] = 0;
}
oldused[i] = used;
oldtotal[i] = total;
}
#endif
}
void free_cpu(struct text_object *) { /* no-op */
}
void update_load_average() {
double v[3];
getloadavg(v, 3);
info.loadavg[0] = (float)v[0];
info.loadavg[1] = (float)v[1];
info.loadavg[2] = (float)v[2];
}
#define OBSD_MAX_SENSORS 256
static struct obsd_sensors_struct {
int device;
float temp[MAXSENSORDEVICES][OBSD_MAX_SENSORS];
unsigned int fan[MAXSENSORDEVICES][OBSD_MAX_SENSORS];
float volt[MAXSENSORDEVICES][OBSD_MAX_SENSORS];
} obsd_sensors;
static conky::simple_config_setting<int> sensor_device("sensor_device", 0,
false);
/* read sensors from sysctl */
void update_obsd_sensors() {
int sensor_cnt, dev, numt, mib[5] = {CTL_HW, HW_SENSORS, 0, 0, 0};
struct sensor sensor;
struct sensordev sensordev;
size_t slen, sdlen;
enum sensor_type type;
slen = sizeof(sensor);
sdlen = sizeof(sensordev);
sensor_cnt = 0;
dev = obsd_sensors.device; // FIXME: read more than one device
/* for (dev = 0; dev < MAXSENSORDEVICES; dev++) { */
mib[2] = dev;
if (sysctl(mib, 3, &sensordev, &sdlen, nullptr, 0) == -1) {
if (errno != ENOENT) { warn("sysctl"); }
return;
// continue;
}
for (type = 0; type < SENSOR_MAX_TYPES; type++) {
mib[3] = type;
for (numt = 0; numt < sensordev.maxnumt[type]; numt++) {
mib[4] = numt;
if (sysctl(mib, 5, &sensor, &slen, nullptr, 0) == -1) {
if (errno != ENOENT) { warn("sysctl"); }
continue;
}
if (sensor.flags & SENSOR_FINVALID) { continue; }
switch (type) {
case SENSOR_TEMP:
obsd_sensors.temp[dev][sensor.numt] =
(sensor.value - 273150000) / 1000000.0;
break;
case SENSOR_FANRPM:
obsd_sensors.fan[dev][sensor.numt] = sensor.value;
break;
case SENSOR_VOLTS_DC:
obsd_sensors.volt[dev][sensor.numt] = sensor.value / 1000000.0;
break;
default:
break;
}
sensor_cnt++;
}
}
/* } */
init_sensors = 1;
}
void parse_obsd_sensor(struct text_object *obj, const char *arg) {
if (!isdigit((unsigned char)arg[0]) || atoi(&arg[0]) < 0 ||
atoi(&arg[0]) > OBSD_MAX_SENSORS - 1) {
obj->data.l = 0;
NORM_ERR("Invalid sensor number!");
} else
obj->data.l = atoi(&arg[0]);
}
void print_obsd_sensors_temp(struct text_object *obj, char *p, int p_max_size) {
obsd_sensors.device = sensor_device.get(*state);
update_obsd_sensors();
temp_print(p, p_max_size, obsd_sensors.temp[obsd_sensors.device][obj->data.l],
TEMP_CELSIUS, 1);
}
void print_obsd_sensors_fan(struct text_object *obj, char *p, int p_max_size) {
obsd_sensors.device = sensor_device.get(*state);
update_obsd_sensors();
snprintf(p, p_max_size, "%d",
obsd_sensors.fan[obsd_sensors.device][obj->data.l]);
}
void print_obsd_sensors_volt(struct text_object *obj, char *p, int p_max_size) {
obsd_sensors.device = sensor_device.get(*state);
update_obsd_sensors();
snprintf(p, p_max_size, "%.2f",
obsd_sensors.volt[obsd_sensors.device][obj->data.l]);
}
/* chipset vendor */
void get_obsd_vendor(struct text_object *obj, char *buf,
size_t client_buffer_size) {
int mib[2];
char vendor[64];
size_t size = sizeof(vendor);
(void)obj;
mib[0] = CTL_HW;
mib[1] = HW_VENDOR;
if (sysctl(mib, 2, vendor, &size, nullptr, 0) == -1) {
NORM_ERR("error reading vendor");
snprintf(buf, client_buffer_size, "%s", "unknown");
} else {
snprintf(buf, client_buffer_size, "%s", vendor);
}
}
/* chipset name */
void get_obsd_product(struct text_object *obj, char *buf,
size_t client_buffer_size) {
int mib[2];
char product[64];
size_t size = sizeof(product);
(void)obj;
mib[0] = CTL_HW;
mib[1] = HW_PRODUCT;
if (sysctl(mib, 2, product, &size, nullptr, 0) == -1) {
NORM_ERR("error reading product");
snprintf(buf, client_buffer_size, "%s", "unknown");
} else {
snprintf(buf, client_buffer_size, "%s", product);
}
}
/* void */
char get_freq(char *p_client_buffer, size_t client_buffer_size,
const char *p_format, int divisor, unsigned int cpu) {
int freq = cpu;
int mib[2] = {CTL_HW, HW_CPUSPEED};
if (!p_client_buffer || client_buffer_size <= 0 || !p_format ||
divisor <= 0) {
return 0;
}
size_t size = sizeof(freq);
if (sysctl(mib, 2, &freq, &size, nullptr, 0) == 0) {
snprintf(p_client_buffer, client_buffer_size, p_format,
(float)freq / divisor);
} else {
snprintf(p_client_buffer, client_buffer_size, p_format, 0.0f);
}
return 1;
}
#if 0
/* deprecated, will rewrite this soon in update_net_stats() -hifi */
void update_wifi_stats()
{
struct net_stat *ns;
struct ifaddrs *ifap, *ifa;
struct ifmediareq ifmr;
struct ieee80211_nodereq nr;
struct ieee80211_bssid bssid;
int s, ibssid;
/* Get iface table */
if (getifaddrs(&ifap) < 0) {
return;
}
for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
ns = get_net_stat((const char *) ifa->ifa_name);
s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
/* Get media type */
bzero(&ifmr, sizeof(ifmr));
strlcpy(ifmr.ifm_name, ifa->ifa_name, IFNAMSIZ);
if (ioctl(s, SIOCGIFMEDIA, (caddr_t) &ifmr) < 0) {
close(s);
return;
}
/* We can monitor only wireless interfaces
* which are not in hostap mode */
if ((ifmr.ifm_active & IFM_IEEE80211)
&& !(ifmr.ifm_active & IFM_IEEE80211_HOSTAP)) {
/* Get wi status */
memset(&bssid, 0, sizeof(bssid));
strlcpy(bssid.i_name, ifa->ifa_name, sizeof(bssid.i_name));
ibssid = ioctl(s, SIOCG80211BSSID, &bssid);
bzero(&nr, sizeof(nr));
bcopy(bssid.i_bssid, &nr.nr_macaddr, sizeof(nr.nr_macaddr));
strlcpy(nr.nr_ifname, ifa->ifa_name, sizeof(nr.nr_ifname));
if (ioctl(s, SIOCG80211NODE, &nr) == 0 && nr.nr_rssi) {
ns->linkstatus = nr.nr_rssi;
}
}
cleanup:
close(s);
}
}
#endif
void clear_diskio_stats() {}
struct diskio_stat *prepare_diskio_stat(const char *s) {}
void update_diskio() { return; /* XXX: implement? hifi: not sure how */ }
/* While topless is obviously better, top is also not bad. */
void get_top_info(void) {
struct kinfo_proc2 *p;
struct process *proc;
int n_processes;
int i;
kvm_init();
p = kvm_getproc2(kd, KERN_PROC_ALL, 0, sizeof(struct kinfo_proc2),
&n_processes);
for (i = 0; i < n_processes; i++) {
if (!((p[i].p_flag & P_SYSTEM)) && p[i].p_comm != nullptr) {
proc = find_process(p[i].p_pid);
if (!proc) proc = new_process(p[i].p_pid);
proc->time_stamp = g_time;
proc->name = strndup(p[i].p_comm, text_buffer_size);
proc->amount = 100.0 * p[i].p_pctcpu / FSCALE;
/* TODO: vsize, rss, total_cpu_time */
}
}
}
/* empty stubs so conky links */
void prepare_update() {}
int get_entropy_avail(unsigned int *val) { return 1; }
int get_entropy_poolsize(unsigned int *val) { return 1; }
| 16,957
|
C++
|
.cc
| 543
| 27.294659
| 80
| 0.628706
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
22,617
|
scroll.cc
|
brndnmtthws_conky/src/scroll.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <vector>
#include "colours.h"
#include "conky.h"
#include "core.h"
#include "display-output.hh"
#include "logging.h"
#include "specials.h"
#include "text_object.h"
/**
* Length of a character in bytes.
* @param c first byte of the character
*/
inline int scroll_character_length(char c) {
#ifdef BUILD_GUI
if (utf8_mode.get(*state)) {
auto uc = static_cast<unsigned char>(c);
int len = 0;
if ((uc & 0x80) == 0) { return 1; }
while (len < 7 && (uc & (0x80 >> len)) != 0) { ++len; }
return len;
}
#else /* BUILD_GUI */
(void)c;
#endif /* BUILD_GUI */
return 1;
}
/**
* Check if a byte should be skipped when counting characters to scroll text to
* right.
*/
inline bool scroll_check_skip_byte(char c) {
#ifdef BUILD_GUI
// Check if byte matches UTF-8 continuation byte pattern (0b10xxxxxx)
if (utf8_mode.get(*state) && (c & 0xC0) == 0x80) { return true; }
#endif
return SPECIAL_CHAR == c;
}
#define SCROLL_LEFT 1
#define SCROLL_RIGHT 2
#define SCROLL_WAIT 3
struct scroll_data {
char *text;
unsigned int show;
unsigned int step;
int wait;
unsigned int wait_arg;
signed int start;
Colour resetcolor;
int direction;
};
/**
* Get count of characters to right from (sd->start) position.
*/
static unsigned int scroll_count_characters_to_right(
struct scroll_data *sd, const std::vector<char> &buf) {
unsigned int n = 0;
unsigned int offset = sd->start;
while ('\0' != buf[offset] && offset < buf.size()) {
offset += scroll_character_length(buf[offset]);
++n;
}
return n;
}
static void scroll_scroll_left(struct scroll_data *sd,
const std::vector<char> &buf,
unsigned int amount) {
for (unsigned int i = 0; (i < amount) && (buf[sd->start] != '\0') &&
(static_cast<unsigned int>(sd->start) < buf.size());
++i) {
sd->start += scroll_character_length(buf[sd->start]);
}
if (buf[sd->start] == 0 ||
static_cast<unsigned int>(sd->start) > strlen(buf.data())) {
sd->start = 0;
}
}
static void scroll_scroll_right(struct scroll_data *sd,
const std::vector<char> &buf,
unsigned int amount) {
for (unsigned int i = 0; i < amount; ++i) {
if (sd->start <= 0) { sd->start = static_cast<int>(strlen(&(buf[0]))); }
while (--(sd->start) >= 0) {
if (!scroll_check_skip_byte(buf[sd->start])) { break; }
}
}
}
void parse_scroll_arg(struct text_object *obj, const char *arg,
void *free_at_crash, char *free_at_crash2) {
struct scroll_data *sd;
int n1 = 0, n2 = 0;
char dirarg[6];
sd = static_cast<struct scroll_data *>(malloc(sizeof(struct scroll_data)));
memset(sd, 0, sizeof(struct scroll_data));
sd->resetcolor = get_current_text_color();
sd->step = 1;
sd->direction = SCROLL_LEFT;
if ((arg != nullptr) && sscanf(arg, "%5s %n", dirarg, &n1) == 1) {
if (strcasecmp(dirarg, "right") == 0 || strcasecmp(dirarg, "r") == 0) {
sd->direction = SCROLL_RIGHT;
} else if (strcasecmp(dirarg, "wait") == 0 ||
strcasecmp(dirarg, "w") == 0) {
sd->direction = SCROLL_WAIT;
} else if (strcasecmp(dirarg, "left") != 0 &&
strcasecmp(dirarg, "l") != 0) {
n1 = 0;
}
}
if ((arg == nullptr) || sscanf(arg + n1, "%u %n", &sd->show, &n2) <= 0) {
free(sd);
#ifdef BUILD_GUI
free(obj->next);
#endif
free(free_at_crash2);
CRIT_ERR_FREE(obj, free_at_crash,
"scroll needs arguments: [left|right|wait] <length> [<step>] "
"[interval] <text>");
}
n1 += n2;
if (sscanf(arg + n1, "%u %n", &sd->step, &n2) == 1) {
n1 += n2;
} else {
sd->step = 1;
}
if (sscanf(arg + n1, "%u %n", &sd->wait_arg, &n2) == 1) {
n1 += n2;
sd->wait = sd->wait_arg;
} else {
sd->wait_arg = sd->wait = 0;
}
sd->text = static_cast<char *>(malloc(strlen(arg + n1) + sd->show + 1));
if (strlen(arg) > sd->show && sd->direction != SCROLL_WAIT) {
for (n2 = 0; static_cast<unsigned int>(n2) < sd->show; n2++) {
sd->text[n2] = ' ';
}
sd->text[n2] = 0;
} else {
sd->text[0] = 0;
}
strncat(sd->text, arg + n1, max_user_text.get(*state) - n1);
sd->start = sd->direction == SCROLL_WAIT ? strlen(sd->text) : 0;
obj->sub =
static_cast<struct text_object *>(malloc(sizeof(struct text_object)));
extract_variable_text_internal(obj->sub, sd->text);
obj->data.opaque = sd;
#ifdef BUILD_GUI
/* add a color object right after scroll to reset any color changes */
#endif /* BUILD_GUI */
}
void print_scroll(struct text_object *obj, char *p, unsigned int p_max_size) {
auto *sd = static_cast<struct scroll_data *>(obj->data.opaque);
unsigned int j, colorchanges = 0, frontcolorchanges = 0,
visibcolorchanges = 0;
std::vector<char> buf(max_user_text.get(*state), static_cast<char>(0));
if (sd == nullptr) { return; }
generate_text_internal(&(buf[0]), max_user_text.get(*state), *obj->sub);
for (j = 0; buf[j] != 0; j++) {
if (buf[j] == '\n') {
// place all the lines behind each other with LINESEPARATOR between them
#define LINESEPARATOR '|'
buf[j] = LINESEPARATOR;
} else if (buf[j] == SPECIAL_CHAR) {
colorchanges++;
}
}
// no scrolling necessary if the length of the text to scroll is too short
if (strlen(&(buf[0])) - colorchanges <= sd->show) {
snprintf(p, p_max_size, "%s", &(buf[0]));
return;
}
// if length of text changed to shorter so the (sd->start) is already
// outside of actual text then reset (sd->start)
if (static_cast<unsigned int>(sd->start) >= strlen(&(buf[0]))) {
sd->start = 0;
}
// make sure a colorchange at the front is not part of the string we are going
// to show
while (buf[sd->start] == SPECIAL_CHAR) { sd->start++; }
// place all chars that should be visible in p, including colorchanges
unsigned int visiblechars;
for (j = 0, visiblechars = 0; visiblechars < sd->show;) {
char c = buf[sd->start + j];
p[j] = c;
if (0 == c) { break; }
++j;
if (SPECIAL_CHAR == c) {
++visibcolorchanges;
} else {
int l = scroll_character_length(c);
while (--l != 0) {
p[j] = buf[sd->start + j];
++j;
}
++visiblechars;
}
}
for (; visiblechars < sd->show; j++, visiblechars++) { p[j] = ' '; }
p[j] = 0;
// count colorchanges in front of the visible part and place that many
// colorchanges in front of the visible part
for (j = 0; j < static_cast<unsigned>(sd->start); j++) {
if (buf[j] == SPECIAL_CHAR) { frontcolorchanges++; }
}
int pwithcolors_len = strlen(p) + 4 + colorchanges - visibcolorchanges;
char *pwithcolors = new char[pwithcolors_len];
for (j = 0; j < frontcolorchanges; j++) { pwithcolors[j] = SPECIAL_CHAR; }
pwithcolors[j] = 0;
strcat(pwithcolors, p);
unsigned int strend = strlen(pwithcolors);
// and place the colorchanges not in front or in the visible part behind the
// visible part
for (j = 0; j < colorchanges - frontcolorchanges - visibcolorchanges; j++) {
pwithcolors[strend + j] = SPECIAL_CHAR;
}
pwithcolors[strend + j] = 0;
strncpy(p, pwithcolors, p_max_size);
delete[] pwithcolors;
// scroll
if (sd->direction == SCROLL_LEFT) {
scroll_scroll_left(sd, buf, sd->step);
} else if (sd->direction == SCROLL_WAIT) {
unsigned int charsleft = scroll_count_characters_to_right(sd, buf);
if (sd->show >= charsleft) {
if (sd->wait_arg == 0) {
sd->start = 0;
} else {
sd->wait--;
if (sd->wait <= 0 && sd->wait_arg != 1) {
sd->wait = sd->wait_arg;
} else {
sd->start = 0;
}
}
} else {
if (sd->wait_arg == 0 || sd->wait_arg == 1 || sd->wait <= 0) {
sd->wait = 0;
if (sd->step < charsleft) {
scroll_scroll_left(sd, buf, sd->step);
} else {
scroll_scroll_left(sd, buf, charsleft);
}
} else {
sd->wait--;
}
}
} else {
scroll_scroll_right(sd, buf, sd->step);
}
#ifdef BUILD_GUI
// reset color when scroll is finished
if (display_output() && display_output()->graphical()) {
new_special(p + strlen(p), text_node_t::FG)->arg =
sd->resetcolor.to_argb32();
}
#endif
}
void free_scroll(struct text_object *obj) {
auto *sd = static_cast<struct scroll_data *>(obj->data.opaque);
if (sd == nullptr) { return; }
free_and_zero(sd->text);
free_text_objects(obj->sub);
free_and_zero(obj->sub);
free_and_zero(obj->data.opaque);
}
| 9,720
|
C++
|
.cc
| 291
| 28.804124
| 80
| 0.610193
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,618
|
prss.cc
|
brndnmtthws_conky/src/prss.cc
|
/*
*
* Copyright (c) 2007 Mikko Sysikaski <mikko.sysikaski@gmail.com>
* Toni Spets <toni.spets@gmail.com>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "prss.h"
#include <libxml/parser.h>
#include <libxml/tree.h>
#include "conky.h"
#include "logging.h"
#ifndef PARSE_OPTIONS
#define PARSE_OPTIONS 0
#endif
void prss_parse_doc(PRSS *result, xmlDocPtr doc);
PRSS::PRSS(const std::string &xml_data)
: version(nullptr),
title(nullptr),
link(nullptr),
description(nullptr),
language(nullptr),
generator(nullptr),
managingEditor(nullptr),
webMaster(nullptr),
docs(nullptr),
lastBuildDate(nullptr),
pubDate(nullptr),
copyright(nullptr),
ttl(nullptr),
items(nullptr),
item_count(0) {
std::unique_ptr<xmlDoc, void (*)(xmlDoc *)> doc(
xmlReadMemory(xml_data.c_str(), xml_data.length(), "", nullptr,
PARSE_OPTIONS),
xmlFreeDoc);
if (!doc) throw std::runtime_error("Unable to parse rss data");
prss_parse_doc(this, doc.get());
}
void free_rss_items(PRSS *data) {
int i;
if (data->items) {
for (i = 0; i < data->item_count; i++) {
#define CLEAR(a) free_and_zero(data->items[i].a);
CLEAR(title);
CLEAR(link);
CLEAR(description);
CLEAR(category);
CLEAR(pubDate);
CLEAR(guid);
#undef CLEAR
}
free_and_zero(data->items);
data->item_count = 0;
}
}
PRSS::~PRSS() {
free_rss_items(this);
free(version);
free(title);
free(link);
free(description);
free(language);
free(pubDate);
free(lastBuildDate);
free(generator);
free(docs);
free(managingEditor);
free(webMaster);
free(copyright);
free(ttl);
}
static inline void prss_null_item(PRSS_Item *i) {
if (i != nullptr) { memset(i, 0, sizeof(*i)); }
}
static inline void read_item(PRSS_Item *res, xmlNodePtr data) {
prss_null_item(res);
for (; data; data = data->next) {
xmlNodePtr child;
if (data->type != XML_ELEMENT_NODE) { continue; }
child = data->children;
if (!child) { continue; }
#define ASSIGN(a) \
if (strcasecmp((const char *)data->name, #a) == EQUAL) { \
free_and_zero(res->a); \
res->a = strdup((const char *)child->content); \
continue; \
}
ASSIGN(title);
ASSIGN(link);
ASSIGN(description);
ASSIGN(category);
ASSIGN(pubDate);
ASSIGN(guid);
#undef ASSIGN
}
}
static inline void read_element(PRSS *res, xmlNodePtr n) {
xmlNodePtr child;
if (n->type != XML_ELEMENT_NODE) { return; }
child = n->children;
if (!child) { return; }
#define ASSIGN(a) \
if (strcasecmp((const char *)n->name, #a) == EQUAL) { \
free_and_zero(res->a); \
res->a = strdup((const char *)child->content); \
return; \
}
ASSIGN(title);
ASSIGN(link);
ASSIGN(description);
ASSIGN(language);
ASSIGN(pubDate);
ASSIGN(lastBuildDate);
ASSIGN(generator);
ASSIGN(docs);
ASSIGN(managingEditor);
ASSIGN(webMaster);
ASSIGN(copyright);
ASSIGN(ttl);
#undef ASSIGN
if (!strcasecmp((const char *)n->name, "item")) {
read_item(&res->items[res->item_count++], n->children);
}
}
static inline int parse_rss_2_0(PRSS *res, xmlNodePtr root) {
xmlNodePtr channel = root->children;
xmlNodePtr n;
int items = 0;
DBGP("parsing rss 2.0 or <1 doc");
while (channel && (channel->type != XML_ELEMENT_NODE ||
strcmp((const char *)channel->name, "channel"))) {
channel = channel->next;
}
if (!channel) { return 0; }
for (n = channel->children; n; n = n->next) {
if (n->type == XML_ELEMENT_NODE && !strcmp((const char *)n->name, "item")) {
++items;
}
}
free_and_zero(res->version);
res->version = strndup("2.0", text_buffer_size.get(*state));
free_rss_items(res);
res->items = (PRSS_Item *)malloc(items * sizeof(PRSS_Item));
res->item_count = 0;
for (n = channel->children; n; n = n->next) { read_element(res, n); }
return 1;
}
static inline int parse_rss_1_0(PRSS *res, xmlNodePtr root) {
int items = 0;
xmlNodePtr n;
DBGP("parsing rss 1.0 doc");
for (n = root->children; n; n = n->next) {
if (n->type == XML_ELEMENT_NODE) {
if (!strcmp((const char *)n->name, "item")) {
++items;
} else if (!strcmp((const char *)n->name, "channel")) {
xmlNodePtr i;
for (i = n->children; i; i = i->next) { read_element(res, i); }
}
}
}
free_and_zero(res->version);
res->version = strndup("1.0", text_buffer_size.get(*state));
free_rss_items(res);
res->items = (PRSS_Item *)malloc(items * sizeof(PRSS_Item));
res->item_count = 0;
for (n = root->children; n; n = n->next) {
if (n->type == XML_ELEMENT_NODE && !strcmp((const char *)n->name, "item")) {
read_item(&res->items[res->item_count++], n->children);
}
}
return 1;
}
void prss_parse_doc(PRSS *result, xmlDocPtr doc) {
xmlNodePtr root = xmlDocGetRootElement(doc);
do {
if (root->type == XML_ELEMENT_NODE) {
if (!strcmp((const char *)root->name, "RDF")) {
// RSS 1.0 document
parse_rss_1_0(result, root);
return;
} else if (!strcmp((const char *)root->name, "rss")) {
// RSS 2.0 or <1.0 document
parse_rss_2_0(result, root);
return;
}
}
root = root->next;
} while (root);
return;
}
| 6,256
|
C++
|
.cc
| 203
| 26.719212
| 80
| 0.613123
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
22,619
|
display-x11.cc
|
brndnmtthws_conky/src/display-x11.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Please see COPYING for details
*
* Copyright (C) 2018-2021 François Revol et al.
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "config.h"
#include "display-x11.hh"
#include <X11/X.h>
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wvariadic-macros"
#include <X11/Xutil.h>
#ifdef BUILD_XFT
#include <X11/Xlib.h>
#endif /* BUILD_XFT */
#pragma GCC diagnostic pop
#ifdef BUILD_XDAMAGE
#include <X11/extensions/Xdamage.h>
#endif /* BUILD_XDAMAGE */
#include "fonts.h"
#ifdef BUILD_IMLIB2
#include "conky-imlib2.h"
#endif /* BUILD_IMLIB2 */
#if defined(BUILD_MOUSE_EVENTS) || defined(BUILD_XINPUT)
#include "mouse-events.h"
#endif /* BUILD_MOUSE_EVENTS || BUILD_XINPUT */
#ifdef BUILD_XINPUT
#include <X11/extensions/XI2.h>
#include <X11/extensions/XInput2.h>
#undef COUNT
#endif /* BUILD_XINPUT */
#include <X11/Xresource.h>
#include <cstdint>
#include <iostream>
#include <map>
#include <sstream>
#include <tuple>
#include <unordered_map>
#include <vector>
#include "colours.h"
#include "conky.h"
#include "geometry.h"
#include "gui.h"
#include "llua.h"
#include "logging.h"
#include "x11-settings.h"
#include "x11.h"
// TODO: cleanup externs (move to conky.h ?)
#ifdef OWN_WINDOW
extern int fixed_size, fixed_pos;
#endif /* OWN_WINDOW */
extern conky::vec2i text_start; /* text start position in window */
extern conky::vec2i text_offset; /* offset for start position */
extern conky::vec2i
text_size; /* initially 1 so no zero-sized window is created */
extern double current_update_time, next_update_time, last_update_time;
void update_text();
extern int need_to_update;
int get_border_total();
extern conky::range_config_setting<int> maximum_width;
extern Colour current_color;
static float screen_dpi = -1;
/* for x_fonts */
struct x_font_list {
XFontStruct *font;
XFontSet fontset;
#ifdef BUILD_XFT
XftFont *xftfont;
int font_alpha;
#endif
x_font_list()
: font(nullptr),
fontset(nullptr)
#ifdef BUILD_XFT
,
xftfont(nullptr),
font_alpha(0xffff)
#endif
{
}
};
static std::vector<x_font_list> x_fonts; /* indexed by selected_font */
#ifdef BUILD_XFT
namespace {
class xftalpha_setting : public conky::simple_config_setting<float> {
using Base = conky::simple_config_setting<float>;
protected:
void lua_setter(lua::state &l, bool init) override {
lua::stack_sentry s(l, -2);
Base::lua_setter(l, init);
if (init && out_to_x.get(*state)) {
x_fonts.resize(std::max(1, static_cast<int>(fonts.size())));
x_fonts[0].font_alpha = do_convert(l, -1).first * 0xffff;
}
++s;
}
public:
xftalpha_setting() : Base("xftalpha", 1.0, false) {}
};
xftalpha_setting xftalpha;
} // namespace
#endif /* BUILD_XFT */
static void X11_create_window();
struct _x11_stuff_s {
Region region;
#ifdef BUILD_XDAMAGE
Damage damage;
XserverRegion region2, part;
int event_base, error_base;
#endif
} x11_stuff;
void update_dpi() {
// Add XRandR support if used
// See dunst PR: https://github.com/dunst-project/dunst/pull/608
#ifdef BUILD_XFT
if (screen_dpi > 0) return;
if (use_xft.get(*state)) {
XrmDatabase db = XrmGetDatabase(display);
if (db != nullptr) {
char *xrmType;
XrmValue xrmValue;
if (XrmGetResource(db, "Xft.dpi", "Xft.dpi", &xrmType, &xrmValue)) {
screen_dpi = strtof(xrmValue.addr, NULL);
}
} else {
auto dpi = XGetDefault(display, "Xft", "dpi");
if (dpi) { screen_dpi = strtof(dpi, nullptr); }
}
}
#endif /* BUILD_XFT */
if (screen_dpi > 0) return;
screen_dpi = static_cast<float>(DisplayWidth(display, screen)) * 25.4 /
static_cast<float>(DisplayWidthMM(display, screen));
}
static void X11_create_window() {
if (!window.window) { return; }
setup_fonts();
load_fonts(utf8_mode.get(*state));
update_dpi();
update_text_area(); /* to position text/window on screen */
#ifdef OWN_WINDOW
if (own_window.get(*state)) {
if (fixed_pos == 0) {
XMoveWindow(display, window.window, window.geometry.x(),
window.geometry.y());
}
set_transparent_background(window.window);
}
#endif
create_gc();
draw_stuff();
x11_stuff.region = XCreateRegion();
#ifdef BUILD_XDAMAGE
if (XDamageQueryExtension(display, &x11_stuff.event_base,
&x11_stuff.error_base) == 0) {
NORM_ERR("Xdamage extension unavailable");
x11_stuff.damage = 0;
} else {
x11_stuff.damage =
XDamageCreate(display, window.window, XDamageReportNonEmpty);
x11_stuff.region2 = XFixesCreateRegionFromWindow(display, window.window, 0);
x11_stuff.part = XFixesCreateRegionFromWindow(display, window.window, 0);
}
#endif /* BUILD_XDAMAGE */
selected_font = 0;
update_text_area(); /* to get initial size of the window */
}
namespace conky {
namespace {
conky::display_output_x11 x11_output;
} // namespace
template <>
void register_output<output_t::X11>(display_outputs_t &outputs) {
outputs.push_back(&x11_output);
}
display_output_x11::display_output_x11() : display_output_base("x11") {
is_graphical = true;
priority = 2;
}
bool display_output_x11::detect() {
if (out_to_x.get(*state)) {
DBGP2("Display output '%s' enabled in config.", name.c_str());
return true;
}
return false;
}
bool display_output_x11::initialize() {
X11_create_window();
return true;
}
bool display_output_x11::shutdown() {
deinit_x11();
return true;
}
void process_surface_events(conky::display_output_x11 *surface,
Display *display);
bool display_output_x11::main_loop_wait(double t) {
/* wait for X event or timeout */
if (!display || !window.gc) return true;
if (XPending(display) == 0) {
fd_set fdsr;
struct timeval tv {};
int s;
// t = next_update_time - get_time();
t = std::min(std::max(t, 0.0), active_update_interval());
tv.tv_sec = static_cast<long>(t);
tv.tv_usec = static_cast<long>(t * 1000000) % 1000000;
FD_ZERO(&fdsr);
FD_SET(ConnectionNumber(display), &fdsr);
s = select(ConnectionNumber(display) + 1, &fdsr, nullptr, nullptr, &tv);
if (s == -1) {
if (errno != EINTR) { NORM_ERR("can't select(): %s", strerror(errno)); }
} else {
/* timeout */
if (s == 0) { update_text(); }
}
}
vec2i border_total = vec2i::uniform(get_border_total());
if (need_to_update != 0) {
#ifdef OWN_WINDOW
auto old_pos = window.geometry.pos();
#endif
need_to_update = 0;
selected_font = 0;
update_text_area();
#ifdef OWN_WINDOW
if (own_window.get(*state)) {
int changed = 0;
/* resize window if it isn't right size */
vec2<long> border_size = border_total * 2;
if ((fixed_size == 0) &&
(text_size + border_size != window.geometry.size())) {
window.geometry.set_size(text_size + border_size);
draw_stuff(); /* redraw everything in our newly sized window */
XResizeWindow(display, window.window, window.geometry.width(),
window.geometry.height()); /* resize window */
set_transparent_background(window.window);
#ifdef BUILD_XDBE
/* swap buffers */
xdbe_swap_buffers();
#else
if (use_xpmdb.get(*state)) {
XFreePixmap(display, window.back_buffer);
window.back_buffer = XCreatePixmap(
display, window.window, window.geometry.width(),
window.geometry.height(), DefaultDepth(display, screen));
if (window.back_buffer != None) {
window.drawable = window.back_buffer;
} else {
// this is probably reallllly bad
NORM_ERR("Failed to allocate back buffer");
}
XSetForeground(display, window.gc, 0);
XFillRectangle(display, window.drawable, window.gc, 0, 0,
window.geometry.width(), window.geometry.height());
}
#endif
changed++;
/* update lua window globals */
llua_update_window_table(rect<int>(text_start, text_size));
}
/* move window if it isn't in right position */
if ((fixed_pos == 0) && old_pos != window.geometry.pos()) {
XMoveWindow(display, window.window, window.geometry.x(),
window.geometry.y());
changed++;
}
/* update struts */
if ((changed != 0) && own_window_type.get(*state) == window_type::PANEL) {
NORM_ERR("defining struts");
set_struts(text_alignment.get(*state));
}
}
#endif
clear_text(1);
#if defined(BUILD_XDBE)
if (use_xdbe.get(*state)) {
#else
if (use_xpmdb.get(*state)) {
#endif
XRectangle rect = conky::rect<int>(text_start - border_total,
text_size + border_total * 2)
.to_xrectangle();
XUnionRectWithRegion(&rect, x11_stuff.region, x11_stuff.region);
}
}
process_surface_events(this, display);
#ifdef BUILD_XDAMAGE
if (x11_stuff.damage) {
XDamageSubtract(display, x11_stuff.damage, x11_stuff.region2, None);
XFixesSetRegion(display, x11_stuff.region2, nullptr, 0);
}
#endif /* BUILD_XDAMAGE */
/* XDBE doesn't seem to provide a way to clear the back buffer
* without interfering with the front buffer, other than passing
* XdbeBackground to XdbeSwapBuffers. That means that if we're
* using XDBE, we need to redraw the text even if it wasn't part of
* the exposed area. OTOH, if we're not going to call draw_stuff at
* all, then no swap happens and we can safely do nothing. */
if (XEmptyRegion(x11_stuff.region) == 0) {
#if defined(BUILD_XDBE)
if (use_xdbe.get(*state)) {
#else
if (use_xpmdb.get(*state)) {
#endif
XRectangle rect = conky::rect<int>(text_start - border_total,
text_size + border_total * 2)
.to_xrectangle();
XUnionRectWithRegion(&rect, x11_stuff.region, x11_stuff.region);
}
XSetRegion(display, window.gc, x11_stuff.region);
#ifdef BUILD_XFT
if (use_xft.get(*state)) {
XftDrawSetClip(window.xftdraw, x11_stuff.region);
}
#endif
draw_stuff();
XDestroyRegion(x11_stuff.region);
x11_stuff.region = XCreateRegion();
}
// handled
return true;
}
enum class x_event_handler {
XINPUT_MOTION,
MOUSE_INPUT,
PROPERTY_NOTIFY,
EXPOSE,
REPARENT,
CONFIGURE,
BORDER_CROSSING,
DAMAGE,
};
template <x_event_handler handler>
bool handle_event(conky::display_output_x11 *surface, Display *display,
XEvent &ev, bool *consumed, void **cookie) {
return false;
}
#ifdef OWN_WINDOW
template <>
bool handle_event<x_event_handler::MOUSE_INPUT>(
conky::display_output_x11 *surface, Display *display, XEvent &ev,
bool *consumed, void **cookie) {
#ifdef BUILD_XINPUT
if (ev.type == ButtonPress || ev.type == ButtonRelease ||
ev.type == MotionNotify) {
// destroy basic X11 events; and manufacture them later when trying to
// propagate XInput ones - this is required because there's no (simple) way
// of making sure the lua hook controls both when it only handles XInput
// ones.
*consumed = true;
return true;
}
if (ev.type != GenericEvent || ev.xgeneric.extension != window.xi_opcode)
return false;
if (!XGetEventData(display, &ev.xcookie)) {
// already consumed
return true;
}
xi_event_type event_type = ev.xcookie.evtype;
if (event_type == XI_HierarchyChanged) {
auto device_change = reinterpret_cast<XIHierarchyEvent *>(ev.xcookie.data);
handle_xi_device_change(device_change);
XFreeEventData(display, &ev.xcookie);
return true;
}
auto *data = xi_event_data::read_cookie(display, ev.xcookie.data);
XFreeEventData(display, &ev.xcookie);
if (data == nullptr) {
// we ate the cookie, Xi event not handled
return true;
}
*cookie = data;
Window event_window = query_x11_window_at_pos(display, data->pos_absolute);
bool same_window = query_x11_top_parent(display, event_window) ==
query_x11_top_parent(display, window.window);
bool cursor_over_conky =
same_window && window.geometry.contains(data->pos_absolute);
// XInput reports events twice on some hardware (even by 'xinput --test-xi2')
auto hash = std::make_tuple(data->serial, data->evtype, data->event);
typedef std::map<decltype(hash), Time> MouseEventDebounceMap;
static MouseEventDebounceMap debounce{};
Time now = data->time;
bool already_handled = debounce.count(hash) > 0;
debounce[hash] = now;
// clear stale entries
for (auto iter = debounce.begin(); iter != debounce.end();) {
if (data->time - iter->second > 1000) {
iter = debounce.erase(iter);
} else {
++iter;
}
}
if (already_handled) {
*consumed = true;
return true;
}
#ifdef BUILD_MOUSE_EVENTS
// query_result is not window.window in some cases.
modifier_state_t mods = x11_modifier_state(data->mods.effective);
if (data->evtype == XI_Motion) {
// TODO: Make valuator_index names configurable?
bool is_move = data->test_valuator(valuator_t::MOVE_X) ||
data->test_valuator(valuator_t::MOVE_Y);
bool is_scroll = data->test_valuator(valuator_t::SCROLL_X) ||
data->test_valuator(valuator_t::SCROLL_Y);
if (is_move) {
static bool cursor_inside = false;
// generate crossing events
if (cursor_over_conky) {
if (!cursor_inside) {
*consumed = llua_mouse_hook(mouse_crossing_event(
mouse_event_t::AREA_ENTER,
data->pos_absolute - window.geometry.pos(), data->pos_absolute));
}
cursor_inside = true;
} else if (cursor_inside) {
*consumed = llua_mouse_hook(mouse_crossing_event(
mouse_event_t::AREA_LEAVE,
data->pos_absolute - window.geometry.pos(), data->pos_absolute));
cursor_inside = false;
}
// generate movement events
if (cursor_over_conky) {
*consumed = llua_mouse_hook(
mouse_move_event(data->pos, data->pos_absolute, mods));
}
}
if (is_scroll && cursor_over_conky) {
scroll_direction_t scroll_direction;
auto vertical = data->valuator_relative_value(valuator_t::SCROLL_Y);
double vertical_value = vertical.value_or(0.0);
if (vertical_value != 0.0) {
scroll_direction = vertical_value < 0.0 ? scroll_direction_t::UP
: scroll_direction_t::DOWN;
} else {
auto horizontal = data->valuator_relative_value(valuator_t::SCROLL_X);
double horizontal_value = horizontal.value_or(0.0);
if (horizontal_value != 0.0) {
scroll_direction = horizontal_value < 0.0 ? scroll_direction_t::LEFT
: scroll_direction_t::RIGHT;
}
}
if (scroll_direction != scroll_direction_t::UNKNOWN) {
*consumed = llua_mouse_hook(mouse_scroll_event(
data->pos, data->pos_absolute, scroll_direction, mods));
}
}
} else if (cursor_over_conky && (data->evtype == XI_ButtonPress ||
data->evtype == XI_ButtonRelease)) {
if (data->detail >= 4 && data->detail <= 7) {
// Handled via motion event valuators, ignoring "backward compatibility"
// ones.
return true;
}
mouse_event_t type = mouse_event_t::PRESS;
if (data->evtype == XI_ButtonRelease) { type = mouse_event_t::RELEASE; }
mouse_button_t button = x11_mouse_button_code(data->detail);
*consumed = llua_mouse_hook(
mouse_button_event(type, data->pos, data->pos_absolute, button, mods));
}
#endif /* BUILD_MOUSE_EVENTS */
#else /* BUILD_XINPUT */
if (ev.type != ButtonPress && ev.type != ButtonRelease &&
ev.type != MotionNotify)
return false;
if (ev.xany.window != window.window) return true; // Skip other windows
#ifdef BUILD_MOUSE_EVENTS
switch (ev.type) {
case ButtonPress: {
modifier_state_t mods = x11_modifier_state(ev.xbutton.state);
if (ev.xbutton.button >= 4 &&
ev.xbutton.button <= 7) { // scroll "buttons"
scroll_direction_t direction = x11_scroll_direction(ev.xbutton.button);
*consumed = llua_mouse_hook(mouse_scroll_event(
vec2i(ev.xbutton.x, ev.xbutton.y),
vec2i(ev.xbutton.x_root, ev.xbutton.y_root), direction, mods));
} else {
mouse_button_t button = x11_mouse_button_code(ev.xbutton.button);
*consumed = llua_mouse_hook(mouse_button_event(
mouse_event_t::PRESS, vec2i(ev.xbutton.x, ev.xbutton.y),
vec2i(ev.xbutton.x_root, ev.xbutton.y_root), button, mods));
}
break;
}
case ButtonRelease: {
/* don't report scroll release events */
if (ev.xbutton.button >= 4 && ev.xbutton.button <= 7) return true;
modifier_state_t mods = x11_modifier_state(ev.xbutton.state);
mouse_button_t button = x11_mouse_button_code(ev.xbutton.button);
*consumed = llua_mouse_hook(mouse_button_event(
mouse_event_t::RELEASE, vec2i(ev.xbutton.x, ev.xbutton.y),
vec2i(ev.xbutton.x_root, ev.xbutton.y_root), button, mods));
break;
}
case MotionNotify: {
modifier_state_t mods = x11_modifier_state(ev.xmotion.state);
*consumed = llua_mouse_hook(
mouse_move_event(vec2i(ev.xmotion.x, ev.xmotion.y),
vec2i(ev.xmotion.x_root, ev.xmotion.y_root), mods));
break;
}
}
#endif /* BUILD_MOUSE_EVENTS */
#endif /* BUILD_XINPUT */
#ifndef BUILD_MOUSE_EVENTS
// always propagate mouse input if not handling mouse events
*consumed = false;
#endif /* BUILD_MOUSE_EVENTS */
if (!own_window.get(*state)) return true;
switch (own_window_type.get(*state)) {
case window_type::NORMAL:
case window_type::UTILITY:
// decorated normal windows always consume events
if (!TEST_HINT(own_window_hints.get(*state), window_hints::UNDECORATED)) {
*consumed = true;
}
break;
case window_type::DESKTOP:
// assume conky is always on bottom; nothing to propagate events to
*consumed = true;
default:
break;
}
return true;
}
template <>
bool handle_event<x_event_handler::REPARENT>(conky::display_output_x11 *surface,
Display *display, XEvent &ev,
bool *consumed, void **cookie) {
if (ev.type != ReparentNotify) return false;
if (own_window.get(*state)) { set_transparent_background(window.window); }
return true;
}
template <>
bool handle_event<x_event_handler::CONFIGURE>(
conky::display_output_x11 *surface, Display *display, XEvent &ev,
bool *consumed, void **cookie) {
if (ev.type != ConfigureNotify) return false;
if (own_window.get(*state)) {
auto configure_size = vec2i(ev.xconfigure.width, ev.xconfigure.height);
/* if window size isn't what's expected, set fixed size */
if (configure_size != window.geometry.size()) {
if (window.geometry.size().surface() != 0) { fixed_size = 1; }
/* clear old stuff before screwing up
* size and pos */
surface->clear_text(1);
{
XWindowAttributes attrs;
if (XGetWindowAttributes(display, window.window, &attrs) != 0) {
window.geometry.set_size(attrs.width, attrs.height);
}
}
auto border_total = vec2i::uniform(get_border_total() * 2);
text_size = window.geometry.size() - border_total;
// don't apply dpi scaling to max pixel size
int mw = dpi_scale(maximum_width.get(*state));
if (mw > 0) { text_size.set_x(std::min(mw, text_size.x())); }
}
/* if position isn't what expected, set fixed pos
* total_updates avoids setting fixed_pos when window
* is set to weird locations when started */
/* // this is broken
if (total_updates >= 2 && !fixed_pos
&& (window.geometry.x != ev.xconfigure.x
|| window.geometry.y != ev.xconfigure.y)
&& (ev.xconfigure.x != 0
|| ev.xconfigure.y != 0)) {
fixed_pos = 1;
} */
}
return true;
}
#ifdef BUILD_MOUSE_EVENTS
template <>
bool handle_event<x_event_handler::BORDER_CROSSING>(
conky::display_output_x11 *surface, Display *display, XEvent &ev,
bool *consumed, void **cookie) {
if (ev.type != EnterNotify && ev.type != LeaveNotify) return false;
if (window.xi_opcode != 0) return true; // handled by mouse_input already
auto crossing_pos = vec2i(ev.xcrossing.x_root, ev.xcrossing.y_root);
bool over_conky = window.geometry.contains(crossing_pos);
if ((!over_conky && ev.xcrossing.type == LeaveNotify) ||
(over_conky && ev.xcrossing.type == EnterNotify)) {
llua_mouse_hook(mouse_crossing_event(
ev.xcrossing.type == EnterNotify ? mouse_event_t::AREA_ENTER
: mouse_event_t::AREA_LEAVE,
vec2i(ev.xcrossing.x, ev.xcrossing.y),
vec2i(ev.xcrossing.x_root, ev.xcrossing.y_root)));
}
return true;
}
#endif /* BUILD_MOUSE_EVENTS */
#endif /* OWN_WINDOW */
template <>
bool handle_event<x_event_handler::PROPERTY_NOTIFY>(
conky::display_output_x11 *surface, Display *display, XEvent &ev,
bool *consumed, void **cookie) {
if (ev.type != PropertyNotify) return false;
if (ev.xproperty.state == PropertyNewValue) {
get_x11_desktop_info(ev.xproperty.display, ev.xproperty.atom);
}
if (ev.xproperty.atom == 0) return false;
if (ev.xproperty.atom == XA_RESOURCE_MANAGER) {
update_x11_resource_db();
update_x11_workarea();
screen_dpi = -1;
update_dpi();
return true;
}
if (!have_argb_visual) {
Atom _XROOTPMAP_ID = XInternAtom(display, "_XROOTPMAP_ID", True);
Atom _XROOTMAP_ID = XInternAtom(display, "_XROOTMAP_ID", True);
if (ev.xproperty.atom == _XROOTPMAP_ID ||
ev.xproperty.atom == _XROOTMAP_ID) {
if (forced_redraw.get(*state)) {
draw_stuff();
next_update_time = get_time();
need_to_update = 1;
}
return true;
}
}
return false;
}
template <>
bool handle_event<x_event_handler::EXPOSE>(conky::display_output_x11 *surface,
Display *display, XEvent &ev,
bool *consumed, void **cookie) {
if (ev.type != Expose) return false;
XRectangle r{
.x = static_cast<short>(ev.xexpose.x),
.y = static_cast<short>(ev.xexpose.y),
.width = static_cast<unsigned short>(ev.xexpose.width),
.height = static_cast<unsigned short>(ev.xexpose.height),
};
XUnionRectWithRegion(&r, x11_stuff.region, x11_stuff.region);
XSync(display, False);
return true;
}
#ifdef BUILD_XDAMAGE
template <>
bool handle_event<x_event_handler::DAMAGE>(conky::display_output_x11 *surface,
Display *display, XEvent &ev,
bool *consumed, void **cookie) {
if (ev.type != x11_stuff.event_base + XDamageNotify) return false;
auto *dev = reinterpret_cast<XDamageNotifyEvent *>(&ev);
XFixesSetRegion(display, x11_stuff.part, &dev->area, 1);
XFixesUnionRegion(display, x11_stuff.region2, x11_stuff.region2,
x11_stuff.part);
return true;
}
#endif /* BUILD_XDAMAGE */
/// Handles all events conky can receive.
///
/// @return true if event should move input focus to conky
bool process_event(conky::display_output_x11 *surface, Display *display,
XEvent ev, bool *consumed, void **cookie) {
#define HANDLE_EV(event) \
if (handle_event<x_event_handler::event>(surface, display, ev, consumed, \
cookie)) { \
return true; \
}
HANDLE_EV(XINPUT_MOTION)
HANDLE_EV(MOUSE_INPUT)
HANDLE_EV(PROPERTY_NOTIFY)
// only accept remaining events if they're sent to Conky.
if (ev.xany.window != window.window) return false;
HANDLE_EV(EXPOSE)
HANDLE_EV(REPARENT)
HANDLE_EV(CONFIGURE)
HANDLE_EV(BORDER_CROSSING)
HANDLE_EV(DAMAGE)
#undef HANDLE_EV
// event not handled
return false;
}
void process_surface_events(conky::display_output_x11 *surface,
Display *display) {
int pending = XPending(display);
if (pending == 0) return;
DBGP2("Processing %d X11 events...", pending);
/* handle X events */
while (XPending(display) != 0) {
XEvent ev;
XNextEvent(display, &ev);
/*
indicates whether processed event was consumed; true by default so we
don't propagate handled events unless they explicitly state they haven't
been consumed.
*/
bool consumed = true;
void *cookie = nullptr;
bool handled = process_event(surface, display, ev, &consumed, &cookie);
if (!consumed) { propagate_x11_event(ev, cookie); }
if (cookie != nullptr) { free(cookie); }
}
DBGP2("Done processing %d events.", pending);
}
void display_output_x11::sigterm_cleanup() {
XDestroyRegion(x11_stuff.region);
x11_stuff.region = nullptr;
#ifdef BUILD_XDAMAGE
if (x11_stuff.damage) {
XDamageDestroy(display, x11_stuff.damage);
XFixesDestroyRegion(display, x11_stuff.region2);
XFixesDestroyRegion(display, x11_stuff.part);
}
#endif /* BUILD_XDAMAGE */
}
void display_output_x11::cleanup() {
if (window_created == 1) {
int border_total = get_border_total();
XClearArea(display, window.window, text_start.x() - border_total,
text_start.y() - border_total, text_size.x() + 2 * border_total,
text_size.y() + 2 * border_total, 0);
}
destroy_window();
free_fonts(utf8_mode.get(*state));
if (x11_stuff.region != nullptr) {
XDestroyRegion(x11_stuff.region);
x11_stuff.region = nullptr;
}
}
void display_output_x11::set_foreground_color(Colour c) {
current_color = c;
#ifdef BUILD_ARGB
if (have_argb_visual) {
current_color.alpha = own_window_argb_value.get(*state);
}
#endif /* BUILD_ARGB */
XSetForeground(display, window.gc,
current_color.to_x11_color(display, screen, have_argb_visual));
}
int display_output_x11::calc_text_width(const char *s) {
std::size_t slen = strlen(s);
#ifdef BUILD_XFT
if (use_xft.get(*state)) {
XGlyphInfo gi;
if (utf8_mode.get(*state)) {
XftTextExtentsUtf8(display, x_fonts[selected_font].xftfont,
reinterpret_cast<const FcChar8 *>(s), slen, &gi);
} else {
XftTextExtents8(display, x_fonts[selected_font].xftfont,
reinterpret_cast<const FcChar8 *>(s), slen, &gi);
}
return gi.xOff;
}
#endif /* BUILD_XFT */
return XTextWidth(x_fonts[selected_font].font, s, slen);
}
void display_output_x11::draw_string_at(int x, int y, const char *s, int w) {
#ifdef BUILD_XFT
if (use_xft.get(*state)) {
XColor c{};
XftColor c2{};
c.pixel = current_color.to_x11_color(display, screen, have_argb_visual);
// query color on custom colormap
XQueryColor(display, window.colourmap, &c);
c2.pixel = c.pixel;
c2.color.red = c.red;
c2.color.green = c.green;
c2.color.blue = c.blue;
c2.color.alpha = x_fonts[selected_font].font_alpha;
if (utf8_mode.get(*state)) {
XftDrawStringUtf8(window.xftdraw, &c2, x_fonts[selected_font].xftfont, x,
y, reinterpret_cast<const XftChar8 *>(s), w);
} else {
XftDrawString8(window.xftdraw, &c2, x_fonts[selected_font].xftfont, x, y,
reinterpret_cast<const XftChar8 *>(s), w);
}
} else
#endif
{
if (utf8_mode.get(*state)) {
Xutf8DrawString(display, window.drawable, x_fonts[selected_font].fontset,
window.gc, x, y, s, w);
} else {
XDrawString(display, window.drawable, window.gc, x, y, s, w);
}
}
}
void display_output_x11::set_line_style(int w, bool solid) {
XSetLineAttributes(display, window.gc, w, solid ? LineSolid : LineOnOffDash,
CapButt, JoinMiter);
}
void display_output_x11::set_dashes(char *s) {
XSetDashes(display, window.gc, 0, s, 2);
}
void display_output_x11::draw_line(int x1, int y1, int x2, int y2) {
XDrawLine(display, window.drawable, window.gc, x1, y1, x2, y2);
}
void display_output_x11::draw_rect(int x, int y, int w, int h) {
XDrawRectangle(display, window.drawable, window.gc, x, y, w, h);
}
void display_output_x11::fill_rect(int x, int y, int w, int h) {
XFillRectangle(display, window.drawable, window.gc, x, y, w, h);
}
void display_output_x11::draw_arc(int x, int y, int w, int h, int a1, int a2) {
XDrawArc(display, window.drawable, window.gc, x, y, w, h, a1, a2);
}
void display_output_x11::move_win(int x, int y) {
#ifdef OWN_WINDOW
window.geometry.set_pos(x, y);
XMoveWindow(display, window.window, x, y);
#endif /* OWN_WINDOW */
}
const float PIXELS_PER_INCH = 96.0;
float display_output_x11::get_dpi_scale() {
if (screen_dpi > 0) {
return static_cast<float>(screen_dpi) / PIXELS_PER_INCH;
}
return 1.0;
}
void display_output_x11::end_draw_stuff() {
#if defined(BUILD_XDBE)
xdbe_swap_buffers();
#else
xpmdb_swap_buffers();
#endif
}
void display_output_x11::clear_text(int exposures) {
#ifdef BUILD_XDBE
if (use_xdbe.get(*state)) {
/* The swap action is XdbeBackground, which clears */
return;
}
#else
if (use_xpmdb.get(*state)) {
return;
} else
#endif
if ((display != nullptr) &&
(window.window != 0u)) { // make sure these are !null
/* there is some extra space for borders and outlines */
int border_total = get_border_total();
XClearArea(display, window.window, text_start.x() - border_total,
text_start.y() - border_total, text_size.x() + 2 * border_total,
text_size.y() + 2 * border_total, exposures != 0 ? True : 0);
}
}
#ifdef BUILD_XFT
int display_output_x11::font_height(unsigned int f) {
assert(f < x_fonts.size());
if (use_xft.get(*state)) {
return x_fonts[f].xftfont->ascent + x_fonts[f].xftfont->descent;
} else {
return x_fonts[f].font->max_bounds.ascent +
x_fonts[f].font->max_bounds.descent;
}
}
int display_output_x11::font_ascent(unsigned int f) {
assert(f < x_fonts.size());
if (use_xft.get(*state)) {
return x_fonts[f].xftfont->ascent;
} else {
return x_fonts[f].font->max_bounds.ascent;
}
}
int display_output_x11::font_descent(unsigned int f) {
assert(f < x_fonts.size());
if (use_xft.get(*state)) {
return x_fonts[f].xftfont->descent;
} else {
return x_fonts[f].font->max_bounds.descent;
}
}
#else
int display_output_x11::font_height(unsigned int f) {
assert(f < x_fonts.size());
return x_fonts[f].font->max_bounds.ascent +
x_fonts[f].font->max_bounds.descent;
}
int display_output_x11::font_ascent(unsigned int f) {
assert(f < x_fonts.size());
return x_fonts[f].font->max_bounds.ascent;
}
int display_output_x11::font_descent(unsigned int f) {
assert(f < x_fonts.size());
return x_fonts[f].font->max_bounds.descent;
}
#endif
void display_output_x11::setup_fonts(void) {
#ifdef BUILD_XFT
if (use_xft.get(*state)) {
if (window.xftdraw != nullptr) {
XftDrawDestroy(window.xftdraw);
window.xftdraw = nullptr;
}
window.xftdraw = XftDrawCreate(display, window.drawable, window.visual,
window.colourmap);
}
#endif /* BUILD_XFT */
}
void display_output_x11::set_font(unsigned int f) {
if (f >= x_fonts.size()) {
DBGP("%d >= x_fonts.size()", f);
return;
}
#ifdef BUILD_XFT
if (use_xft.get(*state)) { return; }
#endif /* BUILD_XFT */
if (x_fonts.size() > f && x_fonts[f].font != nullptr &&
window.gc != nullptr) {
XSetFont(display, window.gc, x_fonts[f].font->fid);
}
}
void display_output_x11::free_fonts(bool utf8) {
for (auto &font : x_fonts) {
#ifdef BUILD_XFT
if (use_xft.get(*state)) {
/* Close each font if it has been initialized */
if (font.xftfont) { XftFontClose(display, font.xftfont); }
} else
#endif /* BUILD_XFT */
{
if (font.font != nullptr) { XFreeFont(display, font.font); }
if (utf8 && (font.fontset != nullptr)) {
XFreeFontSet(display, font.fontset);
}
}
}
x_fonts.clear();
#ifdef BUILD_XFT
if (window.xftdraw != nullptr) {
XftDrawDestroy(window.xftdraw);
window.xftdraw = nullptr;
}
#endif /* BUILD_XFT */
}
void display_output_x11::load_fonts(bool utf8) {
x_fonts.resize(fonts.size());
for (unsigned int i = 0; i < fonts.size(); i++) {
auto &font = fonts[i];
auto &xfont = x_fonts[i];
#ifdef BUILD_XFT
/* load Xft font */
if (use_xft.get(*state)) {
if (xfont.xftfont == nullptr) {
xfont.xftfont = XftFontOpenName(display, screen, font.name.c_str());
}
if (xfont.xftfont != nullptr) { continue; }
NORM_ERR("can't load Xft font '%s'", font.name.c_str());
if ((xfont.xftfont = XftFontOpenName(display, screen, "courier-12")) !=
nullptr) {
continue;
}
CRIT_ERR("can't load Xft font '%s'", "courier-12");
continue;
}
#endif
if (utf8 && xfont.fontset == nullptr) {
char **missing;
int missingnum;
char *missingdrawn;
xfont.fontset = XCreateFontSet(display, font.name.c_str(), &missing,
&missingnum, &missingdrawn);
XFreeStringList(missing);
if (xfont.fontset == nullptr) {
NORM_ERR("can't load font '%s'", font.name.c_str());
xfont.fontset = XCreateFontSet(display, "fixed", &missing, &missingnum,
&missingdrawn);
if (xfont.fontset == nullptr) {
CRIT_ERR("can't load font '%s'", "fixed");
}
}
}
/* load normal font */
if ((xfont.font == nullptr) &&
(xfont.font = XLoadQueryFont(display, font.name.c_str())) == nullptr) {
NORM_ERR("can't load font '%s'", font.name.c_str());
if ((xfont.font = XLoadQueryFont(display, "fixed")) == nullptr) {
CRIT_ERR("can't load font '%s'", "fixed");
}
}
}
}
} // namespace conky
| 35,142
|
C++
|
.cc
| 997
| 29.822467
| 80
| 0.639675
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,620
|
netbsd.cc
|
brndnmtthws_conky/src/netbsd.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "netbsd.h"
#include "net_stat.h"
static kvm_t *kd = nullptr;
int kd_init = 0, nkd_init = 0;
u_int32_t sensvalue;
char errbuf[_POSIX2_LINE_MAX];
static int init_kvm(void) {
if (kd_init) { return 0; }
kd = kvm_openfiles(nullptr, NULL, NULL, KVM_NO_FILES, errbuf);
if (kd == nullptr) {
warnx("cannot kvm_openfiles: %s", errbuf);
return -1;
}
kd_init = 1;
return 0;
}
static int swapmode(int *retavail, int *retfree) {
int n;
struct swapent *sep;
*retavail = 0;
*retfree = 0;
n = swapctl(SWAP_NSWAP, 0, 0);
if (n < 1) {
warn("could not get swap information");
return 0;
}
sep = (struct swapent *)malloc(n * (sizeof(*sep)));
if (sep == nullptr) {
warn("memory allocation failed");
return 0;
}
if (swapctl(SWAP_STATS, (void *)sep, n) < n) {
warn("could not get swap stats");
return 0;
}
for (; n > 0; n--) {
*retavail += (int)dbtob(sep[n - 1].se_nblks);
*retfree += (int)dbtob(sep[n - 1].se_nblks - sep[n - 1].se_inuse);
}
*retavail = (int)(*retavail / 1024);
*retfree = (int)(*retfree / 1024);
return 1;
}
void prepare_update() {}
void update_uptime() {
int mib[2] = {CTL_KERN, KERN_BOOTTIME};
struct timeval boottime;
time_t now;
int size = sizeof(boottime);
if ((sysctl(mib, 2, &boottime, &size, nullptr, 0) != -1) &&
(boottime.tv_sec != 0)) {
time(&now);
info.uptime = now - boottime.tv_sec;
} else {
warn("could not get uptime");
info.uptime = 0;
}
}
int check_mount(struct text_object *obj) {
/* stub */
(void)obj;
return 0;
}
void update_meminfo() {
int mib[] = {CTL_VM, VM_UVMEXP2};
int total_pages, inactive_pages, free_pages;
int swap_avail, swap_free;
const int pagesize = getpagesize();
struct uvmexp_sysctl uvmexp;
size_t size = sizeof(uvmexp);
if (sysctl(mib, 2, &uvmexp, &size, nullptr, 0) < 0) {
warn("could not get memory info");
return;
}
total_pages = uvmexp.npages;
free_pages = uvmexp.free;
inactive_pages = uvmexp.inactive;
info.memmax = (total_pages * pagesize) >> 10;
info.mem = ((total_pages - free_pages - inactive_pages) * pagesize) >> 10;
info.memwithbuffers = info.mem;
info.memeasyfree = info.memfree = info.memmax - info.mem;
info.legacymem = info.mem;
if (swapmode(&swap_avail, &swap_free) >= 0) {
info.swapmax = swap_avail;
info.swap = (swap_avail - swap_free);
info.swapfree = swap_free;
}
}
void update_net_stats() {
int i;
double delta;
struct ifnet ifnet;
struct ifnet_head ifhead; /* interfaces are in a tail queue */
u_long ifnetaddr;
static struct nlist namelist[] = {{"_ifnet"}, {nullptr}};
static kvm_t *nkd;
if (!nkd_init) {
nkd = kvm_openfiles(nullptr, NULL, NULL, O_RDONLY, errbuf);
if (nkd == nullptr) {
warnx("cannot kvm_openfiles: %s", errbuf);
warnx("maybe you need to setgid kmem this program?");
return;
} else if (kvm_nlist(nkd, namelist) != 0) {
warn("cannot kvm_nlist");
return;
} else {
nkd_init = 1;
}
}
if (kvm_read(nkd, (u_long)namelist[0].n_value, (void *)&ifhead,
sizeof(ifhead)) < 0) {
warn("cannot kvm_read");
return;
}
/* get delta */
delta = current_update_time - last_update_time;
if (delta <= 0.0001) { return; }
for (i = 0, ifnetaddr = (u_long)ifhead.tqh_first;
ifnet.if_list.tqe_next && i < 16;
ifnetaddr = (u_long)ifnet.if_list.tqe_next, i++) {
struct net_stat *ns;
long long last_recv, last_trans;
kvm_read(nkd, (u_long)ifnetaddr, (void *)&ifnet, sizeof(ifnet));
ns = get_net_stat(ifnet.if_xname, nullptr, NULL);
ns->up = 1;
last_recv = ns->recv;
last_trans = ns->trans;
if (ifnet.if_ibytes < ns->last_read_recv) {
ns->recv +=
((long long)4294967295U - ns->last_read_recv) + ifnet.if_ibytes;
} else {
ns->recv += (ifnet.if_ibytes - ns->last_read_recv);
}
ns->last_read_recv = ifnet.if_ibytes;
if (ifnet.if_obytes < ns->last_read_trans) {
ns->trans +=
((long long)4294967295U - ns->last_read_trans) + ifnet.if_obytes;
} else {
ns->trans += (ifnet.if_obytes - ns->last_read_trans);
}
ns->last_read_trans = ifnet.if_obytes;
ns->recv += (ifnet.if_ibytes - ns->last_read_recv);
ns->last_read_recv = ifnet.if_ibytes;
ns->trans += (ifnet.if_obytes - ns->last_read_trans);
ns->last_read_trans = ifnet.if_obytes;
ns->recv_speed = (ns->recv - last_recv) / delta;
ns->trans_speed = (ns->trans - last_trans) / delta;
}
}
int update_total_processes() {
/* It's easier to use kvm here than sysctl */
int n_processes;
info.procs = 0;
if (init_kvm() < 0) {
return;
} else {
kvm_getproc2(kd, KERN_PROC_ALL, 0, sizeof(struct kinfo_proc2),
&n_processes);
}
info.procs = n_processes;
return 0;
}
void update_running_processes() {
struct kinfo_proc2 *p;
int n_processes;
int i, cnt = 0;
info.run_procs = 0;
if (init_kvm() < 0) {
return;
} else {
p = kvm_getproc2(kd, KERN_PROC_ALL, 0, sizeof(struct kinfo_proc2),
&n_processes);
for (i = 0; i < n_processes; i++) {
if (p[i].p_stat == LSRUN || p[i].p_stat == LSIDL ||
p[i].p_stat == LSONPROC) {
cnt++;
}
}
}
info.run_procs = cnt;
}
struct cpu_load_struct {
unsigned long load[5];
};
struct cpu_load_struct fresh = {{0, 0, 0, 0, 0}};
long cpu_used, oldtotal, oldused;
void update_cpu_usage() {
long used, total;
static u_int64_t cp_time[CPUSTATES];
size_t len = sizeof(cp_time);
info.cpu_usage = 0;
if (sysctlbyname("kern.cp_time", &cp_time, &len, nullptr, 0) < 0) {
warn("cannot get kern.cp_time");
}
fresh.load[0] = cp_time[CP_USER];
fresh.load[1] = cp_time[CP_NICE];
fresh.load[2] = cp_time[CP_SYS];
fresh.load[3] = cp_time[CP_IDLE];
fresh.load[4] = cp_time[CP_IDLE];
used = fresh.load[0] + fresh.load[1] + fresh.load[2];
total = fresh.load[0] + fresh.load[1] + fresh.load[2] + fresh.load[3];
if ((total - oldtotal) != 0) {
info.cpu_usage = ((double)(used - oldused)) / (double)(total - oldtotal);
} else {
info.cpu_usage = 0;
}
oldused = used;
oldtotal = total;
}
void free_cpu(struct text_object *) { /* no-op */
}
void update_load_average() {
double v[3];
getloadavg(v, 3);
info.loadavg[0] = (float)v[0];
info.loadavg[1] = (float)v[1];
info.loadavg[2] = (float)v[2];
}
double get_acpi_temperature(int fd) { return -1; }
void get_battery_stuff(char *buf, unsigned int n, const char *bat, int item) {}
int open_acpi_temperature(const char *name) { return -1; }
void get_acpi_ac_adapter(char *p_client_buffer, size_t client_buffer_size,
const char *adapter) {
(void)adapter; // only linux uses this
if (!p_client_buffer || client_buffer_size <= 0) { return; }
/* not implemented */
memset(p_client_buffer, 0, client_buffer_size);
}
/* char *get_acpi_fan() */
void get_acpi_fan(char *p_client_buffer, size_t client_buffer_size) {
if (!p_client_buffer || client_buffer_size <= 0) { return; }
/* not implemented */
memset(p_client_buffer, 0, client_buffer_size);
}
int get_entropy_avail(unsigned int *val) { return 1; }
int get_entropy_poolsize(unsigned int *val) { return 1; }
| 8,358
|
C++
|
.cc
| 264
| 27.80303
| 79
| 0.636228
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
22,621
|
nvidia.cc
|
brndnmtthws_conky/src/nvidia.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2008 Markus Meissner
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
/*
*
* Author:
* Fonic <fonic.maxxim@live.com>
*
* Things to do:
* - Move decoding of GPU/MEM freqs to print_nvidia_value() using QUERY_SPECIAL
* so that all quirks are located there
* - Implement nvs->print_type to allow control over how the value is printed
* (int, float, temperature...)
*
* Showcase (conky.conf):
* --==| NVIDIA | ==--
* GPU ${nvidia gpufreq [target_id]}MHz (${nvidia gpufreqmin
* [target_id]}-${nvidia gpufreqmax [target_id]}MHz) MEM ${nvidia memfreq
* [target_id]}MHz (${nvidia memfreqmin [target_id]}-${nvidia memfreqmax
* [target_id]}MHz) MTR ${nvidia mtrfreq [target_id]}MHz (${nvidia mtrfreqmin
* [target_id]}-${nvidia mtrfreqmax [target_id]}MHz) PERF Level ${nvidia
* perflevel [target_id]} (${nvidia perflevelmin [target_id]}-${nvidia
* perflevelmax [target_id]}), Mode: ${nvidia perfmode [target_id]} VRAM
* ${nvidia memutil [target_id]}% (${nvidia memused [target_id]}MB/${nvidia
* memtotal [target_id]}MB) LOAD GPU ${nvidia gpuutil [target_id]}%, RAM
* ${nvidia membwutil [target_id]}%, VIDEO ${nvidia videoutil [target_id]}%,
* PCIe ${nvidia pcieutil [target_id]}% TEMP GPU ${nvidia gputemp
* [target_id]}°C (${nvidia gputempthreshold [target_id]}°C max.), SYS ${nvidia
* ambienttemp [target_id]}°C FAN ${nvidia fanspeed [target_id]} RPM
* (${nvidia fanlevel [target_id]}%)
*
* Miscellaneous:
* OPENGL ${nvidia imagequality [target_id]}
* GPU ${nvidia modelname [target_id]}
* DRIVER ${nvidia driverversion [target_id]}
*
* --==| NVIDIA Bars |==--
* LOAD ${nvidiabar [height][,width] gpuutil [target_id]}
* VRAM ${nvidiabar [height][,width] memutil [target_id]}
* RAM ${nvidiabar [height][,width] membwutil [target_id]}
* VIDEO ${nvidiabar [height][,width] videoutil [target_id]}
* PCIe ${nvidiabar [height][,width] pcieutil [target_id]}
* Fan ${nvidiabar [height][,width] fanlevel [target_id]}
* TEMP ${nvidiabar [height][,width] gputemp [target_id]}
*
* --==| NVIDIA Gauge |==--
* LOAD ${nvidiagauge [height][,width] gpuutil [target_id]}
* VRAM ${nvidiagauge [height][,width] memutil [target_id]}
* RAM ${nvidiagauge [height][,width] membwutil [target_id]}
* VIDEO ${nvidiagauge [height][,width] videoutil [target_id]}
* PCIe ${nvidiagauge [height][,width] pcieutil [target_id]}
* Fan ${nvidiagauge [height][,width] fanlevel [target_id]}
* TEMP ${nvidiagauge [height][,width] gputemp [target_id]}
*
* --==| NVIDIA Graph |==-- (target_id is not optional in this case)
* LOAD ${nvidiagraph gpuutil [height][,width] [gradient color 1] [gradient
* color 2] [scale] [-t] [-l] target_id} VRAM ${nvidiagraph memutil
* [height][,width] [gradient color 1] [gradient color 2] [scale] [-t] [-l]
* target_id} RAM ${nvidiagraph membwutil [height][,width] [gradient color 1]
* [gradient color 2] [scale] [-t] [-l] target_id} VIDEO ${nvidiagraph videoutil
* [height][,width] [gradient color 1] [gradient color 2] [scale] [-t] [-l]
* target_id} PCIe ${nvidiagraph pcieutil [height][,width] [gradient color 1]
* [gradient color 2] [scale] [-t] [-l] target_id} Fan ${nvidiagraph fanlevel
* [height][,width] [gradient color 1] [gradient color 2] [scale] [-t] [-l]
* target_id} TEMP ${nvidiagraph gputemp [height][,width] [gradient color 1]
* [gradient color 2] [scale] [-t] [-l] target_id}
*/
#include "nvidia.h"
#include <X11/Xlib.h>
#include "NVCtrl/NVCtrl.h"
#include "NVCtrl/NVCtrlLib.h"
#include "conky.h"
#include "logging.h"
#include "temphelper.h"
// Current implementation uses X11 specific system utils
#include "x11.h"
#include <memory>
// Separators for nvidia string parsing
// (sample: "perf=0, nvclock=324, nvclockmin=324, nvclockmax=324 ; perf=1,
// nvclock=549, nvclockmin=549, nvclockmax=549")
#define NV_KVPAIR_SEPARATORS ", ;"
#define NV_KEYVAL_SEPARATORS "="
// Module arguments
const char *translate_module_argument[] = {
"temp", // Temperatures
"gputemp", "threshold", "gputempthreshold", "ambient", "ambienttemp",
"gpufreq", // GPU frequency
"gpufreqcur", "gpufreqmin", "gpufreqmax",
"memfreq", // Memory frequency
"memfreqcur", "memfreqmin", "memfreqmax",
"mtrfreq", // Memory transfer rate frequency
"mtrfreqcur", "mtrfreqmin", "mtrfreqmax",
"perflevel", // Performance levels
"perflevelcur", "perflevelmin", "perflevelmax", "perfmode",
"gpuutil", // Load/utilization
"membwutil", // NOTE: this is the memory _bandwidth_ utilization, not the
// percentage of used/available memory!
"videoutil", "pcieutil",
"mem", // RAM statistics
"memused", "memfree", "memavail", "memmax", "memtotal", "memutil",
"memperc",
"fanspeed", // Fan/cooler
"fanlevel",
"imagequality", // Miscellaneous
"modelname", "driverversion"};
// Enum for module arguments
typedef enum _ARG_ID {
ARG_TEMP,
ARG_GPU_TEMP,
ARG_THRESHOLD,
ARG_GPU_TEMP_THRESHOLD,
ARG_AMBIENT,
ARG_AMBIENT_TEMP,
ARG_GPU_FREQ,
ARG_GPU_FREQ_CUR,
ARG_GPU_FREQ_MIN,
ARG_GPU_FREQ_MAX,
ARG_MEM_FREQ,
ARG_MEM_FREQ_CUR,
ARG_MEM_FREQ_MIN,
ARG_MEM_FREQ_MAX,
ARG_MTR_FREQ,
ARG_MTR_FREQ_CUR,
ARG_MTR_FREQ_MIN,
ARG_MTR_FREQ_MAX,
ARG_PERF_LEVEL,
ARG_PERF_LEVEL_CUR,
ARG_PERF_LEVEL_MIN,
ARG_PERF_LEVEL_MAX,
ARG_PERF_MODE,
ARG_GPU_UTIL,
ARG_MEM_BW_UTIL,
ARG_VIDEO_UTIL,
ARG_PCIE_UTIL,
ARG_MEM,
ARG_MEM_USED,
ARG_MEM_FREE,
ARG_MEM_AVAIL,
ARG_MEM_MAX,
ARG_MEM_TOTAL,
ARG_MEM_UTIL,
ARG_MEM_PERC,
ARG_FAN_SPEED,
ARG_FAN_LEVEL,
ARG_IMAGEQUALITY,
ARG_MODEL_NAME,
ARG_DRIVER_VERSION,
ARG_UNKNOWN
} ARG_ID;
// Nvidia query targets
const int translate_nvidia_target[] = {
NV_CTRL_TARGET_TYPE_X_SCREEN,
NV_CTRL_TARGET_TYPE_GPU,
NV_CTRL_TARGET_TYPE_FRAMELOCK,
NV_CTRL_TARGET_TYPE_VCSC,
NV_CTRL_TARGET_TYPE_GVI,
NV_CTRL_TARGET_TYPE_COOLER,
NV_CTRL_TARGET_TYPE_THERMAL_SENSOR,
NV_CTRL_TARGET_TYPE_3D_VISION_PRO_TRANSCEIVER,
NV_CTRL_TARGET_TYPE_DISPLAY,
};
// Enum for nvidia query targets
typedef enum _TARGET_ID {
TARGET_SCREEN,
TARGET_GPU,
TARGET_FRAMELOCK,
TARGET_VCSC,
TARGET_GVI,
TARGET_COOLER,
TARGET_THERMAL,
TARGET_3DVISION,
TARGET_DISPLAY
} TARGET_ID;
// Nvidia query attributes
const int translate_nvidia_attribute[] = {
NV_CTRL_GPU_CORE_TEMPERATURE,
NV_CTRL_GPU_CORE_THRESHOLD,
NV_CTRL_AMBIENT_TEMPERATURE,
NV_CTRL_GPU_CURRENT_CLOCK_FREQS,
NV_CTRL_GPU_CURRENT_CLOCK_FREQS,
NV_CTRL_STRING_PERFORMANCE_MODES,
NV_CTRL_STRING_GPU_CURRENT_CLOCK_FREQS,
NV_CTRL_GPU_POWER_MIZER_MODE,
NV_CTRL_STRING_GPU_UTILIZATION,
NV_CTRL_USED_DEDICATED_GPU_MEMORY,
0,
NV_CTRL_TOTAL_DEDICATED_GPU_MEMORY, // NOTE: NV_CTRL_TOTAL_GPU_MEMORY would
// be better, but returns KB instead of
// MB
0,
NV_CTRL_THERMAL_COOLER_SPEED,
NV_CTRL_THERMAL_COOLER_LEVEL,
NV_CTRL_GPU_CURRENT_PERFORMANCE_LEVEL,
NV_CTRL_IMAGE_SETTINGS,
NV_CTRL_STRING_PRODUCT_NAME,
NV_CTRL_STRING_NVIDIA_DRIVER_VERSION,
};
// Enum for nvidia query attributes
typedef enum _ATTR_ID {
ATTR_GPU_TEMP,
ATTR_GPU_TEMP_THRESHOLD,
ATTR_AMBIENT_TEMP,
ATTR_GPU_FREQ,
ATTR_MEM_FREQ,
ATTR_PERFMODES_STRING,
ATTR_FREQS_STRING,
ATTR_PERF_MODE,
ATTR_UTILS_STRING,
ATTR_MEM_USED,
ATTR_MEM_FREE,
ATTR_MEM_TOTAL,
ATTR_MEM_UTIL,
ATTR_FAN_SPEED,
ATTR_FAN_LEVEL,
ATTR_PERF_LEVEL,
ATTR_IMAGE_QUALITY,
ATTR_MODEL_NAME,
ATTR_DRIVER_VERSION,
} ATTR_ID;
// Enum for query type
typedef enum _QUERY_ID {
QUERY_VALUE,
QUERY_STRING,
QUERY_STRING_VALUE,
QUERY_SPECIAL
} QUERY_ID;
// Enum for string token search mode
typedef enum _SEARCH_ID {
SEARCH_FIRST,
SEARCH_LAST,
SEARCH_MIN,
SEARCH_MAX
} SEARCH_ID;
// Translate special_type into command string
const char *translate_nvidia_special_type[] = {
"nvidia", // NONSPECIAL
"", // HORIZONTAL_LINE
"", // STIPPLED_HR
"nvidiabar", // BAR
"", // FG
"", // BG
"", // OUTLINE
"", // ALIGNR
"", // ALIGNC
"nvidiagague", // GAUGE
"nvidiagraph", // GRAPH
"", // OFFSET
"", // VOFFSET
"", // SAVE_COORDINATES
"", // FONT
"", // GOTO
"" // TAB
};
// Global struct to keep track of queries
class nvidia_s {
public:
nvidia_s()
: command(0),
arg(0),
query(QUERY_VALUE),
target(TARGET_SCREEN),
attribute(ATTR_GPU_TEMP),
token(0),
search(SEARCH_FIRST),
target_id(0),
is_percentage(false) {}
const char *command;
const char *arg;
QUERY_ID query;
TARGET_ID target;
ATTR_ID attribute;
char *token;
SEARCH_ID search;
// added new field for GPU id
int target_id;
bool is_percentage;
};
// Cache by value
struct nvidia_c_value {
int memtotal = -1;
int gputempthreshold = -1;
};
// Cache by string
struct nvidia_c_string {
int nvclockmin = -1;
int nvclockmax = -1;
int memclockmin = -1;
int memclockmax = -1;
int memTransferRatemin = -1;
int memTransferRatemax = -1;
int perfmin = -1;
int perfmax = -1;
};
// Maximum number of GPU connected:
// For cache default value: choosed a model of direct access to array instead of
// list for speed improvement value based on the incoming quad Naples tech
// having 256 PCIe lanes available
const int MAXNUMGPU = 64;
namespace {
// Deleter for nv display to use with std::unique_ptr
void close_nvdisplay(Display *dp) { XCloseDisplay(dp); }
using unique_display_t = std::unique_ptr<Display, decltype(&close_nvdisplay)>;
class nvidia_display_setting
: public conky::simple_config_setting<std::string> {
typedef conky::simple_config_setting<std::string> Base;
protected:
virtual void lua_setter(lua::state &l, bool init);
virtual void cleanup(lua::state &l);
std::string nvdisplay;
public:
nvidia_display_setting() : Base("nvidia_display", std::string(), false) {}
virtual unique_display_t get_nvdisplay();
};
void nvidia_display_setting::lua_setter(lua::state &l, bool init) {
lua::stack_sentry s(l, -2);
Base::lua_setter(l, init);
nvdisplay = do_convert(l, -1).first;
++s;
} // namespace
unique_display_t nvidia_display_setting::get_nvdisplay() {
if (!nvdisplay.empty()) {
unique_display_t nvd(XOpenDisplay(nvdisplay.c_str()), &close_nvdisplay);
if (!nvd) {
NORM_ERR(nullptr, NULL, "can't open nvidia display: %s",
XDisplayName(nvdisplay.c_str()));
}
return nvd;
}
return unique_display_t(nullptr, &close_nvdisplay);
} // namespace
void nvidia_display_setting::cleanup(lua::state &l) {
lua::stack_sentry s(l, -1);
l.pop();
}
nvidia_display_setting nvidia_display;
} // namespace
// Evaluate module parameters and prepare query
int set_nvidia_query(struct text_object *obj, const char *arg,
text_node_t special_type) {
nvidia_s *nvs;
int aid;
int ilen;
// Initialize global struct
nvs = new nvidia_s();
obj->data.opaque = nvs;
// Added new parameter parsing GPU_ID as 0,1,2,..
// if no GPU_ID parameter then default to 0
nvs->target_id = 0;
char *strbuf = strdup(arg);
char *p = strrchr(strbuf, ' ');
if (p && *(p + 1)) {
nvs->target_id = atoi(p + 1);
if ((nvs->target_id > 0) || !strcmp(p + 1, "0")) {
ilen = strlen(strbuf);
ilen = ilen - strlen(p);
strbuf[ilen] = 0;
arg = strbuf;
}
}
// If the value is negative it is set to 0
if (nvs->target_id < 0) nvs->target_id = 0;
// Extract arguments for nvidiabar, etc, and run set_nvidia_query
switch (special_type) {
case text_node_t::BAR:
arg = scan_bar(obj, arg, 100);
break;
case text_node_t::GRAPH: {
auto [buf, skip] = scan_command(arg);
scan_graph(obj, arg + skip, 100, FALSE);
arg = buf;
} break;
case text_node_t::GAUGE:
arg = scan_gauge(obj, arg, 100);
break;
default:
break;
}
// Return error if no argument
// (sometimes scan_graph gets excited and eats the whole string!
if (!arg) {
free_and_zero(strbuf);
return 1;
}
// Translate parameter to id
for (aid = 0; aid < ARG_UNKNOWN; aid++) {
if (strcmp(arg, translate_module_argument[aid]) == 0) break;
}
// free the string buffer after arg is not anymore needed
if (strbuf != nullptr) free_and_zero(strbuf);
// Save pointers to the arg and command strings for debugging and printing
nvs->arg = translate_module_argument[aid];
nvs->command = translate_nvidia_special_type[*special_type];
// Evaluate parameter
switch (aid) {
case ARG_TEMP: // GPU temperature
case ARG_GPU_TEMP:
nvs->query = QUERY_VALUE;
nvs->target = TARGET_GPU;
nvs->attribute = ATTR_GPU_TEMP;
break;
case ARG_THRESHOLD: // GPU temperature threshold
case ARG_GPU_TEMP_THRESHOLD:
nvs->query = QUERY_VALUE;
nvs->target = TARGET_GPU;
nvs->attribute = ATTR_GPU_TEMP_THRESHOLD;
break;
case ARG_AMBIENT: // Ambient temperature
case ARG_AMBIENT_TEMP:
nvs->query = QUERY_VALUE;
nvs->target = TARGET_GPU;
nvs->attribute = ATTR_AMBIENT_TEMP;
break;
case ARG_GPU_FREQ: // Current GPU clock
case ARG_GPU_FREQ_CUR:
nvs->query = QUERY_VALUE;
nvs->target = TARGET_GPU;
nvs->attribute = ATTR_GPU_FREQ;
break;
case ARG_GPU_FREQ_MIN: // Minimum GPU clock
nvs->query = QUERY_STRING_VALUE;
nvs->target = TARGET_GPU;
nvs->attribute = ATTR_PERFMODES_STRING;
nvs->token = (char *)"nvclockmin";
nvs->search = SEARCH_MIN;
break;
case ARG_GPU_FREQ_MAX: // Maximum GPU clock
nvs->query = QUERY_STRING_VALUE;
nvs->target = TARGET_GPU;
nvs->attribute = ATTR_PERFMODES_STRING;
nvs->token = (char *)"nvclockmax";
nvs->search = SEARCH_MAX;
break;
case ARG_MEM_FREQ: // Current memory clock
case ARG_MEM_FREQ_CUR:
nvs->query = QUERY_VALUE;
nvs->target = TARGET_GPU;
nvs->attribute = ATTR_MEM_FREQ;
break;
case ARG_MEM_FREQ_MIN: // Minimum memory clock
nvs->query = QUERY_STRING_VALUE;
nvs->target = TARGET_GPU;
nvs->attribute = ATTR_PERFMODES_STRING;
nvs->token = (char *)"memclockmin";
nvs->search = SEARCH_MIN;
break;
case ARG_MEM_FREQ_MAX: // Maximum memory clock
nvs->query = QUERY_STRING_VALUE;
nvs->target = TARGET_GPU;
nvs->attribute = ATTR_PERFMODES_STRING;
nvs->token = (char *)"memclockmax";
nvs->search = SEARCH_MAX;
break;
case ARG_MTR_FREQ: // Current memory transfer rate clock
case ARG_MTR_FREQ_CUR:
nvs->query = QUERY_STRING_VALUE;
nvs->target = TARGET_GPU;
nvs->attribute = ATTR_FREQS_STRING;
nvs->token = (char *)"memTransferRate";
nvs->search = SEARCH_FIRST;
break;
case ARG_MTR_FREQ_MIN: // Minimum memory transfer rate clock
nvs->query = QUERY_STRING_VALUE;
nvs->target = TARGET_GPU;
nvs->attribute = ATTR_PERFMODES_STRING;
nvs->token = (char *)"memTransferRatemin";
nvs->search = SEARCH_MIN;
break;
case ARG_MTR_FREQ_MAX: // Maximum memory transfer rate clock
nvs->query = QUERY_STRING_VALUE;
nvs->target = TARGET_GPU;
nvs->attribute = ATTR_PERFMODES_STRING;
nvs->token = (char *)"memTransferRatemax";
nvs->search = SEARCH_MAX;
break;
case ARG_PERF_LEVEL: // Current performance level
case ARG_PERF_LEVEL_CUR:
nvs->query = QUERY_VALUE;
nvs->target = TARGET_GPU;
nvs->attribute = ATTR_PERF_LEVEL;
break;
case ARG_PERF_LEVEL_MIN: // Lowest performance level
nvs->query = QUERY_STRING_VALUE;
nvs->target = TARGET_GPU;
nvs->attribute = ATTR_PERFMODES_STRING;
nvs->token = (char *)"perf";
nvs->search = SEARCH_MIN;
break;
case ARG_PERF_LEVEL_MAX: // Highest performance level
nvs->query = QUERY_STRING_VALUE;
nvs->target = TARGET_GPU;
nvs->attribute = ATTR_PERFMODES_STRING;
nvs->token = (char *)"perf";
nvs->search = SEARCH_MAX;
break;
case ARG_PERF_MODE: // Performance mode
nvs->query = QUERY_SPECIAL;
nvs->target = TARGET_GPU;
nvs->attribute = ATTR_PERF_MODE;
break;
case ARG_GPU_UTIL: // GPU utilization %
nvs->query = QUERY_STRING_VALUE;
nvs->target = TARGET_GPU;
nvs->attribute = ATTR_UTILS_STRING;
nvs->token = (char *)"graphics";
nvs->search = SEARCH_FIRST;
nvs->is_percentage = true;
break;
case ARG_MEM_BW_UTIL: // Memory bandwidth utilization %
nvs->query = QUERY_STRING_VALUE;
nvs->target = TARGET_GPU;
nvs->attribute = ATTR_UTILS_STRING;
nvs->token = (char *)"memory";
nvs->search = SEARCH_FIRST;
nvs->is_percentage = true;
break;
case ARG_VIDEO_UTIL: // Video engine utilization %
nvs->query = QUERY_STRING_VALUE;
nvs->target = TARGET_GPU;
nvs->attribute = ATTR_UTILS_STRING;
nvs->token = (char *)"video";
nvs->search = SEARCH_FIRST;
nvs->is_percentage = true;
break;
case ARG_PCIE_UTIL: // PCIe bandwidth utilization %
nvs->query = QUERY_STRING_VALUE;
nvs->target = TARGET_GPU;
nvs->attribute = ATTR_UTILS_STRING;
nvs->token = (char *)"PCIe";
nvs->search = SEARCH_FIRST;
nvs->is_percentage = true;
break;
case ARG_MEM: // Amount of used memory
case ARG_MEM_USED:
nvs->query = QUERY_VALUE;
nvs->target = TARGET_GPU;
nvs->attribute = ATTR_MEM_USED;
break;
case ARG_MEM_FREE: // Amount of free memory
case ARG_MEM_AVAIL:
nvs->query = QUERY_SPECIAL;
nvs->target = TARGET_GPU;
nvs->attribute = ATTR_MEM_FREE;
break;
case ARG_MEM_MAX: // Total amount of memory
case ARG_MEM_TOTAL:
nvs->query = QUERY_VALUE;
nvs->target = TARGET_GPU;
nvs->attribute = ATTR_MEM_TOTAL;
break;
case ARG_MEM_UTIL: // Memory utilization %
case ARG_MEM_PERC:
nvs->query = QUERY_SPECIAL;
nvs->target = TARGET_GPU;
nvs->attribute = ATTR_MEM_UTIL;
nvs->is_percentage = true;
break;
case ARG_FAN_SPEED: // Fan speed
nvs->query = QUERY_VALUE;
nvs->target = TARGET_COOLER;
nvs->attribute = ATTR_FAN_SPEED;
break;
case ARG_FAN_LEVEL: // Fan level %
nvs->query = QUERY_VALUE;
nvs->target = TARGET_COOLER;
nvs->attribute = ATTR_FAN_LEVEL;
nvs->is_percentage = true;
break;
case ARG_IMAGEQUALITY: // Image quality
nvs->query = QUERY_VALUE;
nvs->target = TARGET_SCREEN;
nvs->attribute = ATTR_IMAGE_QUALITY;
break;
case ARG_MODEL_NAME:
nvs->query = QUERY_STRING;
nvs->target = TARGET_GPU;
nvs->attribute = ATTR_MODEL_NAME;
break;
case ARG_DRIVER_VERSION:
nvs->query = QUERY_STRING;
nvs->target = TARGET_GPU;
nvs->attribute = ATTR_DRIVER_VERSION;
break;
default: // Unknown/invalid argument
// Error printed by core.cc
return 1;
}
return 0;
}
// Return the amount of targets present or raise error)
static inline int get_nvidia_target_count(Display *dpy, TARGET_ID tid) {
int num_tgts;
if (!XNVCTRLQueryTargetCount(dpy, translate_nvidia_target[tid], &num_tgts)) {
num_tgts = -1;
}
if (num_tgts < 1 && tid == TARGET_GPU) {
// Print error and exit if there's no NVIDIA's GPU
NORM_ERR(nullptr, NULL,
"%s:"
"\n Trying to query Nvidia target failed (using the "
"proprietary drivers)."
"\n Are you sure they are installed correctly and a "
"Nvidia GPU is in use?"
"\n (display: %d,Nvidia target_count: %d)",
__func__, dpy, num_tgts);
}
return num_tgts;
}
static int cache_nvidia_value(TARGET_ID tid, ATTR_ID aid, Display *dpy,
int *value, int gid, const char *arg) {
static nvidia_c_value ac_value[MAXNUMGPU];
if (aid == ATTR_MEM_TOTAL) {
if (ac_value[gid].memtotal < 0) {
if (!dpy || !XNVCTRLQueryTargetAttribute(
dpy, translate_nvidia_target[tid], gid, 0,
translate_nvidia_attribute[aid], value)) {
NORM_ERR(
"%s: Something went wrong running nvidia query (arg: %s tid: %d, "
"aid: %d)",
__func__, arg, tid, aid);
return -1;
}
ac_value[gid].memtotal = *value;
} else {
*value = ac_value[gid].memtotal;
}
} else if (aid == ATTR_GPU_TEMP_THRESHOLD) {
if (ac_value[gid].gputempthreshold < 0) {
if (!dpy || !XNVCTRLQueryTargetAttribute(
dpy, translate_nvidia_target[tid], gid, 0,
translate_nvidia_attribute[aid], value)) {
NORM_ERR(
"%s: Something went wrong running nvidia query (arg: %s, tid: "
"%d, aid: %d)",
__func__, arg, tid, aid);
return -1;
}
ac_value[gid].gputempthreshold = *value;
} else {
*value = ac_value[gid].gputempthreshold;
}
}
return 0;
}
// Retrieve attribute value via nvidia interface
static int get_nvidia_value(TARGET_ID tid, ATTR_ID aid, int gid,
const char *arg) {
auto nvdpy = nvidia_display.get_nvdisplay();
Display *dpy = nvdpy ? nvdpy.get() : display;
int value;
// Check if the aid is cacheable
if (aid == ATTR_MEM_TOTAL || aid == ATTR_GPU_TEMP_THRESHOLD) {
if (cache_nvidia_value(tid, aid, dpy, &value, gid, arg)) { return -1; }
// If not, then query it
} else {
if (!dpy ||
!XNVCTRLQueryTargetAttribute(dpy, translate_nvidia_target[tid], gid, 0,
translate_nvidia_attribute[aid], &value)) {
NORM_ERR(
"%s: Something went wrong running nvidia query (arg: %s, tid: %d, "
"aid: %d)",
__func__, arg, tid, aid);
return -1;
}
}
// Unpack clock values (see NVCtrl.h for details)
if (aid == ATTR_GPU_FREQ) return value >> 16;
if (aid == ATTR_MEM_FREQ) return value & 0xFFFF;
// Return value
return value;
}
// Retrieve attribute string via nvidia interface
static char *get_nvidia_string(TARGET_ID tid, ATTR_ID aid, int gid,
const char *arg) {
auto nvdpy = nvidia_display.get_nvdisplay();
Display *dpy = nvdpy ? nvdpy.get() : display;
char *str;
// Query nvidia interface
if (!dpy || !XNVCTRLQueryTargetStringAttribute(
dpy, translate_nvidia_target[tid], gid, 0,
translate_nvidia_attribute[aid], &str)) {
NORM_ERR(
"%s: Something went wrong running nvidia string query (arg, tid: %d, "
"aid: "
"%d, GPU %d)",
__func__, arg, tid, aid, gid);
return nullptr;
}
return str;
}
void cache_nvidia_string_value_update(nvidia_c_string *ac_string, char *token,
SEARCH_ID search, int *value, int gid) {
if (strcmp(token, (char *)"nvclockmin") == 0 &&
ac_string[gid].nvclockmin < 0) {
ac_string[gid].nvclockmin = *value;
} else if (strcmp(token, (char *)"nvclockmax") == 0 &&
ac_string[gid].nvclockmax < 0) {
ac_string[gid].nvclockmax = *value;
} else if (strcmp(token, (char *)"memclockmin") == 0 &&
ac_string[gid].memclockmin < 0) {
ac_string[gid].memclockmin = *value;
} else if (strcmp(token, (char *)"memclockmax") == 0 &&
ac_string[gid].memclockmax < 0) {
ac_string[gid].memclockmax = *value;
} else if (strcmp(token, (char *)"memTransferRatemin") == 0 &&
ac_string[gid].memTransferRatemin < 0) {
ac_string[gid].memTransferRatemin = *value;
} else if (strcmp(token, (char *)"memTransferRatemax") == 0 &&
ac_string[gid].memTransferRatemax < 0) {
ac_string[gid].memTransferRatemax = *value;
} else if (strcmp(token, (char *)"perf") == 0) {
if (search == SEARCH_MIN &&
ac_string[gid].perfmin < 0) {
ac_string[gid].perfmin = *value;
} else if (search == SEARCH_MAX &&
ac_string[gid].perfmax < 0) {
ac_string[gid].perfmax = *value;
}
}
}
void cache_nvidia_string_value_noupdate(nvidia_c_string *ac_string, char *token,
SEARCH_ID search, int *value, int gid) {
if (strcmp(token, (char *)"nvclockmin") == 0) {
*value = ac_string[gid].nvclockmin;
} else if (strcmp(token, (char *)"nvclockmax") == 0) {
*value = ac_string[gid].nvclockmax;
} else if (strcmp(token, (char *)"memclockmin") == 0) {
*value = ac_string[gid].memclockmin;
} else if (strcmp(token, (char *)"memclockmax") == 0) {
*value = ac_string[gid].memclockmax;
} else if (strcmp(token, (char *)"memTransferRatemin") == 0) {
*value = ac_string[gid].memTransferRatemin;
} else if (strcmp(token, (char *)"memTransferRatemax") == 0) {
*value = ac_string[gid].memTransferRatemax;
} else if (strcmp(token, (char *)"perf") == 0) {
if (search == SEARCH_MIN) {
*value = ac_string[gid].perfmin;
} else if (search == SEARCH_MAX) {
*value = ac_string[gid].perfmax;
}
}
}
static int cache_nvidia_string_value(TARGET_ID tid, ATTR_ID aid, char *token,
SEARCH_ID search, int *value, int update,
int gid) {
static nvidia_c_string ac_string[MAXNUMGPU];
(void)tid;
(void)aid;
if (update) {
cache_nvidia_string_value_update(ac_string, token, search, value, gid);
} else {
cache_nvidia_string_value_noupdate(ac_string, token, search, value, gid);
}
return 0;
}
// Retrieve token value from nvidia string
static int get_nvidia_string_value(TARGET_ID tid, ATTR_ID aid, char *token,
SEARCH_ID search, int gid, const char *arg) {
char *str;
char *kvp;
char *key;
char *val;
char *saveptr1;
char *saveptr2;
int temp;
int value = -1;
// Checks if the value is cacheable and is already loaded
cache_nvidia_string_value(tid, aid, token, search, &value, 0, gid);
if (value != -1) { return value; }
// Get string via nvidia interface
str = get_nvidia_string(tid, aid, gid, arg);
// Split string into 'key=value' substrings, split substring
// into key and value, from value, check if token was found,
// convert value to int, evaluate value according to specified
// token search mode
kvp = strtok_r(str, NV_KVPAIR_SEPARATORS, &saveptr1);
while (kvp) {
key = strtok_r(kvp, NV_KEYVAL_SEPARATORS, &saveptr2);
val = strtok_r(nullptr, NV_KEYVAL_SEPARATORS, &saveptr2);
if (key && val && (strcmp(token, key) == 0)) {
temp = (int)strtol(val, nullptr, 0);
if (search == SEARCH_FIRST) {
value = temp;
break;
} else if (search == SEARCH_LAST) {
value = temp;
} else if (search == SEARCH_MIN) {
if ((value == -1) || (temp < value)) value = temp;
} else if (search == SEARCH_MAX) {
if (temp > value) value = temp;
} else {
value = -1;
break;
}
}
kvp = strtok_r(nullptr, NV_KVPAIR_SEPARATORS, &saveptr1);
}
// This call updated the cache for the cacheable values
cache_nvidia_string_value(tid, aid, token, search, &value, 1, gid);
// Free string, return value
free_and_zero(str);
return value;
}
bool validate_target_id(Display *dpy, int target_id, ATTR_ID attribute) {
// num_GPU and num_COOLER calculated only once based on the physical target
static int num_GPU = get_nvidia_target_count(dpy, TARGET_GPU) - 1;
static int num_COOLER = get_nvidia_target_count(dpy, TARGET_COOLER) - 1;
if (target_id < 0) return false;
switch (attribute) {
case ATTR_FAN_LEVEL:
case ATTR_FAN_SPEED:
if (target_id > num_COOLER) return false;
break;
default:
if (target_id > num_GPU) return false;
break;
}
return true;
}
// Perform query and print result
void print_nvidia_value(struct text_object *obj, char *p,
unsigned int p_max_size) {
nvidia_s *nvs = static_cast<nvidia_s *>(obj->data.opaque);
int value;
int temp1;
int temp2;
int result;
char *str;
int event_base;
int error_base;
auto nvdpy = nvidia_display.get_nvdisplay();
Display *dpy = nvdpy ? nvdpy.get() : display;
if (!dpy) {
NORM_ERR("%s: no display set (try setting nvidia_display)", __func__);
return;
}
if (!XNVCTRLQueryExtension(dpy, &event_base, &error_base)) {
NORM_ERR("%s: NV-CONTROL X extension not present", __func__);
return;
}
// Assume failure
value = -1;
str = nullptr;
// Perform query if the query exists and isnt stupid
if (nvs != nullptr &&
validate_target_id(dpy, nvs->target_id, nvs->attribute)) {
// Execute switch by query type
switch (nvs->query) {
case QUERY_VALUE:
value = get_nvidia_value(nvs->target, nvs->attribute, nvs->target_id,
nvs->arg);
break;
case QUERY_STRING:
str = get_nvidia_string(nvs->target, nvs->attribute, nvs->target_id,
nvs->arg);
break;
case QUERY_STRING_VALUE:
value = get_nvidia_string_value(nvs->target, nvs->attribute, nvs->token,
nvs->search, nvs->target_id, nvs->arg);
break;
case QUERY_SPECIAL:
switch (nvs->attribute) {
case ATTR_PERF_MODE:
temp1 = get_nvidia_value(nvs->target, nvs->attribute,
nvs->target_id, nvs->arg);
switch (temp1) {
case NV_CTRL_GPU_POWER_MIZER_MODE_ADAPTIVE:
result = asprintf(&str, "Adaptive");
break;
case NV_CTRL_GPU_POWER_MIZER_MODE_PREFER_MAXIMUM_PERFORMANCE:
result = asprintf(&str, "Max. Perf.");
break;
case NV_CTRL_GPU_POWER_MIZER_MODE_AUTO:
result = asprintf(&str, "Auto");
break;
case NV_CTRL_GPU_POWER_MIZER_MODE_PREFER_CONSISTENT_PERFORMANCE:
result = asprintf(&str, "Consistent");
break;
default:
result = asprintf(&str, "Unknown (%d)", value);
break;
}
if (result < 0) { str = nullptr; }
break;
case ATTR_MEM_FREE:
temp1 = get_nvidia_value(nvs->target, ATTR_MEM_USED, nvs->target_id,
nvs->arg);
temp2 = get_nvidia_value(nvs->target, ATTR_MEM_TOTAL,
nvs->target_id, nvs->arg);
value = temp2 - temp1;
break;
case ATTR_MEM_UTIL:
temp1 = get_nvidia_value(nvs->target, ATTR_MEM_USED, nvs->target_id,
nvs->arg);
temp2 = get_nvidia_value(nvs->target, ATTR_MEM_TOTAL,
nvs->target_id, nvs->arg);
value = ((float)temp1 * 100 / (float)temp2) + 0.5;
break;
default:
break;
}
break;
default:
break;
}
}
// Print result
if (value != -1) {
if (nvs->is_percentage) {
percent_print(p, p_max_size, value);
} else {
snprintf(p, p_max_size, "%d", value);
}
} else if (str != nullptr) {
snprintf(p, p_max_size, "%s", str);
free_and_zero(str);
} else {
snprintf(p, p_max_size, "%s", "N/A");
}
}
double get_nvidia_barval(struct text_object *obj) {
nvidia_s *nvs = static_cast<nvidia_s *>(obj->data.opaque);
int temp1;
int temp2;
double value;
int event_base;
int error_base;
auto nvdpy = nvidia_display.get_nvdisplay();
Display *dpy = nvdpy ? nvdpy.get() : display;
if (!dpy) {
NORM_ERR("%s: no display set (try setting nvidia_display)", __func__);
return 0;
}
if (!XNVCTRLQueryExtension(dpy, &event_base, &error_base)) {
NORM_ERR("%s: NV-CONTROL X extension not present", __func__);
return 0;
}
// Assume failure
value = 0;
// Convert query_result to a percentage using ((val-min)÷(max-min)×100)+0.5 if
// needed.
if (nvs != nullptr &&
validate_target_id(dpy, nvs->target_id, nvs->attribute)) {
switch (nvs->attribute) {
case ATTR_UTILS_STRING: // one of the percentage utils (gpuutil,
// membwutil, videoutil and pcieutil)
value =
get_nvidia_string_value(nvs->target, ATTR_UTILS_STRING, nvs->token,
nvs->search, nvs->target_id, nvs->arg);
break;
case ATTR_MEM_UTIL: // memutil
case ATTR_MEM_USED:
temp1 = get_nvidia_value(nvs->target, ATTR_MEM_USED, nvs->target_id,
nvs->arg);
temp2 = get_nvidia_value(nvs->target, ATTR_MEM_TOTAL, nvs->target_id,
nvs->arg);
value = ((float)temp1 * 100 / (float)temp2) + 0.5;
break;
case ATTR_MEM_FREE: // memfree
temp1 = get_nvidia_value(nvs->target, ATTR_MEM_USED, nvs->target_id,
nvs->arg);
temp2 = get_nvidia_value(nvs->target, ATTR_MEM_TOTAL, nvs->target_id,
nvs->arg);
value = temp2 - temp1;
break;
case ATTR_FAN_SPEED: // fanspeed: Warn user we are using fanlevel
NORM_ERR(
"%s: invalid argument specified: '%s' (using 'fanlevel' instead).",
nvs->command, nvs->arg);
/* falls through */
case ATTR_FAN_LEVEL: // fanlevel
value = get_nvidia_value(nvs->target, ATTR_FAN_LEVEL, nvs->target_id,
nvs->arg);
break;
case ATTR_GPU_TEMP: // gputemp (calculate out of gputempthreshold)
temp1 = get_nvidia_value(nvs->target, ATTR_GPU_TEMP, nvs->target_id,
nvs->arg);
temp2 = get_nvidia_value(nvs->target, ATTR_GPU_TEMP_THRESHOLD,
nvs->target_id, nvs->arg);
value = ((float)temp1 * 100 / (float)temp2) + 0.5;
break;
case ATTR_AMBIENT_TEMP: // ambienttemp (calculate out of gputempthreshold
// for consistency)
temp1 = get_nvidia_value(nvs->target, ATTR_AMBIENT_TEMP, nvs->target_id,
nvs->arg);
temp2 = get_nvidia_value(nvs->target, ATTR_GPU_TEMP_THRESHOLD,
nvs->target_id, nvs->arg);
value = ((float)temp1 * 100 / (float)temp2) + 0.5;
break;
case ATTR_GPU_FREQ: // gpufreq (calculate out of gpufreqmax)
temp1 = get_nvidia_value(nvs->target, ATTR_GPU_FREQ, nvs->target_id,
nvs->arg);
temp2 = get_nvidia_string_value(nvs->target, ATTR_PERFMODES_STRING,
(char *)"nvclockmax", SEARCH_MAX,
nvs->target_id, nvs->arg);
value = ((float)temp1 * 100 / (float)temp2) + 0.5;
break;
case ATTR_MEM_FREQ: // memfreq (calculate out of memfreqmax)
temp1 = get_nvidia_value(nvs->target, ATTR_MEM_FREQ, nvs->target_id,
nvs->arg);
temp2 = get_nvidia_string_value(nvs->target, ATTR_PERFMODES_STRING,
(char *)"memclockmax", SEARCH_MAX,
nvs->target_id, nvs->arg);
value = ((float)temp1 * 100 / (float)temp2) + 0.5;
break;
case ATTR_FREQS_STRING: // mtrfreq (calculate out of memfreqmax)
if (strcmp(nvs->token, "memTransferRate") != 0) {
// Just in case error for silly devs
CRIT_ERR(
"%s: attribute is 'ATTR_FREQS_STRING' but token is not "
"\"memTransferRate\" (arg: '%s')",
nvs->command, nvs->arg);
return 0;
}
temp1 =
get_nvidia_string_value(nvs->target, ATTR_FREQS_STRING, nvs->token,
SEARCH_MAX, nvs->target_id, nvs->arg);
temp2 = get_nvidia_string_value(nvs->target, ATTR_PERFMODES_STRING,
(char *)"memTransferRatemax",
SEARCH_MAX, nvs->target_id, nvs->arg);
if (temp1 > temp2) temp1 = temp2; // extra safe here
value = ((float)temp1 * 100 / (float)temp2) + 0.5;
break;
case ATTR_IMAGE_QUALITY: // imagequality
value = get_nvidia_value(nvs->target, ATTR_IMAGE_QUALITY,
nvs->target_id, nvs->arg);
break;
default: // Throw error if unsupported args are used
CRIT_ERR("%s: invalid argument specified: '%s'", nvs->command,
nvs->arg);
}
}
// Return the percentage
return value;
}
// Cleanup
void free_nvidia(struct text_object *obj) {
nvidia_s *nvs = static_cast<nvidia_s *>(obj->data.opaque);
delete nvs;
obj->data.opaque = nullptr;
}
| 38,366
|
C++
|
.cc
| 1,065
| 29.487324
| 80
| 0.608394
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,622
|
ccurl_thread.cc
|
brndnmtthws_conky/src/ccurl_thread.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Please see COPYING for details
*
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "ccurl_thread.h"
#include <cmath>
#include <mutex>
#include "conky.h"
#include "logging.h"
#include "text_object.h"
#ifdef DEBUG
#include <assert.h>
#endif /* DEBUG */
#include <curl/easy.h>
/*
* The following code is the conky curl thread lib, which can be re-used to
* create any curl-based object (see rss). Below is an
* implementation of a curl-only object ($curl) which can also be used as an
* example.
*/
namespace priv {
/* callback used by curl for parsing the header data */
size_t curl_internal::parse_header_cb(void *ptr, size_t size, size_t nmemb,
void *data) {
curl_internal *obj = static_cast<curl_internal *>(data);
const char *value = static_cast<const char *>(ptr);
size_t realsize = size * nmemb;
if (realsize > 0 &&
(value[realsize - 1] == '\r' || value[realsize - 1] == 0)) {
--realsize;
}
if (strncmp(value, "Last-Modified: ", 15) == EQUAL) {
obj->last_modified = std::string(value + 15, realsize - 15);
} else if (strncmp(value, "ETag: ", 6) == EQUAL) {
obj->etag = std::string(value + 6, realsize - 6);
}
return size * nmemb;
}
/* callback used by curl for writing the received data */
size_t curl_internal::write_cb(void *ptr, size_t size, size_t nmemb,
void *data) {
curl_internal *obj = static_cast<curl_internal *>(data);
const char *value = static_cast<const char *>(ptr);
size_t realsize = size * nmemb;
obj->data += std::string(value, realsize);
return realsize;
}
curl_internal::curl_internal(const std::string &url) : curl(curl_easy_init()) {
if (!curl) throw std::runtime_error("curl_easy_init() failed");
curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1);
curl_easy_setopt(curl, CURLOPT_HEADERDATA, this);
curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, parse_header_cb);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, this);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_cb);
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_USERAGENT, "conky-curl/1.1");
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 1000);
curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, 60);
// curl's usage of alarm()+longjmp() is a really bad idea for multi-threaded
// applications
curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
}
/* fetch our datums */
void curl_internal::do_work() {
CURLcode res;
struct headers_ {
struct curl_slist *h;
headers_() : h(nullptr) {}
~headers_() { curl_slist_free_all(h); }
} headers;
data.clear();
if (!last_modified.empty()) {
headers.h = curl_slist_append(
headers.h, ("If-Modified-Since: " + last_modified).c_str());
last_modified.clear();
}
if (!etag.empty()) {
headers.h =
curl_slist_append(headers.h, ("If-None-Match: " + etag).c_str());
etag.clear();
}
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers.h);
res = curl_easy_perform(curl);
if (res == CURLE_OK) {
long http_status_code;
if (curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_status_code) ==
CURLE_OK) {
switch (http_status_code) {
case 200:
process_data();
break;
case 304:
break;
default:
NORM_ERR("curl: no data from server, got HTTP status %ld",
http_status_code);
break;
}
} else {
NORM_ERR("curl: no HTTP status from server");
}
} else {
NORM_ERR("curl: could not retrieve data from server");
}
}
} // namespace priv
namespace {
class simple_curl_cb : public curl_callback<std::string> {
typedef curl_callback<std::string> Base;
protected:
virtual void process_data() {
std::lock_guard<std::mutex> lock(result_mutex);
result = data;
}
public:
simple_curl_cb(uint32_t period, const std::string &uri)
: Base(period, Tuple(uri)) {}
};
} // namespace
/*
* This is where the $curl section begins.
*/
struct curl_data {
char *uri;
float interval;
};
/* prints result data to text buffer, used by $curl */
void ccurl_process_info(char *p, int p_max_size, const std::string &uri,
int interval) {
uint32_t period = std::max(lround(interval / active_update_interval()), 1l);
auto cb = conky::register_cb<simple_curl_cb>(period, uri);
strncpy(p, cb->get_result_copy().c_str(), p_max_size);
}
void curl_parse_arg(struct text_object *obj, const char *arg) {
struct curl_data *cd;
float interval = 0;
char *space;
if (strlen(arg) < 1) {
NORM_ERR("wrong number of arguments for $curl");
return;
}
cd = static_cast<struct curl_data *>(malloc(sizeof(struct curl_data)));
memset(cd, 0, sizeof(struct curl_data));
// Default to a 15 minute interval
cd->interval = 15 * 60;
cd->uri = strdup(arg);
space = strchr(cd->uri, ' ');
if (space) {
// If an explicit interval was given, use that
char *interval_str = &space[1];
*space = '\0';
sscanf(interval_str, "%f", &interval);
cd->interval = interval > 0 ? interval * 60 : active_update_interval();
}
obj->data.opaque = cd;
}
void curl_print(struct text_object *obj, char *p, unsigned int p_max_size) {
struct curl_data *cd = static_cast<struct curl_data *>(obj->data.opaque);
if (!cd) {
NORM_ERR("error processing Curl data");
return;
}
ccurl_process_info(p, p_max_size, cd->uri, cd->interval);
}
void curl_obj_free(struct text_object *obj) {
struct curl_data *cd = static_cast<struct curl_data *>(obj->data.opaque);
free_and_zero(cd->uri);
free_and_zero(obj->data.opaque);
}
| 6,499
|
C++
|
.cc
| 189
| 30.460317
| 79
| 0.663851
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
22,623
|
specials.cc
|
brndnmtthws_conky/src/specials.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "conky.h"
#ifdef BUILD_GUI
#include "fonts.h"
#include "gui.h"
#endif /* BUILD_GUI */
#include <cmath>
#include "logging.h"
#include "nc.h"
#include "specials.h"
#ifdef HAVE_SYS_PARAM_H
#include <sys/param.h>
#endif /* HAVE_SYS_PARAM_H */
#include <algorithm>
#include <map>
#include <sstream>
#include "colours.h"
#include "common.h"
#include "conky.h"
#include "display-output.hh"
struct special_node *specials = nullptr;
int special_count;
int graph_count = 0;
double maxspeedval = 1e-47; /* The maximum value among the speed graphs */
std::map<int, double *> graphs;
namespace {
conky::range_config_setting<int> default_bar_width(
"default_bar_width", 0, std::numeric_limits<int>::max(), 0, false);
conky::range_config_setting<int> default_bar_height(
"default_bar_height", 0, std::numeric_limits<int>::max(), 6, false);
#ifdef BUILD_GUI
conky::range_config_setting<int> default_graph_width(
"default_graph_width", 0, std::numeric_limits<int>::max(), 0, false);
conky::range_config_setting<int> default_graph_height(
"default_graph_height", 0, std::numeric_limits<int>::max(), 25, false);
conky::range_config_setting<int> default_gauge_width(
"default_gauge_width", 0, std::numeric_limits<int>::max(), 40, false);
conky::range_config_setting<int> default_gauge_height(
"default_gauge_height", 0, std::numeric_limits<int>::max(), 25, false);
conky::simple_config_setting<bool> store_graph_data_explicitly(
"store_graph_data_explicitly", true, true);
#endif /* BUILD_GUI */
conky::simple_config_setting<std::string> console_graph_ticks(
"console_graph_ticks", " ,_,=,#", false);
} // namespace
/* special data types flags */
#define SF_SCALED (1 << 0)
#define SF_SHOWLOG (1 << 1)
/* special flag for inverting axis */
#define SF_INVERTX (1 << 0)
#define SF_INVERTY (1 << 1)
/*
* Special data typedefs
*/
struct bar {
char flags;
int width, height;
double scale;
};
struct gauge {
char flags;
int width, height;
double scale;
};
struct graph {
int id;
char flags;
int width, height;
bool colours_set;
Colour first_colour, last_colour;
double scale;
char tempgrad;
char speedgraph; /* If the current graph is a speed graph */
char invertflag; /* If the axis needs to be inverted */
int minheight; /* Clamp values below this threshold to this threshold */
};
struct stippled_hr {
int height, arg;
};
struct tab {
int width, arg;
};
/*
* Scanning arguments to various special text objects
*/
#ifdef BUILD_GUI
const char *scan_gauge(struct text_object *obj, const char *args,
double scale) {
struct gauge *g;
g = static_cast<struct gauge *>(malloc(sizeof(struct gauge)));
memset(g, 0, sizeof(struct gauge));
/*width and height*/
g->width = default_gauge_width.get(*state);
g->height = default_gauge_height.get(*state);
if (scale != 0.0) {
g->scale = scale;
} else {
g->flags |= SF_SCALED;
}
/* gauge's argument is either height or height,width */
if (args != nullptr) {
int n = 0;
if (sscanf(args, "%d,%d %n", &g->height, &g->width, &n) <= 1) {
if (sscanf(args, "%d %n", &g->height, &n) == 2) {
g->width = g->height; /*square gauge*/
}
}
args += n;
}
obj->special_data = g;
return args;
}
#endif
const char *scan_bar(struct text_object *obj, const char *args, double scale) {
struct bar *b;
b = static_cast<struct bar *>(malloc(sizeof(struct bar)));
memset(b, 0, sizeof(struct bar));
/* zero width means all space that is available */
b->width = default_bar_width.get(*state);
b->height = default_bar_height.get(*state);
if (scale != 0.0) {
b->scale = scale;
} else {
b->flags |= SF_SCALED;
}
/* bar's argument is either height or height,width */
if (args != nullptr) {
int n = 0;
if (sscanf(args, "%d,%d %n", &b->height, &b->width, &n) <= 1) {
sscanf(args, "%d %n", &b->height, &n);
}
args += n;
}
obj->special_data = b;
return args;
}
#ifdef BUILD_GUI
void scan_font(struct text_object *obj, const char *args) {
if ((args != nullptr) && (*args != 0)) {
obj->data.s = strndup(args, DEFAULT_TEXT_BUFFER_SIZE);
}
}
void apply_graph_colours(struct graph *g, const char *first_colour_name,
const char *last_colour_name) {
g->first_colour = parse_color(first_colour_name);
g->last_colour = parse_color(last_colour_name);
g->colours_set = true;
}
/**
* parses a possibly-quoted command from the prefix of a string.
* @param[in] s argument string to parse
* @return pair of the command and the number of bytes parsed (counting quotes).
* The command will be nullptr if the string to parse started with a
* digit or an unpaired double-quote.
**/
std::pair<char *, size_t> scan_command(const char *s) {
if (s == nullptr) return {nullptr, 0};
/* unquoted commands are not permitted to begin with digits. This allows
distinguishing a commands from a position in execgraph objects */
if (isdigit(*s)) { return {nullptr, 0}; }
/* extract double-quoted command in case of execgraph */
if (*s == '"') {
size_t _size;
char *_ptr;
if (((_ptr = const_cast<char *>(strrchr(s, '"'))) != nullptr) &&
_ptr != s) {
_size = _ptr - s - 1;
} else {
NORM_ERR("mismatched double-quote in execgraph object");
return {nullptr, 0};
}
char *quoted_cmd = static_cast<char *>(malloc(_size + 1));
quoted_cmd[0] = '\0';
strncpy(quoted_cmd, s + 1, _size);
quoted_cmd[_size] = '\0';
return {quoted_cmd, _size + 2};
} else {
size_t len;
for (len = 0; s[len] != '\0' && !isspace(s[len]); len++)
;
return {strndup(s, len), len};
}
}
/**
* parses for [height,width] [color1 color2] [scale] [-t] [-l] [-m value]
*
* -l will set the showlog flag, enabling logarithmic graph scales
* -t will set the tempgrad member to true, enabling temperature gradient colors
* -x will set the invertx flag to true, inverting the x axis
* -y will set the invertx flag to true, inverting the y axis
* -m will set the minheight to value, this will clamp values below the threshold to the threshold
*
* @param[out] obj struct in which to save width, height and other options
* @param[in] args argument string to parse
* @param[in] defscale default scale if no scale argument given
* @param[in] speedGraph if graph is network speed graph or not
* @return whether parsing was successful
**/
bool scan_graph(struct text_object *obj, const char *argstr, double defscale, char speedGraph) {
char first_colour_name[1024] = {'\0'};
char last_colour_name[1024] = {'\0'};
auto *g = static_cast<struct graph *>(malloc(sizeof(struct graph)));
memset(g, 0, sizeof(struct graph));
obj->special_data = g;
g->id = ++graph_count;
/* zero width means all space that is available */
g->width = default_graph_width.get(*state);
g->height = default_graph_height.get(*state);
g->colours_set = false;
g->first_colour = Colour();
g->last_colour = Colour();
g->scale = defscale;
g->tempgrad = FALSE;
g->invertflag = FALSE;
g->minheight = 0;
if (speedGraph) {
g->speedgraph = TRUE;
}
if (argstr == nullptr) return false;
/* set tempgrad to true if '-t' specified.
* It doesn't matter where the argument is exactly. */
if ((strstr(argstr, " " TEMPGRAD) != nullptr) ||
strncmp(argstr, TEMPGRAD, strlen(TEMPGRAD)) == 0) {
g->tempgrad = TRUE;
}
/* set showlog flag if '-l' specified.
* It doesn't matter where the argument is exactly. */
if ((strstr(argstr, " " LOGGRAPH) != nullptr) ||
strncmp(argstr, LOGGRAPH, strlen(LOGGRAPH)) == 0) {
g->flags |= SF_SHOWLOG;
}
/* set invertx to true if '-x' specified.
* It doesn't matter where the argument is exactly. */
if ((strstr(argstr, " " INVERTX) != nullptr) ||
strncmp(argstr, INVERTX, strlen(INVERTX)) == 0) {
g->invertflag |= SF_INVERTX;
}
/* set inverty to true if '-y' specified.
* It doesn't matter where the argument is exactly. */
if ((strstr(argstr, " " INVERTY) != nullptr) ||
strncmp(argstr, INVERTY, strlen(INVERTY)) == 0) {
g->invertflag |= SF_INVERTY;
}
/* set MINHEIGHT to specified value if '-m' specified.
* It doesn't matter where the argument is exactly.
* Accepted values are from [0-5] */
const char *position = strstr(argstr, " " MINHEIGHT);
if ((position != nullptr) ||
strncmp(argstr, MINHEIGHT, strlen(MINHEIGHT)) == 0) {
int minheight = 0;
position += strlen(MINHEIGHT) + 1;
int size = strlen(argstr);
// Avoid whitespaces
while(*position == ' ' && position < argstr + size) {
position++;
}
// Get the numeric value start and end position
const char* numStart = position;
while (isdigit(*position)) {
position++;
}
// Convert the numeric value to an integer
std::string numStr(numStart, position);
if (!numStr.empty()) {
minheight = atoi(numStr.c_str());
}
// If specified value is greater than the max threshold
minheight = minheight > 5 ? 5 : minheight;
g->minheight = minheight;
}
/* all the following functions try to interpret the beginning of a
* a string with different format strings. If successful, they return from
* the function */
/* interpret the beginning(!) of the argument string as:
* '[height],[width] [color1] [color2] [scale]'
* This means parameters like -t and -l may not be in the beginning */
if (sscanf(argstr, "%d,%d %s %s %lf", &g->height, &g->width,
first_colour_name, last_colour_name, &g->scale) == 5) {
apply_graph_colours(g, first_colour_name, last_colour_name);
return true;
}
g->height = default_graph_height.get(*state);
g->width = default_graph_width.get(*state);
first_colour_name[0] = '\0';
last_colour_name[0] = '\0';
g->scale = defscale;
/* [height],[width] [color1] [color2]
* This could match as [height],[width] [scale] [-l | -t],
* therfore we ensure last_colour_name is not TEMPGRAD or LOGGRAPH */
if (sscanf(argstr, "%d,%d %s %s", &g->height, &g->width, first_colour_name,
last_colour_name) == 4 &&
strchr(last_colour_name,'-') == NULL) {
apply_graph_colours(g, first_colour_name, last_colour_name);
return true;
}
g->height = default_graph_height.get(*state);
g->width = default_graph_width.get(*state);
first_colour_name[0] = '\0';
last_colour_name[0] = '\0';
/* [height],[width] [scale] */
if (sscanf(argstr, "%d,%d %lf", &g->height, &g->width, &g->scale) == 3) {
return true;
}
g->height = default_graph_height.get(*state);
g->width = default_graph_width.get(*state);
g->scale = defscale;
/* [height],[width] */
if (sscanf(argstr, "%d,%d", &g->height, &g->width) == 2) { return true; }
g->height = default_graph_height.get(*state);
g->width = default_graph_width.get(*state);
/* [height], */
char comma;
if (sscanf(argstr, "%d%[,]", &g->height, &comma) == 2) { return true; }
g->height = default_graph_height.get(*state);
/* [color1] [color2] [scale] */
if (sscanf(argstr, "%s %s %lf", first_colour_name, last_colour_name,
&g->scale) == 3) {
apply_graph_colours(g, first_colour_name, last_colour_name);
return true;
}
first_colour_name[0] = '\0';
last_colour_name[0] = '\0';
g->scale = defscale;
/* [color1] [color2]
* This could match as [scale] [-l | -t],
* therfore we ensure last_colour_name is not TEMPGRAD or LOGGRAPH */
if (sscanf(argstr, "%s %s", first_colour_name, last_colour_name) == 2 &&
strchr(last_colour_name,'-') == NULL) {
apply_graph_colours(g, first_colour_name, last_colour_name);
return true;
}
first_colour_name[0] = '\0';
last_colour_name[0] = '\0';
/* [scale] */
if (sscanf(argstr, "%lf", &g->scale) == 1) { return true; }
return true;
}
#endif /* BUILD_GUI */
/*
* Printing various special text objects
*/
struct special_node *new_special_t_node() {
auto *newnode = new special_node;
memset(newnode, 0, sizeof *newnode);
return newnode;
}
/**
* expands the current global linked list specials to special_count elements
*
* increases special_count
* @param[out] buf is set to "\x01\x00" not sure why ???
* @param[in] t special type enum, e.g. alignc, alignr, fg, bg, ...
* @return pointer to the newly inserted special of type t
**/
struct special_node *new_special(char *buf, text_node_t t) {
special_node *current;
buf[0] = SPECIAL_CHAR;
buf[1] = '\0';
if (specials == nullptr) { specials = new_special_t_node(); }
current = specials;
/* allocate special_count linked list elements */
for (int i = 0; i < special_count; i++) {
if (current->next == nullptr) { current->next = new_special_t_node(); }
current = current->next;
}
current->type = t;
special_count++;
return current;
}
void new_gauge_in_shell(struct text_object *obj, char *p,
unsigned int p_max_size, double usage) {
static const char *gaugevals[] = {"_. ", "\\. ", " | ", " ./", " ._"};
auto *g = static_cast<struct gauge *>(obj->special_data);
snprintf(p, p_max_size, "%s",
gaugevals[round_to_positive_int(usage * 4 / g->scale)]);
}
#ifdef BUILD_GUI
void new_gauge_in_gui(struct text_object *obj, char *buf, double usage) {
struct special_node *s = nullptr;
auto *g = static_cast<struct gauge *>(obj->special_data);
if (display_output() == nullptr || !display_output()->graphical()) { return; }
if (g == nullptr) { return; }
s = new_special(buf, text_node_t::GAUGE);
s->arg = usage;
s->width = dpi_scale(g->width);
s->height = dpi_scale(g->height);
s->scale = g->scale;
}
#endif /* BUILD_GUI */
void new_gauge(struct text_object *obj, char *p, unsigned int p_max_size,
double usage) {
auto *g = static_cast<struct gauge *>(obj->special_data);
if ((p_max_size == 0) || (g == nullptr)) { return; }
if ((g->flags & SF_SCALED) != 0) {
g->scale = std::max(g->scale, usage);
} else {
usage = std::min(g->scale, usage);
}
#ifdef BUILD_GUI
if (display_output() && display_output()->graphical()) {
new_gauge_in_gui(obj, p, usage);
}
if (out_to_stdout.get(*state)) {
new_gauge_in_shell(obj, p, p_max_size, usage);
}
#else /* BUILD_GUI */
new_gauge_in_shell(obj, p, p_max_size, usage);
#endif /* BUILD_GUI */
}
#ifdef BUILD_GUI
void new_font(struct text_object *obj, char *p, unsigned int p_max_size) {
struct special_node *s;
unsigned int tmp = selected_font;
if (display_output() == nullptr || !display_output()->graphical()) { return; }
if (p_max_size == 0) { return; }
s = new_special(p, text_node_t::FONT);
if (obj->data.s != nullptr) {
if (s->font_added >= static_cast<int>(fonts.size()) ||
(s->font_added == 0) || obj->data.s != fonts[s->font_added].name) {
selected_font = s->font_added = add_font(obj->data.s);
selected_font = tmp;
}
} else {
selected_font = s->font_added = 0;
selected_font = tmp;
}
}
/**
* Adds value f to graph possibly truncating and scaling the graph
**/
static void graph_append(struct special_node *graph, double f, char showaslog) {
int i;
/* do nothing if we don't even have a graph yet */
if (graph->graph == nullptr) { return; }
if (showaslog != 0) {
#ifdef BUILD_MATH
f = log10(f + 1);
#endif
}
if ((graph->scaled == 0) && f > graph->scale) { f = graph->scale; }
/* shift all the data by 1 */
for (i = graph->graph_allocated - 1; i > 0; i--) {
graph->graph[i] = graph->graph[i - 1];
}
graph->graph[0] = f; /* add new data */
if (graph->scaled != 0) {
/* Get the location of the currentmax in the graph */
double* currentmax =
std::max_element(graph->graph + 0, graph->graph + graph->graph_width);
graph->scale = *currentmax;
if (graph->speedgraph) {
if(maxspeedval < graph->scale){
maxspeedval = graph->scale;
}
graph->scale = maxspeedval;
/* If the currentmax is the maxspeedval and
* currentmax location is at the last position
* Then we reset our maxspeedval */
if(*currentmax == maxspeedval && currentmax == (graph->graph + graph->width - 1)){
maxspeedval = 1e-47;
}
}
if (graph->scale < 1e-47) {
/* avoid NaN's when the graph is all-zero (e.g. before the first update)
* there is nothing magical about 1e-47 here */
graph->scale = 1e-47;
}
}
}
void new_graph_in_shell(struct special_node *s, char *buf, int buf_max_size) {
// Split config string on comma to avoid the hassle of dealing with the
// idiosyncrasies of multi-byte unicode on different platforms.
// TODO(brenden): Parse config string once and cache result.
const std::string ticks = console_graph_ticks.get(*state);
std::stringstream ss(ticks);
std::string tickitem;
std::vector<std::string> tickitems;
while (std::getline(ss, tickitem, ',')) { tickitems.push_back(tickitem); }
char *p = buf;
char *buf_max = buf + (sizeof(char) * buf_max_size);
double scale = (tickitems.size() - 1) / s->scale;
for (int i = s->graph_allocated - 1; i >= 0; i--) {
const unsigned int v = round_to_positive_int(s->graph[i] * scale);
const char *tick = tickitems[v].c_str();
size_t itemlen = tickitems[v].size();
for (unsigned int j = 0; j < itemlen; j++) {
*p++ = tick[j];
if (p == buf_max) { goto graph_buf_end; }
}
}
graph_buf_end:
*p = '\0';
}
double *copy_graph(double *original_graph, int graph_width) {
double *new_graph =
static_cast<double *>(malloc(graph_width * sizeof(double)));
memcpy(new_graph, original_graph, graph_width * sizeof(double));
return new_graph;
}
double *retrieve_graph(int graph_id, int graph_width) {
if (graphs.find(graph_id) == graphs.end()) {
return static_cast<double *>(calloc(1, graph_width * sizeof(double)));
} else {
return copy_graph(graphs[graph_id], graph_width);
}
}
void store_graph(int graph_id, struct special_node *s) {
if (s->graph == nullptr) {
graphs[graph_id] = nullptr;
} else {
if (graphs.find(graph_id) != graphs.end()) { free(graphs[graph_id]); }
graphs[graph_id] = s->graph;
}
}
/**
* Creates a visual graph and/or appends val to the graph / plot
*
* @param[in] obj struct containing all relevant flags like width, height, ...
* @param[in] buf buffer for ascii art graph in console
* @param[in] buf_max_size maximum length of buf
* @param[in] val value to plot i.e. to add to plot
**/
void new_graph(struct text_object *obj, char *buf, int buf_max_size,
double val) {
struct special_node *s = nullptr;
auto *g = static_cast<struct graph *>(obj->special_data);
if ((g == nullptr) || (buf_max_size == 0)) { return; }
s = new_special(buf, text_node_t::GRAPH);
/* set graph (special) width to width in obj */
s->width = dpi_scale(g->width);
if (s->width != 0) { s->graph_width = s->width; }
if (s->graph_width != s->graph_allocated) {
auto *graph = static_cast<double *>(
realloc(s->graph, s->graph_width * sizeof(double)));
DBGP("reallocing graph from %d to %d", s->graph_allocated, s->graph_width);
if (s->graph == nullptr) {
/* initialize */
std::fill_n(graph, s->graph_width, 0.0);
s->scale = 100;
} else if (graph != nullptr) {
if (s->graph_width > s->graph_allocated) {
/* initialize the new region */
std::fill(graph + s->graph_allocated, graph + s->graph_width, 0.0);
}
} else {
DBGP("reallocing FAILED");
graph = s->graph;
s->graph_width = s->graph_allocated;
}
s->graph = graph;
s->graph_allocated = s->graph_width;
graphs[g->id] = graph;
}
s->height = dpi_scale(g->height);
s->colours_set = g->colours_set;
s->first_colour = g->first_colour;
s->last_colour = g->last_colour;
if (g->scale != 0) {
s->scaled = 0;
s->scale = g->scale;
s->show_scale = 0;
} else {
s->scaled = 1;
s->scale = 1;
s->show_scale = 1;
}
s->tempgrad = g->tempgrad;
s->minheight = g->minheight;
#ifdef BUILD_MATH
if ((g->flags & SF_SHOWLOG) != 0) {
s->scale_log = 1;
s->scale = log10(s->scale + 1);
}
#endif
if ((g->invertflag & SF_INVERTX) != 0){
s->invertx = 1;
}
if ((g->invertflag & SF_INVERTY) != 0){
s->inverty = 1;
}
if (g->speedgraph) {
s->speedgraph = TRUE;
}
if (store_graph_data_explicitly.get(*state)) {
if (s->graph) { s->graph = retrieve_graph(g->id, s->graph_width); }
graph_append(s, val, g->flags);
store_graph(g->id, s);
} else {
graph_append(s, val, g->flags);
}
if (out_to_stdout.get(*state)) { new_graph_in_shell(s, buf, buf_max_size); }
}
void new_hr(struct text_object *obj, char *p, unsigned int p_max_size) {
if (display_output() == nullptr || !display_output()->graphical()) { return; }
if (p_max_size == 0) { return; }
new_special(p, text_node_t::HORIZONTAL_LINE)->height = dpi_scale(obj->data.l);
}
void scan_stippled_hr(struct text_object *obj, const char *arg) {
struct stippled_hr *sh;
sh = static_cast<struct stippled_hr *>(malloc(sizeof(struct stippled_hr)));
memset(sh, 0, sizeof(struct stippled_hr));
sh->arg = stippled_borders.get(*state);
sh->height = 1;
if (arg != nullptr) {
if (sscanf(arg, "%d %d", &sh->arg, &sh->height) != 2) {
sscanf(arg, "%d", &sh->height);
}
}
if (sh->arg <= 0) { sh->arg = 1; }
obj->special_data = sh;
}
void new_stippled_hr(struct text_object *obj, char *p,
unsigned int p_max_size) {
struct special_node *s = nullptr;
auto *sh = static_cast<struct stippled_hr *>(obj->special_data);
if (display_output() == nullptr || !display_output()->graphical()) { return; }
if ((sh == nullptr) || (p_max_size == 0)) { return; }
s = new_special(p, text_node_t::STIPPLED_HR);
s->height = dpi_scale(sh->height);
s->arg = dpi_scale(sh->arg);
}
#endif /* BUILD_GUI */
void new_fg(struct text_object *obj, char *p, unsigned int p_max_size) {
if (false
#ifdef BUILD_GUI
|| (display_output() && display_output()->graphical())
#endif /* BUILD_GUI */
#ifdef BUILD_NCURSES
|| out_to_ncurses.get(*state)
#endif /* BUILD_NCURSES */
) {
new_special(p, text_node_t::FG)->arg = obj->data.l;
}
UNUSED(obj);
UNUSED(p);
UNUSED(p_max_size);
}
#ifdef BUILD_GUI
void new_bg(struct text_object *obj, char *p, unsigned int p_max_size) {
if (display_output() == nullptr || !display_output()->graphical()) { return; }
if (p_max_size == 0) { return; }
new_special(p, text_node_t::BG)->arg = obj->data.l;
}
#endif /* BUILD_GUI */
static void new_bar_in_shell(struct text_object *obj, char *buffer,
unsigned int buf_max_size, double usage) {
auto *b = static_cast<struct bar *>(obj->special_data);
unsigned int width, i, scaledusage;
if (b == nullptr) { return; }
width = b->width;
if (width == 0) { width = DEFAULT_BAR_WIDTH_NO_X; }
if (width > buf_max_size) { width = buf_max_size; }
scaledusage = round_to_positive_int(usage * width / b->scale);
for (i = 0; i < scaledusage; i++) {
buffer[i] = *(bar_fill.get(*state).c_str());
}
for (; i < width; i++) { buffer[i] = *(bar_unfill.get(*state).c_str()); }
buffer[i] = 0;
}
#ifdef BUILD_GUI
static void new_bar_in_gui(struct text_object *obj, char *buf, double usage) {
struct special_node *s = nullptr;
auto *b = static_cast<struct bar *>(obj->special_data);
if (display_output() == nullptr || !display_output()->graphical()) { return; }
if (b == nullptr) { return; }
s = new_special(buf, text_node_t::BAR);
s->arg = usage;
s->width = dpi_scale(b->width);
s->height = dpi_scale(b->height);
s->scale = b->scale;
}
#endif /* BUILD_GUI */
/* usage is in range [0,255] */
void new_bar(struct text_object *obj, char *p, unsigned int p_max_size,
double usage) {
auto *b = static_cast<struct bar *>(obj->special_data);
if ((p_max_size == 0) || (b == nullptr)) { return; }
if ((b->flags & SF_SCALED) != 0) {
b->scale = std::max(b->scale, usage);
} else {
usage = std::min(b->scale, usage);
}
#ifdef BUILD_GUI
if (display_output() && display_output()->graphical()) {
new_bar_in_gui(obj, p, usage);
}
if (out_to_stdout.get(*state)) {
new_bar_in_shell(obj, p, p_max_size, usage);
}
#else /* BUILD_GUI */
new_bar_in_shell(obj, p, p_max_size, usage);
#endif /* BUILD_GUI */
}
void new_outline(struct text_object *obj, char *p, unsigned int p_max_size) {
if (p_max_size == 0) { return; }
new_special(p, text_node_t::OUTLINE)->arg = obj->data.l;
}
void new_offset(struct text_object *obj, char *p, unsigned int p_max_size) {
if (p_max_size == 0) { return; }
new_special(p, text_node_t::OFFSET)->arg = dpi_scale(obj->data.l);
}
void new_voffset(struct text_object *obj, char *p, unsigned int p_max_size) {
if (p_max_size == 0) { return; }
new_special(p, text_node_t::VOFFSET)->arg = dpi_scale(obj->data.l);
}
void new_save_coordinates(struct text_object *obj, char *p,
unsigned int p_max_size) {
if (p_max_size == 0) { return; }
new_special(p, text_node_t::SAVE_COORDINATES)->arg = obj->data.l;
}
void new_alignr(struct text_object *obj, char *p, unsigned int p_max_size) {
if (p_max_size == 0) { return; }
new_special(p, text_node_t::ALIGNR)->arg = dpi_scale(obj->data.l);
}
// A positive offset pushes the text further left
void new_alignc(struct text_object *obj, char *p, unsigned int p_max_size) {
if (p_max_size == 0) { return; }
new_special(p, text_node_t::ALIGNC)->arg = dpi_scale(obj->data.l);
}
void new_goto(struct text_object *obj, char *p, unsigned int p_max_size) {
if (p_max_size == 0) { return; }
new_special(p, text_node_t::GOTO)->arg = dpi_scale(obj->data.l);
}
void scan_tab(struct text_object *obj, const char *arg) {
struct tab *t;
t = static_cast<struct tab *>(malloc(sizeof(struct tab)));
memset(t, 0, sizeof(struct tab));
t->width = 10;
t->arg = 0;
if (arg != nullptr) {
if (sscanf(arg, "%d %d", &t->width, &t->arg) != 2) {
sscanf(arg, "%d", &t->arg);
}
}
if (t->width <= 0) { t->width = 1; }
obj->special_data = t;
}
void new_tab(struct text_object *obj, char *p, unsigned int p_max_size) {
struct special_node *s = nullptr;
auto *t = static_cast<struct tab *>(obj->special_data);
if ((t == nullptr) || (p_max_size == 0)) { return; }
s = new_special(p, text_node_t::TAB);
s->width = dpi_scale(t->width);
s->arg = dpi_scale(t->arg);
}
void clear_stored_graphs() {
graph_count = 0;
graphs.clear();
}
| 27,788
|
C++
|
.cc
| 776
| 32.090206
| 98
| 0.634672
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,624
|
sony.cc
|
brndnmtthws_conky/src/sony.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Please see COPYING for details
*
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* Copyright (c) 2009 Yeon-Hyeong Yang <lbird94@gmail.com>
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
/* conky support for information from sony_laptop kernel module
* information from sony_laptop kernel module
* /sys/devices/platform/sony-laptop
* I mimicked the methods from ibm.c
* Yeon-Hyeong Yang <lbird94@gmail.com> */
#include "sony.h"
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "config.h"
#include "conky.h"
#include "logging.h"
#include "text_object.h"
#define SONY_LAPTOP_DIR "/sys/devices/platform/sony-laptop"
/* fanspeed in SONY_LAPTOP_DIR contains an integer value for fanspeed (0~255).
* I don't know the exact measurement unit, though. I may assume that 0 for
* 'fan stopped' and 255 for 'maximum fan speed'. */
void get_sony_fanspeed(struct text_object *obj, char *p_client_buffer,
unsigned int client_buffer_size) {
FILE *fp;
unsigned int speed = 0;
char fan[128];
(void)obj;
if (!p_client_buffer || client_buffer_size <= 0) { return; }
snprintf(fan, 127, "%s/fanspeed", SONY_LAPTOP_DIR);
fp = fopen(fan, "r");
if (fp != nullptr) {
while (!feof(fp)) {
char line[256];
if (fgets(line, 255, fp) == nullptr) { break; }
if (sscanf(line, "%u", &speed)) { break; }
}
} else {
CRIT_ERR(
"can't open '%s': %s\nEnable sony support or remove "
"sony* from your " PACKAGE_NAME " config file.",
fan, strerror(errno));
}
fclose(fp);
snprintf(p_client_buffer, client_buffer_size, "%d", speed);
}
| 2,375
|
C++
|
.cc
| 66
| 32.878788
| 78
| 0.694348
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
22,625
|
tcp-portmon.cc
|
brndnmtthws_conky/src/tcp-portmon.cc
|
/*
*
* tcp-portmon.c - libtcp-portmon hooks
*
* Copyright (C) 2008 Phil Sutter <Phil@nwl.cc>
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "tcp-portmon.h"
#include "conky.h"
#include "libtcp-portmon.h"
#include "logging.h"
#include "text_object.h"
static tcp_port_monitor_collection_t *pmc = nullptr;
static conky::range_config_setting<int> max_port_monitor_connections(
"max_port_monitor_connections", 0, std::numeric_limits<int>::max(),
MAX_PORT_MONITOR_CONNECTIONS_DEFAULT, false);
int tcp_portmon_init(struct text_object *obj, const char *arg) {
int item = -1;
int argc;
int port_begin;
int port_end;
int connection_index;
char itembuf[32];
struct tcp_port_monitor_data *pmd;
memset(itembuf, 0, sizeof(itembuf));
connection_index = 0;
/* massive argument checking */
argc = sscanf(arg, "%d %d %31s %d", &port_begin, &port_end, itembuf,
&connection_index);
if ((argc != 3) && (argc != 4)) {
CRIT_ERR("tcp_portmon: requires 3 or 4 arguments");
}
if ((port_begin < 1) || (port_begin > 65535) || (port_end < 1) ||
(port_end > 65535)) {
CRIT_ERR("tcp_portmon: port values must be from 1 to 65535");
}
if (port_begin > port_end) {
CRIT_ERR("tcp_portmon: starting port must be <= ending port");
}
if (strncmp(itembuf, "count", 31) == EQUAL) {
item = COUNT;
} else if (strncmp(itembuf, "rip", 31) == EQUAL) {
item = REMOTEIP;
} else if (strncmp(itembuf, "rhost", 31) == EQUAL) {
item = REMOTEHOST;
} else if (strncmp(itembuf, "rport", 31) == EQUAL) {
item = REMOTEPORT;
} else if (strncmp(itembuf, "rservice", 31) == EQUAL) {
item = REMOTESERVICE;
} else if (strncmp(itembuf, "lip", 31) == EQUAL) {
item = LOCALIP;
} else if (strncmp(itembuf, "lhost", 31) == EQUAL) {
item = LOCALHOST;
} else if (strncmp(itembuf, "lport", 31) == EQUAL) {
item = LOCALPORT;
} else if (strncmp(itembuf, "lservice", 31) == EQUAL) {
item = LOCALSERVICE;
} else {
CRIT_ERR("tcp_portmon: invalid item specified");
}
if ((argc == 3) && (item != COUNT)) {
CRIT_ERR(
"tcp_portmon: 3 argument form valid only for \"count\" "
"item");
}
if ((argc == 4) && (connection_index < 0)) {
CRIT_ERR("tcp_portmon: connection index must be non-negative");
}
/* ok, args looks good. save the text object data */
pmd = (tcp_port_monitor_data *)malloc(sizeof(struct tcp_port_monitor_data));
memset(pmd, 0, sizeof(struct tcp_port_monitor_data));
pmd->port_range_begin = (in_port_t)port_begin;
pmd->port_range_end = (in_port_t)port_end;
pmd->item = item;
pmd->connection_index = connection_index;
obj->data.opaque = pmd;
/* if the port monitor collection hasn't been created,
* we must create it */
if (!pmc) {
pmc = create_tcp_port_monitor_collection();
if (!pmc) {
CRIT_ERR(
"tcp_portmon: unable to create port monitor "
"collection");
}
}
/* if a port monitor for this port does not exist,
* create one and add it to the collection */
if (find_tcp_port_monitor(pmc, port_begin, port_end) == nullptr) {
tcp_port_monitor_args_t pma;
memset(&pma, 0, sizeof pma);
pma.max_port_monitor_connections = max_port_monitor_connections.get(*state);
/* add the newly created monitor to the collection */
if (insert_new_tcp_port_monitor_into_collection(pmc, port_begin, port_end,
&pma) != 0) {
CRIT_ERR(
"tcp_portmon: unable to add port monitor to "
"collection");
}
}
return 0;
}
void tcp_portmon_action(struct text_object *obj, char *p,
unsigned int p_max_size) {
struct tcp_port_monitor_data *pmd = (tcp_port_monitor_data *)obj->data.opaque;
tcp_port_monitor_t *p_monitor;
if (!pmd) return;
/* grab a pointer to this port monitor */
p_monitor =
find_tcp_port_monitor(pmc, pmd->port_range_begin, pmd->port_range_end);
if (!p_monitor) {
snprintf(p, p_max_size, "%s", "monitor not found");
return;
}
/* now grab the text of interest */
if (peek_tcp_port_monitor(p_monitor, pmd->item, pmd->connection_index, p,
p_max_size) != 0) {
snprintf(p, p_max_size, "%s", "monitor peek error");
}
}
int tcp_portmon_update(void) {
update_tcp_port_monitor_collection(pmc);
return 0;
}
int tcp_portmon_clear(void) {
destroy_tcp_port_monitor_collection(pmc);
pmc = nullptr;
return 0;
}
void tcp_portmon_free(struct text_object *obj) {
free_and_zero(obj->data.opaque);
}
| 5,180
|
C++
|
.cc
| 144
| 31.631944
| 80
| 0.650468
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
22,638
|
macros.h
|
brndnmtthws_conky/3rdparty/Vc/Vc/sse/macros.h
|
/* This file is part of the Vc library. {{{
Copyright © 2009-2015 Matthias Kretz <kretz@kde.org>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the names of contributing organizations nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
}}}*/
#include "../common/macros.h"
#ifndef VC_SSE_MACROS_H_
#define VC_SSE_MACROS_H_
#if defined(Vc_IMPL_SSE4_1) && !defined(Vc_DISABLE_PTEST)
#define Vc_USE_PTEST
#endif
#endif // VC_SSE_MACROS_H_
| 1,759
|
C++
|
.h
| 30
| 56
| 79
| 0.793264
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,653
|
macros.h
|
brndnmtthws_conky/3rdparty/Vc/Vc/scalar/macros.h
|
/* This file is part of the Vc library. {{{
Copyright © 2009-2015 Matthias Kretz <kretz@kde.org>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the names of contributing organizations nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
}}}*/
#include "../common/macros.h"
#ifndef VC_SCALAR_MACROS_H_
#define VC_SCALAR_MACROS_H_
#endif // VC_SCALAR_MACROS_H_
| 1,681
|
C++
|
.h
| 27
| 59.481481
| 79
| 0.796723
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,659
|
limits.h
|
brndnmtthws_conky/3rdparty/Vc/Vc/scalar/limits.h
|
/* This file is part of the Vc library. {{{
Copyright © 2009-2015 Matthias Kretz <kretz@kde.org>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the names of contributing organizations nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
}}}*/
#ifndef VC_SCALAR_LIMITS_H_
#define VC_SCALAR_LIMITS_H_
#endif // VC_SCALAR_LIMITS_H_
| 1,651
|
C++
|
.h
| 26
| 60.653846
| 79
| 0.798641
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,697
|
support.h
|
brndnmtthws_conky/3rdparty/Vc/Vc/common/support.h
|
#ifndef VC_DEPRECATED_COMMON_SUPPORT_H_
#define VC_DEPRECATED_COMMON_SUPPORT_H_
#ifdef __GNUC__
#warning "the <Vc/common/support.h> header is deprecated. Use <Vc/support.h> instead."
#endif
#include <Vc/support.h>
#endif // VC_DEPRECATED_COMMON_SUPPORT_H_
| 256
|
C++
|
.h
| 7
| 35.571429
| 86
| 0.763052
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,701
|
fix_clang_emmintrin.h
|
brndnmtthws_conky/3rdparty/Vc/Vc/common/fix_clang_emmintrin.h
|
/*{{{
Copyright (C) 2013-2015 Matthias Kretz <kretz@kde.org>
Permission to use, copy, modify, and distribute this software
and its documentation for any purpose and without fee is hereby
granted, provided that the above copyright notice appear in all
copies and that both that the copyright notice and this
permission notice and warranty disclaimer appear in supporting
documentation, and that the name of the author not be used in
advertising or publicity pertaining to distribution of the
software without specific, written prior permission.
The author disclaim all warranties with regard to this
software, including all implied warranties of merchantability
and fitness. In no event shall the author be liable for any
special, indirect or consequential damages or any damages
whatsoever resulting from loss of use, data or profits, whether
in an action of contract, negligence or other tortious action,
arising out of or in connection with the use or performance of
this software.
}}}*/
#ifndef VC_COMMON_FIX_CLANG_EMMINTRIN_H_
#define VC_COMMON_FIX_CLANG_EMMINTRIN_H_
#include "../global.h"
#if (defined Vc_CLANG && Vc_CLANG < 0x30700) || (defined Vc_APPLECLANG && Vc_APPLECLANG < 0x70000)
#ifdef _mm_slli_si128
#undef _mm_slli_si128
#define _mm_slli_si128(a, count) __extension__ ({ \
(__m128i)__builtin_ia32_pslldqi128((__m128i)(a), (count)*8); })
#endif
#ifdef _mm_srli_si128
#undef _mm_srli_si128
#define _mm_srli_si128(a, count) __extension__ ({ \
(__m128i)__builtin_ia32_psrldqi128((__m128i)(a), (count)*8); })
#endif
#ifdef _mm_shuffle_epi32
#undef _mm_shuffle_epi32
#define _mm_shuffle_epi32(a, imm) __extension__ ({ \
(__m128i)__builtin_shufflevector((__v4si)(__m128i)(a), (__v4si) _mm_set1_epi32(0), \
(imm) & 0x3, ((imm) & 0xc) >> 2, \
((imm) & 0x30) >> 4, ((imm) & 0xc0) >> 6); })
#endif
#ifdef _mm_shufflelo_epi16
#undef _mm_shufflelo_epi16
#define _mm_shufflelo_epi16(a, imm) __extension__ ({ \
(__m128i)__builtin_shufflevector((__v8hi)(__m128i)(a), (__v8hi) _mm_set1_epi16(0), \
(imm) & 0x3, ((imm) & 0xc) >> 2, \
((imm) & 0x30) >> 4, ((imm) & 0xc0) >> 6, \
4, 5, 6, 7); })
#endif
#ifdef _mm_shufflehi_epi16
#undef _mm_shufflehi_epi16
#define _mm_shufflehi_epi16(a, imm) __extension__ ({ \
(__m128i)__builtin_shufflevector((__v8hi)(__m128i)(a), (__v8hi) _mm_set1_epi16(0), \
0, 1, 2, 3, \
4 + (((imm) & 0x03) >> 0), \
4 + (((imm) & 0x0c) >> 2), \
4 + (((imm) & 0x30) >> 4), \
4 + (((imm) & 0xc0) >> 6)); })
#endif
#ifdef _mm_shuffle_pd
#undef _mm_shuffle_pd
#define _mm_shuffle_pd(a, b, i) __extension__ ({ \
__builtin_shufflevector((__m128d)(a), (__m128d)(b), (i) & 1, (((i) & 2) >> 1) + 2); })
#endif
#endif // Vc_CLANG || Vc_APPLECLANG
#endif // VC_COMMON_FIX_CLANG_EMMINTRIN_H_
| 3,146
|
C++
|
.h
| 65
| 40.569231
| 98
| 0.593414
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,715
|
bitscanintrinsics.h
|
brndnmtthws_conky/3rdparty/Vc/Vc/common/bitscanintrinsics.h
|
/* This file is part of the Vc library. {{{
Copyright © 2011-2015 Matthias Kretz <kretz@kde.org>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the names of contributing organizations nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
}}}*/
#ifndef VC_COMMON_BITSCANINTRINSICS_H_
#define VC_COMMON_BITSCANINTRINSICS_H_
#if defined(Vc_GCC) || defined(Vc_CLANG) || defined(Vc_APPLECLANG)
#include <x86intrin.h>
# ifndef _bit_scan_forward
# define _bit_scan_forward(x) __builtin_ctz(x)
#include "macros.h"
static Vc_ALWAYS_INLINE Vc_CONST int _Vc_bit_scan_reverse_asm(unsigned int x) {
int r;
__asm__("bsr %1,%0" : "=r"(r) : "X"(x));
return r;
}
# define _bit_scan_reverse(x) _Vc_bit_scan_reverse_asm(x)
# endif
#elif defined(_WIN32)
#include <intrin.h>
static inline __forceinline unsigned long _bit_scan_forward(unsigned long x) {
unsigned long index;
_BitScanForward(&index, x);
return index;
}
static inline __forceinline unsigned long _bit_scan_reverse(unsigned long x) {
unsigned long index;
_BitScanReverse(&index, x);
return index;
}
#elif defined(Vc_ICC)
// for all I know ICC supports the _bit_scan_* intrinsics
#else
// just assume the compiler can do it
#endif
#endif // VC_COMMON_BITSCANINTRINSICS_H_
| 2,562
|
C++
|
.h
| 55
| 44.363636
| 79
| 0.7724
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,741
|
macros.h
|
brndnmtthws_conky/3rdparty/Vc/Vc/avx/macros.h
|
/* This file is part of the Vc library. {{{
Copyright © 2009-2015 Matthias Kretz <kretz@kde.org>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the names of contributing organizations nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
}}}*/
#include "../common/macros.h"
#ifndef VC_AVX_MACROS_H_
#define VC_AVX_MACROS_H_
#endif // VC_AVX_MACROS_H_
| 1,672
|
C++
|
.h
| 27
| 59.148148
| 79
| 0.795607
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,753
|
tolua_event.h
|
brndnmtthws_conky/3rdparty/toluapp/src/lib/tolua_event.h
|
/* tolua: event functions
** Support code for Lua bindings.
** Written by Waldemar Celes
** TeCGraf/PUC-Rio
** Apr 2003
** $Id: $
*/
/* This code is free software; you can redistribute it and/or modify it.
** The software provided hereunder is on an "as is" basis, and
** the author has no obligation to provide maintenance, support, updates,
** enhancements, or modifications.
*/
#ifndef TOLUA_EVENT_H
#define TOLUA_EVENT_H
#include "tolua++.h"
TOLUA_API void tolua_moduleevents (lua_State* L);
TOLUA_API int tolua_ismodulemetatable (lua_State* L);
TOLUA_API void tolua_classevents (lua_State* L);
#endif
| 611
|
C++
|
.h
| 19
| 30.894737
| 73
| 0.754685
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| true
| true
| false
| false
| false
| false
| false
| false
|
22,756
|
tvariable.h
|
brndnmtthws_conky/3rdparty/toluapp/src/tests/tvariable.h
|
typedef struct A A;
typedef struct B B;
typedef union U U;
struct A
{
int i;
float f;
double d;
char* s;
void* v;
char n[64];
};
union U
{
int i;
float f;
};
struct B
{
A a;
B* b;
};
extern int i;
extern float f;
extern double d;
extern char* s;
extern void* v;
extern char n[64];
extern A a;
extern B* b;
extern U u;
extern int mi;
extern float mf;
extern double md;
extern char* ms;
extern void* mv;
extern char mn[64];
extern A ma;
extern B* mb;
| 464
|
C++
|
.h
| 39
| 10.512821
| 19
| 0.714286
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,761
|
librsvg-helper.h
|
brndnmtthws_conky/lua/librsvg-helper.h
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Please see COPYING for details
*
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef _LIBRSVG_HELPER_H_
#define _LIBRSVG_HELPER_H_
#include <glib.h>
#include <librsvg/rsvg.h>
#include <stdlib.h>
RsvgDimensionData *rsvg_dimension_data_create(void) {
return (RsvgDimensionData *)calloc(1, sizeof(RsvgDimensionData));
}
void rsvg_dimension_data_destroy(RsvgDimensionData *pointer) {
if (pointer) { free(pointer); }
}
void rsvg_dimension_data_get(RsvgDimensionData *dd, int *width, int *height,
double *em, double *ex) {
if (dd) {
*width = dd->width;
*height = dd->height;
*em = dd->em;
*ex = dd->ex;
}
}
void rsvg_dimension_data_set(RsvgDimensionData *dd, int width, int height,
double em, double ex) {
if (dd) {
dd->width = width;
dd->height = height;
dd->em = em;
dd->ex = ex;
}
}
RsvgPositionData *rsvgPositionDataCreate(void) {
return (RsvgPositionData *)calloc(1, sizeof(RsvgPositionData));
}
void rsvgPositionDataGet(RsvgPositionData *pd, int *x, int *y) {
if (pd) {
*x = pd->x;
*y = pd->y;
}
}
RsvgHandle *rsvg_create_handle_from_file(const char *filename) {
GFile *gfile = g_file_new_for_path(filename);
GError *error = NULL;
RsvgHandle *handle = rsvg_handle_new_from_gfile_sync(
gfile, RSVG_HANDLE_FLAGS_NONE, NULL, &error);
if (error) {
g_object_unref(error);
if (handle) g_object_unref(handle);
handle = NULL;
}
g_object_unref(gfile);
return handle;
}
int rsvg_destroy_handle(RsvgHandle *handle) {
if (handle) { g_object_unref(handle); }
return 0;
}
RsvgRectangle *rsvg_rectangle_create(void) {
return (RsvgRectangle *)calloc(1, sizeof(RsvgRectangle));
}
void rsvg_rectangle_destroy(RsvgRectangle *rect) { free(rect); }
void rsvg_rectangle_set(RsvgRectangle *rect, double x, double y, double width,
double height) {
if (rect) {
rect->x = x;
rect->y = y;
rect->width = width;
rect->height = height;
}
}
void rsvg_rectangle_get(RsvgRectangle *rect, double *x, double *y,
double *width, double *height) {
if (rect) {
*x = rect->x;
*y = rect->y;
*width = rect->width;
*height = rect->height;
}
}
#endif /* _LIBRSVG_HELPER_H_ */
| 3,069
|
C++
|
.h
| 101
| 26.574257
| 78
| 0.674695
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,762
|
libcairo-helper.h
|
brndnmtthws_conky/lua/libcairo-helper.h
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Please see COPYING for details
*
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef _LIBCAIRO_HELPER_H_
#define _LIBCAIRO_HELPER_H_
#include <cairo.h>
#include <cstdlib>
cairo_text_extents_t *create_cairo_text_extents_t(void) {
return (cairo_text_extents_t *)calloc(1, sizeof(cairo_text_extents_t));
}
cairo_font_extents_t *create_cairo_font_extents_t(void) {
return (cairo_font_extents_t *)calloc(1, sizeof(cairo_font_extents_t));
}
cairo_matrix_t *create_cairo_matrix_t(void) {
return (cairo_matrix_t *)calloc(1, sizeof(cairo_matrix_t));
}
void destroy_cairo_text_extents_t(cairo_text_extents_t *pointer) {
free(pointer);
}
void destroy_cairo_font_extents_t(cairo_font_extents_t *pointer) {
free(pointer);
}
void destroy_cairo_matrix_t(cairo_matrix_t *pointer) { free(pointer); }
#endif /* _LIBCAIRO_HELPER_H_ */
| 1,610
|
C++
|
.h
| 44
| 34.659091
| 73
| 0.74438
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,763
|
libcairo_imlib2_helper.h
|
brndnmtthws_conky/lua/libcairo_imlib2_helper.h
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Please see COPYING for details
*
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef _LIBCAIRO_IMAGE_HELPER_H_
#define _LIBCAIRO_IMAGE_HELPER_H_
#include <Imlib2.h>
#include <cairo.h>
#include "logging.h"
void cairo_place_image(const char *file, cairo_t *cr, int x, int y,
int width, int height, double alpha) {
int w, h, stride;
Imlib_Image alpha_image, image, premul;
cairo_surface_t *result;
if (!file) {
NORM_ERR("cairoimagehelper: File is NULL\n");
return;
}
if (!cr) {
NORM_ERR("cairoimagehelper: cairo_t is NULL\n");
return;
}
image = (Imlib_Image *)imlib_load_image(file);
if (!image) {
NORM_ERR("cairoimagehelper: Couldn't load %s\n", file);
return;
}
imlib_context_set_image(image);
w = imlib_image_get_width();
h = imlib_image_get_height();
if ((w <= 0) && (h <= 0)) {
NORM_ERR("cairoimagehelper: %s has 0 size\n", file);
return;
}
/* create scaled version of image to later extract the alpha channel */
alpha_image = imlib_create_cropped_scaled_image(0, 0, w, h, width, height);
/* create temporary image */
premul = imlib_create_image(width, height);
if (!premul) {
NORM_ERR("cairoimagehelper: Couldn't create premul image for %s\n", file);
return;
}
/* fill with opaque black */
imlib_context_set_image(premul);
imlib_context_set_color(0, 0, 0, 255);
imlib_image_fill_rectangle(0, 0, width, height);
/* blend source image on top -
* in effect this multiplies the rgb values by alpha */
imlib_blend_image_onto_image(image, 0, 0, 0, w, h, 0, 0, width, height);
/* and use the alpha channel of the source image */
imlib_image_copy_alpha_to_image(alpha_image, 0, 0);
stride = cairo_format_stride_for_width (CAIRO_FORMAT_ARGB32, width);
/* now pass the result to cairo */
result = cairo_image_surface_create_for_data(
(unsigned char *)imlib_image_get_data_for_reading_only(), CAIRO_FORMAT_ARGB32,
width, height, stride);
cairo_set_source_surface(cr, result, x, y);
cairo_paint_with_alpha(cr, alpha);
imlib_context_set_image(alpha_image);
imlib_free_image();
imlib_context_set_image(image);
imlib_free_image();
imlib_context_set_image(premul);
imlib_free_image();
cairo_surface_destroy(result);
}
void cairo_draw_image(const char *file, cairo_surface_t *cs, int x, int y,
double scale_x, double scale_y, double *return_scale_w,
double *return_scale_h) {
cairo_t *cr;
int w, h;
double scaled_w, scaled_h;
if (!file) {
NORM_ERR("cairoimagehelper: File is NULL\n");
return;
}
if (!cs) {
NORM_ERR("cairoimagehelper: Surface is NULL\n");
return;
}
if ((scale_x <= 0.0) && (scale_y <= 0.0)) {
NORM_ERR("cairoimagehelper: Image Scale is 0, %s\n", file);
return;
}
Imlib_Image *image = (Imlib_Image *)imlib_load_image(file);
if (!image) {
NORM_ERR("cairoimagehelper: Couldn't load %s\n", file);
return;
}
imlib_context_set_image(image);
w = imlib_image_get_width();
h = imlib_image_get_height();
if ((w <= 0) && (h <= 0)) {
NORM_ERR("cairoimagehelper: %s has 0 size\n", file);
return;
}
scaled_w = *return_scale_w = scale_x * (double)w;
scaled_h = *return_scale_h = scale_y * (double)h;
if ((scaled_w <= 0.0) && (scaled_h <= 0.0)) {
NORM_ERR("cairoimagehelper: %s scaled image has 0 size\n", file);
return;
}
cr = cairo_create(cs);
cairo_place_image(file, cr, x, y, scaled_w, scaled_h, 1.0);
cairo_destroy(cr);
}
#endif /* _LIBCAIRO_IMAGE_HELPER_H_ */
| 4,360
|
C++
|
.h
| 126
| 30.793651
| 85
| 0.667539
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,765
|
libmpdclient.h
|
brndnmtthws_conky/src/libmpdclient.h
|
/*
*
* libmpdclient
* (c)2003-2006 by Warren Dukes (warren.dukes@gmail.com)
* This project's homepage is: http://www.musicpd.org
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Music Player Daemon nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
#ifndef LIBMPDCLIENT_H
#define LIBMPDCLIENT_H
#ifdef WIN32
#define __W32API_USE_DLLIMPORT__ 1
#endif
#include <stdarg.h>
#include <sys/time.h>
#define MPD_BUFFER_MAX_LENGTH 50000
#define MPD_ERRORSTR_MAX_LENGTH 1000
#define MPD_WELCOME_MESSAGE "OK MPD "
#define MPD_ERROR_TIMEOUT 10 /* timeout trying to talk to mpd */
#define MPD_ERROR_SYSTEM 11 /* system error */
#define MPD_ERROR_UNKHOST 12 /* unknown host */
#define MPD_ERROR_CONNPORT 13 /* problems connecting to port on host */
#define MPD_ERROR_NOTMPD 14 /* mpd not running on port at host */
#define MPD_ERROR_NORESPONSE 15 /* no response on attempting to connect */
#define MPD_ERROR_SENDING 16 /* error sending command */
#define MPD_ERROR_CONNCLOSED 17 /* connection closed by mpd */
#define MPD_ERROR_ACK 18 /* ACK returned! */
#define MPD_ERROR_BUFFEROVERRUN 19 /* Buffer was overrun! */
#define MPD_ACK_ERROR_UNK -1
#define MPD_ERROR_AT_UNK -1
#define MPD_ACK_ERROR_NOT_LIST 1
#define MPD_ACK_ERROR_ARG 2
#define MPD_ACK_ERROR_PASSWORD 3
#define MPD_ACK_ERROR_PERMISSION 4
#define MPD_ACK_ERROR_UNKNOWN_CMD 5
#define MPD_ACK_ERROR_NO_EXIST 50
#define MPD_ACK_ERROR_PLAYLIST_MAX 51
#define MPD_ACK_ERROR_SYSTEM 52
#define MPD_ACK_ERROR_PLAYLIST_LOAD 53
#define MPD_ACK_ERROR_UPDATE_ALREADY 54
#define MPD_ACK_ERROR_PLAYER_SYNC 55
#define MPD_ACK_ERROR_EXIST 56
typedef enum mpd_TagItems {
MPD_TAG_ITEM_ARTIST,
MPD_TAG_ITEM_ALBUMARTIST,
MPD_TAG_ITEM_ALBUM,
MPD_TAG_ITEM_TITLE,
MPD_TAG_ITEM_TRACK,
MPD_TAG_ITEM_NAME,
MPD_TAG_ITEM_GENRE,
MPD_TAG_ITEM_DATE,
MPD_TAG_ITEM_COMPOSER,
MPD_TAG_ITEM_PERFORMER,
MPD_TAG_ITEM_COMMENT,
MPD_TAG_ITEM_DISC,
MPD_TAG_ITEM_FILENAME,
MPD_TAG_ITEM_ANY,
MPD_TAG_NUM_OF_ITEM_TYPES
} mpd_TagItems;
extern const char *mpdTagItemKeys[MPD_TAG_NUM_OF_ITEM_TYPES];
/* internal stuff don't touch this struct */
typedef struct _mpd_ReturnElement {
char *name;
char *value;
} mpd_ReturnElement;
/* mpd_Connection
* holds info about connection to mpd
* use error, and errorStr to detect errors */
typedef struct _mpd_Connection {
/* use this to check the version of mpd */
int version[3];
/* IMPORTANT, you want to get the error messages from here */
char errorStr[MPD_ERRORSTR_MAX_LENGTH + 1];
int errorCode;
int errorAt;
/* this will be set to MPD_ERROR_* if there is an error, 0 if not */
int error;
/* DON'T TOUCH any of the rest of this stuff */
int sock;
char buffer[MPD_BUFFER_MAX_LENGTH + 1];
int buflen;
int bufstart;
int doneProcessing;
int listOks;
int doneListOk;
int commandList;
mpd_ReturnElement *returnElement;
struct timeval timeout;
char *request;
} mpd_Connection;
/* mpd_newConnection
* use this to open a new connection
* you should use mpd_closeConnection when you're done with the connection,
* even if an error has occurred
* _timeout_ is the connection timeout period in seconds */
mpd_Connection *mpd_newConnection(const char *host, int port, float timeout);
void mpd_setConnectionTimeout(mpd_Connection *connection, float timeout);
/* mpd_closeConnection
* use this to close a connection and free subsequent memory */
void mpd_closeConnection(mpd_Connection *connection);
/* mpd_clearError
* clears error */
void mpd_clearError(mpd_Connection *connection);
/* STATUS STUFF */
/* use these with status.state to determine what state the player is in */
#define MPD_STATUS_STATE_UNKNOWN 0
#define MPD_STATUS_STATE_STOP 1
#define MPD_STATUS_STATE_PLAY 2
#define MPD_STATUS_STATE_PAUSE 3
/* use this with status.volume to determine if mpd has volume support */
#define MPD_STATUS_NO_VOLUME -1
/* mpd_Status
* holds info return from status command */
typedef struct mpd_Status {
/* 0-100, or MPD_STATUS_NO_VOLUME when there is no volume support */
int volume;
/* 1 if repeat is on, 0 otherwise */
int repeat;
/* 1 if random is on, 0 otherwise */
int random;
/* playlist length */
int playlistLength;
/* playlist, use this to determine when the playlist has changed */
long long playlist;
/* use with MPD_STATUS_STATE_* to determine state of player */
int state;
/* crossfade setting in seconds */
int crossfade;
/* if a song is currently selected (always the case when state is PLAY
* or PAUSE), this is the position of the currently playing song in the
* playlist, beginning with 0 */
int song;
/* Song ID of the currently selected song */
int songid;
/* time in seconds that have elapsed in the currently playing/paused song */
int elapsedTime;
/* length in seconds of the currently playing/paused song */
int totalTime;
/* current bit rate in kbs */
int bitRate;
/* audio sample rate */
unsigned int sampleRate;
/* audio bits */
int bits;
/* audio channels */
int channels;
/* 1 if mpd is updating, 0 otherwise */
int updatingDb;
/* error */
char *error;
} mpd_Status;
void mpd_sendStatusCommand(mpd_Connection *connection);
/* mpd_getStatus
* returns status info, be sure to free it with mpd_freeStatus()
* call this after mpd_sendStatusCommand() */
mpd_Status *mpd_getStatus(mpd_Connection *connection);
/* mpd_freeStatus
* free's status info malloc'd and returned by mpd_getStatus */
void mpd_freeStatus(mpd_Status *status);
typedef struct _mpd_Stats {
int numberOfArtists;
int numberOfAlbums;
int numberOfSongs;
unsigned long uptime;
unsigned long dbUpdateTime;
unsigned long playTime;
unsigned long dbPlayTime;
} mpd_Stats;
typedef struct _mpd_SearchStats {
int numberOfSongs;
unsigned long playTime;
} mpd_SearchStats;
void mpd_sendStatsCommand(mpd_Connection *connection);
mpd_Stats *mpd_getStats(mpd_Connection *connection);
void mpd_freeStats(mpd_Stats *stats);
mpd_SearchStats *mpd_getSearchStats(mpd_Connection *connection);
void mpd_freeSearchStats(mpd_SearchStats *stats);
/* SONG STUFF */
#define MPD_SONG_NO_TIME -1
#define MPD_SONG_NO_NUM -1
#define MPD_SONG_NO_ID -1
/* mpd_Song
* for storing song info returned by mpd */
typedef struct _mpd_Song {
/* filename of song */
char *file;
/* artist, maybe nullptr if there is no tag */
char *artist;
/* albumartist, maybe nullptr if there is no tag */
char *albumartist;
/* title, maybe nullptr if there is no tag */
char *title;
/* album, maybe nullptr if there is no tag */
char *album;
/* track, maybe nullptr if there is no tag */
char *track;
/* name, maybe nullptr if there is no tag; it's the name of the current song,
* f.e. the icyName of the stream */
char *name;
/* date */
char *date;
/* added by qball */
/* Genre */
char *genre;
/* Composer */
char *composer;
/* Performer */
char *performer;
/* Disc */
char *disc;
/* Comment */
char *comment;
/* length of song in seconds, check that it is not MPD_SONG_NO_TIME */
int time;
/* if plchanges/playlistinfo/playlistid used, is the position of the song
* in the playlist */
int pos;
/* song id for a song in the playlist */
int id;
} mpd_Song;
/* mpd_newSong
* use to allocate memory for a new mpd_Song
* file, artist, etc all initialized to nullptr
* if you're going to assign values to file, artist, etc., be sure to
* malloc or strdup the memory
* use mpd_freeSong to free the memory for the mpd_Song, it will also
* free memory for file, artist, etc, so don't do it yourself */
mpd_Song *mpd_newSong(void);
/* mpd_freeSong
* use to free memory allocated by mpd_newSong
* also it will free memory pointed to by file, artist, etc, so be careful */
void mpd_freeSong(mpd_Song *song);
/* mpd_songDup
* works like strDup, but for a mpd_Song */
mpd_Song *mpd_songDup(mpd_Song *song);
/* DIRECTORY STUFF */
/* mpd_Directory
* used to store info from directory (right now just the path) */
typedef struct _mpd_Directory {
char *path;
} mpd_Directory;
/* mpd_newDirectory
* allocates memory for a new directory
* use mpd_freeDirectory to free this memory */
mpd_Directory *mpd_newDirectory(void);
/* mpd_freeDirectory
* used to free memory allocated with mpd_newDirectory, and it frees
* path of mpd_Directory, so be careful */
void mpd_freeDirectory(mpd_Directory *directory);
/* mpd_directoryDup
* works like strdup, but for mpd_Directory */
mpd_Directory *mpd_directoryDup(mpd_Directory *directory);
/* PLAYLISTFILE STUFF */
/* mpd_PlaylistFile
* stores info about playlist file returned by lsinfo */
typedef struct _mpd_PlaylistFile {
char *path;
} mpd_PlaylistFile;
/* mpd_newPlaylistFile
* allocates memory for new mpd_PlaylistFile, path is set to nullptr
* free this memory with mpd_freePlaylistFile */
mpd_PlaylistFile *mpd_newPlaylistFile(void);
/* mpd_freePlaylist
* free memory allocated for freePlaylistFile
* will also free path, so be careful */
void mpd_freePlaylistFile(mpd_PlaylistFile *playlist);
/* mpd_playlistFileDup
* works like strdup, but for mpd_PlaylistFile */
mpd_PlaylistFile *mpd_playlistFileDup(mpd_PlaylistFile *playlist);
/* INFO ENTITY STUFF */
/* the type of entity returned from one of the commands that generates info
* use in conjunction with mpd_InfoEntity.type */
#define MPD_INFO_ENTITY_TYPE_DIRECTORY 0
#define MPD_INFO_ENTITY_TYPE_SONG 1
#define MPD_INFO_ENTITY_TYPE_PLAYLISTFILE 2
/* mpd_InfoEntity
* stores info on stuff returned info commands */
typedef struct mpd_InfoEntity {
/* the type of entity, use with MPD_INFO_ENTITY_TYPE_* to determine
* what this entity is (song, directory, etc...) */
int type;
/* the actual data you want, mpd_Song, mpd_Directory, etc */
union {
mpd_Directory *directory;
mpd_Song *song;
mpd_PlaylistFile *playlistFile;
} info;
} mpd_InfoEntity;
mpd_InfoEntity *mpd_newInfoEntity(void);
void mpd_freeInfoEntity(mpd_InfoEntity *entity);
/* INFO COMMANDS AND STUFF */
/* use this function to loop over after calling Info/Listall functions */
mpd_InfoEntity *mpd_getNextInfoEntity(mpd_Connection *connection);
/* fetches the currently selected song (the song referenced by status->song
* and status->songid */
void mpd_sendCurrentSongCommand(mpd_Connection *connection);
/* songNum of -1, means to display the whole list */
void mpd_sendPlaylistInfoCommand(mpd_Connection *connection, int songPos);
/* songId of -1, means to display the whole list */
void mpd_sendPlaylistIdCommand(mpd_Connection *connection, int id);
/* use this to get the changes in the playlist since version _playlist_ */
void mpd_sendPlChangesCommand(mpd_Connection *connection, long long playlist);
/**
* @param connection: A valid and connected mpd_Connection.
* @param playlist: The playlist version you want the diff with.
*
* A more bandwidth efficient version of the mpd_sendPlChangesCommand.
* It only returns the pos+id of the changes song. */
void mpd_sendPlChangesPosIdCommand(mpd_Connection *connection,
long long playlist);
/* recursively fetches all songs/dir/playlists in "dir*
* (no metadata is returned) */
void mpd_sendListallCommand(mpd_Connection *connection, const char *dir);
/* same as sendListallCommand, but also metadata is returned */
void mpd_sendListallInfoCommand(mpd_Connection *connection, const char *dir);
/* non-recursive version of ListallInfo */
void mpd_sendLsInfoCommand(mpd_Connection *connection, const char *dir);
#define MPD_TABLE_ARTIST MPD_TAG_ITEM_ARTIST
#define MPD_TABLE_ALBUM MPD_TAG_ITEM_ALBUM
#define MPD_TABLE_TITLE MPD_TAG_ITEM_TITLE
#define MPD_TABLE_FILENAME MPD_TAG_ITEM_FILENAME
void mpd_sendSearchCommand(mpd_Connection *connection, int table,
const char *str);
void mpd_sendFindCommand(mpd_Connection *connection, int table,
const char *str);
/* LIST TAG COMMANDS */
/* use this function fetch next artist entry, be sure to free the
* returned string.
* nullptr means there are no more.
* Best used with sendListArtists */
char *mpd_getNextArtist(mpd_Connection *connection);
char *mpd_getNextAlbum(mpd_Connection *connection);
char *mpd_getNextTag(mpd_Connection *connection, int type);
/* list artist or albums by artist
* arg1 should be set to the artist if listing albums by a artist
* otherwise nullptr for listing all artists or albums */
void mpd_sendListCommand(mpd_Connection *connection, int table,
const char *arg1);
/* SIMPLE COMMANDS */
void mpd_sendAddCommand(mpd_Connection *connection, const char *file);
int mpd_sendAddIdCommand(mpd_Connection *connection, const char *file);
void mpd_sendDeleteCommand(mpd_Connection *connection, int songPos);
void mpd_sendDeleteIdCommand(mpd_Connection *connection, int id);
void mpd_sendSaveCommand(mpd_Connection *connection, const char *name);
void mpd_sendLoadCommand(mpd_Connection *connection, const char *name);
void mpd_sendRmCommand(mpd_Connection *connection, const char *name);
void mpd_sendRenameCommand(mpd_Connection *connection, const char *from,
const char *to);
void mpd_sendShuffleCommand(mpd_Connection *connection);
void mpd_sendClearCommand(mpd_Connection *connection);
/* use this to start playing at the beginning, useful when in random mode */
#define MPD_PLAY_AT_BEGINNING -1
void mpd_sendPlayCommand(mpd_Connection *connection, int songPos);
void mpd_sendPlayIdCommand(mpd_Connection *connection, int id);
void mpd_sendStopCommand(mpd_Connection *connection);
void mpd_sendPauseCommand(mpd_Connection *connection, int pauseMode);
void mpd_sendNextCommand(mpd_Connection *connection);
void mpd_sendPrevCommand(mpd_Connection *connection);
void mpd_sendMoveCommand(mpd_Connection *connection, int from, int to);
void mpd_sendMoveIdCommand(mpd_Connection *connection, int id, int to);
void mpd_sendSwapCommand(mpd_Connection *connection, int song1, int song2);
void mpd_sendSwapIdCommand(mpd_Connection *connection, int id1, int id2);
void mpd_sendSeekCommand(mpd_Connection *connection, int song, int seek_time);
void mpd_sendSeekIdCommand(mpd_Connection *connection, int id, int seek_time);
void mpd_sendRepeatCommand(mpd_Connection *connection, int repeatMode);
void mpd_sendRandomCommand(mpd_Connection *connection, int randomMode);
void mpd_sendSetvolCommand(mpd_Connection *connection, int volumeChange);
/* WARNING: don't use volume command, its deprecated */
void mpd_sendVolumeCommand(mpd_Connection *connection, int volumeChange);
void mpd_sendCrossfadeCommand(mpd_Connection *connection, int seconds);
void mpd_sendUpdateCommand(mpd_Connection *connection, char *path);
/* returns the update job id, call this after a update command */
int mpd_getUpdateId(mpd_Connection *connection);
void mpd_sendPasswordCommand(mpd_Connection *connection, const char *pass);
/* after executing a command, when you're done with it to get its status
* (you want to check connection->error for an error) */
void mpd_finishCommand(mpd_Connection *connection);
/* command list stuff, use this to do things like add files very quickly */
void mpd_sendCommandListBegin(mpd_Connection *connection);
void mpd_sendCommandListOkBegin(mpd_Connection *connection);
void mpd_sendCommandListEnd(mpd_Connection *connection);
/* advance to the next listOk
* returns 0 if advanced to the next list_OK,
* returns -1 if it advanced to an OK or ACK */
int mpd_nextListOkCommand(mpd_Connection *connection);
typedef struct _mpd_OutputEntity {
int id;
char *name;
int enabled;
} mpd_OutputEntity;
void mpd_sendOutputsCommand(mpd_Connection *connection);
mpd_OutputEntity *mpd_getNextOutput(mpd_Connection *connection);
void mpd_sendEnableOutputCommand(mpd_Connection *connection, int outputId);
void mpd_sendDisableOutputCommand(mpd_Connection *connection, int outputId);
void mpd_freeOutputElement(mpd_OutputEntity *output);
/**
* @param connection a #mpd_Connection
*
* Queries mpd for the allowed commands */
void mpd_sendCommandsCommand(mpd_Connection *connection);
/**
* @param connection a #mpd_Connection
*
* Queries mpd for the not allowed commands */
void mpd_sendNotCommandsCommand(mpd_Connection *connection);
/**
* @param connection a #mpd_Connection
*
* returns the next supported command.
*
* @returns a string, needs to be freed */
char *mpd_getNextCommand(mpd_Connection *connection);
void mpd_sendUrlHandlersCommand(mpd_Connection *connection);
char *mpd_getNextHandler(mpd_Connection *connection);
void mpd_sendTagTypesCommand(mpd_Connection *connection);
char *mpd_getNextTagType(mpd_Connection *connection);
/**
* @param connection a MpdConnection
* @param path the path to the playlist.
*
* List the content, with full metadata, of a stored playlist. */
void mpd_sendListPlaylistInfoCommand(mpd_Connection *connection, char *path);
/**
* @param connection a MpdConnection
* @param path the path to the playlist.
*
* List the content of a stored playlist. */
void mpd_sendListPlaylistCommand(mpd_Connection *connection, char *path);
/**
* @param connection a #mpd_Connection
* @param exact if to match exact
*
* starts a search
* use mpd_addConstraintSearch to add a constraint to the search
* use mpd_commitSearch to do the actual search */
void mpd_startSearch(mpd_Connection *connection, int exact);
/**
* @param connection a #mpd_Connection
* @param type
* @param name */
void mpd_addConstraintSearch(mpd_Connection *connection, int type,
const char *name);
/**
* @param connection a #mpd_Connection */
void mpd_commitSearch(mpd_Connection *connection);
/**
* @param connection a #mpd_Connection
* @param type The type to search for
*
* starts a search for fields... f.e. get a list of artists would be:
* @code
* mpd_startFieldSearch(connection, MPD_TAG_ITEM_ARTIST);
* mpd_commitSearch(connection);
* @endcode
*
* or get a list of artist in genre "jazz" would be:
* @code
* mpd_startFieldSearch(connection, MPD_TAG_ITEM_ARTIST);
* mpd_addConstraintSearch(connection, MPD_TAG_ITEM_GENRE, "jazz")
* mpd_commitSearch(connection);
* @endcode
*
* mpd_startSearch will return a list of songs
* (and you need mpd_getNextInfoEntity)
* this will return a list of only one field (the one specified with type)
* you need mpd_getNextTag to get the results */
void mpd_startFieldSearch(mpd_Connection *connection, int type);
void mpd_startPlaylistSearch(mpd_Connection *connection, int exact);
void mpd_startStatsSearch(mpd_Connection *connection);
void mpd_sendPlaylistClearCommand(mpd_Connection *connection, char *path);
void mpd_sendPlaylistAddCommand(mpd_Connection *connection, char *playlist,
char *path);
void mpd_sendPlaylistMoveCommand(mpd_Connection *connection, char *playlist,
int from, int to);
void mpd_sendPlaylistDeleteCommand(mpd_Connection *connection, char *playlist,
int pos);
#endif
| 20,469
|
C++
|
.h
| 501
| 38.249501
| 79
| 0.756037
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,766
|
conky.h
|
brndnmtthws_conky/src/conky.h
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef _conky_h_
#define _conky_h_
#define __STDC_FORMAT_MACROS
#include "config.h"
#include <arpa/inet.h>
#include <config.h> /* defines */
#include <sys/utsname.h> /* struct uname_s */
#include <csignal>
#include <filesystem>
#include <memory>
#include "colours.h"
#include "common.h" /* at least for struct dns_data */
#include "luamm.hh"
#if defined(HAS_MCHECK_H)
#include <mcheck.h>
#endif /* HAS_MCHECK_H */
#undef EQUAL
#undef FALSE
#undef TRUE
#define EQUAL 0 // returnvalue of strcmp-variants when strings are equal
#define FALSE 0
#define TRUE 1
#define DEFAULT_BAR_WIDTH_NO_X 10
#if !defined(__GNUC__)
#define __attribute__(x) /* nothing */
#endif
#ifndef HAVE_STRNDUP
// use our own strndup() if it's not available
char *strndup(const char *s, size_t n);
#endif /* HAVE_STRNDUP */
/* headers of optional features
* include them here, so we don't need to run the check
* in every code file optionally using the feature
*/
/* forward define to make gcc happy */
struct text_object;
#ifdef BUILD_HDDTEMP
#include "hddtemp.h"
#endif /* BUILD_HDDTEMP */
#ifdef BUILD_MOC
#include "moc.h"
#endif /* BUILD_MOC */
#ifdef BUILD_MPD
#include "mpd.h"
#endif /* BUILD_MPD */
#ifdef BUILD_MYSQL
#include "mysql.h"
#endif /* BUILD_MYSQL */
#ifdef BUILD_PORT_MONITORS
#include "tcp-portmon.h"
#endif
#ifdef BUILD_XMMS2
#include "xmms2.h"
#endif /* BUILD_XMMS2 */
#ifdef BUILD_APCUPSD
#include "apcupsd.h"
#endif /* BUILD_APCUPSD */
/* sony support */
#include "sony.h"
/* A size for temporary, static buffers to use when
* one doesn't know what to choose. Defaults to 256. */
extern conky::range_config_setting<unsigned int> text_buffer_size;
struct usr_info {
char *names;
char *times;
char *ctime;
char *terms;
int number;
};
#ifdef BUILD_X11
struct monitor_info {
int number;
int current;
};
struct desktop_info {
int current;
int number;
std::string all_names;
std::string name;
};
struct x11_info {
struct monitor_info monitor;
struct desktop_info desktop;
};
#endif /* BUILD_X11 */
struct conftree {
char *string;
struct conftree *horz_next;
struct conftree *vert_next;
struct conftree *back;
};
void load_config_file();
char *get_global_text(void);
extern long global_text_lines;
#define MAX_TEMPLATES 10
char **get_templates(void);
/* get_battery_stuff() item selector
* needed by conky.c, linux.c and freebsd.c */
enum { BATTERY_STATUS, BATTERY_TIME };
struct information {
unsigned int mask;
struct utsname uname_s;
#if defined(__DragonFly__)
char uname_v[256]; /* with git version */
#endif
char freq[10];
double uptime;
/* memory information in kilobytes */
unsigned long long mem, memwithbuffers, memavail, memeasyfree, memfree,
memmax, memdirty, shmem, legacymem, memactive, meminactive, memwired,
memlaundry;
unsigned long long swap, swapfree, swapmax;
unsigned long long bufmem, buffers, cached, free_bufcache, free_cached;
unsigned short procs;
unsigned short run_procs;
unsigned short threads;
unsigned short run_threads;
float *cpu_usage;
/* struct cpu_stat cpu_summed; what the hell is this? */
unsigned int cpu_count;
float loadavg[3];
#ifdef BUILD_XMMS2
struct xmms2_s xmms2;
#endif /* BUILD_XMMS2 */
struct usr_info users;
struct process *cpu[10];
struct process *memu[10];
struct process *time[10];
#ifdef BUILD_IOSTATS
struct process *io[10];
#endif /* BUILD_IOSTATS */
struct process *first_process;
unsigned long looped;
#ifdef BUILD_X11
struct x11_info x11;
#endif /* BUILD_X11 */
short kflags; /* kernel settings, see enum KFLAG */
#if defined(__APPLE__) && defined(__MACH__)
/* System Integrity Protection related */
struct csr_config_flags {
bool csr_allow_untrusted_kexts;
bool csr_allow_unrestricted_fs;
bool csr_allow_task_for_pid;
bool csr_allow_kernel_debugger;
bool csr_allow_apple_internal;
bool csr_allow_unrestricted_dtrace;
bool csr_allow_unrestricted_nvram;
bool csr_allow_device_configuration;
bool csr_allow_any_recovery_os;
bool csr_allow_user_approved_kexts;
};
/* SIP typedefs */
typedef csr_config_flags csr_config_flags_t;
typedef uint32_t csr_config_t;
/* SIP variables */
csr_config_t csr_config;
csr_config_flags_t csr_config_flags;
#endif /* defined(__APPLE__) && defined(__MACH__) */
};
class music_player_interval_setting
: public conky::simple_config_setting<double> {
typedef conky::simple_config_setting<double> Base;
protected:
virtual void lua_setter(lua::state &l, bool init);
public:
music_player_interval_setting() : Base("music_player_interval", 0, true) {}
};
extern music_player_interval_setting music_player_interval;
extern conky::range_config_setting<int> cpu_avg_samples;
extern conky::range_config_setting<int> net_avg_samples;
extern conky::range_config_setting<int> diskio_avg_samples;
/* needed by linux.c and top.c -> outsource somewhere */
enum {
/* set to true if kernel uses "long" format for /proc/stats */
KFLAG_IS_LONGSTAT = 0x01,
/* set to true if kernel shows # of threads for the proc value
* in sysinfo() call */
KFLAG_PROC_IS_THREADS = 0x02
/* bits 0x04, 0x08, 0x10, 0x20, 0x40, 0x80 available for future use */
/* KFLAG_NEXT_ONE = 0x04 */
};
#define KFLAG_SETON(a) info.kflags |= a
#define KFLAG_SETOFF(a) info.kflags &= (~a)
#define KFLAG_FLIP(a) info.kflags ^= a
#define KFLAG_ISSET(a) info.kflags &a
#if !defined(MAX)
#define MAX(x, y) \
({ \
__typeof__(x) _x = (x); \
__typeof__(y) _y = (y); \
_x > _y ? _x : _y; \
})
#endif
#if !defined(MIN)
#define MIN(x, y) \
({ \
__typeof__(x) _x = (x); \
__typeof__(y) _y = (y); \
_x < _y ? _x : _y; \
})
#endif
/* defined in conky.c, needed by top.c */
extern int top_cpu, top_mem, top_time;
#ifdef BUILD_IOSTATS
extern int top_io;
#endif /* BUILD_IOSTATS */
extern int top_running;
/* struct that has all info to be shared between
* instances of the same text object */
extern struct information info;
/* defined in conky.c */
extern double current_update_time, last_update_time;
extern conky::range_config_setting<double> update_interval;
extern conky::range_config_setting<double> update_interval_on_battery;
double active_update_interval();
extern conky::simple_config_setting<bool> show_graph_scale;
extern conky::simple_config_setting<bool> show_graph_range;
extern conky::simple_config_setting<int> gap_x;
extern conky::simple_config_setting<int> gap_y;
extern conky::simple_config_setting<bool> draw_borders;
extern conky::simple_config_setting<bool> draw_graph_borders;
extern conky::range_config_setting<char> stippled_borders;
extern conky::simple_config_setting<bool> draw_shades;
extern conky::simple_config_setting<bool> draw_outline;
void set_current_text_color(Colour colour);
Colour get_current_text_color(void);
void set_updatereset(int);
int get_updatereset(void);
int get_total_updates(void);
/* defined in conky.c */
int spaced_print(char *, int, const char *, int, ...)
__attribute__((format(printf, 3, 5)));
extern int inotify_fd;
/* defined in conky.c
* evaluates 'text' and places the result in 'p' of max length 'p_max_size'
*/
void evaluate(const char *text, char *p, int p_max_size);
void parse_conky_vars(struct text_object *, const char *, char *, int);
void extract_object_args_to_sub(struct text_object *, const char *);
void generate_text_internal(char *, int, struct text_object);
void update_text_area();
void draw_stuff();
int percent_print(char *, int, unsigned);
void human_readable(long long, char *, int);
#ifdef BUILD_GUI
/* UTF-8 */
extern conky::simple_config_setting<bool> utf8_mode;
#endif
/* maximum size of config TEXT buffer, i.e. below TEXT line. */
extern conky::range_config_setting<unsigned int> max_user_text;
/* path to config file */
extern std::filesystem::path current_config;
#define DEFAULT_TEXT_BUFFER_SIZE_S "##DEFAULT_TEXT_BUFFER_SIZE"
#define NOBATTERY 0
/* to get rid of 'unused variable' warnings */
#define UNUSED(a) (void)a
#define UNUSED_ATTR __attribute__((unused))
template <class T>
void free_and_zero(T *&ptr) {
if (ptr) {
free(ptr);
ptr = nullptr;
}
}
template <class T>
void delete_block_and_zero(T *&ptr) {
if (ptr) {
delete[] ptr;
ptr = nullptr;
}
}
extern std::unique_ptr<lua::state> state;
extern conky::simple_config_setting<bool> out_to_stdout;
void setup_inotify();
void initialisation(int argc, char **argv);
void set_current_config();
void main_loop();
extern volatile sig_atomic_t g_sigterm_pending, g_sighup_pending,
g_sigusr2_pending;
extern int first_pass;
extern int argc_copy;
extern char **argv_copy;
extern const char *getopt_string;
extern const struct option longopts[];
extern conky::simple_config_setting<bool> out_to_stdout;
extern conky::simple_config_setting<bool> out_to_stderr;
#endif /* _conky_h_ */
| 10,006
|
C++
|
.h
| 315
| 29.6
| 77
| 0.722419
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,767
|
algebra.h
|
brndnmtthws_conky/src/algebra.h
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef _ALGEBRA_H
#define _ALGEBRA_H
enum match_type {
OP_LT = 1, /* < */
OP_GT = 2, /* > */
OP_EQ = 3, /* == */
OP_LEQ = 4, /* <= */
OP_GEQ = 5, /* >= */
OP_NEQ = 6 /* != */
};
enum arg_type {
ARG_BAD = 0, /* something strange */
ARG_STRING = 1, /* "asdf" */
ARG_LONG = 2, /* 123456 */
ARG_DOUBLE = 3 /* 12.456 */
};
int compare(const char *);
int check_if_match(struct text_object *);
int get_match_type(const char *expr);
int find_match_op(const char *expr);
#endif /* _ALGEBRA_H */
| 1,574
|
C++
|
.h
| 49
| 30.081633
| 72
| 0.684418
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,768
|
scroll.h
|
brndnmtthws_conky/src/scroll.h
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef _SCROLL_H
#define _SCROLL_H
void parse_scroll_arg(struct text_object *, const char *, void *, char *);
void print_scroll(struct text_object *, char *, unsigned int);
void free_scroll(struct text_object *);
#endif /* _SCROLL_H */
| 1,292
|
C++
|
.h
| 34
| 36.147059
| 74
| 0.746019
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,769
|
display-x11.hh
|
brndnmtthws_conky/src/display-x11.hh
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Please see COPYING for details
*
* Copyright (C) 2018-2021 François Revol et al.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef DISPLAY_X11_HH
#define DISPLAY_X11_HH
#include "config.h"
#include <limits>
#include <string>
#include <type_traits>
#include "display-output.hh"
#include "luamm.hh"
namespace conky {
/*
* A base class for X11 display output.
*/
class display_output_x11 : public display_output_base {
public:
explicit display_output_x11();
virtual ~display_output_x11() {}
// check if available and enabled in settings
virtual bool detect();
// connect to DISPLAY and other stuff
virtual bool initialize();
virtual bool shutdown();
virtual bool main_loop_wait(double);
virtual void sigterm_cleanup();
virtual void cleanup();
// drawing primitives
virtual void set_foreground_color(Colour);
virtual int calc_text_width(const char *);
// GUI interface
virtual void draw_string_at(int, int, const char *, int);
// X11 lookalikes
virtual void set_line_style(int, bool);
virtual void set_dashes(char *);
virtual void draw_line(int, int, int, int);
virtual void draw_rect(int, int, int, int);
virtual void fill_rect(int, int, int, int);
virtual void draw_arc(int, int, int, int, int, int);
virtual void move_win(int, int);
virtual float get_dpi_scale();
virtual void end_draw_stuff();
virtual void clear_text(int);
virtual int font_height(unsigned int);
virtual int font_ascent(unsigned int);
virtual int font_descent(unsigned int);
virtual void setup_fonts(void);
virtual void set_font(unsigned int);
virtual void free_fonts(bool);
virtual void load_fonts(bool);
// X11-specific
};
} // namespace conky
#endif /* DISPLAY_X11_HH */
| 2,401
|
C++
|
.h
| 72
| 30.833333
| 72
| 0.738209
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,770
|
mysql.h
|
brndnmtthws_conky/src/mysql.h
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Please see COPYING for details
*
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef MYSQL_H_
#define MYSQL_H_
void print_mysql(struct text_object *, char *, unsigned int);
#endif /*MYSQL_H_*/
| 971
|
C++
|
.h
| 27
| 34.037037
| 72
| 0.743889
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,771
|
colours.h
|
brndnmtthws_conky/src/colours.h
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef _COLOURS_H_
#define _COLOURS_H_
#include "config.h"
#include <cassert>
#include <climits>
#include <memory>
#include <string>
#include <unordered_map>
#ifdef BUILD_X11
#include <X11/Xlib.h>
#endif /* BUILD_X11 */
struct Colour {
uint8_t red;
uint8_t green;
uint8_t blue;
uint8_t alpha = 0xff;
public:
Colour() = default;
Colour(uint8_t r, uint8_t g, uint8_t b, uint8_t a = UINT8_MAX)
: red(r), green(g), blue(b), alpha(a) {}
explicit Colour(const std::string &name);
Colour(const Colour &) = default;
Colour(Colour &&) = default;
void operator=(const Colour &c) {
red = c.red;
green = c.green;
blue = c.blue;
alpha = c.alpha;
}
// Compare two instances.
bool operator==(const Colour &c) const {
return c.red == red && c.green == green && c.blue == blue &&
c.alpha == alpha;
}
uint8_t *data() { return reinterpret_cast<uint8_t *>(this); }
// Express the color as a 32-bit ARGB integer (alpha in MSB).
uint32_t to_argb32(void) const {
uint32_t out;
out = alpha << 24 | red << 16 | green << 8 | blue;
return out;
}
// Construct from a 32-bit ARGB integer (alpha in MSB).
static Colour from_argb32(uint32_t argb);
class Hash {
public:
size_t operator()(const Colour &c) const { return c.to_argb32(); }
};
#ifdef BUILD_X11
unsigned long to_x11_color(Display *display, int screen,
bool transparency = false,
bool premultiply = false);
#endif /* BUILD_X11 */
};
const Colour ERROR_COLOUR = Colour{UINT8_MAX, 0, 0, UINT8_MAX};
Colour parse_color(const std::string &color);
#endif /* _COLOURS_H_ */
| 2,728
|
C++
|
.h
| 84
| 29.047619
| 72
| 0.680365
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,772
|
journal.h
|
brndnmtthws_conky/src/journal.h
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef _JOURNAL_H
#define _JOURNAL_H
void free_journal(struct text_object *);
void init_journal(const char *, const char *, struct text_object *, void *);
void print_journal(struct text_object *, char *, unsigned int);
#endif /* _JOURNAL_H */
| 1,300
|
C++
|
.h
| 34
| 36.352941
| 76
| 0.747427
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,773
|
x11-settings.h
|
brndnmtthws_conky/src/x11-settings.h
|
#ifndef CONKY_X11_SETTINGS_H
#define CONKY_X11_SETTINGS_H
#include "setting.hh"
extern conky::simple_config_setting<std::string> display_name;
namespace priv {
class out_to_x_setting : public conky::simple_config_setting<bool> {
typedef conky::simple_config_setting<bool> Base;
protected:
virtual void lua_setter(lua::state &l, bool init);
virtual void cleanup(lua::state &l);
public:
out_to_x_setting() : Base("out_to_x", true, false) {}
};
#ifdef BUILD_XDBE
class use_xdbe_setting : public conky::simple_config_setting<bool> {
typedef conky::simple_config_setting<bool> Base;
bool set_up(lua::state &l);
protected:
virtual void lua_setter(lua::state &l, bool init);
public:
use_xdbe_setting() : Base("double_buffer", false, false) {}
};
#else
class use_xpmdb_setting : public conky::simple_config_setting<bool> {
typedef conky::simple_config_setting<bool> Base;
bool set_up(lua::state &l);
protected:
virtual void lua_setter(lua::state &l, bool init);
public:
use_xpmdb_setting() : Base("double_buffer", false, false) {}
};
#endif
} /* namespace priv */
extern priv::out_to_x_setting out_to_x;
#ifdef BUILD_XFT
extern conky::simple_config_setting<bool> use_xft;
#endif
#ifdef BUILD_XDBE
extern priv::use_xdbe_setting use_xdbe;
#else
extern priv::use_xpmdb_setting use_xpmdb;
#endif
#endif /* CONKY_X11_SETTINGS_H */
| 1,365
|
C++
|
.h
| 43
| 29.651163
| 69
| 0.739464
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,774
|
combine.h
|
brndnmtthws_conky/src/combine.h
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef _COMBINE_H
#define _COMBINE_H
void parse_combine_arg(struct text_object *, const char *);
void print_combine(struct text_object *, char *, unsigned int);
void free_combine(struct text_object *);
#endif /* _COMBINE_H */
| 1,282
|
C++
|
.h
| 34
| 35.852941
| 72
| 0.750401
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,775
|
colour-settings.h
|
brndnmtthws_conky/src/colour-settings.h
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Please see COPYING for details
*
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#pragma once
#include "colours.h"
#include "config.h"
#include "setting.hh"
namespace priv {
struct colour_traits {
static const lua::Type type = lua::TSTRING;
typedef Colour Type;
static inline std::pair<Type, bool> convert(lua::state &l, int index,
const std::string &) {
return {parse_color(l.tostring(index)), true};
}
};
class colour_setting
: public conky::simple_config_setting<Colour, colour_traits> {
typedef conky::simple_config_setting<Colour, colour_traits> Base;
protected:
virtual void lua_setter(lua::state &l, bool init);
public:
colour_setting(const std::string &name_, unsigned long default_value_ = 0)
: Base(name_, Colour::from_argb32(default_value_), true) {}
};
} // namespace priv
#define COLORS_CUSTOM 10
extern priv::colour_setting color[COLORS_CUSTOM];
extern priv::colour_setting default_color;
const unsigned long white_argb32 = 0xffffffff;
const unsigned long black_argb32 = 0xff000000;
| 1,854
|
C++
|
.h
| 51
| 33.254902
| 76
| 0.727425
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,776
|
text_object.h
|
brndnmtthws_conky/src/text_object.h
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef _TEXT_OBJECT_H
#define _TEXT_OBJECT_H
#include "config.h"
#include "exec.h"
#include "specials.h" /* enum special_types */
#include <cstdint> /* uint8_t */
enum class draw_mode_t : uint32_t {
BG = static_cast<uint32_t>(text_node_t::BG),
FG = static_cast<uint32_t>(text_node_t::FG),
OUTLINE = static_cast<uint32_t>(text_node_t::OUTLINE),
};
/* text object callbacks */
struct obj_cb {
/* text object: print obj's output to p */
void (*print)(struct text_object *obj, char *p, unsigned int p_max_size);
/* ifblock object: return zero to trigger jumping */
int (*iftest)(struct text_object *obj);
/* meter objects:
* The following functions return the current meter-type value
* in a range between 0 and the value passed to the appropriate
* scan_* function. Or, if named function has been called with
* a value of 0, make use of auto-scaling (i.e., scaling to the
* maximum value seen so far). */
double (*barval)(struct text_object *obj);
double (*gaugeval)(struct text_object *obj);
double (*graphval)(struct text_object *obj);
/* percentage object: return value in range [0, 100] */
uint8_t (*percentage)(struct text_object *obj);
/* free obj's data */
void (*free)(struct text_object *obj);
};
/* generic free opaque callback
* can be used to simply free obj->data.opaque or obj->data.s */
void gen_free_opaque(struct text_object *);
/* generic iftest returning false (i.e. trigger jumping)
* used for the else object */
int gen_false_iftest(struct text_object *);
/* generic nothing printer callback printing nothing
* used for the endif object */
void gen_print_nothing(struct text_object *, char *, unsigned int);
/* generic obj->data.s printer
* used by the $text object */
void gen_print_obj_data_s(struct text_object *, char *, unsigned int);
class legacy_cb : public conky::callback<void *, int (*)()> {
typedef conky::callback<void *, int (*)()> Base;
protected:
virtual void work() { std::get<0>(tuple)(); }
public:
legacy_cb(uint32_t period, int (*fn)())
: Base(period, true, Base::Tuple(fn)) {}
};
typedef conky::callback_handle<legacy_cb> legacy_cb_handle;
typedef conky::callback_handle<exec_cb> exec_cb_handle;
/**
* This is where Conky collects information on the conky.text objects in your
* config
*
* During startup and reload, objects are parsed and callbacks are set. Note
* that there are currently two types of callback: obj_cb (old style) and
* conky::callback (new style). On each update interval,
* generate_text_internal() in conky.cc traverses the list of text_objects and
* calls the old callbacks. The new style callbacks are run separately by
* conky::run_all_callbacks().
*/
struct text_object {
struct text_object *next, *prev; /* doubly linked list of text objects */
struct text_object *sub; /* for objects parsing text into objects */
struct text_object *ifblock_next; /* jump target for ifblock objects */
union {
void *opaque; /* new style generic per object data */
char *s; /* some string */
int i; /* some integer */
int64_t l; /* some long integer */
} data;
void *special_data;
long line;
bool parse; /* if true then data.s should still be parsed */
bool thread; /* if true then data.s should be set by a separate thread */
struct obj_cb callbacks;
/* Each _cb_handle is a std::shared_ptr with very tight restrictions on
* construction. For now, it is necessary to store them here as regular
* pointers so we can instantiate them later. */
exec_cb_handle *exec_handle;
legacy_cb_handle *cb_handle;
};
/* text object list helpers */
int append_object(struct text_object *root, struct text_object *obj);
/* ifblock helpers
*
* Opaque is a pointer to the address of the ifblock stack's top object.
* Calling clients should pass the address of a defined void pointer which
* was initialised to nullptr (empty stack).
* */
int obj_be_ifblock_if(void **opaque, struct text_object *);
int obj_be_ifblock_else(void **opaque, struct text_object *);
int obj_be_ifblock_endif(void **opaque, struct text_object *);
int ifblock_stack_empty(void **opaque);
/* make the given object be a plain text object printing given string */
void obj_be_plain_text(struct text_object *, const char *);
#endif /* _TEXT_OBJECT_H */
| 5,387
|
C++
|
.h
| 128
| 39.6875
| 79
| 0.717562
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,777
|
fonts.h
|
brndnmtthws_conky/src/fonts.h
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef _FONTS_H
#define _FONTS_H
#include <vector>
#include "conky.h"
/* for fonts */
struct font_list {
std::string name;
font_list() : name() {}
};
/* direct access to registered fonts (FIXME: bad encapsulation) */
extern std::vector<font_list> fonts;
extern unsigned int selected_font;
int font_height();
int font_ascent();
int font_descent();
void setup_fonts(void);
void set_font(void);
int add_font(const char *);
void free_fonts(bool utf8);
void load_fonts(bool utf8);
class font_setting : public conky::simple_config_setting<std::string> {
typedef conky::simple_config_setting<std::string> Base;
protected:
virtual void lua_setter(lua::state &l, bool init);
public:
font_setting() : Base("font", "6x10", false) {}
};
extern font_setting font;
extern conky::simple_config_setting<std::string> font_template[10];
#endif /* _FONTS_H */
| 1,919
|
C++
|
.h
| 58
| 31.206897
| 72
| 0.743104
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,778
|
intel_backlight.h
|
brndnmtthws_conky/src/intel_backlight.h
|
/*
*
* Conky, a system monitor, based on torsmo.
*
* Any original torsmo code is licensed under the BSD license.
* All code written since the fork of torsmo is licensed under the GPL.
* Please see COPYING for details.
*
* Copyright (c) 2021 Rogier Reerink
* (See AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
#ifndef _INTEL_BACKLIGHT_H
#define _INTEL_BACKLIGHT_H
#include "conky.h"
#include "text_object.h"
void init_intel_backlight(struct text_object *obj);
void free_intel_backlight(struct text_object *obj);
void print_intel_backlight(struct text_object *obj, char *p,
unsigned int p_max_size);
#endif /* _INTEL_BACKLIGHT_H */
| 1,314
|
C++
|
.h
| 35
| 34.971429
| 73
| 0.739812
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,779
|
misc.h
|
brndnmtthws_conky/src/misc.h
|
/* -*- mode: c++; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: t -*-
* vim: ts=4 sw=4 noet ai cindent syntax=cpp
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2012 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef _MISC_H
#define _MISC_H
#include "text_object.h"
void print_cat(struct text_object *, char *, unsigned int);
void print_catp(struct text_object *, char *, unsigned int);
void print_startcase(struct text_object *, char *, unsigned int);
void print_lowercase(struct text_object *, char *, unsigned int);
void print_uppercase(struct text_object *, char *, unsigned int);
void strip_trailing_whitespace(struct text_object *, char *, unsigned int);
long long apply_base_multiplier(const char *, long long int);
#endif /* _MISC_H */
| 1,710
|
C++
|
.h
| 40
| 40.975
| 75
| 0.740252
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,780
|
semaphore.hh
|
brndnmtthws_conky/src/semaphore.hh
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Please see COPYING for details
*
* Copyright (C) 2010 Pavel Labath et al.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef SEMAPHORE_HH
#define SEMAPHORE_HH
#include <cerrno>
#include <cstdlib>
#include <cstring>
#include <stdexcept>
#if defined(__APPLE__) && defined(__MACH__)
/*
* On Darwin, unnamed semaphores are not supported!
* The only close equivalent to unnamed semaphores is using
* GCD!
*/
#include <dispatch/dispatch.h>
class semaphore {
dispatch_semaphore_t sem;
semaphore(const semaphore &) = delete;
semaphore &operator=(const semaphore &) = delete;
public:
explicit semaphore(unsigned int value = 0) {
sem = dispatch_semaphore_create(value);
if (!sem) throw std::logic_error(strerror(errno));
}
~semaphore() { dispatch_release(sem); }
void post() { dispatch_semaphore_signal(sem); }
void wait() { dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER); }
bool trywait() {
/* XXX Quick patch */
#define DISPATCH_EAGAIN 49
int ret = dispatch_semaphore_wait(sem, DISPATCH_TIME_NOW);
while (ret > 0) {
if (ret == DISPATCH_EAGAIN) {
return false;
} else if (errno != EINTR) {
abort();
}
}
return true;
}
};
#else
#include <semaphore.h>
class semaphore {
sem_t sem;
semaphore(const semaphore &) = delete;
semaphore &operator=(const semaphore &) = delete;
public:
semaphore(unsigned int value = 0) {
if (sem_init(&sem, 0, value)) throw std::logic_error(strerror(errno));
}
~semaphore() { sem_destroy(&sem); }
void post() {
if (sem_post(&sem)) throw std::overflow_error(strerror(errno));
}
void wait() {
while (sem_wait(&sem)) {
if (errno != EINTR) abort();
}
}
bool trywait() {
while (sem_trywait(&sem)) {
if (errno == EAGAIN)
return false;
else if (errno != EINTR)
abort();
}
return true;
}
};
#endif /* defined(__APPLE__) && defined(__MACH__) */
#endif
| 2,637
|
C++
|
.h
| 91
| 25.571429
| 74
| 0.677112
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,781
|
mboxscan.h
|
brndnmtthws_conky/src/mboxscan.h
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2006 Marco Candrian <mac@calmar.ws>
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef _MBOXSCAN_H_
#define _MBOXSCAN_H_
void parse_mboxscan_arg(struct text_object *, const char *);
void print_mboxscan(struct text_object *, char *, unsigned int);
void free_mboxscan(struct text_object *);
#endif /* _MBOXSCAN_H_ */
| 1,283
|
C++
|
.h
| 34
| 35.852941
| 72
| 0.747191
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,782
|
moc.h
|
brndnmtthws_conky/src/moc.h
|
/*
*
* MOC Conky integration
*
* Please see COPYING for details
*
* Copyright (c) 2008, Henri Häkkinen
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef MOC_H_
#define MOC_H_
void print_moc_state(struct text_object *, char *, unsigned int);
void print_moc_file(struct text_object *, char *, unsigned int);
void print_moc_title(struct text_object *, char *, unsigned int);
void print_moc_artist(struct text_object *, char *, unsigned int);
void print_moc_song(struct text_object *, char *, unsigned int);
void print_moc_album(struct text_object *, char *, unsigned int);
void print_moc_totaltime(struct text_object *, char *, unsigned int);
void print_moc_timeleft(struct text_object *, char *, unsigned int);
void print_moc_curtime(struct text_object *, char *, unsigned int);
void print_moc_bitrate(struct text_object *, char *, unsigned int);
void print_moc_rate(struct text_object *, char *, unsigned int);
#endif /* MOC_H_ */
| 1,551
|
C++
|
.h
| 35
| 42.657143
| 72
| 0.742895
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,783
|
audacious.h
|
brndnmtthws_conky/src/audacious.h
|
/*
*
* audacious.h: conky support for audacious music player
*
* Copyright (C) 2005-2007 Philip Kovacs pkovacs@users.sourceforge.net
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA.
*
*/
#ifndef AUDACIOUS_H
#define AUDACIOUS_H
void print_audacious_status(struct text_object *, char *, unsigned int);
void print_audacious_title(struct text_object *, char *, unsigned int);
void print_audacious_length(struct text_object *, char *, unsigned int);
void print_audacious_length_seconds(struct text_object *, char *, unsigned int);
void print_audacious_position(struct text_object *, char *, unsigned int);
void print_audacious_position_seconds(struct text_object *, char *,
unsigned int);
void print_audacious_bitrate(struct text_object *, char *, unsigned int);
void print_audacious_frequency(struct text_object *, char *, unsigned int);
void print_audacious_channels(struct text_object *, char *, unsigned int);
void print_audacious_filename(struct text_object *, char *, unsigned int);
void print_audacious_playlist_length(struct text_object *, char *,
unsigned int);
void print_audacious_playlist_position(struct text_object *, char *,
unsigned int);
void print_audacious_main_volume(struct text_object *, char *, unsigned int);
double audacious_barval(struct text_object *);
#endif /* AUDACIOUS_H */
| 2,118
|
C++
|
.h
| 42
| 46.142857
| 80
| 0.726001
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,784
|
hddtemp.h
|
brndnmtthws_conky/src/hddtemp.h
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Please see COPYING for details
*
* Copyright (c) 2007 Toni Spets
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef HDDTEMP_H_
#define HDDTEMP_H_
int update_hddtemp(void);
void free_hddtemp(struct text_object *);
void print_hddtemp(struct text_object *, char *, unsigned int);
#endif /*HDDTEMP_H_*/
| 1,079
|
C++
|
.h
| 30
| 34.1
| 72
| 0.74761
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,785
|
lua-config.hh
|
brndnmtthws_conky/src/lua-config.hh
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Please see COPYING for details
*
* Copyright (C) 2010 Pavel Labath et al.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef LUA_CONFIG_HH
#define LUA_CONFIG_HH
#include "luamm.hh"
namespace conky {
void export_symbols(lua::state &l);
}
#endif /* LUA_CONFIG_HH */
| 936
|
C++
|
.h
| 28
| 31.571429
| 72
| 0.748894
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.