1
0
mirror of https://github.com/Llewellynvdm/conky.git synced 2024-12-28 13:00:45 +00:00
conky/src/common.cc

842 lines
24 KiB
C++
Raw Normal View History

/*
*
* 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
2021-02-27 15:14:19 +00:00
* Copyright (c) 2005-2021 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/>.
*
2008-12-09 23:35:49 +00:00
*/
#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 "config.h"
#include "conky.h"
2010-04-17 13:19:44 +00:00
#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"
Basic macOS support (#480) * Initial patches for Darwin support * cmake files ready for building on Sierra. Dont know about other OSX versions * Added darwin.h which will contain darwin specific headers * Patches for enablin asprintf support (needs _POSIX_C_SOURCE >= __DARWIN_C_FULL so remove -D_POSIX_C_SOURCE=200809L). What is more, -D_LARGEFILE64_SOURCE is used by default so not needed on macOS * Stubs for get_entropy_avail and get_entropy_poolsize * More progress to getting to build * More patches * Now builds, remains fixing linking errors. Also implemented some functions * Now links * Now conky runs without sigabrt()'ing... An exception in semaphore.hh caused it to crash immediately upon initialisation * README changes * This was based on an old attempt I did with porting conky where I hadn't cloned the repo and thus it showed 3166 commits behind * Patched a bit the semaphore.hh and now conky runs at 0.7% CPU usage and not in 100% or 200% as it did before! Yeah * This update fixes swap-related miscalculations, though: On macOS there can be used MANY swapfiles ( NOT swap partitions,,, the installation disk is the partition for storing swap memory data ) Thus conky code must be updated for Darwin to support multi-swapfile usage stats. For now, we default to showing stats for swapfile0 * Fixed a bit the comments so they make sense * Realised that the sysctl code can give us stats for the whole swap storage so removed the swapmode( int swapfd, unsigned long * retvail, unsigned long * retfree ) * I think the code is in good condition now * semaphore.hh: Implemented ~semaphore() and added throwing exception when sem initialisation fails just like in sem() for linux… darwin.cc: partially implemented update_cpu_usage() and update_total_processes() * Implements update_total_processes() ( Now it finds the correct number of tasks ) the changes in cmake file don’t change the functionality… It is only comments. In upcoming updates lua support may be enabled and the comments are related to lua support. * get_cpu_count() now conforms to newer sysctl code as suggested by Apple ( we use hw.logicalcpumax instead of hw.ncpus ) --> The new implementation of get_cpu_count() finds the the max value of logical cores the mac could use on a boot. update_total_processes() was patched to allow initialising only ONCE when conky runs the machHost and processorSet ( this could probably be implemented in a better way I guess though... ) * patch * experimental support for get_top_info() and update_cpu_usage() :) * going to patch stuff * adds getting rss memory in get_top_info() * fixes * Couple things made more beautiful but too many things to fix ... * Remove unneeded code from darwin_soundcard.h and keep only needed to compile ( This way we are compatible to GPLv3, i think ) Include GPLv3 header in darwin.cc, darwin.h and darwin_soundcard.h Add more beautiful and explanatory comments to ease the work of other contributors… ( Mostly on things that don’t work! ) * Merged the macOS update_cpu_usage() implementation with the linux implementation but still it doesn't work as expected, plus, there are more memory related problems that will be fixed in newer release! NOTE: It will be really good to see how functions are implemented on linux.cc for more complete implementation * Now using a more linux-influenced implementation and dropping the old... ( only keeps mach stuff ) Needs some more work though to print accurate percentage! :) * Add conky installer (.pkg) project * Now gets thread count aswell! For now, we get this from update_total_processes... Also, removed the installer project because I need to learn more the software * Properly get thread count! - Patched core.cc to enable getting threads count on macOS! - Cleanup in darwin.cc * sort out some things in the code: - running_threads_count is not the same as thread_count on macOS! There is actually a difference! Correct a bit the code! * Enable the if_mounted command and start implementing the check_mount function in darwin.cc * Tighten things up * This patch makes conky build easily and without patching on any supported macOS version! The new flag introduced is a temporary solution for allowing conky to compile on other OS without tweaking the cmake files. If you want to compile it with i18l support you will have to run the command: brew link gettext after you install gettext * Update README to provide more complete info on building on macOS * Fix * patch check_mounted + SIP status This commit: - patches check_mounted function to match the implementation found in FreeBSD.cc! Now conky expects typing something like this: conky -t '${if_mounted /Volumes/MacOS} ${endif}' Please note that the correct way is "/Volumes/MacOS", not "/Volumes/MacOS/" ! You shouldnt put the backslash at the end... It will not work! - Adds a new command called sip_status which you can use to make conky show System Integrity Protection related information such as if filesystem protection is enabled, if user approved kexts protection is enabled and more... you can type conky -t '$sip_status' to see what it does... ( I will most likely update some things later regarding sip_status and check_mounted ) * Further implement sip_status sip_status now has different functionality! If you give no arguments it shows whether SIP is enabled or disabled ( generally ) If you give argument ( takes only ONE ) you can specify which specific thing of SIP you want to show status for... You need to pass 0, 1, ..., 9 to $sip_status as argument to print status for apple-internal, untrusted-kexts, and more... Below you can see the list: ARG: RESULT: nothing --> print enabled / disabled 0 --> allow_apple_internal 1 --> allow_untrusted_kexts 2 --> allow_task_for_pid 3 --> allow_unrestricted_fs 4 --> allow_kernel_debugger 5 --> allow_unrestricted_dtrace 6 --> allow_unrestricted_nvram 7 --> allow_device_configuration 8 --> allow_any_recovery_os 9 --> allow_user_approved_kexts * sip_status progress & if_up enabled This commit adds the 'a' argument for $sip_status which checks if the SIP configuration is ok or it is likely to break in the future. Also, enabled the $if_up command, but there are some problems with it... * sip_status patches - Updated code based on newest version of csrstat utility (v.1.8) The 1.8 version fixes a problem in finding status of ALLOW_DEVICE_CONFIGURATION flag. - Fixed a bug where we mistakenly printed 'disabled' even when SIP was enabled. * Disable ncurses checks in a way that will allow compiling for other OSes! ( it was a really quick patch before ) * More changes in cmake file to make code prettier and more exact * More cmake files cuteness * work for supporting versions prior Sierra This patch brings more compatibility with versions prior to Sierra. The project as is nearly links on a 10.9.5 OSX installation. - on versions prior Sierra clock_gettime() is not implemented thus we need to provide our own implementation for conky to work. ( Currently we have minimal support, more studying needs to be done ) NOTE: In order to compile on versions as old as Mavericks you will need newer compilers because command line tools for 10.9.5 dont support some C++11 features... For this I donwloaded the commandline tools for Xcode 8.1 ( or 8 dont remember well ) and installed only the CommandLine Tools section with Pacifist! ( The OSX installer sees the OS as too old, so you need pacifist! ) * Oops * $if_mounted ready This patch removes the unneded print_mounted() function! Also cleanup code. * $if_up works I think $if_up command works therefore remove the APPLE specific code in core.cc ( there wasnt anything different anyway ) and use the FreeBSD code. Minor conky output changes in darwin.cc * fix compatibility with Mavericks and before... This update allows conky to be compiled on Mavericks and before by checking at compilation time what our build target is. If it is Mavericks or lower, then cant use the csr_get_active_config func because it is not available. On higher versions than Mavericks it works as before... NOTE: For compiling on Mavericks or lower you will have to write 10.9 in CMAKE_OSX_DEPLOYMENT_TARGET when you run ccmake * Added link for youtube video showing conky running on macOS * Improvements Minor improvements related to style Removed unneeded free() calls * Simplify Xcode configuration process! :) * Removed update_cpu_usage() implementation It was quite buggy so I removed it... * Cleanup the source code 1. Bogus TODO comments have been deleted! 2. Started using DEBUG_MODE based printf 3. Explain some things better/cleanup * Last small cleanup The TODO in get_from_load_info() was unneeded. Removed! Also, DEBUG_MODE is enabled for now... * update authors file * Improve README Make it more clean and easier to understand. * Update README.md small tweak * Work for conforming with "Development" rules 1. Add to variables.xml documentation about the $sip_status variable. 2. Add sip_status variable to conkyrc.vim and nanorc to allow highlighting 3. the friends in darwin.cc is ambiguous,,, some are more than friends. * First patch set that implements get_top_info() :) * Calculate cpu usage of all processes more efficiently. (Now results match Activity Monitor's results a lot!!!) More info about the get_top_info() implementation will come once I finish it! (soon) * Cleanup patch! o Move a couple things to better places o Rename get_sample() to get_cpu_sample() to allow to be used by different functions such as get_cpu_usage() ( this is a scene from the future... ) o Improve the way we get cpu usage for each process by passing the already created proc_taskinfo struct to the appropriate function instead of creating another one inside it! * Correctly enable $running_processes variable In our implementation update_top() doesn't calculate the count of running processes! We assign this functionality to the update_running_processes() function. * Removed unneeded flag This is not needed because we do not use update_top() for getting the number of running processes! * Update README.md * Update README.md This adds support for TravisCL. Though this will compile the project only on Linux it is a good sign to know if our port still can compile on Linux or we have broken things. It seems like it can't but I suspect the problem existed before my patches. I will investigate. * First patch towards implementing #15 This patch a reworked get_top_info(). We now use the function get_top_info_for_kinfo_proc() to set the contents of each |process| struct. Also, we calculate the total cpu usage and total process usage concurrently using GCD. Aside from these we bring the function helper_get_proc_list() which makes the code simpler and cleaner. * First fix for the algorithm that calculates % CPU usage of a process The previous patch made the algorithm buggy. It required more reentrant-safe functions. Make calc_cpu_total_r() which is a more reentrant-safe reimplementation of the calc_cpu_total() function. This is not the last commit, more are coming in the future. * Previous commit wasn't pushed... * Problems committing * Make the code cleaner but break the algorithm again #15 The algorithm doesn't work... It is a work in progress! But this time we have merged the cpu_info and cpusample into one struct called cpusample ( I copied some variables from the linux implementation but they will probably be removed ) * Rework the code a bit / CPU usage % algorithm still doesn't work Now get_from_load_info() is renamed to helper_update_threads_processes() and is called by both update_threads() and update_total_processes() This makes the code nicer and removes the enum with the flags * cleanup remove unneeded functions, remove unneeded variables * bugfix * bugfix * remove the whole get_top_info() code! I will rework a lot this code so we can get rid of it. * Work for #15 Now we use the ultimate solution for calculating % usage of CPU of a process! Check the #15 Issue for information about this patch! * Quick memory leak fix & some patches for the get_top_info algorithm * quick patch for semaphore class * Update the comments * For consistency * temp * Revert "Merge branch 'master' into update_cpu_usage" This reverts commit 7267a515c40d54b85107e51016703e6c10f3183e, reversing changes made to 2190ff0b51463c12c61b3357cf846b8e705ebeb4. * Revert "Revert "Merge branch 'master' into update_cpu_usage"" This reverts commit 692bd27a3adb2fe7027d65932467a140e42cc7bc. * Partially implement the overall % CPU usage * bug fix: I meant procs and threads! * make the code better part1 * cleanup * Stabilise the values of get_cpu_sample(). Affects get_top_info() and update_cpu_usage() ( fixes #13 and #15 ) For some reason the code that used host_statistics() function didn't produced bad values quite often. Replaced the function with host_processor_info() and changed the algorithm and now the values are correct! This affects the get_top_info() and update_cpu_usage() functions which wouldn't work correctly until now. * Finish the optimised version of get_top_info() Fixes #15 * Quick fix for #16 Probably I will come up with a different location for get_cpu_count() because I want to conform to linux implementation. Also, the memory leak I am mentioning in get_cpu_count() may not actually exist, as I suspected in the back of my head. * Strictness * Cleanup ConkyPlatformChecks.cmake Cleanup the quick patch code for Lua. * Add warning to README If you are using old version of cmake, update it. It will probably have problems when trying to locate lua. * More cleanup * Fix identation This simplifies the diff. Also, note that by merging the new code for checking for NCURSES we acheive better compatibility and easy build process * Remove mixer related patches and files With the newest patches from upstream, cmake checks if the header soundcard.h exists on the system. If it doesn't exist (in the case of macOS for example) all mixer-related variables are disabled. * Changes for using as submodule for ConkyX * Fixes * Implement get_freq This implements #11 Though it doesn't support getting the **current** cpu frequency. I haven't found a way to do it on macOS but i guess it can be done using a kernel extension. I may come back to this again in the future * First work for correcting mem stats #6 Incorporate the update_pages_stolen() function and all of its dependencies. I will see if I can patch the code in order to avoid license problems * Work for #6 Now we follow the way apple's top works and not Activity Monitor. For this reason we find different values. But correct based on top. * cleanup for #6 * bug fix 1 * cleanup * hmm sorry * More cleanup - Move the libtop_tsamp_t object to darwin.cc. - Remove unneeded member variables. * A bit documentation * Implement secondary memory stats #6 Implement memwithbuffers, memeasyfree and memfree (which isn't secondary) * Quit update_meminfo if libtop_tsamp_update_vm_stats() failed * Update README.md Revert to original conky readme Move all macOS related information to the Wiki: https://github.com/Conky-for-macOS/conky-for-macOS/wiki * Alot junk slipped in too! * Merge net_stats branch For now, I have only tested up / down bytes count on en0, and it works. This is for #14 * Corrections - Fix License headers in darwin* files - Remove ConkyX entry from .gitignore which slipped into from the "forConkyX" branch which was used for another project ... ConkyX. - Cleanup top.h (I will request the changes in a pull request finally) * Fix identation and cleanup * identation-fixes part1 * Try to fix problem compiling on linux Improve checks for headers in ConkyPlatformChecks.cmake to amend the problem; I mistakenly thought that statfs64 wasn't available in sys/statfs.h in macOS thus I tried to add platform specific code. Though, I add the checks in the wrong place and also messed up linux-specific code by replacing checks_include sys/statfs with check_symbol_exists statfs64 * attemp to completely fix linux problem!
2018-05-07 11:27:32 +00:00
#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, except only cheques for $HOME and ~/ in
* path. If HOME is unset it uses an empty string for substitution */
std::string to_real_path(const std::string &source) {
const char *homedir = getenv("HOME") != nullptr ? getenv("HOME") : "";
if (source.find("~/") == 0) { return homedir + source.substr(1); }
if (source.find("$HOME/") == 0) { return homedir + source.substr(5); }
return source;
}
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;
2019-02-23 19:43:44 +00:00
if (isalpha(static_cast<unsigned char>(s[pos + 1])) != 0) {
l = 1;
while (pos + l < s.size() &&
2019-02-23 19:43:44 +00:00
(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);
}
}
2010-03-07 12:29:30 +00:00
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) &&
2019-02-23 19:43:44 +00:00
(isdigit(static_cast<unsigned char>(arg[0])) != 0)) {
obj->data.i = atoi(arg);
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));
2010-04-17 13:19:44 +00:00
}
void free_no_update(struct text_object *obj) { free(obj->data.s); }
2010-04-17 13:19:44 +00:00
void print_no_update(struct text_object *obj, char *p,
unsigned int p_max_size) {
snprintf(p, p_max_size, "%s", obj->data.s);
2010-04-17 13:19:44 +00:00
}
#ifdef BUILD_X11
void scan_loadgraph_arg(struct text_object *obj, const char *arg) {
char *buf = nullptr;
2009-10-25 13:13:26 +00:00
buf = scan_graph(obj, arg, 0);
free_and_zero(buf);
}
double loadgraphval(struct text_object *obj) {
(void)obj;
2009-11-15 23:54:15 +00:00
return info.loadavg[0];
}
#endif /* BUILD_X11 */
2009-11-22 17:02:56 +00:00
uint8_t cpu_percentage(struct text_object *obj) {
2019-02-23 19:43:44 +00:00
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(nullptr, nullptr, "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;
2009-11-25 00:30:21 +00:00
}
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(nullptr, nullptr, "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(memfree)
PRINT_HR_GENERATOR(memmax)
PRINT_HR_GENERATOR(memdirty)
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;
2009-11-22 17:02:56 +00:00
}
2009-11-30 22:55:48 +00:00
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;
2009-11-30 22:55:48 +00:00
return info.swapmax != 0u ? (static_cast<double>(info.swap) / info.swapmax)
: 0;
2009-11-30 22:55:48 +00:00
}
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);
}
2009-11-25 23:22:25 +00:00
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);
2009-11-25 23:22:25 +00:00
}
2009-11-25 23:29:50 +00:00
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);
2009-11-25 23:29:50 +00:00
}
#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);
}
2009-11-26 00:15:33 +00:00
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);
2009-11-26 00:15:33 +00:00
}
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);
}
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__ */
2009-11-29 11:47:11 +00:00
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;
2009-11-29 11:56:09 +00:00
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] = ' '; }
}
2009-11-29 11:56:09 +00:00
snprintf(p, p_max_size, "%s", &(buf[0]));
visible = static_cast<int>(static_cast<int>(visible) == 0);
2009-11-29 11:56:09 +00:00
}
2009-11-29 11:59:04 +00:00
void print_include(struct text_object *obj, char *p, unsigned int p_max_size) {
std::vector<char> buf(max_user_text.get(*state));
2009-11-29 11:59:04 +00:00
if (obj->sub == nullptr) { return; }
2009-11-29 11:59:04 +00:00
generate_text_internal(&(buf[0]), max_user_text.get(*state), *obj->sub);
snprintf(p, p_max_size, "%s", &(buf[0]));
2009-11-29 11:59:04 +00:00
}
2009-11-29 18:48:24 +00:00
2010-04-19 12:54:03 +00:00
#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");
2021-02-04 00:38:41 +00:00
#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();
2019-02-23 19:43:44 +00:00
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);
2010-04-19 12:45:05 +00:00
}
void free_stock(struct text_object *obj) { free(obj->data.s); }
2010-04-19 12:54:03 +00:00
#endif /* BUILD_CURL */
2010-04-19 12:45:05 +00:00
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;
}