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,786
|
entropy.h
|
brndnmtthws_conky/src/entropy.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 _ENTROPY_H
#define _ENTROPY_H
int update_entropy(void);
void print_entropy_avail(struct text_object *, char *, unsigned int);
uint8_t entropy_percentage(struct text_object *);
void print_entropy_poolsize(struct text_object *, char *, unsigned int);
double entropy_barval(struct text_object *);
void print_password(struct text_object *, char *, unsigned int);
#endif /* _ENTROPY_H */
| 1,448
|
C++
|
.h
| 37
| 37.297297
| 72
| 0.754797
|
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,787
|
haiku.h
|
brndnmtthws_conky/src/haiku.h
|
/* */
#ifndef HAIKU_H_
#define HAIKU_H_
#include <err.h>
#include <fcntl.h>
#include <limits.h>
#include <paths.h>
#include <time.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/types.h>
#include <net/if.h>
#include <kernel/fs_info.h>
#include "common.h"
#include "conky.h"
int get_entropy_avail(unsigned int *);
int get_entropy_poolsize(unsigned int *);
/* let's just mimic statfs64 */
struct statfs : public fs_info {};
inline int statfs(const char *path, struct statfs *buf) {
return fs_stat_dev(dev_for_path(path), buf);
}
#define f_blocks total_blocks
#define f_bsize block_size
#define f_bavail free_blocks
#define f_bfree free_blocks
#define f_fstypename fsh_name
#endif /*HAIKU_H_*/
| 740
|
C++
|
.h
| 29
| 24.034483
| 57
| 0.736767
|
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,788
|
pulseaudio.h
|
brndnmtthws_conky/src/pulseaudio.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 _PULSEAUDIO_H
#define _PULSEAUDIO_H
#include <pulse/pulseaudio.h>
#include <string>
#include "text_object.h"
void init_pulseaudio(struct text_object *obj);
void free_pulseaudio(struct text_object *obj);
uint8_t puau_vol(struct text_object *); // preserve pa_* for libpulse
void print_puau_sink_description(struct text_object *obj, char *p,
unsigned int p_max_size);
void print_puau_sink_active_port_name(struct text_object *obj, char *p,
unsigned int p_max_size);
void print_puau_sink_active_port_description(struct text_object *obj, char *p,
unsigned int p_max_size);
void print_puau_card_name(struct text_object *obj, char *p,
unsigned int p_max_size);
void print_puau_card_active_profile(struct text_object *obj, char *p,
unsigned int p_max_size);
double puau_volumebarval(struct text_object *obj);
int puau_muted(struct text_object *obj);
int puau_source_running(struct text_object *obj);
int puau_source_muted(struct text_object *obj);
struct pulseaudio_default_results {
// default sink
std::string sink_name;
std::string sink_description;
std::string sink_active_port_name;
std::string sink_active_port_description;
uint32_t sink_card;
int sink_mute;
uint32_t sink_index;
unsigned int sink_volume; // percentage
// default source
std::string source_name;
pa_source_state source_state;
int source_mute;
// default card
std::string card_active_profile_description;
std::string card_name;
uint32_t card_index;
};
enum pulseaudio_state {
PULSE_CONTEXT_INITIALIZING,
PULSE_CONTEXT_READY,
PULSE_CONTEXT_FINISHED
};
class pulseaudio_c {
public:
pa_threaded_mainloop *mainloop;
pa_mainloop_api *mainloop_api;
pa_context *context;
volatile enum pulseaudio_state cstate;
int ninits;
struct pulseaudio_default_results result;
pulseaudio_c()
: mainloop(nullptr),
mainloop_api(nullptr),
context(nullptr),
cstate(PULSE_CONTEXT_INITIALIZING),
ninits(0),
result({std::string(), std::string(), std::string(), std::string(), 0,
0, 0, 0, std::string(), PA_SOURCE_SUSPENDED, 0, std::string(),
std::string(), 0}){};
};
#endif /* _PULSEAUDIO_H */
| 3,415
|
C++
|
.h
| 93
| 31.989247
| 78
| 0.697253
|
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,789
|
luamm.hh
|
brndnmtthws_conky/src/luamm.hh
|
/*
*
* luamm: C++ binding for lua
*
* 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 LUAMM_HH
#define LUAMM_HH
#include <assert.h>
#include <exception>
#include <functional>
#include <memory>
#include <mutex>
#include <stdexcept>
#include <string>
#include <lua.hpp>
namespace lua {
class state;
typedef lua_Integer integer;
typedef lua_Number number;
typedef std::function<int(state *)> cpp_function;
enum { REGISTRYINDEX = LUA_REGISTRYINDEX };
enum {
GCSTOP = LUA_GCSTOP,
GCRESTART = LUA_GCRESTART,
GCCOLLECT = LUA_GCCOLLECT,
GCCOUNT = LUA_GCCOUNT,
GCCOUNTB = LUA_GCCOUNTB,
GCSTEP = LUA_GCSTEP,
GCSETPAUSE = LUA_GCSETPAUSE,
GCSETSTEPMUL = LUA_GCSETSTEPMUL
};
enum { MULTRET = LUA_MULTRET };
enum Type {
TBOOLEAN = LUA_TBOOLEAN,
TFUNCTION = LUA_TFUNCTION,
TLIGHTUSERDATA = LUA_TLIGHTUSERDATA,
TNIL = LUA_TNIL,
TNONE = LUA_TNONE,
TNUMBER = LUA_TNUMBER,
TSTRING = LUA_TSTRING,
TTABLE = LUA_TTABLE,
TTHREAD = LUA_TTHREAD,
TUSERDATA = LUA_TUSERDATA
};
// we reserve one upvalue for the function pointer
inline int upvalueindex(int n) { return lua_upvalueindex(n + 1); }
/*
* Lua error()s are wrapped in this class when rethrown into C++ code. what()
* returns the error message. push_lua_error() pushes the error onto lua stack.
* The error can only be pushed into the same state it was generated in.
*/
class exception : public std::runtime_error {
/*
* We only allow moving, to avoid complications with multiple references. It
* shouldn't be difficult to modify this to work with copying, if that proves
* unavoidable.
*/
state *L;
int key;
static std::string get_error_msg(state *L);
exception(const exception &) = delete;
const exception &operator=(const exception &) = delete;
public:
exception(exception &&other)
: std::runtime_error(std::move(other)), L(other.L), key(other.key) {
other.L = nullptr;
}
explicit exception(state *l);
virtual ~exception();
void push_lua_error(state *l);
};
class not_string_error : public std::runtime_error {
public:
not_string_error() : std::runtime_error("Cannot convert value to a string") {}
};
// the name says it all
class syntax_error : public lua::exception {
syntax_error(const syntax_error &) = delete;
const syntax_error &operator=(const syntax_error &) = delete;
public:
explicit syntax_error(state *L) : lua::exception(L) {}
syntax_error(syntax_error &&other) : lua::exception(std::move(other)) {}
};
// loadfile() encountered an error while opening/reading the file
class file_error : public lua::exception {
file_error(const file_error &) = delete;
const file_error &operator=(const file_error &) = delete;
public:
explicit file_error(state *L) : lua::exception(L) {}
file_error(file_error &&other) : lua::exception(std::move(other)) {}
};
// double fault, lua encountered an error while running the error handler
// function
class errfunc_error : public lua::exception {
errfunc_error(const errfunc_error &) = delete;
const errfunc_error &operator=(const errfunc_error &) = delete;
public:
explicit errfunc_error(state *L) : lua::exception(L) {}
errfunc_error(errfunc_error &&other) : lua::exception(std::move(other)) {}
};
// a fancy wrapper around lua_State
class state : private std::mutex {
std::shared_ptr<lua_State> cobj;
// destructor for C++ objects stored as lua userdata
template <typename T>
static int destroy_cpp_object(lua_State *l) {
T *ptr = static_cast<T *>(lua_touserdata(l, -1));
assert(ptr);
try {
// throwing exceptions in destructors is a bad idea
// but we catch (and ignore) them, just in case
ptr->~T();
} catch (...) {}
return 0;
}
bool safe_compare(lua_CFunction trampoline, int index1, int index2);
public:
state();
/*
* Lua functions come in three flavours
* a) functions that never throw an exception
* b) functions that throw only in case of a memory allocation error
* c) functions that throw other kinds of errors
*
* Calls to type a functions are simply forwarded to the C api.
* Type c functions are executed in protected mode, to make sure they don't
* longjmp() over us (and our destructors). This add a certain amount
* overhead. If you care about performance, try using the raw versions (if
* possible). Type b functions are not executed in protected mode atm. as
* memory allocation errors don't happen that often (as opposed to the type c,
* where the user get deliberately set a metamethod that throws an error).
* That means those errors will do something undefined, but hopefully that
* won't be a problem.
*
* Semantics are mostly identical to those of the underlying C api. Any
* deviation is noted in the respective functions comment. The most important
* difference is that instead of return values, we use exceptions to indicate
* errors. The lua and C++ exception mechanisms are integrated. That means
* one can throw a C++ exception and catch it in lua (with pcall). Lua
* error()s can be caught in C++ as exceptions of type lua::exception.
*/
// type a, never throw
int absindex(int index) throw() {
return index < 0 && -index <= gettop() ? gettop() + 1 + index : index;
}
bool getmetatable(int index) throw() {
return lua_getmetatable(cobj.get(), index);
}
int gettop() throw() { return lua_gettop(cobj.get()); }
void insert(int index) throw() { lua_insert(cobj.get(), index); }
bool isboolean(int index) throw() { return lua_isboolean(cobj.get(), index); }
bool isfunction(int index) throw() {
return lua_isfunction(cobj.get(), index);
}
bool islightuserdata(int index) throw() {
return lua_islightuserdata(cobj.get(), index);
}
bool isnil(int index) throw() { return lua_isnil(cobj.get(), index); }
bool isnone(int index) throw() { return lua_isnone(cobj.get(), index); }
/* isnumber conflicts with some headers on BSD systems */
bool _isnumber(int index) throw() { return lua_isnumber(cobj.get(), index); }
bool isstring(int index) throw() { return lua_isstring(cobj.get(), index); }
void pop(int n = 1) throw() { lua_pop(cobj.get(), n); }
void pushboolean(bool b) throw() { lua_pushboolean(cobj.get(), b); }
void pushinteger(integer n) throw() { lua_pushinteger(cobj.get(), n); }
void pushlightuserdata(void *p) throw() {
lua_pushlightuserdata(cobj.get(), p);
}
void pushnil() throw() { lua_pushnil(cobj.get()); }
void pushnumber(number n) throw() { lua_pushnumber(cobj.get(), n); }
void pushvalue(int index) throw() { lua_pushvalue(cobj.get(), index); }
void rawget(int index) throw() { lua_rawget(cobj.get(), index); }
void rawgeti(int index, int n) throw() { lua_rawgeti(cobj.get(), index, n); }
bool rawequal(int index1, int index2) throw() {
return lua_rawequal(cobj.get(), index1, index2);
}
void replace(int index) throw() { lua_replace(cobj.get(), index); }
// lua_setmetatable returns int, but docs don't specify it's meaning :/
int setmetatable(int index) throw() {
return lua_setmetatable(cobj.get(), index);
}
void settop(int index) throw() { return lua_settop(cobj.get(), index); }
bool toboolean(int index) throw() { return lua_toboolean(cobj.get(), index); }
integer tointeger(int index) throw() {
return lua_tointeger(cobj.get(), index);
}
number tonumber(int index) throw() { return lua_tonumber(cobj.get(), index); }
void *touserdata(int index) throw() {
return lua_touserdata(cobj.get(), index);
}
Type type(int index) throw() {
return static_cast<Type>(lua_type(cobj.get(), index));
}
// typename is a reserved word :/
const char *type_name(Type tp) throw() {
return lua_typename(cobj.get(), tp);
}
void unref(int t, int ref) throw() { return luaL_unref(cobj.get(), t, ref); }
// type b, throw only on memory allocation errors
// checkstack correctly throws bad_alloc, because lua_checkstack kindly
// informs us of that sitution
void checkstack(int extra);
const char *gsub(const char *s, const char *p, const char *r) {
return luaL_gsub(cobj.get(), s, p, r);
}
bool newmetatable(const char *tname) {
return luaL_newmetatable(cobj.get(), tname);
}
void newtable() { lua_newtable(cobj.get()); }
void *newuserdata(size_t size) { return lua_newuserdata(cobj.get(), size); }
// cpp_function can be anything that std::function can handle, everything else
// remains identical
void pushclosure(const cpp_function &fn, int n);
void pushfunction(const cpp_function &fn) { pushclosure(fn, 0); }
void pushstring(const char *s) { lua_pushstring(cobj.get(), s); }
void pushstring(const char *s, size_t len) {
lua_pushlstring(cobj.get(), s, len);
}
void pushstring(const std::string &s) {
lua_pushlstring(cobj.get(), s.c_str(), s.size());
}
void rawgetfield(int index, const char *k);
void rawset(int index) { lua_rawset(cobj.get(), index); }
void rawsetfield(int index, const char *k);
int ref(int t) { return luaL_ref(cobj.get(), t); }
// len receives length, if not null. Returned value may contain '\0'
const char *tocstring(int index, size_t *len = nullptr) {
return lua_tolstring(cobj.get(), index, len);
}
// Don't use pushclosure() to create a __gc function. The problem is that lua
// calls them in an unspecified order, and we may end up destroying the object
// holding the std::function before we get a chance to call it. This pushes a
// function that simply calls ~T when the time comes. Only set it as __gc on
// userdata of type T.
template <typename T>
void pushdestructor() {
lua_pushcfunction(cobj.get(), &destroy_cpp_object<T>);
}
// type c, throw everything but the kitchen sink
// call() is a protected mode call, we don't allow unprotected calls
void call(int nargs, int nresults, int errfunc = 0);
void concat(int n);
bool equal(int index1, int index2);
int gc(int what, int data);
void getfield(int index, const char *k);
void getglobal(const char *name);
void gettable(int index);
bool lessthan(int index1, int index2);
void loadfile(const char *filename);
void loadstring(const char *s);
bool next(int index);
// register is a reserved word :/
void register_fn(const char *name, const cpp_function &f) {
pushfunction(f);
setglobal(name);
}
void setfield(int index, const char *k);
void setglobal(const char *name);
void settable(int index);
// lua_tostring uses nullptr to indicate conversion error, since there is no
// such thing as a nullptr std::string, we throw an exception. Returned value
// may contain '\0'
std::string tostring(int index);
// allocate a new lua userdata of appropriate size, and create a object in it
// pushes the userdata on stack and returns the pointer
template <typename T, typename... Args>
T *createuserdata(Args &&...args);
using std::mutex::lock;
using std::mutex::try_lock;
using std::mutex::unlock;
};
/*
* Can be used to automatically pop temporary values off the lua stack on exit
* from the function/block (e.g. via an exception). It's destructor makes sure
* the stack contains exactly n items. The constructor initializes n to
* l.gettop()+n_, but that can be later changed with the overloaded operators.
* It is an error if stack contains less than n elements at entry into the
* destructor.
*
* Proposed stack discipline for functions is this:
* - called function always pops parameters off the stack.
* - if functions returns normally, it's return values are on the stack.
* - if function throws an exception, there are no return values on the stack.
* The last point differs from lua C api, which return an error message on the
* stack. But since we have exception.what() for that, putting the message on
* the stack is not necessary.
*/
class stack_sentry {
state *L;
int n;
stack_sentry(const stack_sentry &) = delete;
const stack_sentry &operator=(const stack_sentry &) = delete;
public:
explicit stack_sentry(state &l, int n_ = 0) : L(&l), n(l.gettop() + n_) {
assert(n >= 0);
}
~stack_sentry() {
assert(L->gettop() >= n);
L->settop(n);
}
void operator++() { ++n; }
void operator--() {
--n;
assert(n >= 0);
}
void operator+=(int n_) { n += n_; }
void operator-=(int n_) {
n -= n_;
assert(n >= 0);
}
};
template <typename T, typename... Args>
T *state::createuserdata(Args &&...args) {
stack_sentry s(*this);
void *t = newuserdata(sizeof(T));
new (t) T(std::forward<Args>(args)...);
++s;
return static_cast<T *>(t);
}
} // namespace lua
#endif /* LUAMM_HH */
| 13,268
|
C++
|
.h
| 335
| 36.591045
| 80
| 0.701552
|
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,790
|
i18n.h
|
brndnmtthws_conky/src/i18n.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 I18N_H_
#define I18N_H_
#define _nop(string) string
#ifdef BUILD_I18N
#include <libintl.h>
#define _(string) gettext(string)
#else
#define _(string) string
#endif
#endif /*I18N_H_*/
| 1,046
|
C++
|
.h
| 33
| 29.909091
| 72
| 0.747275
|
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,791
|
exec.h
|
brndnmtthws_conky/src/exec.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 _EXEC_H
#define _EXEC_H
#include "update-cb.hh"
/**
* A callback that executes a command and stores the output as a std::string.
*
* Important note: if more than one exec callback uses the same command,
* then only ONE callback is actually stored. This saves space. However,
* suppose we have the following ${exec} objects in our conky.text:
*
* ${exec ~/bin/foo.sh}
* ${execi 10 ~/bin/foo.sh}
*
* To the callback system, these are identical! Furthermore, the callback
* with the smallest period/interval is the one that is stored. So the execi
* command will in fact run on every update interval, rather than every
* ten seconds as one would expect.
*/
class exec_cb : public conky::callback<std::string, std::string> {
typedef conky::callback<std::string, std::string> Base;
protected:
virtual void work();
public:
exec_cb(uint32_t period, bool wait, const std::string &cmd)
: Base(period, wait, Base::Tuple(cmd)) {}
};
/**
* Flags used to identify the different types of exec commands during
* parsing by scan_exec_arg(). These can be used individually or combined.
* For example, to parse an ${execgraph} object, we pass EF_EXEC | EF_GRAPH
* as the last argument to scan_exec_arg().
*/
enum {
EF_EXEC = (1 << 0),
EF_EXECI = (1 << 1),
EF_BAR = (1 << 2),
EF_GRAPH = (1 << 3),
EF_GAUGE = (1 << 4)
};
void scan_exec_arg(struct text_object *, const char *, unsigned int);
void register_exec(struct text_object *);
void register_execi(struct text_object *);
void print_exec(struct text_object *, char *, unsigned int);
double execbarval(struct text_object *);
void free_exec(struct text_object *);
void free_execi(struct text_object *);
#endif /* _EXEC_H */
| 2,770
|
C++
|
.h
| 75
| 34.893333
| 77
| 0.724972
|
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,792
|
libtcp-portmon.h
|
brndnmtthws_conky/src/libtcp-portmon.h
|
/*
*
* libtcp-portmon.h: 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. */
#ifndef LIBTCP_PORTMON_H
#define LIBTCP_PORTMON_H
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <netdb.h>
/* connection deleted if unseen again after this # of refreshes */
#define TCP_CONNECTION_STARTING_AGE 1
#define BUILD_PORT_MONITORS_HASH_KEY_SIZE 12
#define MAX_PORT_MONITOR_CONNECTIONS_DEFAULT 256
/* -------------------------------------------------------------------
* 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.
* ------------------------------------------------------------------- */
/* The inventory of peekable items within the port monitor. */
enum tcp_port_monitor_peekables {
COUNT = 0,
REMOTEIP,
REMOTEHOST,
REMOTEPORT,
REMOTESERVICE,
LOCALIP,
LOCALHOST,
LOCALPORT,
LOCALSERVICE
};
/* ------------------------------------------------------------
* A port monitor
*
* The definition of the struct is hidden because it contains
* C++-specific stuff and we want to #include this from C code.
* ------------------------------------------------------------ */
typedef struct _tcp_port_monitor_t tcp_port_monitor_t;
/* ------------------------------------------------------------
* A tcp port monitor collection
*
* The definition of the struct is hidden because it contains
* C++-specific stuff and we want to #include this from C code.
* ------------------------------------------------------------ */
typedef struct _tcp_port_monitor_collection_t tcp_port_monitor_collection_t;
/* ----------------------------------------------------------------------
* CLIENT INTERFACE
*
* Clients should call only those functions below this line.
* ---------------------------------------------------------------------- */
/* struct to hold monitor creation arguments */
typedef struct _tcp_port_monitor_args_t {
/* monitor supports tracking at most this many connections */
int max_port_monitor_connections;
} tcp_port_monitor_args_t;
/* ----------------------------------
* 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,
/* (item of interest, from tcp_port_monitor_peekables enum) */
int item,
/* (0 to number of connections in monitor - 1) */
int connection_index,
/* buffer to receive requested value */
char *p_buffer,
/* size of p_buffer */
size_t buffer_size);
/* --------------------------------
* Client operations on collections
* -------------------------------- */
/* Create a monitor collection. Do this one first. */
tcp_port_monitor_collection_t *create_tcp_port_monitor_collection(void);
/* Destroy the monitor collection (and everything it contains).
* Do this one last. */
void destroy_tcp_port_monitor_collection(
tcp_port_monitor_collection_t *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);
/* Creation of redundant monitors is silently ignored
* Returns 0 on success, -1 otherwise. */
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);
/* 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);
#endif
| 4,791
|
C++
|
.h
| 114
| 39.710526
| 76
| 0.644836
|
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,793
|
core.h
|
brndnmtthws_conky/src/core.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_CORE_H_
#define _CONKY_CORE_H_
#include "conky.h"
struct text_object *construct_text_object(const char *s, const char *arg,
long line, void **ifblock_opaque,
void *free_at_crash);
size_t remove_comments(char *string);
int extract_variable_text_internal(struct text_object *retval,
const char *const_p);
void free_text_objects(struct text_object *root);
const char *dev_name(const char *);
#endif /* _CONKY_CORE_H_ */
| 1,612
|
C++
|
.h
| 40
| 35.45
| 75
| 0.696292
|
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,794
|
update-cb.hh
|
brndnmtthws_conky/src/update-cb.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 UPDATE_CB_HH
#define UPDATE_CB_HH
#include <cstdint>
#include <memory>
#include <thread>
// the following probably requires a is-gcc-4.7.0 check
#include <mutex>
#include <tuple>
#include <unordered_set>
#include <assert.h>
#include "c++wrap.hh"
#include "semaphore.hh"
namespace conky {
// forward declarations
template <typename Callback>
class callback_handle;
void run_all_callbacks();
template <typename Callback, typename... Params>
callback_handle<Callback> register_cb(uint32_t period, Params &&...params);
namespace priv {
class callback_base {
typedef callback_handle<callback_base> handle;
typedef std::unordered_set<handle, size_t (*)(const handle &),
bool (*)(const handle &, const handle &)>
Callbacks;
semaphore sem_start;
std::thread *thread;
const size_t hash; /* used to determined callback uniqueness */
uint32_t period; /* how often to run a callback */
uint32_t
remaining; /* update intervals remaining until we can run a callback */
std::pair<int, int> pipefd;
const bool wait; /* whether or not to wait for a callback to finish */
bool done; /* if true, callback is being stopped and destroyed */
uint8_t unused; /* number of update intervals during which no one owns a
callback */
callback_base(const callback_base &) = delete;
callback_base &operator=(const callback_base &) = delete;
virtual bool operator==(const callback_base &) = 0;
void run();
void start_routine();
void stop();
static void deleter(callback_base *ptr) {
ptr->stop();
delete ptr;
}
// a list of registered callbacks
static Callbacks callbacks;
// used by the callbacks list
static inline size_t get_hash(const handle &h);
static inline bool is_equal(const handle &a, const handle &b);
static handle do_register_cb(const handle &h);
template <typename Callback, typename... Params>
friend callback_handle<Callback> conky::register_cb(uint32_t period,
Params &&...params);
friend void conky::run_all_callbacks();
template <typename Callback>
friend class conky::callback_handle;
protected:
callback_base(size_t hash_, uint32_t period_, bool wait_, bool use_pipe)
: thread(nullptr),
hash(hash_),
period(period_),
remaining(0),
pipefd(use_pipe ? pipe2(O_CLOEXEC) : std::pair<int, int>(-1, -1)),
wait(wait_),
done(false),
unused(0) {}
int donefd() { return pipefd.first; }
bool is_done() { return done; }
// to be implemented by descendant classes
virtual void work() = 0;
// called when two registered objects evaluate as equal, the latter is removed
// afterwards
virtual void merge(callback_base &&);
public:
std::mutex result_mutex;
virtual ~callback_base();
};
} // namespace priv
template <typename Callback>
class callback_handle : private std::shared_ptr<Callback> {
typedef std::shared_ptr<Callback> Base;
callback_handle(Callback *ptr) : Base(ptr, &priv::callback_base::deleter) {}
callback_handle(Base &&ptr) : Base(std::move(ptr)) {}
public:
using Base::operator->;
using Base::operator*;
friend void conky::run_all_callbacks();
template <typename Callback_, typename... Params>
friend callback_handle<Callback_> register_cb(uint32_t period,
Params &&...params);
};
template <typename Callback, typename... Params>
callback_handle<Callback> register_cb(uint32_t period, Params &&...params) {
return std::dynamic_pointer_cast<Callback>(
priv::callback_base::do_register_cb(priv::callback_base::handle(
new Callback(period, std::forward<Params>(params)...))));
}
/*
* Callback uniqueness is determined by the hash computed here.
*/
namespace priv {
template <size_t pos, typename... Elements>
struct hash_tuple {
typedef std::tuple<Elements...> Tuple;
typedef typename std::tuple_element<pos - 1, Tuple>::type Element;
static inline size_t hash(const Tuple &tuple) {
return std::hash<Element>()(std::get<pos - 1>(tuple)) +
47 * hash_tuple<pos - 1, Elements...>::hash(tuple);
}
};
template <typename... Elements>
struct hash_tuple<0, Elements...> {
static inline size_t hash(const std::tuple<Elements...> &) { return 0; }
};
} // namespace priv
/*
* To create a callback, inherit from this class. The Result template parameter
* should be the type of your output, so that your users can retrieve it with
* the get_result* functions.
*
* get_result() returns a reference to the internal variable. It can be used
* without locking if the object has wait set to true (wait=true means that the
* run_all_callbacks() waits for the callback to finish work()ing before
* returning). If object has wait=false then the user must first lock the
* result_mutex.
*
* get_result_copy() returns a copy of the result object and it handles the
* necessary locking. Don't call it if you hold a lock on the result_mutex.
*
* You should implement the work() function to do the actual updating and store
* the result in the result variable (lock the mutex while you are doing it,
* especially if you have wait=false).
*
* The Keys... template parameters are parameters for your work function. E.g.,
* a curl callback can have one parameter - the url to retrieve,. hddtemp may
* have two - host and port number of the hddtemp server, etc. The register_cb()
* function make sure that there exists only one object (of the same type) with
* the same values for all the keys.
*
* Callbacks are registered with the register_cb() function. You pass the class
* name as the template parameter, and any additional parameters to the
* constructor as function parameters. The period parameter specifies how often
* the callback will run. It should be left for the user to decide that.
* register_cb() returns a pointer to the newly created object. As long as
* someone holds a pointer to the object, the callback will be run.
*
* run_all_callbacks() runs the registered callbacks (with the specified
* periodicity). It should be called from somewhere inside the main loop,
* according to the update_interval setting. It waits for the callbacks which
* have wait=true. It leaves the rest to run in background.
*/
template <typename Result, typename... Keys>
class callback : public priv::callback_base {
virtual bool operator==(const callback_base &other) {
return tuple == dynamic_cast<const callback &>(other).tuple;
}
public:
typedef std::tuple<Keys...> Tuple;
protected:
const Tuple tuple;
Result result;
template <size_t i>
typename std::add_lvalue_reference<
const typename std::tuple_element<i, Tuple>::type>::type
get() {
return std::get<i>(tuple);
}
public:
callback(uint32_t period_, bool wait_, const Tuple &tuple_,
bool use_pipe = false)
: callback_base(priv::hash_tuple<sizeof...(Keys), Keys...>::hash(tuple_),
period_, wait_, use_pipe),
tuple(tuple_) {}
const Result &get_result() { return result; }
Result get_result_copy() {
std::lock_guard<std::mutex> l(result_mutex);
return result;
}
};
} // namespace conky
#endif /* UPDATE_CB_HH */
| 8,080
|
C++
|
.h
| 204
| 35.794118
| 80
| 0.704621
|
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,795
|
geometry.h
|
brndnmtthws_conky/src/geometry.h
|
#ifndef _CONKY_GEOMETRY_H_
#define _CONKY_GEOMETRY_H_
#include "config.h"
#include "macros.h"
#include <algorithm>
#include <array>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <limits>
#include <numeric>
#include <type_traits>
#include <Vc/Vc>
#ifdef BUILD_X11
#include <X11/Xlib.h>
#endif /* BUILD_X11 */
namespace conky {
namespace _priv_geom {
/// @brief Constructs an index assignable type from an array with different
/// value types using `static_cast`.
///
/// Panics at runtime if `O` can be indexed by every value in range `0` to
/// (excluding) `Length`.
///
/// @tparam Input source array element
/// @tparam R target element type
/// @tparam Output target container
/// @tparam Length array length
/// @param value array to pad/trim
/// @return casted array
template <typename Input, typename R, size_t Length, typename Output>
inline Output cast_to_assignable(const Input &value, Output &target) {
if constexpr (std::is_same_v<Input, Output>) { return value; }
for (size_t i = 0; i < Length; i++) {
target[i] = static_cast<R>(value.at(i));
}
return target;
}
/// @brief Constructs a casted array from an array with different value types
/// using `static_cast`.
///
/// @tparam T source array element
/// @tparam R target array element
/// @tparam Length array length
/// @param value array to pad/trim
/// @return casted array
template <typename T, typename R, size_t Length>
inline std::array<R, Length> cast_array(const std::array<T, Length> &value) {
static_assert(std::is_convertible_v<T, R>, "T is not convertible to R");
if constexpr (std::is_same_v<T, R>) { return value; }
std::array<R, Length> result;
cast_to_assignable<std::array<T, Length>, R, Length, std::array<R, Length>>(
value, result);
return result;
}
/// @brief Takes an array and pads/trims it to the desired length by inserting
/// zeros or discarding unwanted elements
/// @tparam T array element
/// @tparam Source source array length
/// @tparam Target target array length
/// @param value array to pad/trim
/// @return padded/trimmed array
template <typename T, size_t Source, size_t Target>
inline std::array<T, Target> resize_array(std::array<T, Source> value) {
if constexpr (Source == Target) { return value; }
auto buff = std::array<T, Target>{0};
std::copy_n(value.begin(), std::min(Source, Target), buff.begin());
return buff;
}
} // namespace _priv_geom
/// @brief A 2D vector representation.
///
/// Uses eigen under to hood to provide SIMD optimizations on appropriate
/// platforms if available. Doesn't expose any of the eigen functionality
/// directly to avoid pollution.
///
/// @tparam T numeric component type.
template <typename T, size_t Length>
struct vec {
static_assert(std::is_arithmetic_v<T>, "T must be a number");
static_assert(Length >= 2, "Length must be greater than 2");
/// @brief Compile time component type information.
using Component = T;
private:
/// Sealed type used to disable constructor selection.
class _disabled {};
protected:
using Data = Vc::array<T, Length>;
Data value;
public:
vec() : value(Data{0}) {}
vec(const Data &value) : value(value) {}
vec(std::array<T, Length> array) {
_priv_geom::cast_to_assignable<std::array<T, Length>, T, Length,
Vc::array<T, Length>>(array, this->value);
}
vec(const vec<T, Length> &other) : vec(other.value) {}
vec(T x, T y) : vec<T, 2>(std::array<T, 2>{x, y}) {
static_assert(Length == 2, "constructor only valid for vec2<T>");
}
vec(T x, T y, T z) : vec<T, 3>(std::array<T, 3>{x, y, z, 0}) {
static_assert(Length == 3, "constructor only valid for vec3<T>");
}
vec(T x, T y, T z, T w) : vec<T, 4>(std::array<T, 4>{x, y, z, w}) {
static_assert(Length == 4, "constructor only valid for vec4<T>");
}
vec(vec<T, Length> &&other) { this->value = other->value; }
static inline vec<T, Length> uniform(T v) {
std::array<T, Length> data;
data.fill(v);
return vec<T, Length>(data);
}
/// @brief Returns vec component at `index`.
/// @param index component index.
/// @return component at `index` of this vec.
T at(size_t index) const { return static_cast<T>(this->value[index]); }
/// @brief vec x component.
/// @return x value of this vec.
inline T x() const { return this->at(0); }
/// @brief vec y component.
/// @return y value of this vec.
inline T y() const { return this->at(1); }
/// @brief vec z component.
/// @return z value of this vec.
inline T z() const {
static_assert(Length >= 3, "vector doesn't have a z component");
return this->at(2);
}
/// @brief vec w component.
/// @return w value of this vec.
inline T w() const {
static_assert(Length >= 4, "vector doesn't have a w component");
return this->at(3);
}
void set(size_t index, T value) { this->value[index] = value; }
inline void set_x(T new_value) { this->set(0, new_value); }
inline void set_y(T new_value) { this->set(1, new_value); }
inline void set_z(T new_value) {
static_assert(Length >= 3, "vector doesn't have a z component");
this->set(2, new_value);
}
inline void set_w(T new_value) {
static_assert(Length >= 4, "vector doesn't have a w component");
this->set(3, new_value);
}
vec<T, Length> &operator=(const vec<T, Length> &other) {
this->value = other.value;
return *this;
}
vec<T, Length> &operator=(vec<T, Length> &&other) {
this->value = std::move(other.value);
return *this;
}
template <typename O = T>
vec<T, Length> &operator=(std::array<O, Length> other) {
_priv_geom::cast_to_assignable(other, this->value);
return *this;
}
inline T operator[](size_t index) { return this->at(index); }
/// @brief Zero vector value.
static vec<T, Length> Zero() { return vec<T, Length>::uniform(0); }
/// @brief Unit vector value.
static vec<T, Length> One() { return vec<T, Length>::uniform(1); }
/// @brief X unit vector value.
static vec<T, Length> UnitX() {
Data buffer{0};
buffer[0] = static_cast<T>(1);
return vec(buffer);
}
/// @brief Y unit vector value.
static vec<T, Length> UnitY() {
Data buffer{0};
buffer[1] = static_cast<T>(1);
return vec(buffer);
}
/// @brief Z unit vector value.
static vec<T, Length> UnitZ() {
static_assert(Length >= 3, "vector doesn't have a z component");
Data buffer{0};
buffer[2] = static_cast<T>(1);
return vec(buffer);
}
/// @brief W unit vector value.
static vec<T, Length> UnitW() {
static_assert(Length >= 4, "vector doesn't have a w component");
Data buffer{0};
buffer[3] = static_cast<T>(1);
return vec(buffer);
}
// NOTE: All of the following loops will get unrolled by the compiler because
// Length is a constant expression (unless Length is very large).
inline vec<T, Length> operator+(vec<T, Length> other) const {
Data result{this->value};
for (size_t i = 0; i < Length; i++) { result[i] += other.value[i]; }
return vec<T, Length>(result);
}
inline vec<T, Length> &operator+=(vec<T, Length> other) {
for (size_t i = 0; i < Length; i++) { this->value[i] += other.value[i]; }
return *this;
}
inline vec<T, Length> operator-(vec<T, Length> other) const {
Data result{this->value};
for (size_t i = 0; i < Length; i++) { result[i] -= other.value[i]; }
return vec<T, Length>(result);
}
inline vec<T, Length> &operator-=(vec<T, Length> other) {
for (size_t i = 0; i < Length; i++) { this->value[i] -= other.value[i]; }
return *this;
}
inline vec<T, Length> operator*(T scalar) const {
Data result{this->value};
for (size_t i = 0; i < Length; i++) { result[i] *= scalar; }
return vec<T, Length>(result);
}
inline vec<T, Length> &operator*=(T scalar) {
for (size_t i = 0; i < Length; i++) { this->value[i] *= scalar; }
return *this;
}
inline vec<T, Length> operator*(vec<T, Length> other) const {
Data result{this->value};
for (size_t i = 0; i < Length; i++) { result[i] *= other.value[i]; }
return vec<T, Length>(result);
}
inline vec<T, Length> &operator*=(vec<T, Length> other) {
for (size_t i = 0; i < Length; i++) { this->value[i] *= other.value[i]; }
return *this;
}
inline vec<T, Length> operator/(T scalar) const {
Data result{this->value};
for (size_t i = 0; i < Length; i++) { result[i] /= scalar; }
return vec<T, Length>(result);
}
inline vec<T, Length> &operator/=(T scalar) {
for (size_t i = 0; i < Length; i++) { this->value[i] /= scalar; }
return *this;
}
inline vec<T, Length> operator/(vec<T, Length> other) const {
Data result{this->value};
for (size_t i = 0; i < Length; i++) { result[i] /= other.value[i]; }
return vec<T, Length>(result);
}
inline vec<T, Length> &operator/=(vec<T, Length> other) {
for (size_t i = 0; i < Length; i++) { this->value[i] /= other.value[i]; }
return *this;
}
inline bool operator==(vec<T, Length> other) const {
for (size_t i = 0; i < Length; i++) {
if (this->value[i] != other.value[i]) { return false; }
}
return true;
}
inline bool operator!=(vec<T, Length> other) const {
return !(*this == other);
}
inline vec<T, Length> operator-() const {
if constexpr (std::is_signed_v<T>) {
return *this * Data{-1};
} else {
return Data{std::numeric_limits<T>::max()} - *this;
}
}
inline vec<T, Length> abs() const {
if constexpr (std::is_signed_v<T>) {
Data result;
std::transform(this->value.begin(), this->value.end(), result.begin(),
std::abs);
return vec<T, Length>(result);
} else {
return *this;
}
}
/// @brief Computes component-wise vector minimum
/// @param other other vector
/// @returns new vector with min values
inline vec<T, Length> min(const vec<T, Length> &other) {
Data result{this->value};
for (size_t i = 0; i < Length; i++) {
result[i] = std::min(result[i], other.value[i]);
}
return vec<T, Length>(result);
}
/// @brief Computes component-wise vector maximum
/// @param other other vector
/// @returns new vector with max values
inline vec<T, Length> max(const vec<T, Length> &other) {
Data result{this->value};
for (size_t i = 0; i < Length; i++) {
result[i] = std::max(result[i], other.value[i]);
}
return vec<T, Length>(result);
}
inline T distance_squared(vec<T, Length> other) const {
vec<T, Length> buffer = other - *this;
buffer *= buffer;
return std::accumulate(buffer->value.begin(), buffer->value.end(), T{0});
}
inline T distance(vec<T, Length> &other) const {
return std::sqrt(this->distance_squared(other));
}
inline T magnitude_squared() const {
vec<T, Length> buffer = this->value * this->value;
return std::accumulate(buffer->value.begin(), buffer->value.end(), T{0});
}
inline T magnitude() const { return std::sqrt(this->magnitude_squared()); }
T surface() const {
static_assert(Length == 2, "surface computable only for 2D vectors");
return this->x() * this->y();
}
template <typename O>
vec<O, Length> cast() const {
Vc::array<O, Length> buffer;
_priv_geom::cast_to_assignable<Vc::array<T, Length>, O, Length,
Vc::array<O, Length>>(this->value, buffer);
return vec<O, Length>(buffer);
}
std::array<T, Length> to_array() const {
std::array<T, Length> result;
for (size_t i = 0; i < Length; ++i) { result[i] = this->value[i]; }
return result;
}
template <typename O>
operator vec<O, Length>() const {
return this->cast<O>();
}
operator std::array<T, Length>() const { return this->to_array(); }
};
template <typename T>
using vec2 = vec<T, 2>;
using vec2f = vec2<float>;
using vec2d = vec2<double>;
using vec2i = vec2<std::int32_t>;
template <typename T>
using vec3 = vec<T, 3>;
using vec3f = vec3<float>;
using vec3d = vec3<double>;
using vec3i = vec3<std::int32_t>;
template <typename T>
using vec4 = vec<T, 4>;
using vec4f = vec4<float>;
using vec4d = vec4<double>;
using vec4i = vec4<std::int32_t>;
enum class rect_kind {
SIZED,
ABSOLUTE,
};
/// @brief 2D rectangle representation using position and size vectors.
/// @tparam T component number type.
template <typename T = std::int32_t, rect_kind Kind = rect_kind::SIZED>
struct rect {
static_assert(std::is_arithmetic_v<T>, "T must be a number");
using Component = T;
private:
vec2<T> m_pos;
vec2<T> m_other;
public:
rect() : m_pos(vec2<T>::Zero()), m_other(vec2<T>::Zero()) {}
rect(vec2<T> pos, vec2<T> other) : m_pos(pos), m_other(other) {}
/// @brief Rectangle x position.
/// @return x position of this rectangle.
inline T x() const { return this->m_pos.x(); }
/// @brief Rectangle y position.
/// @return y position of this rectangle.
inline T y() const { return this->m_pos.y(); }
inline vec2<T> pos() const { return this->m_pos; }
inline vec2<T> size() const {
if constexpr (Kind == rect_kind::SIZED) {
return this->m_other;
} else {
return this->m_other - this->m_pos;
}
}
inline vec2<T> end_pos() const {
if constexpr (Kind == rect_kind::SIZED) {
return this->m_pos + this->m_other;
} else {
return this->m_other;
}
}
/// @brief Rectangle end x position.
/// @return ending x position of this rectangle.
inline T end_x() const { return this->end_pos().x(); }
/// @brief Rectangle end y position.
/// @return ending y position of this rectangle.
inline T end_y() const { return this->end_pos().y(); }
/// @brief Rectangle width.
/// @return width of this rectangle.
inline T width() const {
return size().x();
}
/// @brief Rectangle height.
/// @return height of this rectangle.
inline T height() const {
return size().y();
}
/// @brief Returns rectangle component at `index`.
/// @param index component index.
/// @return component at `index` of this rectangle.
T at(size_t index) const {
assert_print(index < static_cast<size_t>(4), "index out of bounds");
switch (index) {
case 0:
return this->m_pos.x();
case 1:
return this->m_pos.y();
case 2:
return this->m_other.x();
case 3:
return this->m_other.y();
default:
UNREACHABLE();
}
}
inline void set_pos(vec2<T> value) { this->m_pos = value; }
inline void set_pos(T x, T y) { this->set_pos(vec2<T>(x, y)); }
inline void set_size(vec2<T> value) {
if constexpr (Kind == rect_kind::SIZED) {
this->m_other = value;
} else {
this->m_other = this->m_pos + value;
}
}
inline void set_size(T width, T height) {
this->set_size(vec2<T>(width, height));
}
inline void set_end_pos(vec2<T> value) {
if constexpr (Kind == rect_kind::SIZED) {
this->m_other = value - this->m_pos;
} else {
this->m_other = value;
}
}
inline void set_end_pos(T x, T y) { this->set_end_pos(vec2<T>(x, y)); }
inline void set_x(T value) { this->m_pos.set_x(value); }
inline void set_y(T value) { this->m_pos.set_y(value); }
inline void set_width(T value) {
if constexpr (Kind == rect_kind::SIZED) {
this->m_other.set_x(value);
} else {
this->m_other.set_x(this->m_pos.get_x() + value);
}
}
inline void set_height(T value) {
if constexpr (Kind == rect_kind::SIZED) {
this->m_other.set_y(value);
} else {
this->m_other.set_y(this->m_pos.get_y() + value);
}
}
inline void set_end_x(T value) {
if constexpr (Kind == rect_kind::SIZED) {
this->m_other.set_x(value - this->m_pos.get_x());
} else {
this->m_other.set_x(value);
}
}
inline void set_end_y(T value) {
if constexpr (Kind == rect_kind::SIZED) {
this->m_other.set_y(value - this->m_pos.get_y());
} else {
this->m_other.set_y(value);
}
}
void set(size_t index, T value) {
assert_print(index < static_cast<size_t>(4), "index out of bounds");
switch (index) {
case 0:
return this->m_pos.set_x(value);
case 1:
return this->m_pos.set_y(value);
case 2:
return this->m_other.set_x(value);
case 3:
return this->m_other.set_y(value);
default:
UNREACHABLE();
}
}
std::array<vec2<T>, 4> corners() const {
return std::array<vec2<T>, 4>{
this->m_pos,
this->m_pos + vec2<T>(this->width(), 0),
this->end_pos(),
this->m_pos + vec2<T>(0, this->height()),
};
}
template <typename O = T>
bool contains(vec2<O> p) const {
return p.x() >= this->x() && p.x() < this->x() + this->width() &&
p.y() >= this->y() && p.y() < this->y() + this->height();
}
template <typename O = T>
bool contains(rect<O> other) const {
return contains(other.m_pos) &&
contains(other.m_pos + vec2<O>(other.width(), 0)) &&
contains(other.m_pos + other.m_other) &&
contains(other.m_pos + vec2<O>(0, other.height()));
}
private:
template <typename O = T>
bool _intersects_partial(rect<O> other) const {
return contains(other.m_pos) ||
contains(other.m_pos + vec2<O>(other.width(), 0)) ||
contains(other.m_pos + other.m_other) ||
contains(other.m_pos + vec2<O>(0, other.height()));
}
public:
template <typename O = T>
bool intersects(rect<O> other) const {
return this->_intersects_partial(m_other) ||
other._intersects_partial(*this);
}
rect<T, Kind> &operator=(const rect<T, Kind> &other) {
this->m_pos = other.m_pos;
this->m_other = other.m_other;
return *this;
}
rect<T, Kind> &operator=(rect<T, Kind> &&other) {
this->m_pos = other.m_pos;
this->m_other = other.m_other;
return *this;
}
template <typename O = T>
rect<T, Kind> &operator=(std::array<O, 4> other) {
_priv_geom::cast_to_assignable(other.m_pos, this->m_pos);
_priv_geom::cast_to_assignable(other.m_other, this->m_other);
return *this;
}
inline T operator[](size_t index) {
if (index < 2) {
return this->m_pos[index];
} else if (index < 4) {
return this->m_other[index - 2];
} else {
CRIT_ERR("index out of bounds");
}
}
#ifdef BUILD_X11
XRectangle to_xrectangle() const {
return XRectangle{.x = static_cast<short>(this->x()),
.y = static_cast<short>(this->y()),
.width = static_cast<unsigned short>(this->width()),
.height = static_cast<unsigned short>(this->height())};
}
#endif /* BUILD_X11 */
rect<T, rect_kind::SIZED> to_sized() const {
if constexpr (Kind == rect_kind::SIZED) {
return *this;
} else {
return rect<T, rect_kind::SIZED>{this->m_pos,
this->m_other - this->m_pos};
}
}
rect<T, rect_kind::ABSOLUTE> to_absolute() const {
if constexpr (Kind == rect_kind::ABSOLUTE) {
return *this;
} else {
return rect<T, rect_kind::ABSOLUTE>{this->m_pos,
this->m_pos + this->m_other};
}
}
std::array<T, 4> to_array() const {
return std::array<T, 4>{this->m_pos.x(), this->m_pos.y(), this->m_other.x(),
this->m_other.y()};
}
inline operator std::array<T, 4>() const { return this->to_array(); }
inline explicit operator rect<T, rect_kind::SIZED>() const {
return this->to_sized();
}
inline explicit operator rect<T, rect_kind::ABSOLUTE>() const {
return this->to_absolute();
}
};
template <typename T>
using sized_rect = rect<T>;
template <typename T>
using absolute_rect = rect<T, rect_kind::ABSOLUTE>;
} // namespace conky
#endif /* _CONKY_GEOMETRY_H_ */
| 19,833
|
C++
|
.h
| 579
| 29.929188
| 80
| 0.618211
|
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,796
|
rss.h
|
brndnmtthws_conky/src/rss.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 RSS_H_
#define RSS_H_
void rss_scan_arg(struct text_object *, const char *);
void rss_print_info(struct text_object *, char *, unsigned int);
void rss_free_obj_info(struct text_object *);
#endif /*RSS_H_*/
| 1,069
|
C++
|
.h
| 29
| 35
| 72
| 0.741562
|
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,797
|
ibm.h
|
brndnmtthws_conky/src/ibm.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 _IBM_H
#define _IBM_H
void get_ibm_acpi_fan(struct text_object *, char *, unsigned int);
int get_ibm_acpi_temps(void);
void get_ibm_acpi_volume(struct text_object *, char *, unsigned int);
void get_ibm_acpi_brightness(struct text_object *, char *, unsigned int);
void get_ibm_acpi_thinklight(struct text_object *, char *, unsigned int);
void parse_ibm_temps_arg(struct text_object *, const char *);
void print_ibm_temps(struct text_object *, char *, unsigned int);
#endif /* _IBM_H */
| 1,349
|
C++
|
.h
| 33
| 39.090909
| 73
| 0.741616
|
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,798
|
gui.h
|
brndnmtthws_conky/src/gui.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 _CONKY_GUI_H_
#define _CONKY_GUI_H_
#include "config.h"
#include "geometry.h"
#include "setting.hh"
#include "colour-settings.h"
/// @brief Represents alignment on a single axis.
enum class axis_align : uint8_t {
/// No alignment
NONE = 0,
/// Top or left alignment
START = 0b01,
/// Middle alignment
MIDDLE = 0b10,
/// Bottom or right alignment
END = 0b11,
};
constexpr uint8_t operator*(axis_align index) {
return static_cast<uint8_t>(index);
}
/// @brief Represents alignment on a 2D plane.
///
/// Values are composed of 2 `axis_align` values: 2 bits (at 0x0C) for vertical
/// aligment and 2 least significant bits for horizontal.
enum class alignment : uint8_t {
NONE = 0,
NONE_LEFT = 0b0001,
NONE_MIDDLE = 0b0010,
NONE_RIGHT = 0b0011,
TOP_LEFT = 0b0101,
TOP_MIDDLE = 0b0110,
TOP_RIGHT = 0b0111,
MIDDLE_LEFT = 0b1001,
MIDDLE_MIDDLE = 0b1010,
MIDDLE_RIGHT = 0b1011,
BOTTOM_LEFT = 0b1101,
BOTTOM_MIDDLE = 0b1110,
BOTTOM_RIGHT = 0b1111,
};
constexpr uint8_t operator*(alignment index) {
return static_cast<uint8_t>(index);
}
/// @brief Returns the horizontal axis alignment component of `alignment`.
/// @param of 2D alignment to extract axis alignment from
/// @return horizontal `axis_align`
[[nodiscard]] inline axis_align horizontal_alignment(alignment of) {
return static_cast<axis_align>(static_cast<uint8_t>(of) & 0b11);
}
/// @brief Returns the vertical axis alignment component of `alignment`.
/// @param of 2D alignment to extract axis alignment from
/// @return vertical `axis_align`
[[nodiscard]] inline axis_align vertical_alignment(alignment of) {
return static_cast<axis_align>((static_cast<uint8_t>(of) >> 2) & 0b11);
}
/// @brief Describes how and where a window should be mounted, as well as its
/// behavior.
///
/// We assume the following order of layers:
/// - Background - behind conky and any other windows, contains icons and
/// desktop menus
/// - Background widgets and docks
/// - Windows
/// - Panels - contains content that covers windows
/// - Override windows - input-override windows on X11, custom overlays, lock
/// screens, etc.
///
/// See also:
/// - [X11 wm-spec `_NET_WM_WINDOW_TYPE` property](
/// https://specifications.freedesktop.org/wm-spec/1.3/ar01s05.html#idm45684324619328)
/// - [wlr-layer-shell layers](
/// https://wayland.app/protocols/wlr-layer-shell-unstable-v1#zwlr_layer_shell_v1:enum:layer)
/// - [xdg-positioner::anchor](
/// https://wayland.app/protocols/xdg-shell#xdg_positioner:enum:anchor)
enum class window_type : uint8_t {
/// @brief Acts as a normal window - has decorations, above
/// background, widgets and docks, below panels.
NORMAL = 0,
/// @brief Screen background, no decorations, positioned at the very bottom
/// and behind widgets and docks.
DESKTOP,
/// @brief Normal window, always shown above parent window (group).
///
/// See: [Popup](https://wayland.app/protocols/xdg-shell#xdg_popup) XDG shell
/// surface.
UTILITY,
/// @brief No decorations, between windows and background, attached to screen
/// edge.
DOCK,
/// @brief No decorations, above windows, attached to screen edge, reserves
/// space.
PANEL,
#ifdef BUILD_X11
/// @brief On top of everything else, not controlled by WM.
OVERRIDE,
#endif /* BUILD_X11 */
};
constexpr uint8_t operator*(window_type index) {
return static_cast<uint8_t>(index);
}
#if defined(BUILD_X11) && defined(OWN_WINDOW)
// Only works in X11 because Wayland doesn't support
/// @brief Hints are used to tell WM how it should treat a window.
///
/// See: [X11 wm-spec `_NET_WM_STATE` property](
/// https://specifications.freedesktop.org/wm-spec/1.3/ar01s05.html#idm45684324611552)
enum class window_hints : uint16_t {
UNDECORATED = 0,
BELOW,
ABOVE,
STICKY,
SKIP_TASKBAR,
SKIP_PAGER
};
constexpr uint8_t operator*(window_hints index) {
return static_cast<uint8_t>(index);
}
inline void SET_HINT(window_hints &mask, window_hints hint) {
mask = static_cast<window_hints>(*mask | (1 << (*hint)));
}
inline void SET_HINT(uint16_t &mask, window_hints hint) {
mask = mask | (1 << (*hint));
}
inline bool TEST_HINT(window_hints mask, window_hints hint) {
return (*mask & (1 << (*hint))) != 0;
}
inline bool TEST_HINT(uint16_t mask, window_hints hint) {
return (mask & (1 << (*hint))) != 0;
}
#endif
extern conky::absolute_rect<int> workarea;
extern char window_created;
void destroy_window(void);
void create_gc(void);
void set_struts(int);
bool out_to_gui(lua::state &l);
void print_monitor(struct text_object *, char *, unsigned int);
void print_monitor_number(struct text_object *, char *, unsigned int);
void print_desktop(struct text_object *, char *, unsigned int);
void print_desktop_number(struct text_object *, char *, unsigned int);
void print_desktop_name(struct text_object *, char *, unsigned int);
/* Num lock, Scroll lock, Caps Lock */
void print_key_num_lock(struct text_object *, char *, unsigned int);
void print_key_caps_lock(struct text_object *, char *, unsigned int);
void print_key_scroll_lock(struct text_object *, char *, unsigned int);
/* Keyboard layout and mouse speed in percentage */
void print_keyboard_layout(struct text_object *, char *, unsigned int);
void print_mouse_speed(struct text_object *, char *, unsigned int);
extern conky::simple_config_setting<alignment> text_alignment;
namespace priv {
class own_window_setting : public conky::simple_config_setting<bool> {
typedef conky::simple_config_setting<bool> Base;
protected:
virtual void lua_setter(lua::state &l, bool init);
public:
own_window_setting() : Base("own_window", false, false) {}
};
} // namespace priv
extern conky::simple_config_setting<int> head_index;
extern priv::colour_setting default_shade_color;
extern priv::colour_setting default_outline_color;
extern conky::range_config_setting<int> border_inner_margin;
extern conky::range_config_setting<int> border_outer_margin;
extern conky::range_config_setting<int> border_width;
extern conky::simple_config_setting<bool> forced_redraw;
#ifdef OWN_WINDOW
extern priv::own_window_setting own_window;
extern conky::simple_config_setting<std::string> own_window_title;
/// @brief Window type.
///
/// @see window_type
extern conky::simple_config_setting<window_type> own_window_type;
/// @brief X11 window class; Wayland XDG Shell app_id.
extern conky::simple_config_setting<std::string> own_window_class;
#endif /* OWN_WINDOW */
#if defined(OWN_WINDOW) && defined(BUILD_X11)
struct window_hints_traits {
static const lua::Type type = lua::TSTRING;
typedef uint16_t Type;
static std::pair<Type, bool> convert(lua::state &l, int index,
const std::string &name);
};
extern conky::simple_config_setting<uint16_t, window_hints_traits>
own_window_hints;
#endif /* OWN_WINDOW && BUILD_X11 */
#if defined(OWN_WINDOW) || defined(BUILD_WAYLAND)
extern priv::colour_setting background_colour;
extern conky::simple_config_setting<bool> set_transparent;
#endif /* OWN_WINDOW || BUILD_WAYLAND */
#if defined(BUILD_ARGB) || defined(BUILD_WAYLAND)
extern conky::simple_config_setting<bool> use_argb_visual;
extern conky::range_config_setting<int> own_window_argb_value;
#endif /* BUILD_ARGB || BUILD_WAYLAND */
#endif /* _CONKY_GUI_H_ */
| 8,153
|
C++
|
.h
| 216
| 35.722222
| 95
| 0.728974
|
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,799
|
prioqueue.h
|
brndnmtthws_conky/src/prioqueue.h
|
/*
*
* prioqueue: a simple priority queue implementation
*
* Copyright (C) 2009 Phil Sutter <phil@nwl.cc>
*
* Initially based on the former implementation of sorted processes in
* top.c, Copyright (C) 2005 David Carter <boojit@pundo.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 <http://www.gnu.org/licenses/>.
*
*/
#ifndef _PRIOQUEUE_H
#define _PRIOQUEUE_H
/* forward-define for private data */
struct prio_queue;
/* typedef for a distinct prioqueue object */
typedef struct prio_queue *prio_queue_t;
/* initialise a prioqueue object (mandatory) */
prio_queue_t init_prio_queue(void);
/* set the compare function (mandatory)
* (*compare) shall return:
* <0 if a should come before b,
* >0 if b should come before a,
* 0 if doesn't matter */
void pq_set_compare(prio_queue_t, int (*compare)(void *a, void *b));
/* set the data free function (optional)
* (*free) will be called when:
* - dropping elements from the end of a limited size queue and
* - free_prio_queue() finds leftover elements in the given queue */
void pq_set_free(prio_queue_t, void (*free)(void *));
/* set a maximum queue size (optional) (defaults to INT_MAX) */
void pq_set_max_size(prio_queue_t, int);
/* insert an element into the given queue */
void insert_prio_elem(prio_queue_t, void *);
/* return the number of elements in the queue */
int pq_get_cur_size(prio_queue_t queue);
/* pop the top-most element from the queue
* returns nullptr if queue is empty */
void *pop_prio_elem(prio_queue_t);
/* clear and free the given queue */
void free_prio_queue(prio_queue_t);
#endif /* _PRIOQUEUE_H */
| 2,173
|
C++
|
.h
| 53
| 39.226415
| 72
| 0.736243
|
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,800
|
openbsd.h
|
brndnmtthws_conky/src/openbsd.h
|
/* */
#ifndef OPENBSD_H_
#define OPENBSD_H_
#include <machine/apmvar.h>
#include <sys/param.h>
#include <sys/sensors.h>
#include <sys/sysctl.h>
#include "common.h"
void parse_obsd_sensor(struct text_object *, const char *);
void print_obsd_sensors_temp(struct text_object *, char *, int);
void print_obsd_sensors_fan(struct text_object *, char *, int);
void print_obsd_sensors_volt(struct text_object *, char *, int);
void get_obsd_vendor(struct text_object *, char *buf,
size_t client_buffer_size);
void get_obsd_product(struct text_object *, char *buf,
size_t client_buffer_size);
#if defined(i386) || defined(__i386__)
typedef struct apm_power_info *apm_info_t;
#endif
int get_entropy_avail(unsigned int *);
int get_entropy_poolsize(unsigned int *);
#endif /*OPENBSD_H_*/
| 824
|
C++
|
.h
| 22
| 34.227273
| 64
| 0.699749
|
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,801
|
bsdapm.h
|
brndnmtthws_conky/src/bsdapm.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 _BSDAPM_H
#define _BSDAPM_H
void print_apm_adapter(struct text_object *, char *, unsigned int);
void print_apm_battery_life(struct text_object *, char *, unsigned int);
void print_apm_battery_time(struct text_object *, char *, unsigned int);
#endif /* _BSDAPM_H */
| 1,328
|
C++
|
.h
| 34
| 37.205882
| 72
| 0.749226
|
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,802
|
conky-imlib2.h
|
brndnmtthws_conky/src/conky-imlib2.h
|
/*
*
* 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/>.
*
*/
#ifndef _CONKY_IMBLI2_H_
#define _CONKY_IMBLI2_H_
#include "setting.hh"
#include "text_object.h"
#include <array>
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wvariadic-macros"
#include <X11/Xlib.h>
#pragma GCC diagnostic pop
using saved_coordinates_t = std::array<std::array<int, 2>, 100>;
extern saved_coordinates_t saved_coordinates;
void cimlib_add_image(const char *args);
void cimlib_set_cache_size(long size);
void cimlib_set_cache_flush_interval(long interval);
void cimlib_render(int x, int y, int width, int height, uint32_t flush_interval,
bool draw_blended);
void cimlib_cleanup(void);
void print_image_callback(struct text_object *, char *, unsigned int);
class imlib_cache_size_setting
: public conky::range_config_setting<unsigned long> {
typedef conky::range_config_setting<unsigned long> Base;
protected:
virtual void lua_setter(lua::state &l, bool init);
virtual void cleanup(lua::state &l);
public:
imlib_cache_size_setting()
: Base("imlib_cache_size", 0, std::numeric_limits<unsigned long>::max(),
4096 * 1024, true) {}
};
extern conky::range_config_setting<unsigned int> imlib_cache_flush_interval;
extern conky::simple_config_setting<bool> imlib_draw_blended;
#endif /* _CONKY_IMBLI2_H_ */
| 2,112
|
C++
|
.h
| 54
| 36.537037
| 80
| 0.744868
|
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,803
|
ccurl_thread.h
|
brndnmtthws_conky/src/ccurl_thread.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 _CURL_THREAD_H_
#define _CURL_THREAD_H_
#include <curl/curl.h>
#include "logging.h"
#include "update-cb.hh"
namespace priv {
// factored out stuff that does not depend on the template parameters
class curl_internal {
public:
std::string last_modified;
std::string etag;
std::string data;
CURL *curl;
static size_t parse_header_cb(void *ptr, size_t size, size_t nmemb,
void *data);
static size_t write_cb(void *ptr, size_t size, size_t nmemb, void *data);
void do_work();
// called by do_work() after downloading data from the uri
// it should populate the result variable
virtual void process_data() = 0;
explicit curl_internal(const std::string &url);
virtual ~curl_internal() {
if (curl) curl_easy_cleanup(curl);
}
};
} // namespace priv
/*
* Curl callback class template
* the key is an url
*/
template <typename Result, typename... Keys>
class curl_callback : public conky::callback<Result, std::string, Keys...>,
public priv::curl_internal {
typedef conky::callback<Result, std::string, Keys...> Base1;
typedef priv::curl_internal Base2;
protected:
virtual void work() {
DBGP("reading curl data from '%s'", std::get<0>(Base1::tuple).c_str());
do_work();
}
public:
curl_callback(uint32_t period, const typename Base1::Tuple &tuple)
: Base1(period, false, tuple), Base2(std::get<0>(tuple)) {}
};
/* $curl exports begin */
/* runs instance of $curl */
void ccurl_process_info(char *p, int p_max_size, const std::string &uri,
int interval);
void curl_parse_arg(struct text_object *, const char *);
void curl_print(struct text_object *, char *, unsigned int);
void curl_obj_free(struct text_object *);
/* $curl exports end */
#endif /* _CURL_THREAD_H_ */
| 2,670
|
C++
|
.h
| 76
| 31.815789
| 75
| 0.698216
|
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,804
|
macros.h
|
brndnmtthws_conky/src/macros.h
|
#ifndef _CONKY_MACROS_H_
#define _CONKY_MACROS_H_
#include "logging.h"
// LIKELY and UNLIKELY can be used to mark if statement branches as likely (hot)
// or unlikely (cold). They help compiler rearange code to optimize hot paths
// and can improve perfomance when used on architectures with support for branch
// prediction.
#if defined(__clang__) || defined(__GNUC__)
#define LIKELY(x) __builtin_expect(!!(x), 1)
#define UNLIKELY(x) __builtin_expect(!!(x), 0)
#else
#define LIKELY(x) (!!(x))
#define UNLIKELY(x) (!!(x))
#endif // defined(__clang__) || defined(__GNUC__)
// Assertion with custom error message.
#define assert_print(cond, error) \
(LIKELY(cond) ? static_cast<void>(0) : CRIT_ERR(error))
// Assumptions are contracts which are expected to be upheld by the developer
// 100% of the time. They help the compiler significantly optimize code, but
// cause UB if not upheld. As such, they are not a substitute for proper error
// handling or assertions.
//
// They throw CRIT_ERR in debug builds.
#ifdef NDEBUG
#ifdef _MSC_VER
#define ASSUME(cond) __assume(cond)
#elif defined(__clang__)
#define ASSUME(cond) __builtin_assume(cond)
#elif defined(__GNUC__)
#define ASSUME(cond) ((cond) ? static_cast<void>(0) : __builtin_unreachable())
#else /* other compilers */
#define ASSUME(cond) static_cast<void>(!!(cond))
#endif /* compiler selection */
#else /* DEBUG */
#define ASSUME(cond) assert_print(cond, "assertion " #cond " failed")
#endif /* NDEBUG */
// UNREACHABLE is used to mark unreachable part of code execution which helps
// the compiler optimize code, but also causes UB if marked position in code is
// actually reached.
//
// It throws CRIT_ERR in debug builds.
#ifdef NDEBUG
#ifdef __GNUC__ // GCC, Clang, ICC
#define UNREACHABLE() (__builtin_unreachable())
#elif defined(_MSC_VER) // MSVC
#define UNREACHABLE() (__assume(false))
#else /* other compilers */
// unreachable_impl must be emitted in a separated TU if used from C code due to
// the difference in rule for inline functions in C. Conky is compiled by a C++
// compiler though so it's fine to place it here.
[[noreturn]] inline void unreachable_impl() {}
#define UNREACHABLE() (unreachable_impl())
#endif /* compiler selection */
#else /* DEBUG */
#define UNREACHABLE() (CRIT_ERR("reached unreachable"))
#endif /* NDEBUG */
#endif /* _CONKY_MACROS_H_ */
| 2,353
|
C++
|
.h
| 57
| 40.105263
| 80
| 0.721591
|
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,805
|
proc.h
|
brndnmtthws_conky/src/proc.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_PROC_H
#define CONKY_PROC_H
#define PROCDIR "/proc"
#define READERR "Can't read '%s'"
#define READSIZE 128
void print_pid_chroot(struct text_object *obj, char *p,
unsigned int p_max_size);
void print_pid_cmdline(struct text_object *obj, char *p,
unsigned int p_max_size);
void print_pid_cwd(struct text_object *obj, char *p, unsigned int p_max_size);
void print_pid_environ(struct text_object *obj, char *p,
unsigned int p_max_size);
void print_pid_environ_list(struct text_object *obj, char *p,
unsigned int p_max_size);
void print_pid_exe(struct text_object *obj, char *p, unsigned int p_max_size);
void print_pid_nice(struct text_object *obj, char *p, unsigned int p_max_size);
void print_pid_openfiles(struct text_object *obj, char *p,
unsigned int p_max_size);
void print_pid_parent(struct text_object *obj, char *p,
unsigned int p_max_size);
void print_pid_priority(struct text_object *obj, char *p,
unsigned int p_max_size);
void print_pid_state(struct text_object *obj, char *p, unsigned int p_max_size);
void print_pid_state_short(struct text_object *obj, char *p,
unsigned int p_max_size);
void print_pid_stderr(struct text_object *obj, char *p,
unsigned int p_max_size);
void print_pid_stdin(struct text_object *obj, char *p, unsigned int p_max_size);
void print_pid_stdout(struct text_object *obj, char *p,
unsigned int p_max_size);
void print_pid_threads(struct text_object *obj, char *p,
unsigned int p_max_size);
void print_pid_thread_list(struct text_object *obj, char *p,
unsigned int p_max_size);
void print_pid_time_kernelmode(struct text_object *obj, char *p,
unsigned int p_max_size);
void print_pid_time_usermode(struct text_object *obj, char *p,
unsigned int p_max_size);
void print_pid_time(struct text_object *obj, char *p, unsigned int p_max_size);
void print_pid_uid(struct text_object *obj, char *p, unsigned int p_max_size);
void print_pid_euid(struct text_object *obj, char *p, unsigned int p_max_size);
void print_pid_suid(struct text_object *obj, char *p, unsigned int p_max_size);
void print_pid_fsuid(struct text_object *obj, char *p, unsigned int p_max_size);
void print_pid_gid(struct text_object *obj, char *p, unsigned int p_max_size);
void print_pid_egid(struct text_object *obj, char *p, unsigned int p_max_size);
void print_pid_sgid(struct text_object *obj, char *p, unsigned int p_max_size);
void print_pid_fsgid(struct text_object *obj, char *p, unsigned int p_max_size);
void print_pid_read(struct text_object *obj, char *p, unsigned int p_max_size);
void print_pid_vmpeak(struct text_object *obj, char *p,
unsigned int p_max_size);
void print_pid_vmsize(struct text_object *obj, char *p,
unsigned int p_max_size);
void print_pid_vmlck(struct text_object *obj, char *p, unsigned int p_max_size);
void print_pid_vmhwm(struct text_object *obj, char *p, unsigned int p_max_size);
void print_pid_vmrss(struct text_object *obj, char *p, unsigned int p_max_size);
void print_pid_vmdata(struct text_object *obj, char *p,
unsigned int p_max_size);
void print_pid_vmstk(struct text_object *obj, char *p, unsigned int p_max_size);
void print_pid_vmexe(struct text_object *obj, char *p, unsigned int p_max_size);
void print_pid_vmlib(struct text_object *obj, char *p, unsigned int p_max_size);
void print_pid_vmpte(struct text_object *obj, char *p, unsigned int p_max_size);
void print_pid_write(struct text_object *obj, char *p, unsigned int p_max_size);
void scan_cmdline_to_pid_arg(struct text_object *obj, const char *arg,
void *free_at_crash);
void print_cmdline_to_pid(struct text_object *obj, char *p,
unsigned int p_max_size);
#endif /* CONKY_PROC_H */
| 5,137
|
C++
|
.h
| 95
| 47.8
| 80
| 0.683939
|
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,806
|
display-ncurses.hh
|
brndnmtthws_conky/src/display-ncurses.hh
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Please see COPYING for details
*
* Copyright (C) 2018 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_NCURSES_HH
#define DISPLAY_NCURSES_HH
#include "config.h"
#include <limits>
#include <string>
#include <type_traits>
#include "colours.h"
#include "display-console.hh"
#include "luamm.hh"
namespace conky {
/*
* A base class for ncurses display output.
*/
class display_output_ncurses : public display_output_console {
public:
explicit display_output_ncurses();
virtual ~display_output_ncurses() {}
// check if available and enabled in settings
virtual bool detect();
// connect to DISPLAY and other stuff
virtual bool initialize();
virtual bool shutdown();
virtual bool draw_line_inner_required() { return true; }
// drawing primitives
virtual void set_foreground_color(Colour c);
virtual void begin_draw_text();
virtual void end_draw_text();
virtual void draw_string(const char *s, int w);
virtual void line_inner_done();
virtual int getx();
virtual int gety();
virtual void gotox(int x);
virtual void gotoy(int y);
virtual void gotoxy(int x, int y);
virtual void flush();
// ncurses-specific
};
} // namespace conky
#endif /* DISPLAY_NCURSES_HH */
| 1,915
|
C++
|
.h
| 60
| 29.583333
| 72
| 0.743478
|
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,807
|
i8k.h
|
brndnmtthws_conky/src/i8k.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) 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 _I8K_H
#define _I8K_H
int update_i8k(void);
void print_i8k_left_fan_status(struct text_object *, char *, unsigned int);
void print_i8k_cpu_temp(struct text_object *, char *, unsigned int);
void print_i8k_right_fan_status(struct text_object *, char *, unsigned int);
void print_i8k_ac_status(struct text_object *, char *, unsigned int);
void print_i8k_version(struct text_object *, char *, unsigned int);
void print_i8k_bios(struct text_object *, char *, unsigned int);
void print_i8k_serial(struct text_object *, char *, unsigned int);
void print_i8k_left_fan_rpm(struct text_object *, char *, unsigned int);
void print_i8k_right_fan_rpm(struct text_object *, char *, unsigned int);
void print_i8k_buttons_status(struct text_object *, char *, unsigned int);
#endif /* _I8K_H */
| 1,875
|
C++
|
.h
| 43
| 41.883721
| 76
| 0.745216
|
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,808
|
iconv_tools.h
|
brndnmtthws_conky/src/iconv_tools.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 _ICONV_TOOLS_H
#define _ICONV_TOOLS_H
void free_iconv(struct text_object *);
void iconv_convert(size_t *, char *, char *, size_t);
void init_iconv_start(struct text_object *, void *, const char *);
void init_iconv_stop(void);
void print_iconv_start(struct text_object *, char *, unsigned int);
void print_iconv_stop(struct text_object *, char *, unsigned int);
#endif /* _ICONV_TOOLS_H */
| 1,454
|
C++
|
.h
| 37
| 37.459459
| 72
| 0.744515
|
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,809
|
llua.h
|
brndnmtthws_conky/src/llua.h
|
/*
*
* 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/>.
*
*/
#ifndef LUA_H_
#define LUA_H_
extern "C" {
#include <lauxlib.h>
#include <lua.h>
#include <lualib.h>
}
#include <config.h>
#include "geometry.h"
#ifdef BUILD_MOUSE_EVENTS
#include "mouse-events.h"
#endif /* BUILD_MOUSE_EVENTS */
#define LUAPREFIX "conky_"
#ifdef HAVE_SYS_INOTIFY_H
/* check our lua inotify status */
void llua_inotify_query(int wd, int mask);
#endif /* HAVE_SYS_INOTIFY_H */
void llua_startup_hook(void);
void llua_shutdown_hook(void);
#ifdef BUILD_GUI
void llua_draw_pre_hook(void);
void llua_draw_post_hook(void);
#ifdef BUILD_MOUSE_EVENTS
/**
Takes a mouse_event as argument.
Returns true if event was properly consumed, false otherwise.
*/
template <typename EventT>
bool llua_mouse_hook(const EventT &ev);
#endif /* BUILD_MOUSE_EVENTS */
void llua_setup_window_table(conky::rect<int> text_rect);
void llua_update_window_table(conky::rect<int> text_rect);
#endif /* BUILD_GUI */
void llua_setup_info(struct information *i, double u_interval);
void llua_update_info(struct information *i, double u_interval);
void print_lua(struct text_object *, char *, unsigned int);
void print_lua_parse(struct text_object *, char *, unsigned int);
double lua_barval(struct text_object *);
#endif /* LUA_H_*/
| 2,081
|
C++
|
.h
| 61
| 32.47541
| 72
| 0.748879
|
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,810
|
x11.h
|
brndnmtthws_conky/src/x11.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 CONKY_X11_H
#define CONKY_X11_H
#include "config.h"
#ifndef BUILD_X11
#error x11.h included when BUILD_X11 is disabled
#endif
#include <X11/Xatom.h>
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wvariadic-macros"
#include <X11/Xlib.h>
#pragma GCC diagnostic pop
#ifdef BUILD_XFT
#include <X11/Xft/Xft.h>
#endif
#ifdef BUILD_XDBE
#include <X11/extensions/Xdbe.h>
#endif
#include <cstdint>
#include <functional>
#include <vector>
// TODO: remove lua requirement from x11_init_window
#include "llua.h"
#include "geometry.h"
#include "gui.h"
/* true if use_argb_visual=true and argb visual was found*/
extern bool have_argb_visual;
#define ATOM(a) XInternAtom(display, #a, False)
/// @brief Display where conky is placed
extern Display *display;
/// @brief Screen with conky
extern int screen;
struct conky_x11_window {
/// XID of x11 root window
Window root;
/// XID of Conky window
Window window;
/// XID of DE desktop window (or root if none)
Window desktop;
Drawable drawable;
Visual *visual;
Colormap colourmap;
GC gc;
// Mask containing all events captured by conky
int64_t event_mask;
#ifdef BUILD_XDBE
XdbeBackBuffer back_buffer;
#else /*BUILD_XDBE*/
Pixmap back_buffer;
#endif /*BUILD_XDBE*/
#ifdef BUILD_XFT
XftDraw *xftdraw;
#endif /*BUILD_XFT*/
#if defined(BUILD_MOUSE_EVENTS) || defined(BUILD_XINPUT)
// Don't feature gate with BUILD_XINPUT; controls fallback.
std::int32_t xi_opcode;
#endif /* BUILD_MOUSE_EVENTS || BUILD_XINPUT */
/// @brief Window geometry in screen coordinate space
conky::rect<int> geometry;
};
extern struct conky_x11_window window;
void update_x11_resource_db(bool first_run = false);
void update_x11_workarea();
void init_x11();
void destroy_window(void);
void create_gc(void);
void set_transparent_background(Window win);
void get_x11_desktop_info(Display *current_display, Atom atom);
void set_struts(alignment alignment);
void x11_init_window(lua::state &l, bool own);
void deinit_x11();
/// @brief Forwards argument event to the top-most window at event positon that
/// isn't conky.
///
/// Calling this function is time sensitive as it will query window at event
/// position **at invocation time**.
/// @param event event to forward
/// @param cookie optional cookie data
void propagate_x11_event(XEvent &event, const void *cookie = nullptr);
/// @brief Returns a list of window values for the given atom.
/// @param display display with which the atom is associated
/// @param window window to query for the atom value
/// @param atom atom to query for
/// @return a list of window values for the given atom
std::vector<Window> x11_atom_window_list(Display *display, Window window,
Atom atom);
/// @brief Tries getting a list of windows ordered from bottom to top.
///
/// Whether the list is correctly ordered depends on WM/DE providing the
/// `_NET_CLIENT_LIST_STACKING` atom. If only `_NET_CLIENT_LIST` is defined,
/// this function assumes the WM/DE is a tiling one without stacking order.
///
/// If neither of the atoms are provided, this function tries traversing the
/// window graph in order to collect windows. In this case, map state of windows
/// is ignored.
///
/// @param display which display to query for windows
/// @param eager fallback to very slow tree traversal to ensure a list of
/// windows is returned even if window list atoms aren't defined
/// @return a (likely) ordered list of windows
std::vector<Window> query_x11_windows(Display *display, bool eager = false);
/// @brief Finds the last ascendant of a window (trunk) before root.
///
/// If provided `child` is root or has no windows between root and itself, the
/// `child` is returned.
///
/// @param display display of parent
/// @param child window whose parents to query
/// @return the top level ascendant window
Window query_x11_top_parent(Display *display, Window child);
/// @brief Returns the top-most window overlapping provided screen coordinates.
///
/// @param display display of parent
/// @param x screen X position contained by window
/// @param y screen Y position contained by window
/// @return a top-most window at provided screen coordinates, or root
Window query_x11_window_at_pos(Display *display, conky::vec2i pos);
/// @brief Returns a list of windows overlapping provided screen coordinates.
///
/// Vector returned by this function will never contain root because it's
/// assumed to always cover the entire display.
///
/// @param display display of parent
/// @param x screen X position contained by window
/// @param y screen Y position contained by window
/// @param predicate any additional predicates to apply for XWindowAttributes
/// (besides bounds testing).
/// @return a vector of windows at provided screen coordinates
std::vector<Window> query_x11_windows_at_pos(
Display *display, conky::vec2i pos,
std::function<bool(XWindowAttributes &)> predicate =
[](XWindowAttributes &a) { return true; },
bool eager = false);
#ifdef BUILD_XDBE
void xdbe_swap_buffers(void);
#else
void xpmdb_swap_buffers(void);
#endif /* BUILD_XDBE */
#endif /* CONKY_X11_H */
| 6,018
|
C++
|
.h
| 161
| 35.47205
| 80
| 0.747257
|
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,811
|
tailhead.h
|
brndnmtthws_conky/src/tailhead.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 _TAILHEAD_H
#define _TAILHEAD_H
void free_tailhead(struct text_object *);
void init_tailhead(const char *, const char *, struct text_object *, void *);
void print_head(struct text_object *, char *, unsigned int);
void print_tail(struct text_object *, char *, unsigned int);
void print_lines(struct text_object *, char *, unsigned int);
void print_words(struct text_object *, char *, unsigned int);
#endif /* _TAILHEAD_H */
| 1,488
|
C++
|
.h
| 37
| 38.378378
| 77
| 0.746372
|
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,812
|
darwin.h
|
brndnmtthws_conky/src/darwin.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) 2018-2019, npyl <n.pylarinos@hotmail.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 <http://www.gnu.org/licenses/>.
*
*/
#ifndef DARWIN_H
#define DARWIN_H
#include <stdio.h>
#include <strings.h>
#include <sys/mount.h>
#include <sys/param.h>
/*
* on versions prior to Sierra clock_gettime is not implemented.
*/
#ifndef HAVE_CLOCK_GETTIME
/* only CLOCK_REALTIME and CLOCK_MONOTONIC are emulated */
#ifndef CLOCK_REALTIME
#define CLOCK_REALTIME 0
#endif
#ifndef CLOCK_MONOTONIC
#define CLOCK_MONOTONIC 1
#endif
int clock_gettime(int clock_id, struct timespec *ts);
#endif /* ifndef HAVE_CLOCK_GETTIME */
int update_running_threads(void);
int get_entropy_avail(const unsigned int *);
int get_entropy_poolsize(const unsigned int *);
/* System Integrity Protection */
int get_sip_status(void);
void print_sip_status(struct text_object *obj, char *p,
unsigned int p_max_size);
void deallocate_cpu_sample(struct text_object *obj);
#endif /*DARWIN_H*/
| 1,796
|
C++
|
.h
| 52
| 32.442308
| 72
| 0.754902
|
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,813
|
nc.h
|
brndnmtthws_conky/src/nc.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/>.
*
*/
#if defined(BUILD_NCURSES) && !defined(CONKY_NC_H)
#define CONKY_NC_H
#include <ncurses.h>
#include "setting.hh"
#ifdef LEAKFREE_NCURSES
extern "C" {
void _nc_free_and_exit(int);
}
#endif
namespace priv {
class out_to_ncurses_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_ncurses_setting() : Base("out_to_ncurses", false, false) {}
};
} // namespace priv
extern priv::out_to_ncurses_setting out_to_ncurses;
#endif /* CONKY_NC_H */
| 1,675
|
C++
|
.h
| 49
| 32.244898
| 74
| 0.745826
|
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,814
|
mouse-events.h
|
brndnmtthws_conky/src/mouse-events.h
|
/*
* mouse_events.h: 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/>.
*
*/
#ifndef MOUSE_EVENTS_H
#define MOUSE_EVENTS_H
#include <bitset>
#include <cstdint>
#include <string>
#include "config.h"
#include "geometry.h"
#include "logging.h"
#ifdef BUILD_XINPUT
#include <array>
#include <map>
#include <optional>
#include <tuple>
#include <variant>
#include <vector>
#endif /* BUILD_XINPUT */
extern "C" {
#ifdef BUILD_X11
#include <X11/X.h>
#ifdef BUILD_XINPUT
#include <X11/extensions/XInput.h>
#include <X11/extensions/XInput2.h>
#undef COUNT // define from X11/extensions/Xi.h
#endif /* BUILD_XINPUT */
#endif /* BUILD_X11 */
#include <lua.h>
#ifdef __linux
#include <linux/input-event-codes.h>
#elif __FreeBSD__
#include <dev/evdev/input-event-codes.h>
#elif __DragonFly__
#include <dev/misc/evdev/input-event-codes.h>
#else /* platform */
// Probably incorrect for some platforms, feel free to add your platform to the
// above list if it has other event codes or a standard file containing them.
// Left mouse button event code
#define BTN_LEFT 0x110
// Right mouse button event code
#define BTN_RIGHT 0x111
// Middle mouse button event code
#define BTN_MIDDLE 0x112
// Back mouse button event code
#define BTN_BACK 0x116
// Forward mouse button event code
#define BTN_FORWARD 0x115
#endif /* platform */
}
namespace conky {
#ifdef BUILD_MOUSE_EVENTS
enum class mouse_event_t : uint32_t {
PRESS = 0,
RELEASE = 1,
SCROLL = 2,
MOVE = 3,
AREA_ENTER = 4,
AREA_LEAVE = 5,
};
const size_t MOUSE_EVENT_COUNT =
static_cast<size_t>(mouse_event_t::AREA_LEAVE) + 1;
constexpr uint32_t operator*(mouse_event_t index) {
return static_cast<uint32_t>(index);
}
enum class mouse_button_t : uint32_t {
LEFT = BTN_LEFT,
RIGHT = BTN_RIGHT,
MIDDLE = BTN_MIDDLE,
BACK = BTN_BACK,
FORWARD = BTN_FORWARD,
};
constexpr uint32_t operator*(mouse_button_t index) {
return static_cast<uint32_t>(index);
}
#ifdef BUILD_X11
inline mouse_button_t x11_mouse_button_code(unsigned int x11_mouse_button) {
mouse_button_t button;
switch (x11_mouse_button) {
case Button1:
button = mouse_button_t::LEFT;
break;
case Button2:
button = mouse_button_t::MIDDLE;
break;
case Button3:
button = mouse_button_t::RIGHT;
break;
case 8:
button = mouse_button_t::BACK;
break;
case 9:
button = mouse_button_t::FORWARD;
break;
default:
DBGP("X11 button %d is not mapped", x11_mouse_button);
break;
}
return button;
}
#endif /* BUILD_X11 */
struct mouse_event {
mouse_event_t type; // type of event
std::size_t time; // ms since epoch when the event happened
explicit mouse_event(mouse_event_t type);
void push_lua_table(lua_State *L) const;
virtual void push_lua_data(lua_State *L) const = 0;
};
struct mouse_positioned_event : public mouse_event {
/// @brief Position relative to event window
vec2<size_t> pos;
/// @brief Position relative to desktop/root window
vec2<size_t> pos_absolute;
mouse_positioned_event(mouse_event_t type, vec2<size_t> pos,
vec2<size_t> pos_absolute)
: mouse_event(type), pos(pos), pos_absolute(pos_absolute){};
void push_lua_data(lua_State *L) const;
};
typedef std::bitset<6> modifier_state_t;
enum class modifier_key : uint32_t {
SHIFT = 0,
CONTROL = 1,
ALT = 2,
// Windows/MacOS key on most keyboards
SUPER = 3,
CAPS_LOCK = 4,
NUM_LOCK = 5,
};
constexpr uint32_t operator*(modifier_key index) {
return static_cast<uint32_t>(index);
}
std::string modifier_name(modifier_key key);
#ifdef BUILD_X11
inline modifier_state_t x11_modifier_state(unsigned int mods) {
modifier_state_t result;
result[*modifier_key::SHIFT] = mods & ShiftMask;
result[*modifier_key::CONTROL] = mods & ControlMask;
result[*modifier_key::ALT] = mods & Mod1Mask;
result[*modifier_key::SUPER] = mods & Mod4Mask;
result[*modifier_key::CAPS_LOCK] = mods & LockMask;
result[*modifier_key::NUM_LOCK] = mods & Mod2Mask;
return result;
}
#endif /* BUILD_X11 */
struct mouse_move_event : public mouse_positioned_event {
modifier_state_t mods; // held buttons and modifiers (ctrl, shift, ...)
mouse_move_event(vec2<size_t> pos, vec2<size_t> pos_absolute,
modifier_state_t mods = 0)
: mouse_positioned_event{mouse_event_t::MOVE, pos, pos_absolute},
mods(mods){};
void push_lua_data(lua_State *L) const;
};
enum class scroll_direction_t : uint8_t {
UNKNOWN = 0,
UP,
DOWN,
LEFT,
RIGHT,
};
constexpr uint8_t operator*(scroll_direction_t index) {
return static_cast<uint8_t>(index);
}
#ifdef BUILD_X11
inline scroll_direction_t x11_scroll_direction(unsigned int x11_mouse_button) {
scroll_direction_t direction = scroll_direction_t::UNKNOWN;
switch (x11_mouse_button) {
case Button4:
direction = scroll_direction_t::UP;
break;
case Button5:
direction = scroll_direction_t::DOWN;
break;
case 6:
direction = scroll_direction_t::LEFT;
break;
case 7:
direction = scroll_direction_t::RIGHT;
break;
}
return direction;
}
#endif /* BUILD_X11 */
struct mouse_scroll_event : public mouse_positioned_event {
modifier_state_t mods; // held buttons and modifiers (ctrl, shift, ...)
scroll_direction_t direction;
mouse_scroll_event(vec2<size_t> pos, vec2<size_t> pos_absolute,
scroll_direction_t direction, modifier_state_t mods = 0)
: mouse_positioned_event{mouse_event_t::SCROLL, pos, pos_absolute},
direction(direction),
mods(mods){};
void push_lua_data(lua_State *L) const;
};
struct mouse_button_event : public mouse_positioned_event {
modifier_state_t mods; // held buttons and modifiers (ctrl, shift, ...)
mouse_button_t button;
mouse_button_event(mouse_event_t type, vec2<size_t> pos,
vec2<size_t> pos_absolute, mouse_button_t button,
modifier_state_t mods = 0)
: mouse_positioned_event{type, pos, pos_absolute},
button(button),
mods(mods){};
void push_lua_data(lua_State *L) const;
};
struct mouse_crossing_event : public mouse_positioned_event {
mouse_crossing_event(mouse_event_t type, vec2<size_t> pos,
vec2<size_t> pos_absolute)
: mouse_positioned_event{type, pos, pos_absolute} {};
};
#endif /* BUILD_MOUSE_EVENTS */
#ifdef BUILD_XINPUT
typedef int xi_device_id;
typedef int xi_event_type;
enum class valuator_t : size_t { MOVE_X, MOVE_Y, SCROLL_X, SCROLL_Y, UNKNOWN };
const size_t VALUATOR_COUNT = static_cast<size_t>(valuator_t::UNKNOWN);
constexpr uint8_t operator*(valuator_t index) {
return static_cast<uint8_t>(index);
}
struct conky_valuator_info {
size_t index;
double min;
double max;
double value;
bool relative;
};
struct device_info {
/// @brief Device name.
xi_device_id id;
std::string name;
std::array<conky_valuator_info, VALUATOR_COUNT> valuators{};
static device_info *from_xi_id(xi_device_id id, Display *display = nullptr);
conky_valuator_info &valuator(valuator_t valuator);
private:
void init_xi_device(Display *display,
std::variant<xi_device_id, XIDeviceInfo *> device);
};
void handle_xi_device_change(const XIHierarchyEvent *event);
/// Almost an exact copy of `XIDeviceEvent`, except it owns all data.
struct xi_event_data {
xi_event_type evtype;
unsigned long serial;
Bool send_event;
Display *display;
/// XI extension offset
// TODO: Check whether this is consistent between different clients by
// printing.
int extension;
Time time;
device_info *device;
int sourceid;
int detail;
Window root;
Window event;
Window child;
conky::vec2d pos_absolute;
conky::vec2d pos;
int flags;
/// pressed button mask
std::bitset<32> buttons;
std::map<size_t, double> valuators;
XIModifierState mods;
XIGroupState group;
// Extra data
/// Precomputed relative values
std::array<double, VALUATOR_COUNT> valuators_relative;
static xi_event_data *read_cookie(Display *display, const void *data);
bool test_valuator(valuator_t id) const;
conky_valuator_info *valuator_info(valuator_t id) const;
std::optional<double> valuator_value(valuator_t id) const;
std::optional<double> valuator_relative_value(valuator_t valuator) const;
std::vector<std::tuple<int, XEvent *>> generate_events(
Window target, Window child, conky::vec2d target_pos) const;
};
#endif /* BUILD_XINPUT */
} // namespace conky
#endif /* MOUSE_EVENTS_H */
| 9,248
|
C++
|
.h
| 291
| 28.42268
| 79
| 0.707547
|
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,815
|
tcp-portmon.h
|
brndnmtthws_conky/src/tcp-portmon.h
|
/*
*
* tcp-portmon.h - libtcp-portmon hooks prototypes
*
* 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/>.
*
*/
#ifndef _TCP_PORTMON_H
#define _TCP_PORTMON_H
#include "libtcp-portmon.h"
struct tcp_port_monitor_data {
/* starting port to monitor */
in_port_t port_range_begin;
/* ending port to monitor */
in_port_t port_range_end;
/* enum from libtcp-portmon.h, e.g. COUNT, etc. */
int item;
/* 0 to n-1 connections. */
int connection_index;
};
/* forward declare to make gcc happy */
struct text_object;
int tcp_portmon_init(struct text_object *, const char *);
void tcp_portmon_action(struct text_object *, char *, unsigned int);
int tcp_portmon_update(void);
int tcp_portmon_clear(void);
void tcp_portmon_free(struct text_object *);
#endif /* _TCP_PORTMON_H */
| 1,434
|
C++
|
.h
| 40
| 33.875
| 72
| 0.735781
|
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,816
|
apcupsd.h
|
brndnmtthws_conky/src/apcupsd.h
|
/*
*
* apcupsd.h: 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.
*
*/
#ifndef APCUPSD_H_
#define APCUPSD_H_
int apcupsd_scan_arg(const char *);
/* Service routine for the conky main thread */
int update_apcupsd(void);
double apcupsd_loadbarval(struct text_object *);
void print_apcupsd_name(struct text_object *, char *, unsigned int);
void print_apcupsd_model(struct text_object *, char *, unsigned int);
void print_apcupsd_upsmode(struct text_object *, char *, unsigned int);
void print_apcupsd_cable(struct text_object *, char *, unsigned int);
void print_apcupsd_status(struct text_object *, char *, unsigned int);
void print_apcupsd_linev(struct text_object *, char *, unsigned int);
void print_apcupsd_load(struct text_object *, char *, unsigned int);
void print_apcupsd_charge(struct text_object *, char *, unsigned int);
void print_apcupsd_timeleft(struct text_object *, char *, unsigned int);
void print_apcupsd_temp(struct text_object *, char *, unsigned int);
void print_apcupsd_lastxfer(struct text_object *, char *, unsigned int);
#endif /*APCUPSD_H_*/
| 1,883
|
C++
|
.h
| 40
| 45.4
| 72
| 0.756668
|
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,817
|
specials.h
|
brndnmtthws_conky/src/specials.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 _SPECIALS_H
#define _SPECIALS_H
#include <tuple>
#include "colours.h"
/* special stuff in text_buffer */
#define SPECIAL_CHAR '\x01'
// don't use spaces in LOGGRAPH or NORMGRAPH if you change them
#define LOGGRAPH "-l"
#define TEMPGRAD "-t"
#define INVERTX "-x"
#define INVERTY "-y"
#define MINHEIGHT "-m"
enum class text_node_t : uint32_t {
NONSPECIAL = 0,
HORIZONTAL_LINE = 1,
STIPPLED_HR,
BAR,
FG,
BG,
OUTLINE,
ALIGNR,
ALIGNC,
GAUGE,
GRAPH,
OFFSET,
VOFFSET,
SAVE_COORDINATES,
FONT,
GOTO,
TAB
};
constexpr uint32_t operator*(text_node_t index) {
return static_cast<uint32_t>(index);
}
struct special_node {
text_node_t type;
short height;
short width;
double arg;
double *graph;
double scale; /* maximum value */
short show_scale;
int graph_width;
int graph_allocated;
int scaled; /* auto adjust maximum */
int scale_log;
bool colours_set;
Colour first_colour; // for graph gradient
Colour last_colour;
short font_added;
char tempgrad;
char speedgraph;
char invertx;
char inverty;
int minheight;
struct special_node *next;
};
/* direct access to the registered specials (FIXME: bad encapsulation) */
extern struct special_node *specials;
extern int special_count;
/* forward declare to avoid mutual inclusion between specials.h and
* text_object.h */
struct text_object;
/* scanning special arguments */
const char *scan_bar(struct text_object *, const char *, double);
const char *scan_gauge(struct text_object *, const char *, double);
#ifdef BUILD_GUI
void scan_font(struct text_object *, const char *);
std::pair<char *, size_t> scan_command(const char *);
bool scan_graph(struct text_object *, const char *, double, char);
void scan_tab(struct text_object *, const char *);
void scan_stippled_hr(struct text_object *, const char *);
/* printing specials */
void new_font(struct text_object *, char *, unsigned int);
void new_graph(struct text_object *, char *, int, double);
void new_hr(struct text_object *, char *, unsigned int);
void new_stippled_hr(struct text_object *, char *, unsigned int);
#endif /* BUILD_GUI */
void new_gauge(struct text_object *, char *, unsigned int, double);
void new_bar(struct text_object *, char *, unsigned int, double);
void new_fg(struct text_object *, char *, unsigned int);
void new_bg(struct text_object *, char *, unsigned int);
void new_outline(struct text_object *, char *, unsigned int);
void new_offset(struct text_object *, char *, unsigned int);
void new_voffset(struct text_object *, char *, unsigned int);
void new_save_coordinates(struct text_object *, char *, unsigned int);
void new_alignr(struct text_object *, char *, unsigned int);
void new_alignc(struct text_object *, char *, unsigned int);
void new_goto(struct text_object *, char *, unsigned int);
void new_tab(struct text_object *, char *, unsigned int);
void clear_stored_graphs();
struct special_node *new_special(char *buf, enum text_node_t t);
#endif /* _SPECIALS_H */
| 4,043
|
C++
|
.h
| 121
| 31.429752
| 73
| 0.734459
|
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,818
|
top.h
|
brndnmtthws_conky/src/top.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) 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/>.
*
*/
#ifndef _top_h_
#define _top_h_
/* Ensure there's an operating system defined.
* compile with gcc -DOS ...
* There is *no* default because every OS has it's own way of revealing
* CPU/memory usage. */
/******************************************
* Includes *
******************************************/
#include "conky.h"
#include "text_object.h"
#define CPU_THRESHHOLD 0 /* threshold for the cpu diff to appear */
#include <assert.h>
#include <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <math.h>
#include <signal.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <pwd.h>
#include <regex.h>
/******************************************
* Defines *
******************************************/
/* XXX: I shouldn't really use this BUFFER_LEN variable but scanf is so lame
* and it'll take me a while to write a replacement. */
#define BUFFER_LEN 1024
#define MAX_SP 10 // number of elements to sort
/******************************************
* Process class *
******************************************/
struct process {
struct process *next;
struct process *previous;
pid_t pid;
char *name;
char *basename;
uid_t uid;
float amount;
// User and kernel times are in hundredths of seconds
unsigned long user_time;
unsigned long total;
unsigned long kernel_time;
unsigned long previous_user_time;
unsigned long previous_kernel_time;
unsigned long total_cpu_time;
unsigned long previous_total_cpu_time;
unsigned long long vsize;
unsigned long long rss;
#ifdef BUILD_IOSTATS
unsigned long long read_bytes;
unsigned long long previous_read_bytes;
unsigned long long write_bytes;
unsigned long long previous_write_bytes;
float io_perc;
#endif
unsigned int time_stamp;
unsigned int counted;
unsigned int changed;
};
struct sorted_process {
struct sorted_process *greater;
struct sorted_process *less;
struct process *proc;
};
/* lookup a program by it's name */
struct process *get_process_by_name(const char *);
int parse_top_args(const char *s, const char *arg, struct text_object *obj);
int update_top(void);
void get_top_info(void);
extern struct process *first_process;
extern unsigned long g_time;
struct process *get_process(pid_t pid);
#endif /* _top_h_ */
| 3,575
|
C++
|
.h
| 113
| 29.628319
| 76
| 0.681871
|
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,819
|
user.h
|
brndnmtthws_conky/src/user.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 _USER_H
#define _USER_H
void print_gid_name(struct text_object *obj, char *p, unsigned int p_max_size);
void print_uid_name(struct text_object *obj, char *p, unsigned int p_max_size);
#endif /* _USER_H */
| 1,271
|
C++
|
.h
| 33
| 36.606061
| 79
| 0.746559
|
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,820
|
mail.h
|
brndnmtthws_conky/src/mail.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 _MAIL_H
#define _MAIL_H
#include "setting.hh"
void parse_local_mail_args(struct text_object *, const char *);
#define PRINT_MAILS_PROTO_GENERATOR(x) \
void print_##x##mails(struct text_object *, char *, unsigned int);
PRINT_MAILS_PROTO_GENERATOR()
PRINT_MAILS_PROTO_GENERATOR(new_)
PRINT_MAILS_PROTO_GENERATOR(seen_)
PRINT_MAILS_PROTO_GENERATOR(unseen_)
PRINT_MAILS_PROTO_GENERATOR(flagged_)
PRINT_MAILS_PROTO_GENERATOR(unflagged_)
PRINT_MAILS_PROTO_GENERATOR(forwarded_)
PRINT_MAILS_PROTO_GENERATOR(unforwarded_)
PRINT_MAILS_PROTO_GENERATOR(replied_)
PRINT_MAILS_PROTO_GENERATOR(unreplied_)
PRINT_MAILS_PROTO_GENERATOR(draft_)
PRINT_MAILS_PROTO_GENERATOR(trashed_)
void free_local_mails(struct text_object *obj);
void parse_global_imap_mail_args(const char *);
void parse_global_pop3_mail_args(const char *);
void parse_imap_mail_args(struct text_object *, const char *);
void parse_pop3_mail_args(struct text_object *, const char *);
void free_mail_obj(struct text_object *);
void print_imap_unseen(struct text_object *, char *, unsigned int);
void print_imap_messages(struct text_object *, char *, unsigned int);
void print_pop3_unseen(struct text_object *, char *, unsigned int);
void print_pop3_used(struct text_object *, char *, unsigned int);
namespace priv {
class current_mail_spool_setting
: public conky::simple_config_setting<std::string> {
typedef conky::simple_config_setting<std::string> Base;
protected:
virtual std::pair<std::string, bool> do_convert(lua::state &l, int index);
public:
current_mail_spool_setting() : Base("current_mail_spool", "$MAIL", true) {}
};
} // namespace priv
extern priv::current_mail_spool_setting current_mail_spool;
#endif /* _MAIL_H */
| 2,571
|
C++
|
.h
| 63
| 39.031746
| 77
| 0.759118
|
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,821
|
dragonfly.h
|
brndnmtthws_conky/src/dragonfly.h
|
/* */
#ifndef DRAGONFLY_H_
#define DRAGONFLY_H_
#include <fcntl.h>
#include <kvm.h>
#include <sys/mount.h>
#include <sys/param.h>
#include <sys/ucred.h>
#include "common.h"
#if (defined(i386) || defined(__i386__))
#include <machine/apm_bios.h>
#endif /* i386 || __i386__ */
int get_entropy_avail(unsigned int *);
int get_entropy_poolsize(unsigned int *);
#endif /*DRAGONFLY_H_*/
| 383
|
C++
|
.h
| 15
| 24.266667
| 41
| 0.695055
|
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,822
|
colour-names-stub.hh
|
brndnmtthws_conky/src/colour-names-stub.hh
|
/*
* To generate colour-names.hh, you must have gperf installed during build.
* This is a dummy implementation for builds without gperf.
* Color name matching will always return null (i.e. no match).
*/
#pragma once
#include <cstdint>
#include "logging.h"
struct rgb {
const char *name;
uint8_t red;
uint8_t green;
uint8_t blue;
};
class color_name_hash {
public:
static const struct rgb *in_word_set(const char *str, size_t len);
};
const struct rgb *color_name_hash::in_word_set(const char *str, size_t len) {
DBGP2("color parsing not supported");
return nullptr;
}
| 593
|
C++
|
.h
| 22
| 24.818182
| 77
| 0.732743
|
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,823
|
cpu.h
|
brndnmtthws_conky/src/cpu.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 _CPU_H
#define _CPU_H
#ifdef __x86_64__
uintmax_t rdtsc(void);
void get_cpu_clock_speed(char *, unsigned int);
uint8_t has_tsc_reg(void);
void print_freq2(struct text_object *, char *, unsigned int);
#endif /* __x86_64__ */
#endif /* _CPU_H */
| 1,308
|
C++
|
.h
| 37
| 33.540541
| 72
| 0.738959
|
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,824
|
fs.h
|
brndnmtthws_conky/src/fs.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 _FS_H
#define _FS_H
#include "conky.h" /* DEFAULT_TEXT_BUFFER_SIZE */
/* needed here and by fs.c */
struct fs_stat {
char path[DEFAULT_TEXT_BUFFER_SIZE];
char type[DEFAULT_TEXT_BUFFER_SIZE];
long long size;
long long avail;
long long free;
char set;
char errored;
};
/* forward declare to make gcc happy (fs.h <-> text_object.h include) */
struct text_object;
void init_fs_bar(struct text_object *, const char *);
double fs_barval(struct text_object *);
double fs_free_barval(struct text_object *);
void init_fs(struct text_object *, const char *);
uint8_t fs_free_percentage(struct text_object *);
uint8_t fs_used_percentage(struct text_object *);
void print_fs_free(struct text_object *, char *, unsigned int);
void print_fs_size(struct text_object *, char *, unsigned int);
void print_fs_used(struct text_object *, char *, unsigned int);
void print_fs_type(struct text_object *, char *, unsigned int);
int update_fs_stats(void);
struct fs_stat *prepare_fs_stat(const char *s);
void clear_fs_stats(void);
#endif /* _FS_H */
| 2,109
|
C++
|
.h
| 57
| 35.140351
| 72
| 0.739726
|
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,825
|
display-output.hh
|
brndnmtthws_conky/src/display-output.hh
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Please see COPYING for details
*
* Copyright (C) 2018 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_OUTPUT_HH
#define DISPLAY_OUTPUT_HH
#include <string.h>
#include <cmath>
#include <limits>
#include <string>
#include <type_traits>
#include <vector>
#include "colours.h"
#include "logging.h"
#include "luamm.hh"
namespace conky {
bool initialize_display_outputs();
bool shutdown_display_outputs();
/*
* A base class for all display outputs.
* API consists of two functions:
* - get_number should return numeric representation of the data (if available).
* This can then be used when drawing graphs, bars, ... The default
* implementation returns NaN.
* - get_text should return textual representation of the data. This is used
* when simple displaying the value of the data source. The default
* implementation converts get_number() to a string, but you can override to
* return anything (e.g. add units)
*/
class display_output_base {
private:
// copying is a REALLY bad idea
display_output_base(const display_output_base &) = delete;
display_output_base &operator=(const display_output_base &) = delete;
public:
const std::string name;
bool is_active = false;
bool is_graphical = false;
int priority = -1;
explicit display_output_base(const std::string &name) : name(name){};
virtual ~display_output_base() {}
static bool priority_compare(const display_output_base *a,
const display_output_base *b) {
return a->priority > b->priority;
}
// check if available and enabled in settings
virtual bool detect() { return false; }
// connect to DISPLAY and other stuff
virtual bool initialize() { return false; }
virtual bool shutdown() { return false; }
virtual bool graphical() { return is_graphical; };
virtual bool draw_line_inner_required() { return is_graphical; }
virtual bool main_loop_wait(double /*t*/) { return false; }
virtual void sigterm_cleanup() {}
virtual void cleanup() {}
// drawing primitives
virtual void set_foreground_color(Colour /*c*/) {}
virtual int calc_text_width(const char *s) { return strlen(s); }
virtual void begin_draw_text() {}
virtual void end_draw_text() {}
virtual void draw_string(const char * /*s*/, int /*w*/) {}
virtual void line_inner_done() {}
// GUI interface
virtual void draw_string_at(int /*x*/, int /*y*/, const char * /*s*/,
int /*w*/) {}
// X11 lookalikes
virtual void set_line_style(int /*w*/, bool /*solid*/) {}
virtual void set_dashes(char * /*s*/) {}
virtual void draw_line(int /*x1*/, int /*y1*/, int /*x2*/, int /*y2*/) {}
virtual void draw_rect(int /*x*/, int /*y*/, int /*w*/, int /*h*/) {}
virtual void fill_rect(int /*x*/, int /*y*/, int /*w*/, int /*h*/) {}
virtual void draw_arc(int /*x*/, int /*y*/, int /*w*/, int /*h*/, int /*a1*/,
int /*a2*/) {}
virtual void move_win(int /*x*/, int /*y*/) {}
virtual float get_dpi_scale() { return 1.0; };
virtual void begin_draw_stuff() {}
virtual void end_draw_stuff() {}
virtual void clear_text(int /*exposures*/) {}
// font stuff
virtual int font_height(unsigned int) { return 0; }
virtual int font_ascent(unsigned int) { return 0; }
virtual int font_descent(unsigned int) { return 0; }
virtual void setup_fonts(void) {}
virtual void set_font(unsigned int) {}
virtual void free_fonts(bool /*utf8*/) {}
virtual void load_fonts(bool /*utf8*/) {}
// tty interface
virtual int getx() { return 0; }
virtual int gety() { return 0; }
virtual void gotox(int /*x*/) {}
virtual void gotoy(int /*y*/) {}
virtual void gotoxy(int /*x*/, int /*y*/) {}
virtual void flush() {}
friend bool conky::initialize_display_outputs();
friend bool conky::shutdown_display_outputs();
protected:
virtual bool active() { return is_active; }
};
using display_outputs_t = std::vector<display_output_base *>;
enum class output_t : uint32_t {
CONSOLE,
NCURSES,
FILE,
HTTP,
X11,
WAYLAND,
OUTPUT_COUNT
};
template <output_t Output>
void register_output(display_outputs_t &outputs);
/*
* The selected and active display outputs.
*/
extern 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.
*/
extern std::vector<conky::display_output_base *> current_display_outputs;
} // namespace conky
// XXX: move to namespace?
static inline std::vector<conky::display_output_base *> &display_outputs() {
if (conky::current_display_outputs.size())
return conky::current_display_outputs;
return conky::active_display_outputs;
}
static inline conky::display_output_base *display_output() {
if (conky::current_display_outputs.size())
return conky::current_display_outputs[0];
// XXX; not really what intended yet...
if (conky::active_display_outputs.size())
return conky::active_display_outputs[0];
return nullptr;
}
template <typename T>
inline T dpi_scale(T value) {
static_assert(std::is_arithmetic_v<T>,
"dpi_scale value type must be a number");
#ifdef BUILD_GUI
auto output = display_output();
if (output) {
return T(std::round(static_cast<double>(value) * output->get_dpi_scale()));
}
#endif /* BUILD_GUI */
return value;
}
static inline void unset_display_output() {
conky::current_display_outputs.clear();
}
static inline void set_display_output(conky::display_output_base *output) {
conky::current_display_outputs.clear();
conky::current_display_outputs.push_back(output);
}
#endif /* DISPLAY_OUTPUT_HH */
| 6,324
|
C++
|
.h
| 171
| 33.883041
| 80
| 0.695666
|
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,826
|
common.h
|
brndnmtthws_conky/src/common.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 _COMMON_H
#define _COMMON_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <string>
#include "setting.hh"
#include "text_object.h"
char *readfile(const char *filename, int *total_read, char showerror);
void print_to_bytes(struct text_object *, char *, unsigned int);
void strfold(char *start, int count);
int check_mount(struct text_object *);
void prepare_update(void);
int update_uptime(void);
int update_meminfo(void);
int update_net_stats(void);
int update_cpu_usage(void);
int update_total_processes(void);
int update_uname(void);
int update_threads(void);
int update_running_processes(void);
void update_stuff(void);
char get_freq(char *, size_t, const char *, int, unsigned int);
void print_voltage_mv(struct text_object *, char *, unsigned int);
void print_voltage_v(struct text_object *, char *, unsigned int);
int update_load_average(void);
void free_all_processes(void);
struct process *get_first_process(void);
void get_cpu_count(void);
double get_time(void);
/* 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);
FILE *open_file(const char *file, int *reported);
int open_fifo(const char *file, int *reported);
std::string variable_substitute(std::string s);
void format_seconds(char *buf, unsigned int n, long seconds);
void format_seconds_short(char *buf, unsigned int n, long seconds);
int round_to_int_temp(float);
unsigned int round_to_positive_int(float);
extern conky::simple_config_setting<bool> no_buffers;
extern conky::simple_config_setting<std::string> bar_fill;
extern conky::simple_config_setting<std::string> bar_unfill;
extern conky::simple_config_setting<std::string> github_token;
int open_acpi_temperature(const char *name);
double get_acpi_temperature(int fd);
void get_acpi_ac_adapter(char *p_client_buffer, size_t client_buffer_size,
const char *adapter);
void get_acpi_fan(char *, size_t);
void get_battery_stuff(char *buf, unsigned int n, const char *bat, int item);
int get_battery_perct(const char *bat);
void get_battery_power_draw(char *buffer, unsigned int n, const char *bat);
double get_battery_perct_bar(struct text_object *);
void get_battery_short_status(char *buf, unsigned int n, const char *bat);
void scan_no_update(struct text_object *, const char *);
void print_no_update(struct text_object *, char *, unsigned int);
void free_no_update(struct text_object *);
void scan_loadavg_arg(struct text_object *, const char *);
void print_loadavg(struct text_object *, char *, unsigned int);
#ifdef BUILD_GUI
void scan_loadgraph_arg(struct text_object *, const char *);
double loadgraphval(struct text_object *);
#endif /* BUILD_GUI */
uint8_t cpu_percentage(struct text_object *);
double cpu_barval(struct text_object *);
void print_mem(struct text_object *, char *, unsigned int);
void print_memwithbuffers(struct text_object *, char *, unsigned int);
void print_memeasyfree(struct text_object *, char *, unsigned int);
void print_legacymem(struct text_object *, char *, unsigned int);
void print_memfree(struct text_object *, char *, unsigned int);
void print_memmax(struct text_object *, char *, unsigned int);
void print_memactive(struct text_object *, char *, unsigned int);
void print_meminactive(struct text_object *, char *, unsigned int);
void print_memwired(struct text_object *, char *, unsigned int);
void print_memlaundry(struct text_object *, char *, unsigned int);
void print_memdirty(struct text_object *, char *, unsigned int);
void print_shmem(struct text_object *, char *, unsigned int);
void print_memavail(struct text_object *, char *, unsigned int);
void print_swap(struct text_object *, char *, unsigned int);
void print_swapfree(struct text_object *, char *, unsigned int);
void print_swapmax(struct text_object *, char *, unsigned int);
uint8_t mem_percentage(struct text_object *);
double mem_barval(struct text_object *);
double mem_with_buffers_barval(struct text_object *);
uint8_t swap_percentage(struct text_object *);
double swap_barval(struct text_object *);
void print_kernel(struct text_object *, char *, unsigned int);
void print_machine(struct text_object *, char *, unsigned int);
void print_nodename(struct text_object *, char *, unsigned int);
void print_nodename_short(struct text_object *, char *, unsigned int);
void print_sysname(struct text_object *, char *, unsigned int);
#if defined(__DragonFly__)
void print_version(struct text_object *obj, char *p, unsigned int p_max_size);
#endif
void print_uptime(struct text_object *, char *, unsigned int);
void print_uptime_short(struct text_object *, char *, unsigned int);
void print_processes(struct text_object *, char *, unsigned int);
void print_running_processes(struct text_object *, char *, unsigned int);
void print_running_threads(struct text_object *, char *, unsigned int);
void print_threads(struct text_object *, char *, unsigned int);
void print_buffers(struct text_object *, char *, unsigned int);
void print_cached(struct text_object *, char *, unsigned int);
void print_free_bufcache(struct text_object *, char *, unsigned int);
void print_free_cached(struct text_object *, char *, unsigned int);
void print_evaluate(struct text_object *, char *, unsigned int);
int if_empty_iftest(struct text_object *);
int if_existing_iftest(struct text_object *);
int if_running_iftest(struct text_object *);
#ifndef __OpenBSD__
void print_acpitemp(struct text_object *, char *, unsigned int);
void free_acpitemp(struct text_object *);
#endif /* !__OpenBSD__ */
void print_freq(struct text_object *, char *, unsigned int);
void print_freq_g(struct text_object *, char *, unsigned int);
#ifndef __OpenBSD__
void print_acpifan(struct text_object *, char *, unsigned int);
void print_acpiacadapter(struct text_object *, char *, unsigned int);
void print_battery(struct text_object *, char *, unsigned int);
void print_battery_time(struct text_object *, char *, unsigned int);
uint8_t battery_percentage(struct text_object *);
void battery_power_draw(struct text_object *, char *, unsigned int);
void print_battery_short(struct text_object *, char *, unsigned int);
void print_battery_status(struct text_object *, char *, unsigned int);
#endif /* !__OpenBSD__ */
void free_cpu(struct text_object *);
void print_blink(struct text_object *, char *, unsigned int);
void print_include(struct text_object *, char *, unsigned int);
void print_updates(struct text_object *, char *, unsigned int);
int updatenr_iftest(struct text_object *);
#ifdef BUILD_CURL
void print_github(struct text_object *, char *, unsigned int);
void print_stock(struct text_object *, char *, unsigned int);
void free_stock(struct text_object *);
#endif /* BUILD_CURL */
#endif /* _COMMON_H */
| 7,682
|
C++
|
.h
| 159
| 46.823899
| 78
| 0.7499
|
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,827
|
netbsd.h
|
brndnmtthws_conky/src/netbsd.h
|
/* */
#ifndef NETBSD_H_
#define NETBSD_H_
#include <err.h>
#include <fcntl.h>
#include <kvm.h>
#include <limits.h>
#include <nlist.h>
#include <paths.h>
#include <time.h>
#include <unistd.h>
#include <sys/envsys.h>
#include <sys/sched.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 <net/if.h>
#include <uvm/uvm_extern.h>
#include <machine/param.h>
#include "common.h"
#include "conky.h"
int get_entropy_avail(unsigned int *);
int get_entropy_poolsize(unsigned int *);
#endif /*NETBSD_H_*/
| 600
|
C++
|
.h
| 27
| 20.888889
| 41
| 0.723404
|
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,828
|
c++wrap.hh
|
brndnmtthws_conky/src/c++wrap.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 CPPWRAP_HH
#define CPPWRAP_HH
#ifdef HAVE_O_CLOEXEC
#include <fcntl.h>
#else
enum { O_CLOEXEC = 02000000 };
#endif
#include <cerrno>
#include <stdexcept>
#include <string>
#include <utility>
std::string strerror_r(int errnum);
std::pair<int, int> pipe2(int flags);
class errno_error : public std::runtime_error {
typedef std::runtime_error Base;
public:
explicit errno_error(const std::string &prefix, int err_ = errno)
: Base(prefix + ": " + strerror_r(err_)), err(err_) {}
const int err;
};
#endif /* CPPWRAP_HH */
| 1,331
|
C++
|
.h
| 42
| 29.714286
| 72
| 0.734582
|
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,829
|
mixer.h
|
brndnmtthws_conky/src/mixer.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) 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 MIXER_H_
#define MIXER_H_
void parse_mixer_arg(struct text_object *, const char *);
uint8_t mixer_percentage(struct text_object *obj);
uint8_t mixerl_percentage(struct text_object *obj);
uint8_t mixerr_percentage(struct text_object *obj);
int check_mixer_muted(struct text_object *);
void scan_mixer_bar(struct text_object *, const char *);
double mixer_barval(struct text_object *);
double mixerl_barval(struct text_object *);
double mixerr_barval(struct text_object *);
#endif /*MIXER_H_*/
| 1,590
|
C++
|
.h
| 41
| 37
| 72
| 0.757282
|
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,830
|
logging.h
|
brndnmtthws_conky/src/logging.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 _LOGGING_H
#define _LOGGING_H
#include <cinttypes> // correct formatting for int types
#include <cstdio>
#include <stdexcept>
#include "config.h"
#include "i18n.h"
class fork_throw : public std::runtime_error {
public:
fork_throw() : std::runtime_error("Fork happened") {}
fork_throw(const std::string &msg) : std::runtime_error(msg) {}
};
class unknown_arg_throw : public std::runtime_error {
public:
unknown_arg_throw() : std::runtime_error("Unknown argumunt given") {}
unknown_arg_throw(const std::string &msg) : std::runtime_error(msg) {}
};
class combine_needs_2_args_error : public std::runtime_error {
public:
combine_needs_2_args_error()
: std::runtime_error("combine needs arguments: <text1> <text2>") {}
combine_needs_2_args_error(const std::string &msg)
: std::runtime_error(msg) {}
};
class obj_create_error : public std::runtime_error {
public:
obj_create_error() : std::runtime_error("Failed to create object") {}
obj_create_error(const std::string &msg) : std::runtime_error(msg) {}
};
void clean_up(void);
template <typename... Args>
inline void gettextize_format(const char *format, Args &&...args) {
fprintf(stderr, _(format), args...);
}
// explicit specialization for no arguments to avoid the
// "format not a string literal and no format arguments" warning
inline void gettextize_format(const char *format) { fputs(_(format), stderr); }
template <typename... Args>
void NORM_ERR(const char *format, Args &&...args) {
fprintf(stderr, PACKAGE_NAME ": ");
gettextize_format(format, args...);
fputs("\n", stderr);
}
/* critical error with additional cleanup */
template <typename... Args>
__attribute__((noreturn)) inline void CRIT_ERR_FREE(void *memtofree1,
void *memtofree2,
const char *format,
Args &&...args) {
NORM_ERR(format, args...);
free(memtofree1);
free(memtofree2);
clean_up();
exit(EXIT_FAILURE);
}
/* critical error */
template <typename... Args>
__attribute__((noreturn)) inline void CRIT_ERR(const char *format,
Args &&...args) {
CRIT_ERR_FREE(nullptr, nullptr, format, args...);
}
namespace conky {
class error : public std::runtime_error {
public:
error(const std::string &msg) : std::runtime_error(msg) {}
};
} // namespace conky
/* debugging output */
extern int global_debug_level;
#define __DBGP(level, ...) \
do { \
if (global_debug_level > level) { \
fprintf(stderr, "DEBUG(%d) [" __FILE__ ":%d]: ", level, __LINE__); \
gettextize_format(__VA_ARGS__); \
fputs("\n", stderr); \
} \
} while (0)
#define DBGP(...) __DBGP(0, __VA_ARGS__)
#define DBGP2(...) __DBGP(1, __VA_ARGS__)
#endif /* _LOGGING_H */
| 4,204
|
C++
|
.h
| 108
| 34.861111
| 79
| 0.616667
|
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,831
|
data-source.hh
|
brndnmtthws_conky/src/data-source.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 DATA_SOURCE_HH
#define DATA_SOURCE_HH
#include <limits>
#include <string>
#include <type_traits>
#include "luamm.hh"
namespace conky {
/*
* A base class for all data sources.
* API consists of two functions:
* - get_number should return numeric representation of the data (if available).
* This can then be used when drawing graphs, bars, ... The default
* implementation returns NaN.
* - get_text should return textual representation of the data. This is used
* when simple displaying the value of the data source. The default
* implementation converts get_number() to a string, but you can override to
* return anything (e.g. add units)
*/
class data_source_base {
public:
const std::string name;
explicit data_source_base(const std::string &name_) : name(name_) {}
virtual ~data_source_base() {}
virtual double get_number() const;
virtual std::string get_text() const;
};
/*
* A simple data source that returns the value of some variable. It ignores the
* lua table. The source variable can be specified as a fixed parameter to the
* register_data_source constructor, or one can create a subclass and then set
* the source from the subclass constructor.
*/
template <typename T>
class simple_numeric_source : public data_source_base {
static_assert(std::is_convertible<T, double>::value,
"T must be convertible to double");
const T *source;
public:
simple_numeric_source(lua::state *, const std::string &name_,
const T *source_)
: data_source_base(name_), source(source_) {}
virtual double get_number() const { return *source; }
};
/*
* This is a part of the implementation, but it cannot be in .cc file because
* the template functions below call it
*/
namespace priv {
const char data_source_metatable[] = "conky::data_source_metatable";
void do_register_data_source(const std::string &name,
const lua::cpp_function &fn);
class disabled_data_source : public simple_numeric_source<float> {
public:
disabled_data_source(lua::state *l, const std::string &name,
const std::string &setting);
};
} // namespace priv
/*
* Declaring an object of this type at global scope will register a data source
* with the given name. Any additional parameters are passed on to the data
* source constructor.
*/
template <typename T>
class register_data_source {
template <typename... Args>
static int factory(lua::state *l, const std::string &name,
const Args &...args) {
T *t = static_cast<T *>(l->newuserdata(sizeof(T)));
l->insert(1);
new (t) T(l, name, args...);
l->settop(1);
l->rawgetfield(lua::REGISTRYINDEX, priv::data_source_metatable);
l->setmetatable(-2);
return 1;
}
public:
template <typename... Args>
explicit register_data_source(const std::string &name, Args &&...args) {
priv::do_register_data_source(
name,
std::bind(&factory<Args...>, std::placeholders::_1, name, args...));
}
};
/*
* Use this to declare a data source that has been disabled during compilation.
* We can then print a nice error message telling the used which setting to
* enable.
*/
class register_disabled_data_source
: public register_data_source<priv::disabled_data_source> {
public:
register_disabled_data_source(const std::string &name,
const std::string &setting);
};
/*
* It expects to have a table at the top of lua stack. It then exports all the
* data sources into that table (actually, into a "variables" subtable).
*/
void export_data_sources(lua::state &l);
} // namespace conky
#endif /* DATA_SOURCE_HH */
| 4,478
|
C++
|
.h
| 122
| 33.155738
| 80
| 0.70572
|
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,832
|
freebsd.h
|
brndnmtthws_conky/src/freebsd.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 FREEBSD_H_
#define FREEBSD_H_
#include <fcntl.h>
#include <kvm.h>
#include <strings.h>
#include <sys/mount.h>
#include <sys/param.h>
#include <sys/ucred.h>
#include "common.h"
#if (defined(i386) || defined(__i386__))
#include <machine/apm_bios.h>
#endif /* i386 || __i386__ */
extern kvm_t *kd;
int get_entropy_avail(unsigned int *);
int get_entropy_poolsize(unsigned int *);
void print_sysctlbyname(struct text_object *, char *, unsigned int);
bool is_conky_already_running(void);
#endif /*FREEBSD_H_*/
| 1,571
|
C++
|
.h
| 46
| 32.434783
| 72
| 0.741935
|
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,833
|
darwin_sip.h
|
brndnmtthws_conky/src/darwin_sip.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) 2018-2019, npyl <n.pylarinos@hotmail.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 <http://www.gnu.org/licenses/>.
*
*/
//
// Defines for System Integrity Protection monitoring
// based on csrstat tool by Pike R. Alpha.
// https://github.com/Piker-Alpha/csrstat
//
#ifndef DARWIN_SIP_H
#define DARWIN_SIP_H
/* Rootless configuration flags */
#define CSR_ALLOW_UNTRUSTED_KEXTS (1 << 0) // 1
#define CSR_ALLOW_UNRESTRICTED_FS (1 << 1) // 2
#define CSR_ALLOW_TASK_FOR_PID (1 << 2) // 4
#define CSR_ALLOW_KERNEL_DEBUGGER (1 << 3) // 8
#define CSR_ALLOW_APPLE_INTERNAL (1 << 4) // 16
#define CSR_ALLOW_UNRESTRICTED_DTRACE (1 << 5) // 32
#define CSR_ALLOW_UNRESTRICTED_NVRAM (1 << 6) // 64
#define CSR_ALLOW_DEVICE_CONFIGURATION (1 << 7) // 128
#define CSR_ALLOW_ANY_RECOVERY_OS (1 << 8) // 256
#define CSR_ALLOW_UNAPPROVED_KEXTS (1 << 9) // 512
#define CSR_VALID_FLAGS \
(CSR_ALLOW_UNTRUSTED_KEXTS | CSR_ALLOW_UNRESTRICTED_FS | \
CSR_ALLOW_TASK_FOR_PID | CSR_ALLOW_KERNEL_DEBUGGER | \
CSR_ALLOW_APPLE_INTERNAL | CSR_ALLOW_UNRESTRICTED_DTRACE | \
CSR_ALLOW_UNRESTRICTED_NVRAM | CSR_ALLOW_DEVICE_CONFIGURATION | \
CSR_ALLOW_ANY_RECOVERY_OS | CSR_ALLOW_UNAPPROVED_KEXTS)
/* Syscalls */
// mark these symbols as weakly linked, as they may not be available
// at runtime on older OS X versions.
extern "C" {
int csr_get_active_config(information::csr_config_t* config)
__attribute__((weak_import));
};
#endif
| 2,370
|
C++
|
.h
| 56
| 40.482143
| 72
| 0.690208
|
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,834
|
linux.h
|
brndnmtthws_conky/src/linux.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 _LINUX_H
#define _LINUX_H
#include "common.h"
void print_disk_protect_queue(struct text_object *, char *, unsigned int);
void print_ioscheduler(struct text_object *, char *, unsigned int);
void print_laptop_mode(struct text_object *, char *, unsigned int);
void print_cpugovernor(struct text_object *, char *, unsigned int);
int update_gateway_info(void);
int update_gateway_info2(void);
void free_gateway_info(struct text_object *obj);
int gateway_exists(struct text_object *);
void print_gateway_iface(struct text_object *, char *, unsigned int);
void print_gateway_iface2(struct text_object *, char *, unsigned int);
void print_gateway_ip(struct text_object *, char *, unsigned int);
void print_battery_status(struct text_object *, char *, unsigned int);
enum { PB_BATT_STATUS, PB_BATT_PERCENT, PB_BATT_TIME };
void get_powerbook_batt_info(struct text_object *, char *, unsigned int);
void parse_i2c_sensor(struct text_object *, const char *);
void parse_hwmon_sensor(struct text_object *, const char *);
void parse_platform_sensor(struct text_object *, const char *);
void print_sysfs_sensor(struct text_object *, char *, unsigned int);
void free_sysfs_sensor(struct text_object *);
int get_entropy_avail(unsigned int *);
int get_entropy_poolsize(unsigned int *);
int update_stat(void);
void print_distribution(struct text_object *, char *, unsigned int);
bool is_conky_already_running(void);
extern char e_iface[64];
extern char interfaces_arr[MAX_NET_INTERFACES][64];
#endif /* _LINUX_H */
| 2,369
|
C++
|
.h
| 53
| 43.037736
| 74
| 0.754234
|
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,835
|
sony.h
|
brndnmtthws_conky/src/sony.h
|
/*
*
* 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> */
#ifndef _SONY_H
#define _SONY_H
void get_sony_fanspeed(struct text_object *, char *, unsigned int);
#endif /* _SONY_H */
| 1,268
|
C++
|
.h
| 33
| 36.515152
| 72
| 0.74513
|
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,836
|
irc.h
|
brndnmtthws_conky/src/irc.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 IRC_H_
#define IRC_H_
void parse_irc_args(struct text_object *, const char *);
void print_irc(struct text_object *, char *, unsigned int);
void free_irc(struct text_object *);
#endif /*IRC_H_*/
| 1,057
|
C++
|
.h
| 29
| 34.586207
| 72
| 0.741463
|
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,837
|
display-file.hh
|
brndnmtthws_conky/src/display-file.hh
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Please see COPYING for details
*
* Copyright (C) 2018 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_FILE_HH
#define DISPLAY_FILE_HH
#include <limits>
#include <string>
#include <type_traits>
#include "display-output.hh"
#include "luamm.hh"
namespace conky {
/*
* A base class for file display output.
*/
class display_output_file : public display_output_base {
public:
explicit display_output_file(const std::string &name_);
virtual ~display_output_file() {}
// check if available and enabled in settings
virtual bool detect();
// connect to DISPLAY and other stuff
virtual bool initialize();
virtual bool shutdown();
virtual void draw_string(const char *s, int w);
virtual void begin_draw_stuff();
virtual void end_draw_stuff();
// file-specific
};
} // namespace conky
#endif /* DISPLAY_FILE_HH */
| 1,542
|
C++
|
.h
| 48
| 29.9375
| 72
| 0.744265
|
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,838
|
nvidia.h
|
brndnmtthws_conky/src/nvidia.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) 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/>.
*
*/
#ifndef NVIDIA_CONKY_H
#define NVIDIA_CONKY_H
#include "specials.h"
int set_nvidia_query(struct text_object *, const char *, text_node_t);
void print_nvidia_value(struct text_object *, char *, unsigned int);
double get_nvidia_barval(struct text_object *);
void free_nvidia(struct text_object *);
#endif
| 1,336
|
C++
|
.h
| 36
| 35.25
| 72
| 0.75463
|
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,839
|
diskio.h
|
brndnmtthws_conky/src/diskio.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 DISKIO_H_
#define DISKIO_H_
#include <limits.h>
#include <cstring>
struct diskio_stat {
diskio_stat()
: next(nullptr),
current(0),
current_read(0),
current_write(0),
last(UINT_MAX),
last_read(UINT_MAX),
last_write(UINT_MAX) {
std::memset(sample, 0, sizeof(sample));
std::memset(sample_read, 0, sizeof(sample_read));
std::memset(sample_write, 0, sizeof(sample_write));
}
struct diskio_stat *next;
char *dev;
double sample[15];
double sample_read[15];
double sample_write[15];
double current;
double current_read;
double current_write;
double last;
double last_read;
double last_write;
};
extern struct diskio_stat stats;
struct diskio_stat *prepare_diskio_stat(const char *);
int update_diskio(void);
void clear_diskio_stats(void);
void update_diskio_values(struct diskio_stat *, unsigned int, unsigned int);
void parse_diskio_arg(struct text_object *, const char *);
void print_diskio(struct text_object *, char *, unsigned int);
void print_diskio_read(struct text_object *, char *, unsigned int);
void print_diskio_write(struct text_object *, char *, unsigned int);
#ifdef BUILD_GUI
void parse_diskiograph_arg(struct text_object *, const char *);
double diskiographval(struct text_object *);
double diskiographval_read(struct text_object *);
double diskiographval_write(struct text_object *);
#endif /* BUILD_GUI */
#endif /* DISKIO_H_ */
| 2,500
|
C++
|
.h
| 73
| 31.520548
| 76
| 0.731405
|
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,840
|
cmus.h
|
brndnmtthws_conky/src/cmus.h
|
/*
*
* CMUS Conky integration
*
* Please see COPYING for details
*
* Copyright (c) 2011, Christian Brabandt <cb@256bit.org>
*
* 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 CMUS_H_
#define CMUS_H_
void print_cmus_state(struct text_object *, char *, unsigned int);
void print_cmus_file(struct text_object *, char *, unsigned int);
void print_cmus_title(struct text_object *, char *, unsigned int);
void print_cmus_artist(struct text_object *, char *, unsigned int);
void print_cmus_album(struct text_object *, char *, unsigned int);
void print_cmus_totaltime(struct text_object *, char *, unsigned int);
void print_cmus_timeleft(struct text_object *, char *, unsigned int);
void print_cmus_curtime(struct text_object *, char *, unsigned int);
void print_cmus_random(struct text_object *, char *, unsigned int);
void print_cmus_repeat(struct text_object *, char *, unsigned int);
void print_cmus_aaa(struct text_object *, char *, unsigned int);
void print_cmus_track(struct text_object *, char *, unsigned int);
void print_cmus_genre(struct text_object *, char *, unsigned int);
void print_cmus_date(struct text_object *, char *, unsigned int);
void print_cmus_bar(struct text_object *, char *, unsigned int);
double cmus_progress(struct text_object *obj);
uint8_t cmus_percent(struct text_object *obj);
#endif /* CMUS_H_ */
| 1,944
|
C++
|
.h
| 41
| 45.853659
| 72
| 0.747368
|
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,841
|
solaris.h
|
brndnmtthws_conky/src/solaris.h
|
#ifndef SOLARIS_H_
#define SOLARIS_H_
int get_entropy_avail(unsigned int *);
int get_entropy_poolsize(unsigned int *);
#endif /*SOLARIS_H_*/
| 143
|
C++
|
.h
| 5
| 27.2
| 41
| 0.75
|
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,842
|
temphelper.h
|
brndnmtthws_conky/src/temphelper.h
|
/*
*
* temphelper.h: 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.
*
*/
#ifndef TEMPHELPER_H
#define TEMPHELPER_H
#include <cstddef>
enum TEMP_UNIT { TEMP_CELSIUS, TEMP_FAHRENHEIT };
int temp_print(char *, std::size_t, double, enum TEMP_UNIT, int);
#endif /* TEMPHELPER_H */
| 1,046
|
C++
|
.h
| 28
| 35.428571
| 72
| 0.750247
|
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,843
|
read_tcpip.h
|
brndnmtthws_conky/src/read_tcpip.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 _READ_TCP_H
#define _READ_TCP_H
void parse_read_tcpip_arg(struct text_object *, const char *, void *);
void parse_tcp_ping_arg(struct text_object *obj, const char *arg,
void *free_at_crash);
void print_read_tcp(struct text_object *, char *, unsigned int);
void print_read_udp(struct text_object *, char *, unsigned int);
void print_tcp_ping(struct text_object *, char *, unsigned int);
void free_read_tcpip(struct text_object *);
void free_tcp_ping(struct text_object *);
#endif /* _READ_TCP_H */
| 1,585
|
C++
|
.h
| 39
| 38.25641
| 72
| 0.734284
|
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,844
|
display-wayland.hh
|
brndnmtthws_conky/src/display-wayland.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_WAYLAND_HH
#define DISPLAY_WAYLAND_HH
#include "config.h"
#include <limits>
#include <string>
#include <type_traits>
#include "colours.h"
#include "display-output.hh"
#include "luamm.hh"
#include "wl.h"
namespace conky {
/*
* A base class for Wayland display output.
*/
class display_output_wayland : public display_output_base {
public:
explicit display_output_wayland();
virtual ~display_output_wayland() {}
// 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);
// Wayland-specific
};
} // namespace conky
#endif /* DISPLAY_WAYLAND_HH */
| 2,470
|
C++
|
.h
| 74
| 30.905405
| 72
| 0.741379
|
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,845
|
mpd.h
|
brndnmtthws_conky/src/mpd.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 MPD_H_
#define MPD_H_
#include <cstdint>
/* text object functions */
double mpd_barval(struct text_object *);
int check_mpd_playing(struct text_object *);
uint8_t mpd_percentage(struct text_object *);
void print_mpd_album(struct text_object *, char *, unsigned int);
void print_mpd_albumartist(struct text_object *, char *, unsigned int);
void print_mpd_artist(struct text_object *, char *, unsigned int);
void print_mpd_bitrate(struct text_object *, char *, unsigned int);
void print_mpd_comment(struct text_object *, char *, unsigned int);
void print_mpd_date(struct text_object *, char *, unsigned int);
void print_mpd_elapsed(struct text_object *, char *, unsigned int);
void print_mpd_file(struct text_object *, char *, unsigned int);
void print_mpd_length(struct text_object *, char *, unsigned int);
void print_mpd_name(struct text_object *, char *, unsigned int);
void print_mpd_random(struct text_object *, char *, unsigned int);
void print_mpd_repeat(struct text_object *, char *, unsigned int);
void print_mpd_smart(struct text_object *, char *, unsigned int);
void print_mpd_status(struct text_object *, char *, unsigned int);
void print_mpd_title(struct text_object *, char *, unsigned int);
void print_mpd_track(struct text_object *, char *, unsigned int);
void print_mpd_vol(struct text_object *, char *, unsigned int);
#endif /*MPD_H_*/
| 2,217
|
C++
|
.h
| 48
| 44.645833
| 72
| 0.743649
|
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,846
|
ical.h
|
brndnmtthws_conky/src/ical.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 ICAL_H_
#define ICAL_H_
void parse_ical_args(struct text_object *, const char *, void *, void *);
void print_ical(struct text_object *, char *, unsigned int);
void free_ical(struct text_object *);
#endif /*ICAL_H_*/
| 1,079
|
C++
|
.h
| 29
| 35.344828
| 73
| 0.739255
|
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,847
|
smapi.h
|
brndnmtthws_conky/src/smapi.h
|
/*
*
* smapi.h: 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.
*
*/
#ifndef _SMAPI_H
#define _SMAPI_H
void print_smapi(struct text_object *, char *, unsigned int);
uint8_t smapi_bat_percentage(struct text_object *);
void print_smapi_bat_temp(struct text_object *, char *, unsigned int);
void print_smapi_bat_power(struct text_object *, char *, unsigned int);
double smapi_bat_barval(struct text_object *);
int smapi_bat_installed(struct text_object *obj);
#endif /* _SMAPI_H */
| 1,247
|
C++
|
.h
| 31
| 38.451613
| 72
| 0.749382
|
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,848
|
display-console.hh
|
brndnmtthws_conky/src/display-console.hh
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Please see COPYING for details
*
* Copyright (C) 2018 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_CONSOLE_HH
#define DISPLAY_CONSOLE_HH
#include <limits>
#include <string>
#include <type_traits>
#include "display-output.hh"
#include "luamm.hh"
namespace conky {
/*
* A base class for console display output.
*/
class display_output_console : public display_output_base {
public:
explicit display_output_console(const std::string &name_);
virtual ~display_output_console() {}
// check if available and enabled in settings
virtual bool detect();
// connect to DISPLAY and other stuff
virtual bool initialize();
virtual bool shutdown();
virtual void draw_string(const char *s, int w);
// console-specific
};
} // namespace conky
#endif /* DISPLAY_CONSOLE_HH */
| 1,497
|
C++
|
.h
| 46
| 30.413043
| 72
| 0.749306
|
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,849
|
wl.h
|
brndnmtthws_conky/src/wl.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_WL_H
#define CONKY_WL_H
#include "config.h"
#ifndef BUILD_WAYLAND
#error wl.h included when BUILD_WAYLAND is disabled
#endif
#include <wayland-client.h>
#include "setting.hh"
namespace priv {
class out_to_wayland_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_wayland_setting() : Base("out_to_wayland", false, false) {}
};
} // namespace priv
extern priv::out_to_wayland_setting out_to_wayland;
#endif /* CONKY_WL_H */
| 1,677
|
C++
|
.h
| 48
| 32.958333
| 74
| 0.751699
|
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,850
|
net_stat.h
|
brndnmtthws_conky/src/net_stat.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 _NET_STAT_H
#define _NET_STAT_H
#include <netinet/in.h> /* struct in6_addr */
#include <sys/socket.h> /* struct sockaddr */
#include "config.h"
#ifdef BUILD_IPV6
struct v6addr {
struct in6_addr addr;
unsigned int netmask;
char scope;
struct v6addr *next;
};
#endif /* BUILD_IPV6 */
struct net_stat {
/* interface name, e.g. wlan0, eth0, ... */
char *dev;
/* set to 1, if interface is up */
int up;
/* network traffic read on last call in order to calculate how much
* was received or transmitted since the last call. contains -1 if
* it was never read before. in bytes */
long long last_read_recv, last_read_trans;
/* total received and transmitted data statistics in bytes */
long long recv, trans;
/* averaged network speed in bytes / second */
double recv_speed, trans_speed;
/* struct with at least the member sa_data which is a const * containing
* the socket address.
* @see http://pubs.opengroup.org/onlinepubs/7908799/xns/syssocket.h.html */
struct sockaddr addr;
#ifdef BUILD_IPV6
struct v6addr *v6addrs;
bool v6show_nm;
bool v6show_sc;
#endif /* BUILD_IPV6 */
#if defined(__linux__)
char addrs[17 * MAX_NET_INTERFACES + 1];
#endif /* __linux__ */
/* network speeds between two conky calls in bytes per second.
* An average over these samples is calculated in recv_speed and
* trans_speed */
double net_rec[15], net_trans[15];
// wireless extensions
char essid[35];
int channel;
char freq[16];
char bitrate[16];
char mode[16];
int link_qual;
int link_qual_max;
char ap[18];
};
extern struct net_stat netstats[];
struct net_stat *get_net_stat(const char *, void *, void *);
void parse_net_stat_arg(struct text_object *, const char *, void *);
void parse_net_stat_bar_arg(struct text_object *, const char *, void *);
void print_downspeed(struct text_object *, char *, unsigned int);
void print_downspeedf(struct text_object *, char *, unsigned int);
void print_upspeed(struct text_object *, char *, unsigned int);
void print_upspeedf(struct text_object *, char *, unsigned int);
void print_totaldown(struct text_object *, char *, unsigned int);
void print_totalup(struct text_object *, char *, unsigned int);
void print_addr(struct text_object *, char *, unsigned int);
#ifdef __linux__
void print_addrs(struct text_object *, char *, unsigned int);
#ifdef BUILD_IPV6
void print_v6addrs(struct text_object *, char *, unsigned int);
#endif /* BUILD_IPV6 */
#endif /* __linux__ */
#ifdef BUILD_GUI
void parse_net_stat_graph_arg(struct text_object *, const char *, void *);
double downspeedgraphval(struct text_object *);
double upspeedgraphval(struct text_object *);
#endif /* BUILD_GUI */
#ifdef BUILD_WLAN
void print_wireless_essid(struct text_object *, char *, unsigned int);
void print_wireless_channel(struct text_object *, char *, unsigned int);
void print_wireless_frequency(struct text_object *, char *, unsigned int);
void print_wireless_mode(struct text_object *, char *, unsigned int);
void print_wireless_bitrate(struct text_object *, char *, unsigned int);
void print_wireless_ap(struct text_object *, char *, unsigned int);
void print_wireless_link_qual(struct text_object *, char *, unsigned int);
void print_wireless_link_qual_max(struct text_object *, char *, unsigned int);
void print_wireless_link_qual_perc(struct text_object *, char *, unsigned int);
double wireless_link_barval(struct text_object *);
#endif /* BUILD_WLAN */
void clear_net_stats(void);
void clear_net_stats(net_stat *);
void parse_if_up_arg(struct text_object *, const char *);
int interface_up(struct text_object *);
void free_if_up(struct text_object *);
void free_dns_data(struct text_object *);
int update_dns_data(void);
void parse_nameserver_arg(struct text_object *, const char *);
void print_nameserver(struct text_object *, char *, unsigned int);
#endif /* _NET_STAT_H */
| 4,926
|
C++
|
.h
| 124
| 37.774194
| 79
| 0.73158
|
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,851
|
gradient.h
|
brndnmtthws_conky/src/gradient.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 _GRADIENT_H
#define _GRADIENT_H
#include <memory>
#include "colours.h"
namespace conky {
class gradient_factory {
public:
typedef std::unique_ptr<Colour[]> colour_array;
static const long SCALE = 512L;
static const long SCALE2 = SCALE * 2;
static const long SCALE4 = SCALE * 4;
static const long SCALE6 = SCALE * 6;
static const long SCALE60 = SCALE * 60;
static const long SCALE120 = SCALE * 120;
static const long SCALE180 = SCALE * 180;
static const long SCALE240 = SCALE * 240;
static const long SCALE300 = SCALE * 300;
static const long SCALE360 = SCALE * 360;
public:
gradient_factory(int width, Colour first_colour, Colour last_colour);
virtual ~gradient_factory() {}
colour_array create_gradient();
virtual void convert_from_scaled_rgb(long *const scaled, long *target) = 0;
virtual void convert_to_scaled_rgb(long *const target, long *scaled) = 0;
void convert_from_rgb(Colour original, long *array);
Colour convert_to_rgb(long *const array);
protected:
virtual void fix_diff(long *) {}
static long get_hue(long *const scaled, long chroma, long value);
static long get_intermediate(long hue, long chroma);
private:
int width;
Colour first_colour;
Colour last_colour;
};
class rgb_gradient_factory : public gradient_factory {
using gradient_factory::gradient_factory;
public:
void convert_from_scaled_rgb(long *const scaled, long *target);
void convert_to_scaled_rgb(long *const target, long *scaled);
};
class hsv_gradient_factory : public gradient_factory {
using gradient_factory::gradient_factory;
public:
void fix_diff(long *diff);
void convert_from_scaled_rgb(long *const scaled, long *target);
void convert_to_scaled_rgb(long *const target, long *scaled);
};
class hcl_gradient_factory : public gradient_factory {
using gradient_factory::gradient_factory;
public:
void fix_diff(long *diff);
void convert_from_scaled_rgb(long *const scaled, long *target);
void convert_to_scaled_rgb(long *const target, long *scaled);
};
} // namespace conky
#endif /* _GRADIENT_H */
| 3,137
|
C++
|
.h
| 85
| 34.482353
| 77
| 0.747611
|
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,852
|
setting.hh
|
brndnmtthws_conky/src/setting.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 SETTING_HH
#define SETTING_HH
#include <limits>
#include <string>
#include <type_traits>
#include "logging.h"
#include "luamm.hh"
namespace conky {
/*
* Checks settings, and does initial calls to the setters.
* Should be called after reading the user config.
* stack on entry: | ... |
* stack on exit: | ... |
*/
void set_config_settings(lua::state &l);
/*
* Calls cleanup functions.
* Should be called before exit/restart.
* stack on entry: | ... |
* stack on exit: | ... |
*/
void cleanup_config_settings(lua::state &l);
template <typename T, bool is_integral = std::is_integral<T>::value,
bool floating_point = std::is_floating_point<T>::value,
bool is_enum = std::is_enum<T>::value>
struct lua_traits {
// integral is here to force the compiler to evaluate the assert at
// instantiation time
static_assert(is_integral && false,
"Only specializations for enum, string, integral and floating "
"point types are available");
};
// specialization for integral types
template <typename T>
struct lua_traits<T, true, false, false> {
static const lua::Type type = lua::TNUMBER;
typedef lua::integer Type;
static inline std::pair<Type, bool> convert(lua::state &l, int index,
const std::string &) {
return {l.tointeger(index), true};
}
};
// specialization for floating point types
template <typename T>
struct lua_traits<T, false, true, false> {
static const lua::Type type = lua::TNUMBER;
typedef lua::number Type;
static inline std::pair<Type, bool> convert(lua::state &l, int index,
const std::string &) {
return {l.tonumber(index), true};
}
};
// specialization for std::string
template <>
struct lua_traits<std::string, false, false, false> {
static const lua::Type type = lua::TSTRING;
typedef std::string Type;
static inline std::pair<Type, bool> convert(lua::state &l, int index,
const std::string &) {
return {l.tostring(index), true};
}
};
// specialization for bool
template <>
struct lua_traits<bool, true, false, false> {
static const lua::Type type = lua::TBOOLEAN;
typedef bool Type;
static inline std::pair<Type, bool> convert(lua::state &l, int index,
const std::string &) {
return {l.toboolean(index), true};
}
};
// specialization for enums
// to use this, one first has to declare string<->value map
template <typename T>
struct lua_traits<T, false, false, true> {
static const lua::Type type = lua::TSTRING;
typedef T Type;
typedef std::initializer_list<std::pair<std::string, T>> Map;
static Map map;
static std::pair<T, bool> convert(lua::state &l, int index,
const std::string &name) {
std::string val = l.tostring(index);
for (auto i = map.begin(); i != map.end(); ++i) {
if (i->first == val) return {i->second, true};
}
std::string msg = "Invalid value '" + val + "' for setting '" + name +
"'. Valid values are: ";
for (auto i = map.begin(); i != map.end(); ++i) {
if (i != map.begin()) msg += ", ";
msg += "'" + i->first + "'";
}
msg += ".";
NORM_ERR("%s", msg.c_str());
return {T(), false};
}
};
namespace priv {
class config_setting_base {
private:
static void process_setting(lua::state &l, bool init);
static int config__newindex(lua::state *l);
static void make_conky_config(lua::state &l);
// copying is a REALLY bad idea
config_setting_base(const config_setting_base &) = delete;
config_setting_base &operator=(const config_setting_base &) = delete;
protected:
/*
* Set the setting, if the value is sane
* stack on entry: | ... potential_new_value old_value |
* stack on exit: | ... real_new_value |
* real_new_value can be the old value if the new value doesn't make sense
*/
virtual void lua_setter(lua::state &l, bool init) = 0;
/*
* Called on exit/restart.
* stack on entry: | ... new_value |
* stack on exit: | ... |
*/
virtual void cleanup(lua::state &l) { l.pop(); }
public:
const std::string name;
const size_t seq_no;
static bool seq_compare(const config_setting_base *a,
const config_setting_base *b) {
return a->seq_no < b->seq_no;
}
explicit config_setting_base(std::string name_);
virtual ~config_setting_base() {}
/*
* Set the setting manually.
* stack on entry: | ... new_value |
* stack on exit: | ... |
*/
void lua_set(lua::state &l);
friend void conky::set_config_settings(lua::state &l);
friend void conky::cleanup_config_settings(lua::state &l);
};
} // namespace priv
// If you need some very exotic setting, derive it from this class. Otherwise,
// scroll down.
template <typename T>
class config_setting_template : public priv::config_setting_base {
public:
explicit config_setting_template(const std::string &name_)
: config_setting_base(name_) {}
// get the value of the setting as a C++ type
T get(lua::state &l);
protected:
/*
* Convert the value into a C++ type.
* stack on entry: | ... value |
* stack on exit: | ... |
*/
virtual T getter(lua::state &l) = 0;
};
template <typename T>
T config_setting_template<T>::get(lua::state &l) {
std::lock_guard<lua::state> guard(l);
lua::stack_sentry s(l);
l.checkstack(2);
l.getglobal("conky");
l.getfield(-1, "config");
l.replace(-2);
l.getfield(-1, name.c_str());
l.replace(-2);
return getter(l);
}
/*
* Declares a setting <name> in the conky.config table.
* Getter function is used to translate the lua value into C++. It receives the
* value on the lua stack. It should pop it and return the C++ value. In case
* the value is nil, it should return a predefined default value. Translation
* into basic types works with the help of lua_traits template above The
* lua_setter function is called when someone tries to set the value. It
* receives the new and the old value on the stack (old one is on top). It
* should return the new value for the setting. It doesn't have to be the value
* the user set, if e.g. the value doesn't make sense. The second parameter is
* true if the assignment occurs during the initial parsing of the config file,
* and false afterwards. Some settings obviously cannot be changed (easily?)
* when conky is running, but some (e.g. x/y position of the window) can.
*/
template <typename T, typename Traits = lua_traits<T>>
class simple_config_setting : public config_setting_template<T> {
typedef config_setting_template<T> Base;
public:
explicit simple_config_setting(const std::string &name_,
const T &default_value_ = T(),
bool modifiable_ = false)
: Base(name_), default_value(default_value_), modifiable(modifiable_) {}
simple_config_setting(const char *name_, const T &default_value_ = T(),
bool modifiable_ = false)
: Base(std::string(name_)),
default_value(default_value_),
modifiable(modifiable_) {}
protected:
const T default_value;
const bool modifiable;
virtual std::pair<typename Traits::Type, bool> do_convert(lua::state &l,
int index);
virtual void lua_setter(lua::state &l, bool init);
virtual T getter(lua::state &l) {
lua::stack_sentry s(l, -1);
auto ret = do_convert(l, -1);
l.pop();
// setter function should make sure the value is valid
assert(ret.second);
return ret.first;
}
};
template <typename T, typename Traits>
std::pair<typename Traits::Type, bool>
simple_config_setting<T, Traits>::do_convert(lua::state &l, int index) {
if (l.isnil(index)) return {default_value, true};
if (l.type(index) != Traits::type) {
NORM_ERR(
"Invalid value of type '%s' for setting '%s'. "
"Expected value of type '%s'.",
l.type_name(l.type(index)), Base::name.c_str(),
l.type_name(Traits::type));
return {default_value, false};
}
return Traits::convert(l, index, Base::name);
}
template <typename T, typename Traits>
void simple_config_setting<T, Traits>::lua_setter(lua::state &l, bool init) {
lua::stack_sentry s(l, -2);
bool ok = true;
if (!init && !modifiable) {
NORM_ERR("Setting '%s' is not modifiable", Base::name.c_str());
ok = false;
}
if (ok && do_convert(l, -2).second) {
l.pop();
} else {
l.replace(-2);
}
++s;
}
template <typename Signed1, typename Signed2>
bool between(Signed1 value, Signed2 min,
typename std::enable_if<std::is_signed<Signed2>::value,
Signed2>::type max) {
return value >= min && value <= max;
}
template <typename Signed1, typename Unsigned2>
bool between(Signed1 value, Unsigned2 min,
typename std::enable_if<std::is_unsigned<Unsigned2>::value,
Unsigned2>::type max) {
return value >= 0 &&
static_cast<typename std::make_unsigned<Signed1>::type>(value) >=
min &&
static_cast<typename std::make_unsigned<Signed1>::type>(value) <= max;
}
// Just like simple_config_setting, except that in only accepts value in the
// [min, max] range
template <typename T, typename Traits = lua_traits<T>>
class range_config_setting : public simple_config_setting<T, Traits> {
typedef simple_config_setting<T, Traits> Base;
const T min;
const T max;
public:
explicit range_config_setting(const std::string &name_,
const T &min_ = std::numeric_limits<T>::min(),
const T &max_ = std::numeric_limits<T>::max(),
const T &default_value_ = T(),
bool modifiable_ = false)
: Base(name_, default_value_, modifiable_), min(min_), max(max_) {
assert(min <= Base::default_value && Base::default_value <= max);
}
protected:
virtual std::pair<typename Traits::Type, bool> do_convert(lua::state &l,
int index) {
auto ret = Base::do_convert(l, index);
if (ret.second && !between(ret.first, min, max)) {
NORM_ERR("Value is out of range for setting '%s'", Base::name.c_str());
// we ignore out-of-range values. an alternative would be to clamp them.
// do we want to do that?
ret.second = false;
}
return ret;
}
};
} // namespace conky
#endif /* SETTING_HH */
| 11,448
|
C++
|
.h
| 306
| 31.947712
| 79
| 0.636864
|
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,853
|
users.h
|
brndnmtthws_conky/src/users.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 _USERS_H
#define _USERS_H
int update_users(void);
void print_user_names(struct text_object *, char *, unsigned int);
void print_user_terms(struct text_object *, char *, unsigned int);
void print_user_times(struct text_object *, char *, unsigned int);
void print_user_time(struct text_object *, char *, unsigned int);
void print_user_number(struct text_object *, char *, unsigned int);
void free_user_names(struct text_object *);
void free_user_terms(struct text_object *);
void free_user_times(struct text_object *);
void free_user_time(struct text_object *);
#endif /* _USERS_H */
| 1,648
|
C++
|
.h
| 41
| 38.414634
| 72
| 0.749688
|
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,854
|
xmms2.h
|
brndnmtthws_conky/src/xmms2.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) 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 XMMS2_H_
#define XMMS2_H_
#include <xmmsclient/xmmsclient.h>
struct xmms2_s {
char *artist;
char *album;
char *title;
char *genre;
char *comment;
char *url;
char *date;
char *playlist;
int tracknr;
int bitrate;
unsigned int id;
int duration;
int elapsed;
int timesplayed;
float size;
float progress;
int percent;
char *status;
int conn_state;
};
int update_xmms2(void);
void print_xmms2_tracknr(struct text_object *, char *, unsigned int);
void print_xmms2_elapsed(struct text_object *, char *, unsigned int);
void print_xmms2_duration(struct text_object *, char *, unsigned int);
double xmms2_barval(struct text_object *);
void print_xmms2_smart(struct text_object *, char *, unsigned int);
void print_xmms2_artist(struct text_object *, char *, unsigned int);
void print_xmms2_album(struct text_object *, char *, unsigned int);
void print_xmms2_title(struct text_object *, char *, unsigned int);
void print_xmms2_genre(struct text_object *, char *, unsigned int);
void print_xmms2_comment(struct text_object *, char *, unsigned int);
void print_xmms2_url(struct text_object *, char *, unsigned int);
void print_xmms2_status(struct text_object *, char *, unsigned int);
void print_xmms2_date(struct text_object *, char *, unsigned int);
void print_xmms2_bitrate(struct text_object *, char *, unsigned int);
void print_xmms2_id(struct text_object *, char *, unsigned int);
void print_xmms2_size(struct text_object *, char *, unsigned int);
void print_xmms2_playlist(struct text_object *, char *, unsigned int);
void print_xmms2_timesplayed(struct text_object *, char *, unsigned int);
void print_xmms2_percent(struct text_object *, char *, unsigned int);
int if_xmms2_connected(struct text_object *);
void free_xmms2(struct text_object *);
#endif /*XMMS2_H_*/
| 2,804
|
C++
|
.h
| 74
| 35.918919
| 73
| 0.74504
|
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,855
|
prss.h
|
brndnmtthws_conky/src/prss.h
|
/*
*
* 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. */
#ifndef PRSS_H
#define PRSS_H
#include <libxml/parser.h>
#include <string>
typedef struct PRSS_Item_ {
char *title;
char *link;
char *description;
char *category;
char *pubDate;
char *guid;
} PRSS_Item;
class PRSS {
public:
char *version;
char *title;
char *link;
char *description;
char *language;
char *generator;
char *managingEditor;
char *webMaster;
char *docs;
char *lastBuildDate;
char *pubDate;
char *copyright;
char *ttl;
PRSS_Item *items;
int item_count;
explicit PRSS(const std::string &xml_data);
~PRSS();
};
#endif /* PRSS_H */
| 1,443
|
C++
|
.h
| 49
| 27.020408
| 75
| 0.743867
|
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,856
|
display-http.hh
|
brndnmtthws_conky/src/display-http.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_HTTP_HH
#define DISPLAY_HTTP_HH
#include "config.h"
#include <limits>
#include <string>
#include <type_traits>
#include "display-output.hh"
#include "luamm.hh"
namespace conky {
/*
* A base class for HTTP display output.
*/
class display_output_http : public display_output_base {
public:
explicit display_output_http();
virtual ~display_output_http() {}
// check if available and enabled in settings
virtual bool detect();
// connect to DISPLAY and other stuff
virtual bool initialize();
virtual bool shutdown();
// drawing primitives
virtual void set_foreground_color(Colour) {}
virtual void begin_draw_text();
virtual void end_draw_text();
virtual void draw_string(const char *, int);
// HTTP-specific
private:
// std::string webpage;
// struct MHD_Daemon *httpd;
};
} // namespace conky
#endif /* DISPLAY_HTTP_HH */
| 1,676
|
C++
|
.h
| 54
| 28.814815
| 72
| 0.741615
|
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,857
|
template.h
|
brndnmtthws_conky/src/template.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 _TEMPLATE_H
#define _TEMPLATE_H
char *find_and_replace_templates(const char *);
int text_contains_templates(const char *);
#endif /* _TEMPLATE_H */
| 1,212
|
C++
|
.h
| 33
| 34.818182
| 72
| 0.752551
|
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,858
|
timeinfo.h
|
brndnmtthws_conky/src/timeinfo.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 _TIMEINFO_H
#define _TIMEINFO_H
#include "setting.hh"
extern conky::simple_config_setting<bool> times_in_seconds;
/* since time and utime are quite equal, certain functions
* are shared in between both text object types. */
/* parse args passed to *time objects */
void scan_time(struct text_object *, const char *);
void scan_tztime(struct text_object *, const char *);
/* print the time */
void print_time(struct text_object *, char *, unsigned int);
void print_utime(struct text_object *, char *, unsigned int);
void print_tztime(struct text_object *, char *, unsigned int);
void print_format_time(struct text_object *obj, char *p,
unsigned int p_max_size);
/* free object data */
void free_time(struct text_object *);
void free_tztime(struct text_object *);
#endif /* _TIMEINFO_H */
| 1,879
|
C++
|
.h
| 47
| 37.744681
| 72
| 0.73863
|
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,871
|
main.cpp
|
cemu-project_Cemu/src/main.cpp
|
#include "gui/guiWrapper.h"
#include "gui/wxgui.h"
#include "util/crypto/aes128.h"
#include "gui/MainWindow.h"
#include "Cafe/OS/RPL/rpl.h"
#include "Cafe/OS/libs/gx2/GX2.h"
#include "Cafe/OS/libs/coreinit/coreinit_Thread.h"
#include "Cafe/GameProfile/GameProfile.h"
#include "Cafe/GraphicPack/GraphicPack2.h"
#include "config/CemuConfig.h"
#include "config/NetworkSettings.h"
#include "config/LaunchSettings.h"
#include "input/InputManager.h"
#include "gui/CemuApp.h"
#include "Cafe/CafeSystem.h"
#include "Cafe/TitleList/TitleList.h"
#include "Cafe/TitleList/SaveList.h"
#include "Common/ExceptionHandler/ExceptionHandler.h"
#include "Common/cpu_features.h"
#include <wx/setup.h>
#include "util/helpers/helpers.h"
#include "config/ActiveSettings.h"
#include "Cafe/HW/Latte/Renderer/Vulkan/VsyncDriver.h"
#include "Cafe/IOSU/legacy/iosu_crypto.h"
#include "Cafe/OS/libs/vpad/vpad.h"
#include "audio/IAudioAPI.h"
#include "audio/IAudioInputAPI.h"
#if BOOST_OS_WINDOWS
#pragma comment(lib,"Dbghelp.lib")
#endif
#define SDL_MAIN_HANDLED
#include <SDL.h>
#if BOOST_OS_LINUX
#define _putenv(__s) putenv((char*)(__s))
#include <sys/sysinfo.h>
#elif BOOST_OS_MACOS
#define _putenv(__s) putenv((char*)(__s))
#include <sys/types.h>
#include <sys/sysctl.h>
#endif
#if BOOST_OS_WINDOWS
extern "C"
{
__declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
__declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001;
}
#endif
std::atomic_bool g_isGPUInitFinished = false;
std::wstring executablePath;
// some implementations of _putenv dont copy the string and instead only store a pointer
// thus we use a helper to keep a permanent copy
std::vector<std::string*> sPutEnvMap;
void _putenvSafe(const char* c)
{
auto s = new std::string(c);
sPutEnvMap.emplace_back(s);
_putenv(s->c_str());
}
void reconfigureGLDrivers()
{
// reconfigure GL drivers to store
const fs::path nvCacheDir = ActiveSettings::GetCachePath("shaderCache/driver/nvidia/");
std::error_code err;
fs::create_directories(nvCacheDir, err);
std::string nvCacheDirEnvOption("__GL_SHADER_DISK_CACHE_PATH=");
nvCacheDirEnvOption.append(_pathToUtf8(nvCacheDir));
#if BOOST_OS_WINDOWS
std::wstring tmpW = boost::nowide::widen(nvCacheDirEnvOption);
_wputenv(tmpW.c_str());
#else
_putenvSafe(nvCacheDirEnvOption.c_str());
#endif
_putenvSafe("__GL_SHADER_DISK_CACHE_SKIP_CLEANUP=1");
}
void reconfigureVkDrivers()
{
_putenvSafe("DISABLE_LAYER_AMD_SWITCHABLE_GRAPHICS_1=1");
_putenvSafe("DISABLE_VK_LAYER_VALVE_steam_fossilize_1=1");
}
void WindowsInitCwd()
{
#if BOOST_OS_WINDOWS
executablePath.resize(4096);
int i = GetModuleFileName(NULL, executablePath.data(), executablePath.size());
if(i >= 0)
executablePath.resize(i);
else
executablePath.clear();
SetCurrentDirectory(executablePath.c_str());
// set high priority
SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS);
#endif
}
void CemuCommonInit()
{
reconfigureGLDrivers();
reconfigureVkDrivers();
// crypto init
AES128_init();
// init PPC timer
// call this as early as possible because it measures frequency of RDTSC using an asynchronous thread over 3 seconds
PPCTimer_init();
WindowsInitCwd();
ExceptionHandler_Init();
// read config
g_config.Load();
if (NetworkConfig::XMLExists())
n_config.Load();
// parallelize expensive init code
std::future<int> futureInitAudioAPI = std::async(std::launch::async, []{ IAudioAPI::InitializeStatic(); IAudioInputAPI::InitializeStatic(); return 0; });
std::future<int> futureInitGraphicPacks = std::async(std::launch::async, []{ GraphicPack2::LoadAll(); return 0; });
InputManager::instance().load();
futureInitAudioAPI.wait();
futureInitGraphicPacks.wait();
// init Cafe system
CafeSystem::Initialize();
// init title list
CafeTitleList::Initialize(ActiveSettings::GetUserDataPath("title_list_cache.xml"));
for (auto& it : GetConfig().game_paths)
CafeTitleList::AddScanPath(_utf8ToPath(it));
fs::path mlcPath = ActiveSettings::GetMlcPath();
if (!mlcPath.empty())
CafeTitleList::SetMLCPath(mlcPath);
CafeTitleList::Refresh();
// init save list
CafeSaveList::Initialize();
if (!mlcPath.empty())
{
CafeSaveList::SetMLCPath(mlcPath);
CafeSaveList::Refresh();
}
}
void mainEmulatorLLE();
void ppcAsmTest();
void gx2CopySurfaceTest();
void ExpressionParser_test();
void FSTVolumeTest();
void CRCTest();
void UnitTests()
{
ExpressionParser_test();
gx2CopySurfaceTest();
ppcAsmTest();
FSTVolumeTest();
CRCTest();
}
bool isConsoleConnected = false;
void requireConsole()
{
#if BOOST_OS_WINDOWS
if (isConsoleConnected)
return;
if (AttachConsole(ATTACH_PARENT_PROCESS) != FALSE)
{
freopen("CONIN$", "r", stdin);
freopen("CONOUT$", "w", stdout);
freopen("CONOUT$", "w", stderr);
isConsoleConnected = true;
}
#endif
}
void HandlePostUpdate()
{
// finalize update process
// delete update cemu.exe.backup if available
const auto filename = ActiveSettings::GetExecutablePath().replace_extension("exe.backup");
if (fs::exists(filename))
{
#if BOOST_OS_WINDOWS
HANDLE lock;
do
{
lock = CreateMutex(nullptr, TRUE, L"Global\\cemu_update_lock");
std::this_thread::sleep_for(std::chrono::milliseconds(1));
} while (lock == nullptr);
const DWORD wait_result = WaitForSingleObject(lock, 2000);
CloseHandle(lock);
if (wait_result == WAIT_OBJECT_0)
{
std::this_thread::sleep_for(std::chrono::milliseconds(500));
std::error_code ec;
fs::remove(filename, ec);
}
#else
while (fs::exists(filename))
{
std::error_code ec;
fs::remove(filename, ec);
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
#endif
}
}
void ToolShaderCacheMerger();
#if BOOST_OS_WINDOWS
// entrypoint for release builds
int wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPTSTR lpCmdLine, _In_ int nShowCmd)
{
if (FAILED(CoInitializeEx(nullptr, COINIT_MULTITHREADED | COINIT_DISABLE_OLE1DDE)))
cemuLog_log(LogType::Force, "CoInitializeEx() failed");
SDL_SetMainReady();
if (!LaunchSettings::HandleCommandline(lpCmdLine))
return 0;
gui_create();
return 0;
}
// entrypoint for debug builds with console
int main(int argc, char* argv[])
{
if (FAILED(CoInitializeEx(nullptr, COINIT_MULTITHREADED | COINIT_DISABLE_OLE1DDE)))
cemuLog_log(LogType::Force, "CoInitializeEx() failed");
SDL_SetMainReady();
if (!LaunchSettings::HandleCommandline(argc, argv))
return 0;
gui_create();
return 0;
}
#else
int main(int argc, char *argv[])
{
#if BOOST_OS_LINUX
XInitThreads();
#endif
if (!LaunchSettings::HandleCommandline(argc, argv))
return 0;
gui_create();
return 0;
}
#endif
extern "C" DLLEXPORT uint64 gameMeta_getTitleId()
{
return CafeSystem::GetForegroundTitleId();
}
| 6,751
|
C++
|
.cpp
| 233
| 26.961373
| 154
| 0.754164
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,872
|
mainLLE.cpp
|
cemu-project_Cemu/src/mainLLE.cpp
|
#include "gui/wxgui.h"
#include "util/crypto/aes128.h"
#include "gui/MainWindow.h"
#include "gui/guiWrapper.h"
#include "Common/FileStream.h"
void CemuCommonInit();
typedef struct
{
/* +0x000 */ uint32be magic;
}ppcAncastHeader_t;
void loadEncryptedPPCAncastKernel()
{
auto kernelData = FileStream::LoadIntoMemory("kernel.img");
if (!kernelData)
exit(-1);
// check header
ppcAncastHeader_t* ancastHeader = (ppcAncastHeader_t*)kernelData->data();
if(ancastHeader->magic != (uint32be)0xEFA282D9)
assert_dbg(); // invalid magic
memcpy(memory_getPointerFromPhysicalOffset(0x08000000), kernelData->data(), kernelData->size());
}
void loadPPCBootrom()
{
auto bootromData = FileStream::LoadIntoMemory("bootrom.bin");
if (!bootromData)
exit(-1);
memcpy(memory_getPointerFromPhysicalOffset(0x00000000), bootromData->data(), bootromData->size());
}
void mainEmulatorLLE()
{
CemuCommonInit();
// memory init
memory_initPhysicalLayout();
// start GUI thread
gui_create();
// load kernel ancast image
loadPPCBootrom();
loadEncryptedPPCAncastKernel();
PPCTimer_waitForInit();
// begin execution
PPCCoreLLE_startSingleCoreScheduler(0x00000100);
}
| 1,171
|
C++
|
.cpp
| 42
| 25.952381
| 99
| 0.774799
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,873
|
IniParser.cpp
|
cemu-project_Cemu/src/util/IniParser/IniParser.cpp
|
#include "util/IniParser/IniParser.h"
IniParser::IniParser(std::span<char> iniContents, std::string_view name) : m_name(name)
{
// we dont support utf8 but still skip the byte order mark in case the user saved the document with the wrong encoding
if (iniContents.size() >= 3 && (uint8)iniContents[0] == 0xEF && (uint8)iniContents[1] == 0xBB && (uint8)iniContents[2] == 0xBF)
iniContents = iniContents.subspan(3);
m_iniFileData.assign(iniContents.begin(), iniContents.end());
m_isValid = parse();
}
bool IniParser::ReadNextLine(std::string_view& lineString)
{
if (m_parseOffset >= m_iniFileData.size())
return false;
// skip \r and \n
for (; m_parseOffset < m_iniFileData.size(); m_parseOffset++)
{
char c = m_iniFileData[m_parseOffset];
if (c == '\r' || c == '\n')
continue;
break;
}
if (m_parseOffset >= m_iniFileData.size())
return false;
size_t lineStart = m_parseOffset;
// parse until end of line/file
for (; m_parseOffset < m_iniFileData.size(); m_parseOffset++)
{
char c = m_iniFileData[m_parseOffset];
if (c == '\r' || c == '\n')
break;
}
size_t lineEnd = m_parseOffset;
lineString = { m_iniFileData.data() + lineStart, lineEnd - lineStart };
return true;
}
void IniParser::TrimWhitespaces(std::string_view& str)
{
while (!str.empty())
{
char c = str[0];
if (c != ' ' && c != '\t')
break;
str.remove_prefix(1);
}
while (!str.empty())
{
char c = str.back();
if (c != ' ' && c != '\t')
break;
str.remove_suffix(1);
}
}
bool IniParser::parse()
{
sint32 lineNumber = 0;
std::string_view lineView;
while (ReadNextLine(lineView))
{
lineNumber++;
// skip whitespaces
while (!lineView.empty())
{
char c = lineView[0];
if (c != ' ' && c != '\t')
break;
lineView.remove_prefix(1);
}
if (lineView.empty())
continue;
// cut off comments (starting with # or ;)
bool isInQuote = false;
for (size_t i = 0; i < lineView.size(); i++)
{
if (lineView[i] == '\"')
isInQuote = !isInQuote;
if ((lineView[i] == '#' || lineView[i] == ';') && !isInQuote)
{
lineView.remove_suffix(lineView.size() - i);
break;
}
}
if(lineView.empty())
continue;
// handle section headers
if (lineView[0] == '[')
{
isInQuote = false;
bool endsWithBracket = false;
for (size_t i = 1; i < lineView.size(); i++)
{
if (lineView[i] == '\"')
isInQuote = !isInQuote;
if (lineView[i] == ']')
{
lineView.remove_suffix(lineView.size() - i);
lineView.remove_prefix(1);
endsWithBracket = true;
break;
}
}
if (!endsWithBracket)
PrintWarning(lineNumber, "Section doesn't end with a ]", lineView);
StartSection(lineView, lineNumber);
continue;
}
// otherwise try to parse it as an option in the form name = value
// find and split at = character
std::string_view option_name;
std::string_view option_value;
bool invalidName = true;
for (size_t i = 0; i < lineView.size(); i++)
{
if (lineView[i] == '=')
{
option_name = lineView.substr(0, i);
option_value = lineView.substr(i+1);
invalidName = false;
break;
}
}
if (invalidName)
{
TrimWhitespaces(lineView);
if (!lineView.empty())
PrintWarning(lineNumber, "Not a valid section header or name-value pair", lineView);
continue;
}
// validate
TrimWhitespaces(option_name);
TrimWhitespaces(option_value);
if (option_name.empty())
{
PrintWarning(lineNumber, "Empty option name is not allowed", lineView);
continue;
}
bool invalidCharacter = false;
for (auto& _c : option_name)
{
uint8 c = (uint8)_c;
if (c == ']' || c == '[')
{
PrintWarning(lineNumber, "Option name may not contain [ or ]", lineView);
invalidCharacter = true;
break;
}
else if (c < 32 || c > 128 || c == ' ')
{
PrintWarning(lineNumber, "Option name may only contain ANSI characters and no spaces", lineView);
invalidCharacter = true;
break;
}
}
if(invalidCharacter)
continue;
// remove quotes from value
if (!option_value.empty() && option_value.front() == '\"')
{
option_value.remove_prefix(1);
if (option_value.size() >= 2 && option_value.back() == '\"')
{
option_value.remove_suffix(1);
}
else
{
PrintWarning(lineNumber, "Option value starts with a quote character \" but does not end with one", lineView);
continue;
}
}
if (m_sectionList.empty())
{
// no current section
PrintWarning(lineNumber, "Option defined without first defining a section", lineView);
continue;
}
// convert name to lower case
m_sectionList.back().m_optionPairs.emplace_back(option_name, option_value);
}
return true;
}
void IniParser::StartSection(std::string_view sectionName, size_t lineNumber)
{
m_sectionList.emplace_back(sectionName, lineNumber);
}
bool IniParser::NextSection()
{
if (m_currentSectionIndex == std::numeric_limits<size_t>::max())
{
m_currentSectionIndex = 0;
return m_currentSectionIndex < m_sectionList.size();
}
if (m_currentSectionIndex >= m_sectionList.size())
return false;
m_currentSectionIndex++;
return m_currentSectionIndex < m_sectionList.size();
}
std::string_view IniParser::GetCurrentSectionName()
{
if (m_currentSectionIndex == std::numeric_limits<size_t>::max() || m_currentSectionIndex >= m_sectionList.size())
return "";
return m_sectionList[m_currentSectionIndex].m_sectionName;
}
size_t IniParser::GetCurrentSectionLineNumber()
{
if (m_currentSectionIndex == std::numeric_limits<size_t>::max() || m_currentSectionIndex >= m_sectionList.size())
return 0;
return m_sectionList[m_currentSectionIndex].m_lineNumber;
}
std::optional<std::string_view> IniParser::FindOption(std::string_view optionName)
{
if (m_currentSectionIndex == std::numeric_limits<size_t>::max() || m_currentSectionIndex >= m_sectionList.size())
return std::nullopt;
auto& optionPairsList = m_sectionList[m_currentSectionIndex].m_optionPairs;
for (auto& itr : optionPairsList)
{
auto& itrOptionName = itr.first;
// case insensitive ANSI string comparison
if(itrOptionName.size() != optionName.size())
continue;
bool isMatch = true;
for (size_t i = 0; i < itrOptionName.size(); i++)
{
char c0 = itrOptionName[i];
char c1 = optionName[i];
if (c0 >= 'A' && c0 <= 'Z')
c0 -= ('A' - 'a');
if (c1 >= 'A' && c1 <= 'Z')
c1 -= ('A' - 'a');
if (c0 != c1)
{
isMatch = false;
break;
}
}
if (!isMatch)
continue;
return itr.second;
}
return std::nullopt;
}
std::span<std::pair<std::string_view, std::string_view>> IniParser::GetAllOptions()
{
if (m_currentSectionIndex == std::numeric_limits<size_t>::max() || m_currentSectionIndex >= m_sectionList.size())
return {};
return m_sectionList[m_currentSectionIndex].m_optionPairs;
}
void IniParser::PrintWarning(int lineNumber, std::string_view msg, std::string_view lineView)
{
// INI logging is silenced
// cemuLog_log(LogType::Force, "File: {} Line {}: {}", m_name, lineNumber, msg);
}
| 6,984
|
C++
|
.cpp
| 250
| 24.864
| 128
| 0.665129
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,875
|
FiberWin.cpp
|
cemu-project_Cemu/src/util/Fiber/FiberWin.cpp
|
#include "Fiber.h"
#include <Windows.h>
thread_local Fiber* sCurrentFiber{};
Fiber::Fiber(void(*FiberEntryPoint)(void* userParam), void* userParam, void* privateData) : m_privateData(privateData)
{
HANDLE fiberHandle = CreateFiber(2 * 1024 * 1024, (LPFIBER_START_ROUTINE)FiberEntryPoint, userParam);
this->m_implData = (void*)fiberHandle;
}
Fiber::Fiber(void* privateData) : m_privateData(privateData)
{
this->m_implData = (void*)ConvertThreadToFiber(nullptr);
this->m_stackPtr = nullptr;
}
Fiber::~Fiber()
{
DeleteFiber((HANDLE)m_implData);
}
Fiber* Fiber::PrepareCurrentThread(void* privateData)
{
cemu_assert_debug(sCurrentFiber == nullptr); // thread already prepared
Fiber* currentFiber = new Fiber(privateData);
sCurrentFiber = currentFiber;
return currentFiber;
}
void Fiber::Switch(Fiber& targetFiber)
{
sCurrentFiber = &targetFiber;
SwitchToFiber((HANDLE)targetFiber.m_implData);
}
void* Fiber::GetFiberPrivateData()
{
return sCurrentFiber->m_privateData;
}
| 986
|
C++
|
.cpp
| 33
| 28.30303
| 118
| 0.781184
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,876
|
FiberUnix.cpp
|
cemu-project_Cemu/src/util/Fiber/FiberUnix.cpp
|
#include "Fiber.h"
#include <ucontext.h>
#include <atomic>
thread_local Fiber* sCurrentFiber{};
Fiber::Fiber(void(*FiberEntryPoint)(void* userParam), void* userParam, void* privateData) : m_privateData(privateData)
{
ucontext_t* ctx = (ucontext_t*)malloc(sizeof(ucontext_t));
const size_t stackSize = 2 * 1024 * 1024;
m_stackPtr = malloc(stackSize);
getcontext(ctx);
ctx->uc_stack.ss_sp = m_stackPtr;
ctx->uc_stack.ss_size = stackSize;
ctx->uc_link = &ctx[0];
makecontext(ctx, (void(*)())FiberEntryPoint, 1, userParam);
this->m_implData = (void*)ctx;
}
Fiber::Fiber(void* privateData) : m_privateData(privateData)
{
ucontext_t* ctx = (ucontext_t*)malloc(sizeof(ucontext_t));
getcontext(ctx);
this->m_implData = (void*)ctx;
m_stackPtr = nullptr;
}
Fiber::~Fiber()
{
if(m_stackPtr)
free(m_stackPtr);
free(m_implData);
}
Fiber* Fiber::PrepareCurrentThread(void* privateData)
{
cemu_assert_debug(sCurrentFiber == nullptr);
sCurrentFiber = new Fiber(privateData);
return sCurrentFiber;
}
void Fiber::Switch(Fiber& targetFiber)
{
Fiber* leavingFiber = sCurrentFiber;
sCurrentFiber = &targetFiber;
std::atomic_thread_fence(std::memory_order_seq_cst);
swapcontext((ucontext_t*)(leavingFiber->m_implData), (ucontext_t*)(targetFiber.m_implData));
std::atomic_thread_fence(std::memory_order_seq_cst);
}
void* Fiber::GetFiberPrivateData()
{
return sCurrentFiber->m_privateData;
}
| 1,413
|
C++
|
.cpp
| 47
| 28.106383
| 118
| 0.741888
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,878
|
aes128.cpp
|
cemu-project_Cemu/src/util/crypto/aes128.cpp
|
/*
Original implementation based on Tiny-AES-c (2015)
https://github.com/kokke/tiny-AES-c
Modified by Exzap
*/
/*****************************************************************************/
/* Includes: */
/*****************************************************************************/
#include "aes128.h"
#include "Common/cpu_features.h"
/*****************************************************************************/
/* Defines: */
/*****************************************************************************/
// The number of columns comprising a state in AES. This is a constant in AES. Value=4
#define Nb 4
// The number of 32 bit words in a key.
#define Nk 4
// Key length in bytes [128 bit]
#define KEYLEN 16
// The number of rounds in AES Cipher.
#define Nr 10
typedef uint8 state_t[4][4];
typedef struct
{
state_t* state;
uint8 RoundKey[176];
}aes128Ctx_t;
#define stateVal(__x, __y) ((*aesCtx->state)[__x][__y])
#define stateValU32(__x) (*(uint32*)((*aesCtx->state)[__x]))
// The lookup-tables are marked const so they can be placed in read-only storage instead of RAM
// The numbers below can be computed dynamically trading ROM for RAM -
// This can be useful in (embedded) bootloader applications, where ROM is often limited.
static const uint8 sbox[256] = {
//0 1 2 3 4 5 6 7 8 9 A B C D E F
0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 };
static const uint8 rsbox[256] =
{ 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb,
0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb,
0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,
0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25,
0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92,
0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,
0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06,
0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b,
0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,
0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e,
0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b,
0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,
0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f,
0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef,
0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,
0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d };
// The round constant word array, Rcon[i], contains the values given by
// x to th e power (i-1) being powers of x (x is denoted as {02}) in the field GF(2^8)
// Note that i starts at 1, not 0).
static const uint8 Rcon[255] = {
0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a,
0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39,
0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a,
0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8,
0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef,
0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc,
0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b,
0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3,
0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94,
0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20,
0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35,
0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f,
0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04,
0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63,
0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd,
0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb };
/*****************************************************************************/
/* Private functions: */
/*****************************************************************************/
uint8 getSBoxValue(uint8 num)
{
return sbox[num];
}
uint8 getSBoxInvert(uint8 num)
{
return rsbox[num];
}
// This function produces Nb(Nr+1) round keys. The round keys are used in each round to decrypt the states.
void KeyExpansion(aes128Ctx_t* aesCtx, const uint8* key)
{
uint32 i, j, k;
uint8 tempa[4]; // Used for the column/row operations
// The first round key is the key itself.
for (i = 0; i < Nk; ++i)
{
aesCtx->RoundKey[(i * 4) + 0] = key[(i * 4) + 0];
aesCtx->RoundKey[(i * 4) + 1] = key[(i * 4) + 1];
aesCtx->RoundKey[(i * 4) + 2] = key[(i * 4) + 2];
aesCtx->RoundKey[(i * 4) + 3] = key[(i * 4) + 3];
}
// All other round keys are found from the previous round keys.
for (; (i < (Nb * (Nr + 1))); ++i)
{
for (j = 0; j < 4; ++j)
{
tempa[j] = aesCtx->RoundKey[(i - 1) * 4 + j];
}
if (i % Nk == 0)
{
// This function rotates the 4 bytes in a word to the left once.
// [a0,a1,a2,a3] becomes [a1,a2,a3,a0]
// Function RotWord()
{
k = tempa[0];
tempa[0] = tempa[1];
tempa[1] = tempa[2];
tempa[2] = tempa[3];
tempa[3] = k;
}
// SubWord() is a function that takes a four-byte input word and
// applies the S-box to each of the four bytes to produce an output word.
// Function Subword()
{
tempa[0] = getSBoxValue(tempa[0]);
tempa[1] = getSBoxValue(tempa[1]);
tempa[2] = getSBoxValue(tempa[2]);
tempa[3] = getSBoxValue(tempa[3]);
}
tempa[0] = tempa[0] ^ Rcon[i / Nk];
}
else if (Nk > 6 && i % Nk == 4)
{
// Function Subword()
{
tempa[0] = getSBoxValue(tempa[0]);
tempa[1] = getSBoxValue(tempa[1]);
tempa[2] = getSBoxValue(tempa[2]);
tempa[3] = getSBoxValue(tempa[3]);
}
}
aesCtx->RoundKey[i * 4 + 0] = aesCtx->RoundKey[(i - Nk) * 4 + 0] ^ tempa[0];
aesCtx->RoundKey[i * 4 + 1] = aesCtx->RoundKey[(i - Nk) * 4 + 1] ^ tempa[1];
aesCtx->RoundKey[i * 4 + 2] = aesCtx->RoundKey[(i - Nk) * 4 + 2] ^ tempa[2];
aesCtx->RoundKey[i * 4 + 3] = aesCtx->RoundKey[(i - Nk) * 4 + 3] ^ tempa[3];
}
}
// This function adds the round key to state.
// The round key is added to the state by an XOR function.
void AddRoundKey(aes128Ctx_t* aesCtx, uint8 round)
{
// note: replacing this with two 64bit xor operations decreased performance in benchmarks, probably because the state bytes need to be stored back in memory
stateVal(0, 0) ^= aesCtx->RoundKey[round * Nb * 4 + 0 * Nb + 0];
stateVal(0, 1) ^= aesCtx->RoundKey[round * Nb * 4 + 0 * Nb + 1];
stateVal(0, 2) ^= aesCtx->RoundKey[round * Nb * 4 + 0 * Nb + 2];
stateVal(0, 3) ^= aesCtx->RoundKey[round * Nb * 4 + 0 * Nb + 3];
stateVal(1, 0) ^= aesCtx->RoundKey[round * Nb * 4 + 1 * Nb + 0];
stateVal(1, 1) ^= aesCtx->RoundKey[round * Nb * 4 + 1 * Nb + 1];
stateVal(1, 2) ^= aesCtx->RoundKey[round * Nb * 4 + 1 * Nb + 2];
stateVal(1, 3) ^= aesCtx->RoundKey[round * Nb * 4 + 1 * Nb + 3];
stateVal(2, 0) ^= aesCtx->RoundKey[round * Nb * 4 + 2 * Nb + 0];
stateVal(2, 1) ^= aesCtx->RoundKey[round * Nb * 4 + 2 * Nb + 1];
stateVal(2, 2) ^= aesCtx->RoundKey[round * Nb * 4 + 2 * Nb + 2];
stateVal(2, 3) ^= aesCtx->RoundKey[round * Nb * 4 + 2 * Nb + 3];
stateVal(3, 0) ^= aesCtx->RoundKey[round * Nb * 4 + 3 * Nb + 0];
stateVal(3, 1) ^= aesCtx->RoundKey[round * Nb * 4 + 3 * Nb + 1];
stateVal(3, 2) ^= aesCtx->RoundKey[round * Nb * 4 + 3 * Nb + 2];
stateVal(3, 3) ^= aesCtx->RoundKey[round * Nb * 4 + 3 * Nb + 3];
}
// The SubBytes Function Substitutes the values in the
// state matrix with values in an S-box.
void SubBytes(aes128Ctx_t* aesCtx)
{
uint8 i, j;
for (i = 0; i < 4; ++i)
{
for (j = 0; j < 4; ++j)
{
stateVal(j, i) = getSBoxValue(stateVal(j, i));
}
}
}
// The ShiftRows() function shifts the rows in the state to the left.
// Each row is shifted with different offset.
// Offset = Row number. So the first row is not shifted.
void ShiftRows(aes128Ctx_t* aesCtx)
{
uint8 temp;
// Rotate first row 1 columns to left
temp = stateVal(0, 1);
stateVal(0, 1) = stateVal(1, 1);
stateVal(1, 1) = stateVal(2, 1);
stateVal(2, 1) = stateVal(3, 1);
stateVal(3, 1) = temp;
// Rotate second row 2 columns to left
temp = stateVal(0, 2);
stateVal(0, 2) = stateVal(2, 2);
stateVal(2, 2) = temp;
temp = stateVal(1, 2);
stateVal(1, 2) = stateVal(3, 2);
stateVal(3, 2) = temp;
// Rotate third row 3 columns to left
temp = stateVal(0, 3);
stateVal(0, 3) = stateVal(3, 3);
stateVal(3, 3) = stateVal(2, 3);
stateVal(2, 3) = stateVal(1, 3);
stateVal(1, 3) = temp;
}
uint8 aes_xtime(uint8 x)
{
return ((x << 1) ^ (((x >> 7) & 1) * 0x1b));
}
// MixColumns function mixes the columns of the state matrix
void MixColumns(aes128Ctx_t* aesCtx)
{
uint8 i;
uint8 Tmp, Tm, t;
for (i = 0; i < 4; ++i)
{
t = stateVal(i, 0);
Tmp = stateVal(i, 0) ^ stateVal(i, 1) ^ stateVal(i, 2) ^ stateVal(i, 3);
Tm = stateVal(i, 0) ^ stateVal(i, 1); Tm = aes_xtime(Tm); stateVal(i, 0) ^= Tm ^ Tmp;
Tm = stateVal(i, 1) ^ stateVal(i, 2); Tm = aes_xtime(Tm); stateVal(i, 1) ^= Tm ^ Tmp;
Tm = stateVal(i, 2) ^ stateVal(i, 3); Tm = aes_xtime(Tm); stateVal(i, 2) ^= Tm ^ Tmp;
Tm = stateVal(i, 3) ^ t; Tm = aes_xtime(Tm); stateVal(i, 3) ^= Tm ^ Tmp;
}
}
// Multiply is used to multiply numbers in the field GF(2^8)
#define Multiply(x, y) \
( ((y & 1) * x) ^ \
((y>>1 & 1) * aes_xtime(x)) ^ \
((y>>2 & 1) * aes_xtime(aes_xtime(x))) ^ \
((y>>3 & 1) * aes_xtime(aes_xtime(aes_xtime(x)))) ^ \
((y>>4 & 1) * aes_xtime(aes_xtime(aes_xtime(aes_xtime(x))))))
uint32 lookupTable_multiply[256];
//// MixColumns function mixes the columns of the state matrix.
//// The method used to multiply may be difficult to understand for the inexperienced.
//// Please use the references to gain more information.
//void InvMixColumns(aes128Ctx_t* aesCtx)
//{
// int i;
// uint8 a, b, c, d;
// for (i = 0; i < 4; ++i)
// {
// a = stateVal(i, 0);
// b = stateVal(i, 1);
// c = stateVal(i, 2);
// d = stateVal(i, 3);
//
// uint32 _a = lookupTable_multiply[a];
// uint32 _b = lookupTable_multiply[b];
// uint32 _c = lookupTable_multiply[c];
// uint32 _d = lookupTable_multiply[d];
//
//
// //stateVal(i, 0) = entryA->vE ^ entryB->vB ^ entryC->vD ^ entryD->v9;
// //stateVal(i, 1) = entryA->v9 ^ entryB->vE ^ entryC->vB ^ entryD->vD;
// //stateVal(i, 2) = entryA->vD ^ entryB->v9 ^ entryC->vE ^ entryD->vB;
// //stateVal(i, 3) = entryA->vB ^ entryB->vD ^ entryC->v9 ^ entryD->vE;
//
// //stateVal(i, 0) = Multiply(a, 0x0e) ^ Multiply(b, 0x0b) ^ Multiply(c, 0x0d) ^ Multiply(d, 0x09);
// //stateVal(i, 1) = Multiply(a, 0x09) ^ Multiply(b, 0x0e) ^ Multiply(c, 0x0b) ^ Multiply(d, 0x0d);
// //stateVal(i, 2) = Multiply(a, 0x0d) ^ Multiply(b, 0x09) ^ Multiply(c, 0x0e) ^ Multiply(d, 0x0b);
// //stateVal(i, 3) = Multiply(a, 0x0b) ^ Multiply(b, 0x0d) ^ Multiply(c, 0x09) ^ Multiply(d, 0x0e);
//
// //stateVal(i, 0) = Multiply(b, 0x0b) ^ Multiply(c, 0x0d) ^ Multiply(d, 0x09);
// //stateVal(i, 1) = Multiply(b, 0x0e) ^ Multiply(c, 0x0b) ^ Multiply(d, 0x0d);
// //stateVal(i, 2) = Multiply(b, 0x09) ^ Multiply(c, 0x0e) ^ Multiply(d, 0x0b);
// //stateVal(i, 3) = Multiply(b, 0x0d) ^ Multiply(c, 0x09) ^ Multiply(d, 0x0e);
//
// stateValU32(i) = _a ^ _rotl(_b, 8) ^ _rotl(_c, 16) ^ _rotl(_d, 24);
//
// }
//}
// MixColumns function mixes the columns of the state matrix.
// The method used to multiply may be difficult to understand for the inexperienced.
// Please use the references to gain more information.
void InvMixColumns(aes128Ctx_t* aesCtx)
{
uint8 a, b, c, d;
// i0
a = stateVal(0, 0);
b = stateVal(0, 1);
c = stateVal(0, 2);
d = stateVal(0, 3);
stateValU32(0) = lookupTable_multiply[a] ^ std::rotl<uint32>(lookupTable_multiply[b], 8) ^ std::rotl<uint32>(lookupTable_multiply[c], 16) ^ std::rotl<uint32>(lookupTable_multiply[d], 24);
// i1
a = stateVal(1, 0);
b = stateVal(1, 1);
c = stateVal(1, 2);
d = stateVal(1, 3);
stateValU32(1) = lookupTable_multiply[a] ^ std::rotl<uint32>(lookupTable_multiply[b], 8) ^ std::rotl<uint32>(lookupTable_multiply[c], 16) ^ std::rotl<uint32>(lookupTable_multiply[d], 24);
// i2
a = stateVal(2, 0);
b = stateVal(2, 1);
c = stateVal(2, 2);
d = stateVal(2, 3);
stateValU32(2) = lookupTable_multiply[a] ^ std::rotl<uint32>(lookupTable_multiply[b], 8) ^ std::rotl<uint32>(lookupTable_multiply[c], 16) ^ std::rotl<uint32>(lookupTable_multiply[d], 24);
// i3
a = stateVal(3, 0);
b = stateVal(3, 1);
c = stateVal(3, 2);
d = stateVal(3, 3);
stateValU32(3) = lookupTable_multiply[a] ^ std::rotl<uint32>(lookupTable_multiply[b], 8) ^ std::rotl<uint32>(lookupTable_multiply[c], 16) ^ std::rotl<uint32>(lookupTable_multiply[d], 24);
}
// The SubBytes Function Substitutes the values in the
// state matrix with values in an S-box.
void InvSubBytes(aes128Ctx_t* aesCtx)
{
stateVal(0, 0) = rsbox[stateVal(0, 0)];
stateVal(1, 0) = rsbox[stateVal(1, 0)];
stateVal(2, 0) = rsbox[stateVal(2, 0)];
stateVal(3, 0) = rsbox[stateVal(3, 0)];
stateVal(0, 1) = rsbox[stateVal(0, 1)];
stateVal(1, 1) = rsbox[stateVal(1, 1)];
stateVal(2, 1) = rsbox[stateVal(2, 1)];
stateVal(3, 1) = rsbox[stateVal(3, 1)];
stateVal(0, 2) = rsbox[stateVal(0, 2)];
stateVal(1, 2) = rsbox[stateVal(1, 2)];
stateVal(2, 2) = rsbox[stateVal(2, 2)];
stateVal(3, 2) = rsbox[stateVal(3, 2)];
stateVal(0, 3) = rsbox[stateVal(0, 3)];
stateVal(1, 3) = rsbox[stateVal(1, 3)];
stateVal(2, 3) = rsbox[stateVal(2, 3)];
stateVal(3, 3) = rsbox[stateVal(3, 3)];
}
void InvShiftRows(aes128Ctx_t* aesCtx)
{
uint8 temp;
// Rotate first row 1 columns to right
temp = stateVal(3, 1);
stateVal(3, 1) = stateVal(2, 1);
stateVal(2, 1) = stateVal(1, 1);
stateVal(1, 1) = stateVal(0, 1);
stateVal(0, 1) = temp;
// Rotate second row 2 columns to right
temp = stateVal(0, 2);
stateVal(0, 2) = stateVal(2, 2);
stateVal(2, 2) = temp;
temp = stateVal(1, 2);
stateVal(1, 2) = stateVal(3, 2);
stateVal(3, 2) = temp;
// Rotate third row 3 columns to right
temp = stateVal(0, 3);
stateVal(0, 3) = stateVal(1, 3);
stateVal(1, 3) = stateVal(2, 3);
stateVal(2, 3) = stateVal(3, 3);
stateVal(3, 3) = temp;
}
// Cipher is the main function that encrypts the PlainText.
void Cipher(aes128Ctx_t* aesCtx)
{
uint8 round = 0;
// Add the First round key to the state before starting the rounds.
AddRoundKey(aesCtx, 0);
// There will be Nr rounds.
// The first Nr-1 rounds are identical.
// These Nr-1 rounds are executed in the loop below.
for (round = 1; round < Nr; ++round)
{
SubBytes(aesCtx);
ShiftRows(aesCtx);
MixColumns(aesCtx);
AddRoundKey(aesCtx, round);
}
// The last round is given below.
// The MixColumns function is not here in the last round.
SubBytes(aesCtx);
ShiftRows(aesCtx);
AddRoundKey(aesCtx, Nr);
}
void InvCipher(aes128Ctx_t* aesCtx)
{
uint8 round = 0;
// Add the First round key to the state before starting the rounds.
AddRoundKey(aesCtx, Nr);
// There will be Nr rounds.
// The first Nr-1 rounds are identical.
// These Nr-1 rounds are executed in the loop below.
for (round = Nr - 1; round > 0; round--)
{
InvShiftRows(aesCtx);
InvSubBytes(aesCtx);
AddRoundKey(aesCtx, round);
InvMixColumns(aesCtx);
}
// The last round is given below.
// The MixColumns function is not here in the last round.
InvShiftRows(aesCtx);
InvSubBytes(aesCtx);
AddRoundKey(aesCtx, 0);
}
static void BlockCopy(uint8* output, uint8* input)
{
uint8 i;
for (i = 0; i < KEYLEN; ++i)
{
output[i] = input[i];
}
}
/*****************************************************************************/
/* Public functions: */
/*****************************************************************************/
void __soft__AES128_ECB_encrypt(uint8* input, const uint8* key, uint8* output)
{
aes128Ctx_t aesCtx;
// Copy input to output, and work in-memory on output
BlockCopy(output, input);
aesCtx.state = (state_t*)output;
KeyExpansion(&aesCtx, key);
// The next function call encrypts the PlainText with the Key using AES algorithm.
Cipher(&aesCtx);
}
void AES128_ECB_decrypt(uint8* input, const uint8* key, uint8 *output)
{
aes128Ctx_t aesCtx;
// Copy input to output, and work in-memory on output
BlockCopy(output, input);
aesCtx.state = (state_t*)output;
// The KeyExpansion routine must be called before encryption.
KeyExpansion(&aesCtx, key);
InvCipher(&aesCtx);
}
void XorWithIv(uint8* buf, const uint8* iv)
{
uint8 i;
for (i = 0; i < KEYLEN; ++i)
{
buf[i] ^= iv[i];
}
}
void AES128_CBC_encrypt(uint8* output, uint8* input, uint32 length, const uint8* key, const uint8* iv)
{
aes128Ctx_t aesCtx;
intptr_t i;
uint8 remainders = length % KEYLEN; /* Remaining bytes in the last non-full block */
BlockCopy(output, input);
aesCtx.state = (state_t*)output;
KeyExpansion(&aesCtx, key);
const uint8* currentIv = iv;
for (i = 0; i < length; i += KEYLEN)
{
XorWithIv(input, currentIv);
BlockCopy(output, input);
aesCtx.state = (state_t*)output;
Cipher(&aesCtx);
currentIv = output;
input += KEYLEN;
output += KEYLEN;
}
cemu_assert_debug(remainders == 0);
}
void __soft__AES128_CBC_decrypt(uint8* output, uint8* input, uint32 length, const uint8* key, const uint8* iv)
{
aes128Ctx_t aesCtx;
intptr_t i;
uint8 remainders = length % KEYLEN;
KeyExpansion(&aesCtx, key);
uint8 currentIv[KEYLEN];
uint8 nextIv[KEYLEN];
if (iv)
BlockCopy(currentIv, (uint8*)iv);
else
memset(currentIv, 0, sizeof(currentIv));
for (i = 0; i < length; i += KEYLEN)
{
aesCtx.state = (state_t*)output;
BlockCopy(output, input);
BlockCopy(nextIv, input);
InvCipher(&aesCtx);
XorWithIv(output, currentIv);
BlockCopy(currentIv, nextIv);
output += KEYLEN;
input += KEYLEN;
}
cemu_assert_debug(remainders == 0);
}
void AES128_CBC_decrypt_buffer_depr(uint8* output, uint8* input, uint32 length, const uint8* key, const uint8* iv)
{
aes128Ctx_t aesCtx;
intptr_t i;
uint8 remainders = length % KEYLEN; /* Remaining bytes in the last non-full block */
BlockCopy(output, input);
KeyExpansion(&aesCtx, key);
const uint8* currentIv = iv;
for (i = 0; i < length; i += KEYLEN)
{
BlockCopy(output, input);
aesCtx.state = (state_t*)output;
InvCipher(&aesCtx);
XorWithIv(output, currentIv);
currentIv = input;
input += KEYLEN;
output += KEYLEN;
}
cemu_assert_debug(remainders == 0);
}
void AES128_CBC_decrypt_updateIV(uint8* output, uint8* input, uint32 length, const uint8* key, uint8* iv)
{
length &= ~0xF;
uint8 newIv[16];
if (length == 0)
return;
cemu_assert_debug((length&0xF) == 0);
memcpy(newIv, input + (length - 16), KEYLEN);
AES128_CBC_decrypt(output, input, length, key, iv);
memcpy(iv, newIv, KEYLEN);
}
#if defined(ARCH_X86_64)
ATTRIBUTE_AESNI inline __m128i AESNI128_ASSIST(
__m128i temp1,
__m128i temp2)
{
__m128i temp3;
temp2 = _mm_shuffle_epi32(temp2, 0xff);
temp3 = _mm_slli_si128(temp1, 0x4);
temp1 = _mm_xor_si128(temp1, temp3);
temp3 =
_mm_slli_si128(temp3, 0x4);
temp1 =
_mm_xor_si128(temp1, temp3);
temp3 =
_mm_slli_si128(temp3, 0x4);
temp1 =
_mm_xor_si128(temp1, temp3);
temp1 = _mm_xor_si128(temp1, temp2);
return temp1;
}
ATTRIBUTE_AESNI void AESNI128_KeyExpansionEncrypt(const unsigned char *userkey, unsigned char *key)
{
__m128i temp1, temp2;
__m128i *Key_Schedule = (__m128i*)key;
temp1 = _mm_loadu_si128((__m128i*)userkey);
Key_Schedule[0] = temp1;
temp2 = _mm_aeskeygenassist_si128(temp1, 0x1);
temp1 = AESNI128_ASSIST(temp1, temp2);
Key_Schedule[1] = temp1;
temp2 = _mm_aeskeygenassist_si128(temp1, 0x2);
temp1 = AESNI128_ASSIST(temp1, temp2);
Key_Schedule[2] = temp1;
temp2 = _mm_aeskeygenassist_si128(temp1, 0x4);
temp1 = AESNI128_ASSIST(temp1, temp2);
Key_Schedule[3] = temp1;
temp2 = _mm_aeskeygenassist_si128(temp1, 0x8);
temp1 = AESNI128_ASSIST(temp1, temp2);
Key_Schedule[4] = temp1;
temp2 = _mm_aeskeygenassist_si128(temp1, 0x10);
temp1 = AESNI128_ASSIST(temp1, temp2);
Key_Schedule[5] = temp1;
temp2 = _mm_aeskeygenassist_si128(temp1, 0x20);
temp1 = AESNI128_ASSIST(temp1, temp2);
Key_Schedule[6] = temp1;
temp2 = _mm_aeskeygenassist_si128(temp1, 0x40);
temp1 = AESNI128_ASSIST(temp1, temp2);
Key_Schedule[7] = temp1;
temp2 = _mm_aeskeygenassist_si128(temp1, 0x80);
temp1 = AESNI128_ASSIST(temp1, temp2);
Key_Schedule[8] = temp1;
temp2 = _mm_aeskeygenassist_si128(temp1, 0x1b);
temp1 = AESNI128_ASSIST(temp1, temp2);
Key_Schedule[9] = temp1;
temp2 = _mm_aeskeygenassist_si128(temp1, 0x36);
temp1 = AESNI128_ASSIST(temp1, temp2);
Key_Schedule[10] = temp1;
}
ATTRIBUTE_AESNI void AESNI128_KeyExpansionDecrypt(const unsigned char *userkey, unsigned char *key)
{
__m128i temp1, temp2;
__m128i *Key_Schedule = (__m128i*)key;
temp1 = _mm_loadu_si128((__m128i*)userkey);
Key_Schedule[0] = temp1;
temp2 = _mm_aeskeygenassist_si128(temp1, 0x1);
temp1 = AESNI128_ASSIST(temp1, temp2);
Key_Schedule[1] = temp1;
temp2 = _mm_aeskeygenassist_si128(temp1, 0x2);
temp1 = AESNI128_ASSIST(temp1, temp2);
Key_Schedule[2] = temp1;
temp2 = _mm_aeskeygenassist_si128(temp1, 0x4);
temp1 = AESNI128_ASSIST(temp1, temp2);
Key_Schedule[3] = temp1;
temp2 = _mm_aeskeygenassist_si128(temp1, 0x8);
temp1 = AESNI128_ASSIST(temp1, temp2);
Key_Schedule[4] = temp1;
temp2 = _mm_aeskeygenassist_si128(temp1, 0x10);
temp1 = AESNI128_ASSIST(temp1, temp2);
Key_Schedule[5] = temp1;
temp2 = _mm_aeskeygenassist_si128(temp1, 0x20);
temp1 = AESNI128_ASSIST(temp1, temp2);
Key_Schedule[6] = temp1;
temp2 = _mm_aeskeygenassist_si128(temp1, 0x40);
temp1 = AESNI128_ASSIST(temp1, temp2);
Key_Schedule[7] = temp1;
temp2 = _mm_aeskeygenassist_si128(temp1, 0x80);
temp1 = AESNI128_ASSIST(temp1, temp2);
Key_Schedule[8] = temp1;
temp2 = _mm_aeskeygenassist_si128(temp1, 0x1b);
temp1 = AESNI128_ASSIST(temp1, temp2);
Key_Schedule[9] = temp1;
temp2 = _mm_aeskeygenassist_si128(temp1, 0x36);
temp1 = AESNI128_ASSIST(temp1, temp2);
Key_Schedule[10] = temp1;
// inverse
for (sint32 i = 1; i < 10; i++)
{
Key_Schedule[i] = _mm_aesimc_si128(Key_Schedule[i]);
}
}
ATTRIBUTE_AESNI void AESNI128_CBC_encrypt(const unsigned char *in,
unsigned char *out,
unsigned char ivec[16],
unsigned long length,
unsigned char *key,
int number_of_rounds)
{
__m128i feedback, data;
int j;
if (length % 16)
length = length / 16 + 1;
else length /= 16;
feedback = _mm_loadu_si128((__m128i*)ivec);
for (unsigned long i = 0; i < length; i++)
{
data =
_mm_loadu_si128(&((__m128i*)in)[i]);
feedback = _mm_xor_si128(data, feedback);
feedback = _mm_xor_si128(feedback, ((__m128i*)key)[0]);
for (j = 1; j < number_of_rounds; j++)
feedback =
_mm_aesenc_si128(feedback, ((__m128i*)key)[j]);
feedback =
_mm_aesenclast_si128(feedback, ((__m128i*)key)[j]);
_mm_storeu_si128(&((__m128i*)out)[i], feedback);
}
}
ATTRIBUTE_AESNI void AESNI128_CBC_decryptWithExpandedKey(const unsigned char *in,
unsigned char *out,
const unsigned char ivec[16],
unsigned long length,
unsigned char *key)
{
__m128i data, feedback, lastin;
int j;
if (length % 16)
length = length / 16 + 1;
else length /= 16;
feedback = _mm_loadu_si128((__m128i*)ivec);
for (unsigned long i = 0; i < length; i++)
{
lastin = _mm_loadu_si128(&((__m128i*)in)[i]);
data = _mm_xor_si128(lastin, ((__m128i*)key)[10]);
for (j = 9; j > 0; j--)
{
data = _mm_aesdec_si128(data, ((__m128i*)key)[j]);
}
data = _mm_aesdeclast_si128(data, ((__m128i*)key)[0]);
data = _mm_xor_si128(data, feedback);
_mm_storeu_si128(&((__m128i*)out)[i], data);
feedback = lastin;
}
}
ATTRIBUTE_AESNI void __aesni__AES128_CBC_decrypt(uint8* output, uint8* input, uint32 length, const uint8* key, const uint8* iv)
{
alignas(16) uint8 expandedKey[11 * 16];
AESNI128_KeyExpansionDecrypt(key, expandedKey);
if (iv)
{
AESNI128_CBC_decryptWithExpandedKey(input, output, iv, length, expandedKey);
}
else
{
uint8 zeroIv[16] = { 0 };
AESNI128_CBC_decryptWithExpandedKey(input, output, zeroIv, length, expandedKey);
}
}
ATTRIBUTE_AESNI void __aesni__AES128_ECB_encrypt(uint8* input, const uint8* key, uint8* output)
{
alignas(16) uint8 expandedKey[11 * 16];
AESNI128_KeyExpansionEncrypt(key, expandedKey);
// encrypt single ECB block
__m128i feedback;
feedback = _mm_loadu_si128(&((__m128i*)input)[0]);
feedback = _mm_xor_si128(feedback, ((__m128i*)expandedKey)[0]);
feedback = _mm_aesenc_si128(feedback, ((__m128i*)expandedKey)[1]);
feedback = _mm_aesenc_si128(feedback, ((__m128i*)expandedKey)[2]);
feedback = _mm_aesenc_si128(feedback, ((__m128i*)expandedKey)[3]);
feedback = _mm_aesenc_si128(feedback, ((__m128i*)expandedKey)[4]);
feedback = _mm_aesenc_si128(feedback, ((__m128i*)expandedKey)[5]);
feedback = _mm_aesenc_si128(feedback, ((__m128i*)expandedKey)[6]);
feedback = _mm_aesenc_si128(feedback, ((__m128i*)expandedKey)[7]);
feedback = _mm_aesenc_si128(feedback, ((__m128i*)expandedKey)[8]);
feedback = _mm_aesenc_si128(feedback, ((__m128i*)expandedKey)[9]);
feedback = _mm_aesenclast_si128(feedback, ((__m128i*)expandedKey)[10]);
_mm_storeu_si128(&((__m128i*)output)[0], feedback);
}
#endif
void(*AES128_ECB_encrypt)(uint8* input, const uint8* key, uint8* output);
void (*AES128_CBC_decrypt)(uint8* output, uint8* input, uint32 length, const uint8* key, const uint8* iv) = nullptr;
// AES128-CTR encrypt/decrypt
void AES128CTR_transform(uint8* data, sint32 length, uint8* key, uint8* nonceIv)
{
for (sint32 i = 0; i < length; i += 16)
{
uint8* d = data + i;
uint8 tempArray[16];
AES128_ECB_encrypt(nonceIv, key, tempArray);
for (sint32 f = 0; f < 16; f++)
{
d[f] ^= tempArray[f];
}
// increase nonce
*(uint32*)(nonceIv + 0xC) = _swapEndianU32(_swapEndianU32(*(uint32*)(nonceIv + 0xC)) + 1);
if (*(uint32*)(nonceIv + 0xC) == 0)
{
*(uint32*)(nonceIv + 0x8) = _swapEndianU32(_swapEndianU32(*(uint32*)(nonceIv + 0x8)) + 1);
if (*(uint32*)(nonceIv + 0x8) == 0)
{
*(uint32*)(nonceIv + 0x4) = _swapEndianU32(_swapEndianU32(*(uint32*)(nonceIv + 0x4)) + 1);
if (*(uint32*)(nonceIv + 0x4) == 0)
{
*(uint32*)(nonceIv + 0) = _swapEndianU32(_swapEndianU32(*(uint32*)(nonceIv + 0)) + 1);
}
}
}
}
}
void AES128_init()
{
for (uint32 i = 0; i <= 0xFF; i++)
{
uint32 vE = Multiply((uint8)(i & 0xFF), 0x0E) & 0xFF;
uint32 v9 = Multiply((uint8)(i & 0xFF), 0x09) & 0xFF;
uint32 vD = Multiply((uint8)(i & 0xFF), 0x0D) & 0xFF;
uint32 vB = Multiply((uint8)(i & 0xFF), 0x0B) & 0xFF;
lookupTable_multiply[i] = (vE << 0) | (v9 << 8) | (vD << 16) | (vB << 24);
}
// check if AES-NI is available
#if defined(ARCH_X86_64)
if (g_CPUFeatures.x86.aesni)
{
// AES-NI implementation
AES128_CBC_decrypt = __aesni__AES128_CBC_decrypt;
AES128_ECB_encrypt = __aesni__AES128_ECB_encrypt;
}
else
{
// basic software implementation
AES128_CBC_decrypt = __soft__AES128_CBC_decrypt;
AES128_ECB_encrypt = __soft__AES128_ECB_encrypt;
}
#else
AES128_CBC_decrypt = __soft__AES128_CBC_decrypt;
AES128_ECB_encrypt = __soft__AES128_ECB_encrypt;
#endif
}
| 29,787
|
C++
|
.cpp
| 764
| 36.73822
| 188
| 0.639704
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,879
|
md5.cpp
|
cemu-project_Cemu/src/util/crypto/md5.cpp
|
/*
* This is an OpenSSL-compatible implementation of the RSA Data Security, Inc.
* MD5 Message-Digest Algorithm (RFC 1321).
*
* Homepage:
* http://openwall.info/wiki/people/solar/software/public-domain-source-code/md5
*
* Author:
* Alexander Peslyak, better known as Solar Designer <solar at openwall.com>
*
* This software was written by Alexander Peslyak in 2001. No copyright is
* claimed, and the software is hereby placed in the public domain.
* In case this attempt to disclaim copyright and place the software in the
* public domain is deemed null and void, then the software is
* Copyright (c) 2001 Alexander Peslyak and it is hereby released to the
* general public under the following terms:
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted.
*
* There's ABSOLUTELY NO WARRANTY, express or implied.
*
* (This is a heavily cut-down "BSD license".)
*
* This differs from Colin Plumb's older public domain implementation in that
* no exactly 32-bit integer data type is required (any 32-bit or wider
* unsigned integer data type will do), there's no compile-time endianness
* configuration, and the function prototypes match OpenSSL's. No code from
* Colin Plumb's implementation has been reused; this comment merely compares
* the properties of the two independent implementations.
*
* The primary goals of this implementation are portability and ease of use.
* It is meant to be fast, but not as fast as possible. Some known
* optimizations are not included to reduce source code size and avoid
* compile-time configuration.
*/
#ifndef HAVE_OPENSSL
#include <string.h>
#include "md5.h"
/*
* The basic MD5 functions.
*
* F and G are optimized compared to their RFC 1321 definitions for
* architectures that lack an AND-NOT instruction, just like in Colin Plumb's
* implementation.
*/
#define F(x, y, z) ((z) ^ ((x) & ((y) ^ (z))))
#define G(x, y, z) ((y) ^ ((z) & ((x) ^ (y))))
#define H(x, y, z) (((x) ^ (y)) ^ (z))
#define H2(x, y, z) ((x) ^ ((y) ^ (z)))
#define I(x, y, z) ((y) ^ ((x) | ~(z)))
/*
* The MD5 transformation for all four rounds.
*/
#define STEP(f, a, b, c, d, x, t, s) \
(a) += f((b), (c), (d)) + (x) + (t); \
(a) = (((a) << (s)) | (((a) & 0xffffffff) >> (32 - (s)))); \
(a) += (b);
/*
* SET reads 4 input bytes in little-endian byte order and stores them in a
* properly aligned word in host byte order.
*
* The check for little-endian architectures that tolerate unaligned memory
* accesses is just an optimization. Nothing will break if it fails to detect
* a suitable architecture.
*
* Unfortunately, this optimization may be a C strict aliasing rules violation
* if the caller's data buffer has effective type that cannot be aliased by
* MD5_u32plus. In practice, this problem may occur if these MD5 routines are
* inlined into a calling function, or with future and dangerously advanced
* link-time optimizations. For the time being, keeping these MD5 routines in
* their own translation unit avoids the problem.
*/
#if defined(__i386__) || defined(__x86_64__) || defined(__vax__)
#define SET(n) \
(*(MD5_u32plus *)&ptr[(n) * 4])
#define GET(n) \
SET(n)
#else
#define SET(n) \
(ctx->block[(n)] = \
(MD5_u32plus)ptr[(n) * 4] | \
((MD5_u32plus)ptr[(n) * 4 + 1] << 8) | \
((MD5_u32plus)ptr[(n) * 4 + 2] << 16) | \
((MD5_u32plus)ptr[(n) * 4 + 3] << 24))
#define GET(n) \
(ctx->block[(n)])
#endif
/*
* This processes one or more 64-byte data blocks, but does NOT update the bit
* counters. There are no alignment requirements.
*/
static const void *body(MD5_CTX *ctx, const void *data, unsigned long size)
{
const unsigned char *ptr;
MD5_u32plus a, b, c, d;
MD5_u32plus saved_a, saved_b, saved_c, saved_d;
ptr = (const unsigned char *)data;
a = ctx->a;
b = ctx->b;
c = ctx->c;
d = ctx->d;
do {
saved_a = a;
saved_b = b;
saved_c = c;
saved_d = d;
/* Round 1 */
STEP(F, a, b, c, d, SET(0), 0xd76aa478, 7)
STEP(F, d, a, b, c, SET(1), 0xe8c7b756, 12)
STEP(F, c, d, a, b, SET(2), 0x242070db, 17)
STEP(F, b, c, d, a, SET(3), 0xc1bdceee, 22)
STEP(F, a, b, c, d, SET(4), 0xf57c0faf, 7)
STEP(F, d, a, b, c, SET(5), 0x4787c62a, 12)
STEP(F, c, d, a, b, SET(6), 0xa8304613, 17)
STEP(F, b, c, d, a, SET(7), 0xfd469501, 22)
STEP(F, a, b, c, d, SET(8), 0x698098d8, 7)
STEP(F, d, a, b, c, SET(9), 0x8b44f7af, 12)
STEP(F, c, d, a, b, SET(10), 0xffff5bb1, 17)
STEP(F, b, c, d, a, SET(11), 0x895cd7be, 22)
STEP(F, a, b, c, d, SET(12), 0x6b901122, 7)
STEP(F, d, a, b, c, SET(13), 0xfd987193, 12)
STEP(F, c, d, a, b, SET(14), 0xa679438e, 17)
STEP(F, b, c, d, a, SET(15), 0x49b40821, 22)
/* Round 2 */
STEP(G, a, b, c, d, GET(1), 0xf61e2562, 5)
STEP(G, d, a, b, c, GET(6), 0xc040b340, 9)
STEP(G, c, d, a, b, GET(11), 0x265e5a51, 14)
STEP(G, b, c, d, a, GET(0), 0xe9b6c7aa, 20)
STEP(G, a, b, c, d, GET(5), 0xd62f105d, 5)
STEP(G, d, a, b, c, GET(10), 0x02441453, 9)
STEP(G, c, d, a, b, GET(15), 0xd8a1e681, 14)
STEP(G, b, c, d, a, GET(4), 0xe7d3fbc8, 20)
STEP(G, a, b, c, d, GET(9), 0x21e1cde6, 5)
STEP(G, d, a, b, c, GET(14), 0xc33707d6, 9)
STEP(G, c, d, a, b, GET(3), 0xf4d50d87, 14)
STEP(G, b, c, d, a, GET(8), 0x455a14ed, 20)
STEP(G, a, b, c, d, GET(13), 0xa9e3e905, 5)
STEP(G, d, a, b, c, GET(2), 0xfcefa3f8, 9)
STEP(G, c, d, a, b, GET(7), 0x676f02d9, 14)
STEP(G, b, c, d, a, GET(12), 0x8d2a4c8a, 20)
/* Round 3 */
STEP(H, a, b, c, d, GET(5), 0xfffa3942, 4)
STEP(H2, d, a, b, c, GET(8), 0x8771f681, 11)
STEP(H, c, d, a, b, GET(11), 0x6d9d6122, 16)
STEP(H2, b, c, d, a, GET(14), 0xfde5380c, 23)
STEP(H, a, b, c, d, GET(1), 0xa4beea44, 4)
STEP(H2, d, a, b, c, GET(4), 0x4bdecfa9, 11)
STEP(H, c, d, a, b, GET(7), 0xf6bb4b60, 16)
STEP(H2, b, c, d, a, GET(10), 0xbebfbc70, 23)
STEP(H, a, b, c, d, GET(13), 0x289b7ec6, 4)
STEP(H2, d, a, b, c, GET(0), 0xeaa127fa, 11)
STEP(H, c, d, a, b, GET(3), 0xd4ef3085, 16)
STEP(H2, b, c, d, a, GET(6), 0x04881d05, 23)
STEP(H, a, b, c, d, GET(9), 0xd9d4d039, 4)
STEP(H2, d, a, b, c, GET(12), 0xe6db99e5, 11)
STEP(H, c, d, a, b, GET(15), 0x1fa27cf8, 16)
STEP(H2, b, c, d, a, GET(2), 0xc4ac5665, 23)
/* Round 4 */
STEP(I, a, b, c, d, GET(0), 0xf4292244, 6)
STEP(I, d, a, b, c, GET(7), 0x432aff97, 10)
STEP(I, c, d, a, b, GET(14), 0xab9423a7, 15)
STEP(I, b, c, d, a, GET(5), 0xfc93a039, 21)
STEP(I, a, b, c, d, GET(12), 0x655b59c3, 6)
STEP(I, d, a, b, c, GET(3), 0x8f0ccc92, 10)
STEP(I, c, d, a, b, GET(10), 0xffeff47d, 15)
STEP(I, b, c, d, a, GET(1), 0x85845dd1, 21)
STEP(I, a, b, c, d, GET(8), 0x6fa87e4f, 6)
STEP(I, d, a, b, c, GET(15), 0xfe2ce6e0, 10)
STEP(I, c, d, a, b, GET(6), 0xa3014314, 15)
STEP(I, b, c, d, a, GET(13), 0x4e0811a1, 21)
STEP(I, a, b, c, d, GET(4), 0xf7537e82, 6)
STEP(I, d, a, b, c, GET(11), 0xbd3af235, 10)
STEP(I, c, d, a, b, GET(2), 0x2ad7d2bb, 15)
STEP(I, b, c, d, a, GET(9), 0xeb86d391, 21)
a += saved_a;
b += saved_b;
c += saved_c;
d += saved_d;
ptr += 64;
} while (size -= 64);
ctx->a = a;
ctx->b = b;
ctx->c = c;
ctx->d = d;
return ptr;
}
void MD5_Init(MD5_CTX *ctx)
{
ctx->a = 0x67452301;
ctx->b = 0xefcdab89;
ctx->c = 0x98badcfe;
ctx->d = 0x10325476;
ctx->lo = 0;
ctx->hi = 0;
}
void MD5_Update(MD5_CTX *ctx, const void *data, unsigned long size)
{
MD5_u32plus saved_lo;
unsigned long used, available;
saved_lo = ctx->lo;
if ((ctx->lo = (saved_lo + size) & 0x1fffffff) < saved_lo)
ctx->hi++;
ctx->hi += size >> 29;
used = saved_lo & 0x3f;
if (used) {
available = 64 - used;
if (size < available) {
memcpy(&ctx->buffer[used], data, size);
return;
}
memcpy(&ctx->buffer[used], data, available);
data = (const unsigned char *)data + available;
size -= available;
body(ctx, ctx->buffer, 64);
}
if (size >= 64) {
data = body(ctx, data, size & ~(unsigned long)0x3f);
size &= 0x3f;
}
memcpy(ctx->buffer, data, size);
}
#define OUT_MD5(dst, src) \
(dst)[0] = (unsigned char)(src); \
(dst)[1] = (unsigned char)((src) >> 8); \
(dst)[2] = (unsigned char)((src) >> 16); \
(dst)[3] = (unsigned char)((src) >> 24);
void MD5_Final(unsigned char *result, MD5_CTX *ctx)
{
unsigned long used, available;
used = ctx->lo & 0x3f;
ctx->buffer[used++] = 0x80;
available = 64 - used;
if (available < 8)
{
memset(&ctx->buffer[used], 0, available);
body(ctx, ctx->buffer, 64);
used = 0;
available = 64;
}
memset(&ctx->buffer[used], 0, available - 8);
ctx->lo <<= 3;
OUT_MD5(&ctx->buffer[56], ctx->lo)
OUT_MD5(&ctx->buffer[60], ctx->hi)
body(ctx, ctx->buffer, 64);
OUT_MD5(&result[0], ctx->a)
OUT_MD5(&result[4], ctx->b)
OUT_MD5(&result[8], ctx->c)
OUT_MD5(&result[12], ctx->d)
memset(ctx, 0, sizeof(*ctx));
}
#endif
// HMAC-MD5
void hmacMD5_init_rfc2104(const unsigned char* key, int key_len, HMACMD5Ctx *ctx)
{
int i;
memset(ctx, 0, sizeof(HMACMD5Ctx));
/* if key is longer than 64 bytes reset it to key=MD5(key) */
if (key_len > 64)
{
unsigned char tk[16];
MD5_CTX tctx;
MD5_Init(&tctx);
MD5_Update(&tctx, key, key_len);
MD5_Final(tk, &tctx);
key = tk;
key_len = 16;
}
/* start out by storing key in pads */
memcpy(ctx->k_ipad, key, key_len);
memcpy(ctx->k_opad, key, key_len);
/* XOR key with ipad and opad values */
for (i = 0; i < 64; i++)
{
ctx->k_ipad[i] ^= 0x36;
ctx->k_opad[i] ^= 0x5c;
}
MD5_Init(&ctx->ctx);
MD5_Update(&ctx->ctx, ctx->k_ipad, 64);
}
void hmacMD5_init_limK_to_64(const unsigned char* key, int key_len, HMACMD5Ctx *ctx)
{
if (key_len > 64)
{
key_len = 64;
}
hmacMD5_init_rfc2104(key, key_len, ctx);
}
void hmacMD5_update(const unsigned char* text, int text_len, HMACMD5Ctx *ctx)
{
MD5_Update(&ctx->ctx, text, text_len);
}
void hmacMD5_final(unsigned char* digest, HMACMD5Ctx *ctx)
{
MD5_CTX ctx_o;
MD5_Final(digest, &ctx->ctx);
MD5_Init(&ctx_o);
MD5_Update(&ctx_o, ctx->k_opad, 64);
MD5_Update(&ctx_o, digest, 16);
MD5_Final(digest, &ctx_o);
}
void hmacMD5(const unsigned char* key, int keyLen, const unsigned char* text, int textLen, unsigned char* digest)
{
HMACMD5Ctx ctx;
hmacMD5_init_limK_to_64(key, keyLen, &ctx);
hmacMD5_update(text, textLen, &ctx);
hmacMD5_final(digest, &ctx);
}
| 10,245
|
C++
|
.cpp
| 308
| 30.899351
| 113
| 0.633118
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| true
| false
|
22,880
|
libusbWrapper.cpp
|
cemu-project_Cemu/src/util/libusbWrapper/libusbWrapper.cpp
|
#include "libusbWrapper.h"
/*
#include "config/ActiveSettings.h"
libusbWrapper::libusbWrapper()
{
}
void libusbWrapper::init()
{
#if BOOST_OS_WINDOWS
if (m_isInitialized)
return;
m_isInitialized = true;
// load module
m_module = LoadLibraryW(L"libusb-1.0.dll");
if (!m_module)
{
const auto path = ActiveSettings::GetDataPath("resources/libusb-1.0.dll");
m_module = LoadLibraryW(path.generic_wstring().c_str());
if (!m_module)
{
cemuLog_log(LogType::Force, "libusbWrapper: can't load libusb-1.0.dll");
return;
}
}
// grab imports
#define FETCH_IMPORT(__NAME__) p_##__NAME__ = (decltype(&__NAME__))GetProcAddress(m_module, #__NAME__)
FETCH_IMPORT(libusb_init);
FETCH_IMPORT(libusb_exit);
FETCH_IMPORT(libusb_interrupt_transfer);
FETCH_IMPORT(libusb_get_device_list);
FETCH_IMPORT(libusb_get_device_descriptor);
FETCH_IMPORT(libusb_open);
FETCH_IMPORT(libusb_close);
FETCH_IMPORT(libusb_kernel_driver_active);
FETCH_IMPORT(libusb_detach_kernel_driver);
FETCH_IMPORT(libusb_claim_interface);
FETCH_IMPORT(libusb_free_device_list);
FETCH_IMPORT(libusb_get_config_descriptor);
FETCH_IMPORT(libusb_hotplug_register_callback);
FETCH_IMPORT(libusb_hotplug_deregister_callback);
FETCH_IMPORT(libusb_has_capability);
FETCH_IMPORT(libusb_error_name);
FETCH_IMPORT(libusb_get_string_descriptor);
FETCH_IMPORT(libusb_get_string_descriptor_ascii);
FETCH_IMPORT(libusb_free_config_descriptor);
#undef FETCH_IMPORT
// create default context
if (p_libusb_init)
p_libusb_init(nullptr);
#else
cemuLog_log(LogType::Force, "libusbWrapper: Not supported on this OS");
#endif
}
libusbWrapper::~libusbWrapper()
{
#if BOOST_OS_WINDOWS
// destroy default context
if(p_libusb_exit)
p_libusb_exit(nullptr);
// unload module
if(m_module)
FreeLibrary(m_module);
#endif
}
*/
| 1,812
|
C++
|
.cpp
| 65
| 25.815385
| 102
| 0.757907
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,881
|
HighResolutionTimer.cpp
|
cemu-project_Cemu/src/util/highresolutiontimer/HighResolutionTimer.cpp
|
#include "util/highresolutiontimer/HighResolutionTimer.h"
#include "Common/precompiled.h"
HighResolutionTimer HighResolutionTimer::now()
{
#if BOOST_OS_WINDOWS
LARGE_INTEGER pc;
QueryPerformanceCounter(&pc);
return HighResolutionTimer(pc.QuadPart);
#elif BOOST_OS_LINUX
timespec pc;
clock_gettime(CLOCK_MONOTONIC_RAW, &pc);
uint64 nsec = (uint64)pc.tv_sec * (uint64)1000000000 + (uint64)pc.tv_nsec;
return HighResolutionTimer(nsec);
#elif BOOST_OS_MACOS
return HighResolutionTimer(clock_gettime_nsec_np(CLOCK_MONOTONIC_RAW));
#endif
}
HRTick HighResolutionTimer::getFrequency()
{
return m_freq;
}
uint64 HighResolutionTimer::m_freq = []() -> uint64 {
#if BOOST_OS_WINDOWS
LARGE_INTEGER freq;
QueryPerformanceFrequency(&freq);
return (uint64)(freq.QuadPart);
#else
timespec pc;
clock_getres(CLOCK_MONOTONIC_RAW, &pc);
return (uint64)1000000000 / (uint64)pc.tv_nsec;
#endif
}();
| 916
|
C++
|
.cpp
| 32
| 26.40625
| 78
| 0.77185
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,882
|
MemMapperUnix.cpp
|
cemu-project_Cemu/src/util/MemMapper/MemMapperUnix.cpp
|
#include "util/MemMapper/MemMapper.h"
#include <unistd.h>
#include <sys/mman.h>
namespace MemMapper
{
const size_t sPageSize{ []()
{
return (size_t)getpagesize();
}()
};
size_t GetPageSize()
{
return sPageSize;
}
int GetProt(PAGE_PERMISSION permissionFlags)
{
int p = 0;
if (HAS_FLAG(permissionFlags, PAGE_PERMISSION::P_READ) && HAS_FLAG(permissionFlags, PAGE_PERMISSION::P_WRITE) && HAS_FLAG(permissionFlags, PAGE_PERMISSION::P_EXECUTE))
p = PROT_READ | PROT_WRITE | PROT_EXEC;
else if (HAS_FLAG(permissionFlags, PAGE_PERMISSION::P_READ) && HAS_FLAG(permissionFlags, PAGE_PERMISSION::P_WRITE) && !HAS_FLAG(permissionFlags, PAGE_PERMISSION::P_EXECUTE))
p = PROT_READ | PROT_WRITE;
else if (HAS_FLAG(permissionFlags, PAGE_PERMISSION::P_READ) && !HAS_FLAG(permissionFlags, PAGE_PERMISSION::P_WRITE) && !HAS_FLAG(permissionFlags, PAGE_PERMISSION::P_EXECUTE))
p = PROT_READ;
else
cemu_assert_unimplemented();
return p;
}
void* ReserveMemory(void* baseAddr, size_t size, PAGE_PERMISSION permissionFlags)
{
return mmap(baseAddr, size, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
}
void FreeReservation(void* baseAddr, size_t size)
{
munmap(baseAddr, size);
}
void* AllocateMemory(void* baseAddr, size_t size, PAGE_PERMISSION permissionFlags, bool fromReservation)
{
void* r;
if(fromReservation)
{
if( mprotect(baseAddr, size, GetProt(permissionFlags)) == 0 )
r = baseAddr;
else
r = nullptr;
}
else
r = mmap(baseAddr, size, GetProt(permissionFlags), MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
return r;
}
void FreeMemory(void* baseAddr, size_t size, bool fromReservation)
{
if (fromReservation)
mprotect(baseAddr, size, PROT_NONE);
else
munmap(baseAddr, size);
}
};
| 1,785
|
C++
|
.cpp
| 57
| 28.087719
| 176
| 0.712042
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,883
|
MemMapperWin.cpp
|
cemu-project_Cemu/src/util/MemMapper/MemMapperWin.cpp
|
#include "util/MemMapper/MemMapper.h"
#include <Windows.h>
namespace MemMapper
{
const size_t sPageSize{ []()
{
SYSTEM_INFO si;
GetSystemInfo(&si);
return (size_t)si.dwPageSize;
}()
};
size_t GetPageSize()
{
return sPageSize;
}
DWORD GetPageProtection(PAGE_PERMISSION permissionFlags)
{
DWORD p = 0;
if (HAS_FLAG(permissionFlags, PAGE_PERMISSION::P_READ) && HAS_FLAG(permissionFlags, PAGE_PERMISSION::P_WRITE) && HAS_FLAG(permissionFlags, PAGE_PERMISSION::P_EXECUTE))
p = PAGE_EXECUTE_READWRITE;
else if (HAS_FLAG(permissionFlags, PAGE_PERMISSION::P_READ) && HAS_FLAG(permissionFlags, PAGE_PERMISSION::P_WRITE) && !HAS_FLAG(permissionFlags, PAGE_PERMISSION::P_EXECUTE))
p = PAGE_READWRITE;
else if (HAS_FLAG(permissionFlags, PAGE_PERMISSION::P_READ) && !HAS_FLAG(permissionFlags, PAGE_PERMISSION::P_WRITE) && !HAS_FLAG(permissionFlags, PAGE_PERMISSION::P_EXECUTE))
p = PAGE_READONLY;
else
cemu_assert_unimplemented();
return p;
}
void* ReserveMemory(void* baseAddr, size_t size, PAGE_PERMISSION permissionFlags)
{
void* r = VirtualAlloc(baseAddr, size, MEM_RESERVE, GetPageProtection(permissionFlags));
return r;
}
void FreeReservation(void* baseAddr, size_t size)
{
VirtualFree(baseAddr, size, MEM_RELEASE);
}
void* AllocateMemory(void* baseAddr, size_t size, PAGE_PERMISSION permissionFlags, bool fromReservation)
{
void* r;
if(fromReservation)
r = VirtualAlloc(baseAddr, size, MEM_COMMIT, GetPageProtection(permissionFlags));
else
r = VirtualAlloc(baseAddr, size, MEM_RESERVE | MEM_COMMIT, GetPageProtection(permissionFlags));
return r;
}
void FreeMemory(void* baseAddr, size_t size, bool fromReservation)
{
if(fromReservation)
VirtualFree(baseAddr, size, MEM_DECOMMIT);
else
VirtualFree(baseAddr, size, MEM_RELEASE);
}
};
| 1,820
|
C++
|
.cpp
| 54
| 30.962963
| 176
| 0.751281
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,884
|
ZpIREmitGLSL.cpp
|
cemu-project_Cemu/src/util/Zir/EmitterGLSL/ZpIREmitGLSL.cpp
|
#include "util/Zir/Core/IR.h"
#include "util/Zir/Core/ZirUtility.h"
#include "util/Zir/Core/ZpIRPasses.h"
#include "util/Zir/EmitterGLSL/ZpIREmitGLSL.h"
#include "util/Zir/Core/ZpIRScheduler.h"
// string buffer helper class which keeps buffer space at the front and end, allow fast prepend and append
class DualStringBuffer
{
static constexpr size_t N = 1024;
public:
DualStringBuffer() : m_offsetBegin(N / 2), m_offsetEnd(N / 2) { }
~DualStringBuffer() = default;
static_assert(sizeof(char) == sizeof(uint8));
void reset()
{
m_offsetBegin = N / 2;
m_offsetEnd = m_offsetBegin;
}
void append(std::string_view strView)
{
cemu_assert_debug((m_offsetEnd + strView.size()) <= N);
std::memcpy(m_strBuffer + m_offsetEnd, strView.data(), strView.size());
m_offsetEnd += (uint32)strView.size();
}
template <typename... Args>
void appendFmt(const char* format_str, Args... args)
{
char* buf = (char*)(m_strBuffer + m_offsetEnd);
char* r = fmt::format_to(buf, fmt::runtime(format_str), std::forward<Args>(args)...);
cemu_assert_debug(r <= (char*)(m_strBuffer + N));
m_offsetEnd += (uint32)(r - buf);
}
void prepend(std::string_view strView)
{
assert_dbg();
}
size_t size() const
{
return m_offsetEnd - m_offsetBegin;
}
operator std::string_view()
{
return std::basic_string_view<char>((char*)(m_strBuffer + m_offsetBegin), m_offsetEnd - m_offsetBegin);
}
private:
//void resizeBuffer(uint32 spaceRequiredFront, uint32 spaceRequiredBack)
//{
// uint32 newTotalSize = spaceRequiredFront + size() + spaceRequiredBack;
// // round to next multiple of 32 and add extra buffer
// newTotalSize = (newTotalSize + 31) & ~31;
// newTotalSize += (newTotalSize / 4);
// //
//}
//uint8* m_bufferPtr{ nullptr };
//size_t m_bufferSize{ 0 };
//std::vector<uint8> m_buffer;
uint32 m_offsetBegin;
uint32 m_offsetEnd;
uint8 m_strBuffer[N];
};
namespace ZirEmitter
{
static const char g_idx_to_element[] = { 'x' , 'y', 'z', 'w'};
void GLSL::Emit(ZpIR::ZpIRFunction* irFunction, StringBuf* output)
{
m_irFunction = irFunction;
m_glslSource = output;
cemu_assert_debug(m_irFunction->m_entryBlocks.size() == 1);
cemu_assert_debug(m_irFunction->m_basicBlocks.size() == 1); // other sizes are todo
m_glslSource->add("void main()\r\n{\r\n");
GenerateBasicBlockCode(*m_irFunction->m_entryBlocks[0]);
m_glslSource->add("}\r\n");
}
void GLSL::GenerateBasicBlockCode(ZpIR::ZpIRBasicBlock& basicBlock)
{
// init context
#ifdef CEMU_DEBUG_ASSERT
for (auto& itr : m_blockContext.regInlinedExpression)
{
cemu_assert_debug(itr == nullptr); // leaked buffer
}
#endif
m_blockContext.regReadTracking.clear();
m_blockContext.regReadTracking.resize(basicBlock.m_regs.size());
m_blockContext.regInlinedExpression.resize(basicBlock.m_regs.size());
m_blockContext.currentBasicBlock = &basicBlock;
// we first do an analysis pass in which we determine the read count for each register
// every register which is only consumed once can be directly inlined instead of storing and referencing it via a variable
ZpIR::IR::__InsBase* instruction = basicBlock.m_instructionFirst;
while (instruction)
{
ZpIR::ZpIRCmdUtil::forEachAccessedReg(basicBlock, instruction,
[this](ZpIR::IRReg readReg)
{
if (readReg >= 0x8000)
assert_dbg();
// read access
auto& entry = m_blockContext.regReadTracking.at(readReg);
if (entry < 255)
entry++;
},
[](ZpIR::IRReg writtenReg)
{
});
instruction = instruction->next;
}
// emit GLSL for this block
instruction = basicBlock.m_instructionFirst;
while (instruction)
{
if (auto ins = ZpIR::IR::InsRR::getIfForm(instruction))
HandleInstruction(ins);
else if (auto ins = ZpIR::IR::InsRRR::getIfForm(instruction))
HandleInstruction(ins);
else if (auto ins = ZpIR::IR::InsIMPORT::getIfForm(instruction))
HandleInstruction(ins);
else if (auto ins = ZpIR::IR::InsEXPORT::getIfForm(instruction))
HandleInstruction(ins);
else
{
assert_dbg();
}
instruction = instruction->next;
}
}
void GLSL::HandleInstruction(ZpIR::IR::InsRR* ins)
{
DualStringBuffer* expressionBuf = GetStringBuffer();
bool forceNoInline = false;
switch (ins->opcode)
{
case ZpIR::IR::OpCode::BITCAST:
{
auto srcType = m_blockContext.currentBasicBlock->getRegType(ins->rB);
auto dstType = m_blockContext.currentBasicBlock->getRegType(ins->rA);
if (srcType == ZpIR::DataType::U32 && dstType == ZpIR::DataType::F32)
expressionBuf->append("uintBitsToFloat(");
else if (srcType == ZpIR::DataType::S32 && dstType == ZpIR::DataType::F32)
expressionBuf->append("intBitsToFloat(");
else if (srcType == ZpIR::DataType::F32 && dstType == ZpIR::DataType::U32)
expressionBuf->append("floatBitsToUint(");
else if (srcType == ZpIR::DataType::F32 && dstType == ZpIR::DataType::S32)
expressionBuf->append("floatBitsToInt(");
else
assert_dbg();
appendSourceString(expressionBuf, ins->rB);
expressionBuf->append(")");
break;
}
case ZpIR::IR::OpCode::SWAP_ENDIAN:
{
auto srcType = m_blockContext.currentBasicBlock->getRegType(ins->rB);
auto dstType = m_blockContext.currentBasicBlock->getRegType(ins->rA);
cemu_assert_debug(srcType == dstType);
// todo - should we store expressionBuf in a temporary variable? We reference it multiple times and reducing complexity would be good
if (srcType == ZpIR::DataType::U32)
{
expressionBuf->append("(((");
appendSourceString(expressionBuf, ins->rB);
expressionBuf->append(")>>24)");
expressionBuf->append("|");
expressionBuf->append("(((");
appendSourceString(expressionBuf, ins->rB);
expressionBuf->append(")>>8)&0xFF00)");
expressionBuf->append("|");
expressionBuf->append("(((");
appendSourceString(expressionBuf, ins->rB);
expressionBuf->append(")<<8)&0xFF0000)");
expressionBuf->append("|");
expressionBuf->append("((");
appendSourceString(expressionBuf, ins->rB);
expressionBuf->append(")<<24))");
// (v>>24)|((v>>8)&0xFF00)|((v<<8)&0xFF0000)|((v<<24))
}
else
assert_dbg();
forceNoInline = true; // avoid inlining endian-swapping, since it would add too much complexity to expressions
break;
}
case ZpIR::IR::OpCode::MOV:
appendSourceString(expressionBuf, ins->rB);
break;
case ZpIR::IR::OpCode::CONVERT_FLOAT_TO_INT:
{
auto srcType = m_blockContext.currentBasicBlock->getRegType(ins->rB);
auto dstType = m_blockContext.currentBasicBlock->getRegType(ins->rA);
cemu_assert_debug(srcType == ZpIR::DataType::F32);
cemu_assert_debug(dstType == ZpIR::DataType::S32 || dstType == ZpIR::DataType::U32);
if(dstType == ZpIR::DataType::U32)
expressionBuf->append("uint(");
else
expressionBuf->append("int(");
appendSourceString(expressionBuf, ins->rB);
expressionBuf->append(")");
break;
}
case ZpIR::IR::OpCode::CONVERT_INT_TO_FLOAT:
{
auto srcType = m_blockContext.currentBasicBlock->getRegType(ins->rB);
auto dstType = m_blockContext.currentBasicBlock->getRegType(ins->rA);
cemu_assert_debug(srcType == ZpIR::DataType::S32 || srcType == ZpIR::DataType::U32);
cemu_assert_debug(dstType == ZpIR::DataType::F32);
expressionBuf->append("float(");
appendSourceString(expressionBuf, ins->rB);
expressionBuf->append(")");
break;
}
default:
assert_dbg();
}
AssignResult(ins->rA, expressionBuf, forceNoInline);
}
void GLSL::HandleInstruction(ZpIR::IR::InsRRR* ins)
{
DualStringBuffer* expressionBuf = GetStringBuffer();
switch (ins->opcode)
{
case ZpIR::IR::OpCode::ADD:
{
appendSourceString(expressionBuf, ins->rB);
expressionBuf->append(" + ");
appendSourceString(expressionBuf, ins->rC);
break;
}
case ZpIR::IR::OpCode::MUL:
{
appendSourceString(expressionBuf, ins->rB);
expressionBuf->append(" * ");
appendSourceString(expressionBuf, ins->rC);
break;
}
case ZpIR::IR::OpCode::DIV:
{
appendSourceString(expressionBuf, ins->rB);
expressionBuf->append(" / ");
appendSourceString(expressionBuf, ins->rC);
break;
}
default:
assert_dbg();
}
AssignResult(ins->rA, expressionBuf);
}
void GLSL::HandleInstruction(ZpIR::IR::InsIMPORT* ins)
{
ZpIR::ShaderSubset::ShaderImportLocation loc(ins->importSymbol);
DualStringBuffer* buf = GetStringBuffer();
if (loc.IsUniformRegister())
{
uint16 index;
loc.GetUniformRegister(index);
// todo - this is complex. Solve via callback
buf->appendFmt("uf_remappedVS[{}].{}", index/4, g_idx_to_element[index&3]);
AssignResult(ins->regArray[0], buf);
}
else if (loc.IsVertexAttribute())
{
uint16 attributeIndex;
uint16 channelIndex;
loc.GetVertexAttribute(attributeIndex, channelIndex);
cemu_assert_debug(ins->count == 1);
cemu_assert_debug(ZpIR::isRegVar(ins->regArray[0]));
cemu_assert_debug(channelIndex < 4);
cemu_assert_debug(m_blockContext.currentBasicBlock->getRegType(ins->regArray[0]) == ZpIR::DataType::U32);
buf->appendFmt("attrDataSem{}.{}", attributeIndex, g_idx_to_element[channelIndex]);
AssignResult(ins->regArray[0], buf);
}
else
{
cemu_assert_debug(false);
}
}
void GLSL::HandleInstruction(ZpIR::IR::InsEXPORT* ins)
{
ZpIR::ShaderSubset::ShaderExportLocation loc(ins->exportSymbol);
DualStringBuffer* buf = GetStringBuffer();
if (loc.IsPosition())
{
// todo - support for output mask (e.g. xyzw, x_zw) ?
buf->append("SET_POSITION(vec4(");
cemu_assert_debug(ins->count == 4);
for (uint32 i = 0; i < ins->count; i++)
{
if(i > 0)
buf->append(", ");
appendSourceString(buf, ins->regArray[i]);
}
m_glslSource->add(*buf);
m_glslSource->add("));\r\n");
}
else if (loc.IsOutputAttribute())
{
uint16 attributeIndex;
loc.GetOutputAttribute(attributeIndex);
buf->appendFmt("passParameterSem{} = vec4(", attributeIndex);
cemu_assert_debug(ins->count == 4);
for (uint32 i = 0; i < ins->count; i++)
{
if (i > 0)
buf->append(", ");
appendSourceString(buf, ins->regArray[i]);
}
m_glslSource->add(*buf);
m_glslSource->add(");\r\n");
}
else
{
assert_dbg();
}
ReleaseStringBuffer(buf);
}
void GLSL::AssignResult(ZpIR::IRReg irReg, DualStringBuffer* buf, bool forceNoInline)
{
if (buf->size() > 100)
forceNoInline = true; // expression too long
if (m_blockContext.CanInlineRegister(irReg) && !forceNoInline)
{
SetRegInlinedExpression(irReg, buf);
}
else
{
ZpIR::DataType regType = m_blockContext.currentBasicBlock->getRegType(irReg);
if (regType == ZpIR::DataType::F32)
m_glslSource->add("float ");
else if (regType == ZpIR::DataType::S32)
m_glslSource->add("int ");
else if (regType == ZpIR::DataType::U32)
m_glslSource->add("uint ");
else
{
cemu_assert_debug(false);
}
char regName[16];
getRegisterName(regName, irReg);
m_glslSource->add(regName);
m_glslSource->add(" = ");
m_glslSource->add(*buf);
m_glslSource->add(";\r\n");
ReleaseStringBuffer(buf);
}
}
void GLSL::appendSourceString(DualStringBuffer* buf, ZpIR::IRReg irReg)
{
if (ZpIR::isConstVar(irReg))
{
ZpIR::IRRegConstDef* constDef = m_blockContext.currentBasicBlock->getConstant(irReg);
if (constDef->type == ZpIR::DataType::U32)
{
buf->appendFmt("{}", constDef->value_u32);
return;
}
else if (constDef->type == ZpIR::DataType::S32)
{
buf->appendFmt("{}", constDef->value_s32);
return;
}
else if (constDef->type == ZpIR::DataType::F32)
{
buf->appendFmt("{}", constDef->value_f32);
return;
}
assert_dbg();
}
else
{
cemu_assert_debug(ZpIR::isRegVar(irReg));
uint16 regIndex = ZpIR::getRegIndex(irReg);
DualStringBuffer* expressionBuf = m_blockContext.regInlinedExpression[regIndex];
if (expressionBuf)
{
buf->append(*expressionBuf);
return;
}
char regName[16];
getRegisterName(regName, irReg);
buf->append(regName);
}
}
void GLSL::getRegisterName(char buf[16], ZpIR::IRReg irReg)
{
auto& regData = m_blockContext.currentBasicBlock->m_regs[(uint16)irReg & 0x7FFF];
cemu_assert_debug(regData.hasAssignedPhysicalRegister());
ZpIR::ZpIRPhysicalReg physReg = regData.physicalRegister;
char typeChar;
if (ZirPass::RegisterAllocatorForGLSL::IsPhysRegTypeF32(physReg))
typeChar = 'f';
else if (ZirPass::RegisterAllocatorForGLSL::IsPhysRegTypeS32(physReg))
typeChar = 'i';
else if (ZirPass::RegisterAllocatorForGLSL::IsPhysRegTypeU32(physReg))
typeChar = 'u';
else
{
typeChar = 'x';
cemu_assert_debug(false);
}
auto r = fmt::format_to(buf, "r{}{}", ZirPass::RegisterAllocatorForGLSL::GetPhysRegIndex(physReg), typeChar);
*r = '\0';
}
void GLSL::SetRegInlinedExpression(ZpIR::IRReg irReg, DualStringBuffer* buf)
{
cemu_assert_debug(ZpIR::isRegVar(irReg));
uint16 dstIndex = (uint16)irReg;
if (m_blockContext.regInlinedExpression[dstIndex])
ReleaseStringBuffer(m_blockContext.regInlinedExpression[dstIndex]);
m_blockContext.regInlinedExpression[dstIndex] = buf;
}
void GLSL::ResetRegInlinedExpression(ZpIR::IRReg irReg)
{
cemu_assert_debug(ZpIR::isRegVar(irReg));
uint16 dstIndex = (uint16)irReg;
if (m_blockContext.regInlinedExpression[dstIndex])
{
ReleaseStringBuffer(m_blockContext.regInlinedExpression[dstIndex]);
m_blockContext.regInlinedExpression[dstIndex] = nullptr;
}
}
DualStringBuffer* GLSL::GetRegInlinedExpression(ZpIR::IRReg irReg)
{
cemu_assert_debug(ZpIR::isRegVar(irReg));
uint16 dstIndex = (uint16)irReg;
return m_blockContext.regInlinedExpression[dstIndex];
}
DualStringBuffer* GLSL::GetStringBuffer()
{
if (m_stringBufferCache.empty())
return new DualStringBuffer();
DualStringBuffer* buf = m_stringBufferCache.back();
m_stringBufferCache.pop_back();
buf->reset();
return buf;
}
void GLSL::ReleaseStringBuffer(DualStringBuffer* buf)
{
m_stringBufferCache.emplace_back(buf);
}
};
| 13,994
|
C++
|
.cpp
| 436
| 28.62156
| 136
| 0.702785
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,885
|
RegisterAllocatorForGLSL.cpp
|
cemu-project_Cemu/src/util/Zir/Passes/RegisterAllocatorForGLSL.cpp
|
#include "util/Zir/Core/IR.h"
#include "util/Zir/Core/ZirUtility.h"
#include "util/Zir/Core/ZpIRPasses.h"
#include "util/Zir/Core/ZpIRDebug.h"
namespace ZirPass
{
void RegisterAllocatorForGLSL::assignPhysicalRegisters()
{
if (m_irFunction->m_basicBlocks.size() != 1)
cemu_assert_unimplemented();
for (auto& itr : m_irFunction->m_basicBlocks)
assignPhysicalRegistersForBlock(itr);
}
void RegisterAllocatorForGLSL::assignPhysicalRegistersForBlock(ZpIR::ZpIRBasicBlock* basicBlock)
{
// resolve imports
for (auto& itr : basicBlock->m_imports)
{
assert_dbg(); // todo - If imported reg not assigned physical register yet -> create a shared physical register (MSB set in reg index?) And assign it to this basic block but also all the shared IRRegs in the other linked basic blocks
// how to handle import:
// - match physical register of every input/output
// - every import must have a matching export in all the previous basic blocks. If not all match this is an error.
// In our shader emitter this could happen if the original R600 code references an uninitialized register
// note - we also have to make sure the register type matches. If a linked block has a shared register with a different type then we need to create a new register and insert a bitcast instruction in that block
}
// assign a register index to every virtual register
for (auto& itr : basicBlock->m_regs)
{
if (itr.type != ZpIR::DataType::NONE && !itr.hasAssignedPhysicalRegister())
{
if (itr.type == ZpIR::DataType::F32)
itr.assignPhysicalRegister(MakePhysReg(PHYS_REG_TYPE::F32, m_physicalRegisterCounterF32++));
else if (itr.type == ZpIR::DataType::S32)
itr.assignPhysicalRegister(MakePhysReg(PHYS_REG_TYPE::S32, m_physicalRegisterCounterS32++));
else if (itr.type == ZpIR::DataType::U32)
itr.assignPhysicalRegister(MakePhysReg(PHYS_REG_TYPE::U32, m_physicalRegisterCounterU32++));
else
{
cemu_assert_debug(false);
}
}
}
}
std::string RegisterAllocatorForGLSL::DebugPrintHelper_getPhysRegisterName(ZpIR::ZpIRBasicBlock* block, ZpIR::ZpIRPhysicalReg r)
{
std::string s;
uint32 regIndex = GetPhysRegIndex(r);
if (IsPhysRegTypeF32(r))
s = fmt::format("r{}f", regIndex);
else if (IsPhysRegTypeU32(r))
s = fmt::format("r{}u", regIndex);
else if (IsPhysRegTypeS32(r))
s = fmt::format("r{}i", regIndex);
return s;
}
}
| 2,421
|
C++
|
.cpp
| 56
| 39.821429
| 236
| 0.737378
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,886
|
ZpIRRegisterAllocator.cpp
|
cemu-project_Cemu/src/util/Zir/Passes/ZpIRRegisterAllocator.cpp
|
#include "util/Zir/Core/IR.h"
#include "util/Zir/Core/ZirUtility.h"
#include "util/Zir/Core/ZpIRPasses.h"
#include "util/Zir/Core/ZpIRDebug.h"
namespace ZirPass
{
using namespace ZpIR;
/*
Algorithm description:
Prepare phase:
Assign every basic block an index
Create internal arrays to match index count
First phase:
Create liveness ranges for each basic block
Link liveness ranges by import/export
Constrained instructions split affected ranges into their own single instruction liveness range
Second phase:
Assign registers. Start with constrained ranges first, then process from beginning to end
Whenever we assign a register to a range, we also try to propagate it to all the connected/coalesced ranges
A liveness range is described by:
- Source (Can be any of: List of previous basic blocks, liveness range in same basic block)
- Destination (list of liveness ranges)
- Index of basic block
- First instruction (where register is assigned, -1 if passed from previous block)
- Last instruction (where register is last accessed)
- IR-Register (within the same basic block)
During algorithm:
- Spillcost (probably can calculate this dynamically)
- Physical location (-1 if not assigned. Otherwise register index or spill memory offset)
*/
RALivenessRange_t::RALivenessRange_t(RABlock_t* block, IRReg irReg, sint32 start, sint32 end, DataType irDataType) : m_block(block), m_irReg(irReg), m_irDataType(irDataType)
{
block->livenessRanges.emplace(irReg, this);
m_startIndex = start;
m_endIndex = end;
// register
for (auto& itr : block->livenessRanges)
{
RALivenessRange_t* itrRange = itr.second;
if (start < itrRange->m_endIndex && end >= itrRange->m_startIndex)
{
m_overlappingRanges.emplace_back(itrRange);
itrRange->m_overlappingRanges.emplace_back(this);
// todo - also immediately flag physical registers as unavailable
}
}
block->unassignedRanges.emplace(this);
}
RALivenessRange_t::~RALivenessRange_t()
{
for (auto& itr : m_overlappingRanges)
{
RALivenessRange_t* overlappedRange = itr;
// todo - unflag physical register (if this has one set)
overlappedRange->m_overlappingRanges.erase(std::remove(overlappedRange->m_overlappingRanges.begin(), overlappedRange->m_overlappingRanges.end(), overlappedRange), overlappedRange->m_overlappingRanges.end());
}
m_overlappingRanges.clear();
assert_dbg();
}
void RALivenessRange_t::setStart(sint32 startIndex)
{
m_startIndex = startIndex;
assert_dbg(); // re-register in sorted range list (if no reg assigned)
}
void RALivenessRange_t::setEnd(sint32 endIndex)
{
if (endIndex > m_endIndex)
{
// add ranges that are now overlapping
for (auto& itr : m_block->livenessRanges)
{
RALivenessRange_t* itrRange = itr.second;
if(itrRange->isOverlapping(this))
continue; // was overlapping before
if(itrRange == this)
continue;
if (itrRange->isOverlapping(m_startIndex, endIndex))
{
m_overlappingRanges.emplace_back(itrRange);
itrRange->m_overlappingRanges.emplace_back(this);
// todo - also immediately flag physical registers as unavailable
}
}
}
else if (endIndex < m_endIndex)
{
// remove ranges that are no longer overlapping
cemu_assert_suspicious();
}
m_endIndex = endIndex;
}
void RALivenessRange_t::assignPhysicalRegister(ZpIRPhysicalReg physReg)
{
if (m_location != LOCATION::UNASSIGNED)
cemu_assert_suspicious();
m_location = LOCATION::PHYSICAL_REGISTER;
m_physicalRegister = physReg;
// remove this from unassignedRanges
auto itr = m_block->unassignedRanges.find(this);
if (itr == m_block->unassignedRanges.end())
cemu_assert_suspicious();
if (*itr != this)
cemu_assert_suspicious();
m_block->unassignedRanges.erase(itr);
}
void RARegular::prepareRABlocks()
{
auto& irBasicBlocks = m_irFunction->m_basicBlocks;
m_raBlockArray.resize(m_irFunction->m_basicBlocks.size());
}
void RARegular::generateLivenessRanges()
{
auto& irBasicBlocks = m_irFunction->m_basicBlocks;
//for (auto& itr : irBasicBlocks)
for (uint32 basicBlockIndex = 0; basicBlockIndex < (uint32)irBasicBlocks.size(); basicBlockIndex++)
{
auto& blockItr = irBasicBlocks[basicBlockIndex];
RABlock_t* raBlock = m_raBlockArray.data() + basicBlockIndex;
std::unordered_map<IRReg, RALivenessRange_t*>& blockRanges = raBlock->livenessRanges;
// init ranges for imports first
for (auto& regImport : blockItr->m_imports)
{
new RALivenessRange_t(raBlock, regImport.reg, -1, -1, blockItr->m_regs[(uint16)regImport.reg].type);
// imports start before the current basic block
}
// parse instructions and create/update ranges
IR::__InsBase* ins = blockItr->m_instructionFirst;
size_t i = 0;
while(ins)
{
ZpIRCmdUtil::forEachAccessedReg(*blockItr, ins,
[&blockRanges, i, raBlock](IRReg readReg)
{
if (readReg >= 0x8000)
cemu_assert_suspicious();
// read access
auto livenessRange = blockRanges.find(readReg);
if (livenessRange == blockRanges.end())
cemu_assert_suspicious();
livenessRange->second->setEnd((sint32)i);
},
[&blockRanges, i, raBlock, blockItr](IRReg writtenReg)
{
if (writtenReg >= 0x8000)
cemu_assert_suspicious();
// write access
auto livenessRange = blockRanges.find(writtenReg);
if (livenessRange != blockRanges.end())
cemu_assert_suspicious();
new RALivenessRange_t(raBlock, writtenReg, (sint32)i, (sint32)i, blockItr->m_regs[(uint16)writtenReg].type);
});
i++;
ins = ins->next;
}
// exports extend ranges to one instruction past the end of the block
for (auto& regExport : blockItr->m_exports)
{
auto livenessRange = blockRanges.find(regExport.reg);
if (livenessRange == blockRanges.end())
cemu_assert_suspicious();
cemu_assert_unimplemented();
//livenessRange->second->setEnd((sint32)blockItr->m_cmdsDepr.size());
}
}
// connect liveness ranges across basic blocks based on their import/export names
std::unordered_map<LocationSymbolName, RALivenessRange_t*> listExportedRanges;
for (uint32 basicBlockIndex = 0; basicBlockIndex < (uint32)irBasicBlocks.size(); basicBlockIndex++)
{
// for each block take all exported ranges and connect them to the imports of the successor blocks
auto& blockItr = irBasicBlocks[basicBlockIndex];
// collect all exported liveness ranges
std::unordered_map<IRReg, RALivenessRange_t*>& localRanges = m_raBlockArray[basicBlockIndex].livenessRanges;
listExportedRanges.clear();
for (auto& regExport : blockItr->m_exports)
{
auto livenessRange = localRanges.find(regExport.reg);
if (livenessRange == localRanges.end())
assert_dbg();
listExportedRanges.emplace(regExport.name, livenessRange->second);
}
// handle imports in the connected blocks
if (blockItr->m_branchTaken)
{
ZpIRBasicBlock* successorBlock = blockItr->m_branchTaken;
std::unordered_map<IRReg, RALivenessRange_t*>& successorRanges = localRanges = m_raBlockArray[basicBlockIndex].livenessRanges;
for (auto& regImport : successorBlock->m_exports)
{
auto livenessRange = successorRanges.find(regImport.reg);
if (livenessRange == successorRanges.end())
assert_dbg();
auto connectedSourceRange = listExportedRanges.find(regImport.name);
if (connectedSourceRange == listExportedRanges.end())
assert_dbg();
livenessRange->second->addSourceFromPreviousBlock(connectedSourceRange->second);
}
}
// handle imports for entry blocks
// todo
// handle export for exit blocks
// todo
}
}
void RARegular::assignPhysicalRegistersForBlock(RABlock_t& raBlock)
{
debugPrint(raBlock);
std::vector<sint32> physRegCandidates;
physRegCandidates.reserve(32);
// process livenessRanges ascending by start address
while (!raBlock.unassignedRanges.empty())
{
RALivenessRange_t* range = *raBlock.unassignedRanges.begin();
// get a list of potential physical registers
std::span<sint32> physReg = extGetSuitablePhysicalRegisters(range->m_irDataType);
physRegCandidates.clear();
for (auto& r : physReg)
physRegCandidates.emplace_back(r);
// try to find a physical register that we can assign to the entire liveness span (current range and all connected ranges)
// todo
// handle special cases like copy coalescing
// todo
// try to find a register for only the current range
filterCandidates(physRegCandidates, range);
if (!physRegCandidates.empty())
{
// pick preferred register
ZpIRPhysicalReg physRegister = extPickPreferredRegister(physRegCandidates);
range->assignPhysicalRegister(physRegister);
continue;
}
// spill is necessary
assert_dbg();
assert_dbg();
}
printf("Assigned:\n");
debugPrint(raBlock);
}
void RARegular::assignPhysicalRegisters()
{
// todo - first we should assign all the fixed registers. E.g. imports/exports, constrained instructions
for (auto& raBlockInfo : m_raBlockArray)
assignPhysicalRegistersForBlock(raBlockInfo);
}
void RARegular::rewrite()
{
for (size_t i = 0; i < m_raBlockArray.size(); i++)
rewriteBlock(*m_irFunction->m_basicBlocks[i], m_raBlockArray[i]);
}
void RARegular::rewriteBlock(ZpIRBasicBlock& basicBlock, RABlock_t& raBlock)
{
assert_dbg();
//std::vector<ZpIRCmd> cmdOut;
//std::unordered_map<ZpIRReg, ZpIRReg> translationTable;
//for (auto& itr : raBlock.livenessRanges)
// translationTable.emplace(itr.second->m_irReg, itr.second->m_physicalRegister);
//// todo - since ir var registers are created in incremental order we could instead use a std::vector for fast look-up instead of a map?
//for (uint32 i = 0; i < (uint32)basicBlock.m_cmdsDepr.size(); i++)
//{
// // todo - insert spill and load instructions
// // todo - insert register moves for range-to-range copies
//
// ZpIRCmd* currentCmd = basicBlock.m_cmdsDepr.data() + i;
// // replace registers and then insert into output command list
// ZpIRCmdUtil::replaceRegisters(*currentCmd, translationTable);
// cmdOut.emplace_back(*currentCmd);
//}
//basicBlock.m_cmdsDepr = std::move(cmdOut);
// todo - should we keep imports/exports but update them to use physical register indices?
// the code emitter needs to know which physical registers are exported in order to determine which optimizations are allowed
basicBlock.m_imports.clear();
basicBlock.m_imports.shrink_to_fit();
basicBlock.m_exports.clear();
basicBlock.m_exports.shrink_to_fit();
basicBlock.m_regs.clear();
basicBlock.m_regs.shrink_to_fit();
}
}
| 10,710
|
C++
|
.cpp
| 276
| 34.887681
| 210
| 0.732397
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,887
|
IR.cpp
|
cemu-project_Cemu/src/util/Zir/Core/IR.cpp
|
#include "util/Zir/Core/IR.h"
#include "util/Zir/Core/ZpIRDebug.h"
#include <cinttypes>
namespace ZpIR
{
const char* getOpcodeName(IR::OpCode opcode)
{
switch (opcode)
{
case IR::OpCode::ADD:
return "ADD";
case IR::OpCode::MOV:
return "MOV";
case IR::OpCode::MUL:
return "MUL";
case IR::OpCode::DIV:
return "DIV";
case IR::OpCode::BITCAST:
return "BITCAST";
case IR::OpCode::SWAP_ENDIAN:
return "SWAP_ENDIAN";
case IR::OpCode::CONVERT_INT_TO_FLOAT:
return "CONV_I2F";
case IR::OpCode::CONVERT_FLOAT_TO_INT:
return "CONV_F2I";
case IR::OpCode::IMPORT_SINGLE:
return "IMPORT_S";
case IR::OpCode::EXPORT:
return "EXPORT";
case IR::OpCode::IMPORT:
return "IMPORT";
default:
cemu_assert_debug(false);
return "UKN";
}
return "";
}
const char* getTypeName(DataType t)
{
switch (t)
{
case DataType::S64:
return "s64";
case DataType::U64:
return "u64";
case DataType::S32:
return "s32";
case DataType::U32:
return "u32";
case DataType::S16:
return "s16";
case DataType::U16:
return "u16";
case DataType::S8:
return "s8";
case DataType::U8:
return "u8";
case DataType::BOOL:
return "bool";
case DataType::POINTER:
return "ptr";
}
return "";
}
std::string DebugPrinter::getRegisterName(ZpIRBasicBlock* block, IRReg r)
{
std::string s;
if ((uint16)r < 0x8000 && m_showPhysicalRegisters)
{
auto& reg = block->m_regs[(uint16)r];
if (!reg.hasAssignedPhysicalRegister())
return "UNASSIGNED";
s = m_getPhysicalRegisterNameCustom(block, reg.physicalRegister);
return s;
}
if ((uint16)r < 0x8000 && m_getRegisterNameCustom)
{
return m_getRegisterNameCustom(block, r);
}
if ((uint16)r >= 0x8000)
{
auto& reg = block->m_consts[(uint16)r & 0x7FFF];
switch (reg.type)
{
case DataType::POINTER:
return fmt::format("ptr:{}", reg.value_ptr);
case DataType::U64:
{
if(reg.value_u64 >= 0x1000)
return fmt::format("u64:0x{0:x}", reg.value_u64);
return fmt::format("u64:{}", reg.value_u64);
}
case DataType::U32:
return fmt::format("u32:{}", reg.value_u32);
case DataType::S32:
return fmt::format("s32:{}", reg.value_u32);
case DataType::F32:
return fmt::format("f32:{}", reg.value_f32);
default:
break;
}
return "ukn_const_type";
}
else
{
auto& reg = block->m_regs[(uint16)r];
const char* regLetter = "r";
switch (reg.type)
{
case DataType::U64:
regLetter = "uq"; // quad-word
break;
case DataType::U32:
regLetter = "ud"; // double-word
break;
case DataType::U16:
regLetter = "uw"; // word
break;
case DataType::U8:
regLetter = "uc"; // char
break;
case DataType::S64:
regLetter = "sq"; // signed quad-word
break;
case DataType::S32:
regLetter = "sd"; // signed double-word
break;
case DataType::S16:
regLetter = "sw"; // signed word
break;
case DataType::S8:
regLetter = "sc"; // signed char
break;
case DataType::F32:
regLetter = "fv"; // 32bit float
break;
case DataType::POINTER:
regLetter = "ptr";
break;
default:
assert_dbg();
}
if (reg.elementCount != 1)
assert_dbg();
s = fmt::format("{}{}", regLetter, (uint16)r);
}
return s;
}
std::string DebugPrinter::getInstructionHRF(ZpIRBasicBlock* block, IR::__InsBase* cmd)
{
if (auto ins = IR::InsRR::getIfForm(cmd))
{
return fmt::format("{:<10} {}, {}", getOpcodeName(cmd->opcode), getRegisterName(block, ins->rA), getRegisterName(block, ins->rB));
}
else if (auto ins = IR::InsRRR::getIfForm(cmd))
{
return fmt::format("{:<10} {}, {}, {}", getOpcodeName(cmd->opcode), getRegisterName(block, ins->rA), getRegisterName(block, ins->rB), getRegisterName(block, ins->rC));
}
else if (auto ins = IR::InsEXPORT::getIfForm(cmd))
{
if (ins->count == 4)
return fmt::format("{:<10} {}, {}, {}, {}, loc: {}", getOpcodeName(cmd->opcode), getRegisterName(block, ins->regArray[0]), getRegisterName(block, ins->regArray[1]), getRegisterName(block, ins->regArray[2]), getRegisterName(block, ins->regArray[3]), ins->exportSymbol);
else if (ins->count == 3)
return fmt::format("{:<10} {}, {}, {}, loc: {}", getOpcodeName(cmd->opcode), getRegisterName(block, ins->regArray[0]), getRegisterName(block, ins->regArray[1]), getRegisterName(block, ins->regArray[2]), ins->exportSymbol);
else if (ins->count == 2)
return fmt::format("{:<10} {}, {}, loc: {}", getOpcodeName(cmd->opcode), getRegisterName(block, ins->regArray[0]), getRegisterName(block, ins->regArray[1]), ins->exportSymbol);
else if (ins->count == 1)
return fmt::format("{:<10} {}, loc: {}", getOpcodeName(cmd->opcode), getRegisterName(block, ins->regArray[0]), ins->exportSymbol);
assert_dbg();
}
else if (auto ins = IR::InsIMPORT::getIfForm(cmd))
{
ShaderSubset::ShaderImportLocation importLocation = ins->importSymbol;
std::string locDebugName = importLocation.GetDebugName();
if (ins->count == 4)
return fmt::format("{:<10} {}, {}, {}, {}, loc: {}", getOpcodeName(cmd->opcode), getRegisterName(block, ins->regArray[0]), getRegisterName(block, ins->regArray[1]), getRegisterName(block, ins->regArray[2]), getRegisterName(block, ins->regArray[3]), locDebugName);
else if (ins->count == 3)
return fmt::format("{:<10} {}, {}, {}, loc: {}", getOpcodeName(cmd->opcode), getRegisterName(block, ins->regArray[0]), getRegisterName(block, ins->regArray[1]), getRegisterName(block, ins->regArray[2]), locDebugName);
else if (ins->count == 2)
return fmt::format("{:<10} {}, {}, loc: {}", getOpcodeName(cmd->opcode), getRegisterName(block, ins->regArray[0]), getRegisterName(block, ins->regArray[1]), locDebugName);
else if (ins->count == 1)
return fmt::format("{:<10} {}, loc: {}", getOpcodeName(cmd->opcode), getRegisterName(block, ins->regArray[0]), locDebugName);
assert_dbg();
}
else
assert_dbg();
return "";
}
void DebugPrinter::debugPrintBlock(ZpIRBasicBlock* block)
{
// print name
printf("IRBasicBlock %" PRIxPTR "\n", (uintptr_t)block);
// print imports
printf("Imports:\n");
for(auto itr : block->m_imports)
printf(" reg: %s sym:0x%llx\n", getRegisterName(block, itr.reg).c_str(), itr.name);
// print exports
printf("Exports:\n");
for (auto itr : block->m_exports)
printf(" reg: %s sym:0x%llx\n", getRegisterName(block, itr.reg).c_str(), itr.name);
// print instructions
printf("Assembly:\n");
IR::__InsBase* instruction = block->m_instructionFirst;
size_t i = 0;
while(instruction)
{
std::string s = getInstructionHRF(block, instruction);
printf("%04x %s\n", (unsigned int)i, s.c_str());
i++;
instruction = instruction->next;
}
}
void DebugPrinter::debugPrint(ZpIRFunction* irFunction)
{
printf("--- Print IR function assembly ---\n");
for (auto& itr : irFunction->m_basicBlocks)
{
debugPrintBlock(itr);
printf("\n");
}
}
}
| 6,989
|
C++
|
.cpp
| 222
| 27.806306
| 272
| 0.6516
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,888
|
VirtualHeap.cpp
|
cemu-project_Cemu/src/util/VirtualHeap/VirtualHeap.cpp
|
#include "VirtualHeap.h"
VirtualBufferHeap_t* virtualBufferHeap_create(uint32 virtualHeapSize, void* baseAddr)
{
VirtualBufferHeap_t* bufferHeap = (VirtualBufferHeap_t*)malloc(sizeof(VirtualBufferHeap_t));
memset(bufferHeap, 0, sizeof(VirtualBufferHeap_t));
bufferHeap->firstEntry = nullptr;
virtualHeapSize = (virtualHeapSize + 31)&~31;
bufferHeap->virtualSize = virtualHeapSize;
bufferHeap->baseAddress = baseAddr;
bufferHeap->updateTrackIndex = 0;
// create pool of unused entries
sint32 unusedEntryPoolSize = 1024 * 16;
VirtualBufferHeapEntry_t* unusedEntryPool = (VirtualBufferHeapEntry_t*)malloc(sizeof(VirtualBufferHeapEntry_t)*unusedEntryPoolSize);
for (sint32 i = 0; i < unusedEntryPoolSize - 1; i++)
{
unusedEntryPool[i].next = unusedEntryPool + i + 1;
}
unusedEntryPool[unusedEntryPoolSize - 1].next = nullptr;
bufferHeap->firstUnusedEntry = unusedEntryPool + 0;
return bufferHeap;
}
VirtualBufferHeapEntry_t* virtualBufferHeap_createEntry(VirtualBufferHeap_t* bufferHeap)
{
VirtualBufferHeapEntry_t* newEntry = bufferHeap->firstUnusedEntry;
if (newEntry == nullptr)
{
cemuLog_log(LogType::Force, "virtualBufferHeap_createEntry: Pool empty");
cemu_assert_suspicious();
}
bufferHeap->firstUnusedEntry = newEntry->next;
newEntry->previous = NULL;
newEntry->next = NULL;
return newEntry;
}
void virtualBufferHeap_releaseEntry(VirtualBufferHeap_t* bufferHeap, VirtualBufferHeapEntry_t* entry)
{
bufferHeap->stats.allocatedMemory -= (entry->endOffset - entry->startOffset);
bufferHeap->stats.numActiveAllocs--;
entry->next = bufferHeap->firstUnusedEntry;
bufferHeap->firstUnusedEntry = entry;
}
// Allocate memory region from virtual heap. Always allocates memory at the lowest possible address
VirtualBufferHeapEntry_t* virtualBufferHeap_allocate(VirtualBufferHeap_t* bufferHeap, uint32 size)
{
// align size
size = (size + 255)&~255;
// iterate already allocated entries and try to find free space between them
VirtualBufferHeapEntry_t* entryItr = bufferHeap->firstEntry;
if (entryItr == NULL)
{
// entire heap is unallocated
VirtualBufferHeapEntry_t* newEntry = virtualBufferHeap_createEntry(bufferHeap);
newEntry->startOffset = 0;
newEntry->endOffset = size;
newEntry->previous = NULL;
newEntry->next = NULL;
bufferHeap->firstEntry = newEntry;
bufferHeap->stats.allocatedMemory += size;
bufferHeap->stats.numActiveAllocs++;
return newEntry;
}
else
{
uint32 currentAllocationOffset = 0;
VirtualBufferHeapEntry_t* entryPrev = nullptr;
while (entryItr)
{
if ((currentAllocationOffset + size) > entryItr->startOffset)
{
// space occupied
currentAllocationOffset = entryItr->endOffset;
currentAllocationOffset = (currentAllocationOffset + 255)&~255;
// next
entryPrev = entryItr;
entryItr = entryItr->next;
continue;
}
else
{
if ((currentAllocationOffset + size) > bufferHeap->virtualSize)
return nullptr; // out of heap memory
// free space found
VirtualBufferHeapEntry_t* newEntry = virtualBufferHeap_createEntry(bufferHeap);
newEntry->startOffset = currentAllocationOffset;
newEntry->endOffset = currentAllocationOffset + size;
// insert between previous entry and entryItr
newEntry->previous = entryItr->previous;
newEntry->next = entryItr;
if (entryItr->previous)
entryItr->previous->next = newEntry;
else
bufferHeap->firstEntry = newEntry;
entryItr->previous = newEntry;
bufferHeap->stats.allocatedMemory += size;
bufferHeap->stats.numActiveAllocs++;
return newEntry;
}
}
// add after entryPrev
if ((currentAllocationOffset + size) > bufferHeap->virtualSize)
return NULL; // out of heap memory
VirtualBufferHeapEntry_t* newEntry = virtualBufferHeap_createEntry(bufferHeap);
newEntry->startOffset = currentAllocationOffset;
newEntry->endOffset = currentAllocationOffset + size;
// insert after previous entry
cemu_assert_debug(entryPrev);
cemu_assert_debug(entryPrev->next == nullptr);
newEntry->previous = entryPrev;
newEntry->next = entryPrev->next;
entryPrev->next = newEntry;
bufferHeap->stats.allocatedMemory += size;
bufferHeap->stats.numActiveAllocs++;
return newEntry;
}
return NULL;
}
void virtualBufferHeap_free(VirtualBufferHeap_t* bufferHeap, VirtualBufferHeapEntry_t* entry)
{
if (entry->previous == NULL)
{
// make the next entry the first one
if (entry->next)
entry->next->previous = NULL;
bufferHeap->firstEntry = entry->next;
}
else
entry->previous->next = entry->next;
if (entry->next)
entry->next->previous = entry->previous;
// release entry
virtualBufferHeap_releaseEntry(bufferHeap, entry);
}
void* virtualBufferHeap_allocateAddr(VirtualBufferHeap_t* bufferHeap, uint32 size)
{
VirtualBufferHeapEntry_t* heapEntry = virtualBufferHeap_allocate(bufferHeap, size);
return ((uint8*)bufferHeap->baseAddress + heapEntry->startOffset);
}
void virtualBufferHeap_freeAddr(VirtualBufferHeap_t* bufferHeap, void* addr)
{
auto entry = bufferHeap->firstEntry;
while(entry)
{
const auto entry_address = (uint8*)bufferHeap->baseAddress + entry->startOffset;
if(entry_address == (uint8*)addr)
{
virtualBufferHeap_free(bufferHeap, entry);
return;
}
entry = entry->next;
}
cemu_assert_suspicious();
}
| 5,289
|
C++
|
.cpp
| 152
| 31.993421
| 133
| 0.767791
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,889
|
Serializer.cpp
|
cemu-project_Cemu/src/util/helpers/Serializer.cpp
|
#include "Serializer.h"
template<>
uint8 MemStreamReader::readBE()
{
if (!reserveReadLength(sizeof(uint8)))
return 0;
uint8 v = m_data[m_cursorPos];
m_cursorPos += sizeof(uint8);
return v;
}
template<>
uint16 MemStreamReader::readBE()
{
if (!reserveReadLength(sizeof(uint16)))
return 0;
const uint8* p = m_data + m_cursorPos;
uint16 v;
std::memcpy(&v, p, sizeof(v));
v = _BE(v);
m_cursorPos += sizeof(uint16);
return v;
}
template<>
uint32 MemStreamReader::readBE()
{
if (!reserveReadLength(sizeof(uint32)))
return 0;
const uint8* p = m_data + m_cursorPos;
uint32 v;
std::memcpy(&v, p, sizeof(v));
v = _BE(v);
m_cursorPos += sizeof(uint32);
return v;
}
template<>
uint64 MemStreamReader::readBE()
{
if (!reserveReadLength(sizeof(uint64)))
return 0;
const uint8* p = m_data + m_cursorPos;
uint64 v;
std::memcpy(&v, p, sizeof(v));
v = _BE(v);
m_cursorPos += sizeof(uint64);
return v;
}
template<>
std::string MemStreamReader::readBE()
{
std::string s;
uint32 stringSize = readBE<uint32>();
if (hasError())
return s;
if (stringSize >= (32 * 1024 * 1024))
{
// out of bounds read or suspiciously large string
m_hasError = true;
return std::string();
}
s.resize(stringSize);
readData(s.data(), stringSize);
return s;
}
template<>
uint8 MemStreamReader::readLE()
{
return readBE<uint8>();
}
template<>
uint32 MemStreamReader::readLE()
{
if (!reserveReadLength(sizeof(uint32)))
return 0;
const uint8* p = m_data + m_cursorPos;
uint32 v;
std::memcpy(&v, p, sizeof(v));
v = _LE(v);
m_cursorPos += sizeof(uint32);
return v;
}
template<>
uint64 MemStreamReader::readLE()
{
if (!reserveReadLength(sizeof(uint64)))
return 0;
const uint8* p = m_data + m_cursorPos;
uint64 v;
std::memcpy(&v, p, sizeof(v));
v = _LE(v);
m_cursorPos += sizeof(uint64);
return v;
}
template<>
void MemStreamWriter::writeBE<uint64>(const uint64& v)
{
m_buffer.resize(m_buffer.size() + 8);
uint8* p = m_buffer.data() + m_buffer.size() - 8;
uint64 tmp = _BE(v);
std::memcpy(p, &tmp, sizeof(tmp));
}
template<>
void MemStreamWriter::writeBE<uint32>(const uint32& v)
{
m_buffer.resize(m_buffer.size() + 4);
uint8* p = m_buffer.data() + m_buffer.size() - 4;
uint32 tmp = _BE(v);
std::memcpy(p, &tmp, sizeof(tmp));
}
template<>
void MemStreamWriter::writeBE<uint16>(const uint16& v)
{
m_buffer.resize(m_buffer.size() + 2);
uint8* p = m_buffer.data() + m_buffer.size() - 2;
uint16 tmp = _BE(v);
std::memcpy(p, &tmp, sizeof(tmp));
}
template<>
void MemStreamWriter::writeBE<uint8>(const uint8& v)
{
m_buffer.emplace_back(v);
}
template<>
void MemStreamWriter::writeBE<std::string>(const std::string& v)
{
writeBE<uint32>((uint32)v.size());
writeData(v.data(), v.size());
}
template<>
void MemStreamWriter::writeLE<uint64>(const uint64& v)
{
m_buffer.resize(m_buffer.size() + 8);
uint8* p = m_buffer.data() + m_buffer.size() - 8;
uint64 tmp = _LE(v);
std::memcpy(p, &tmp, sizeof(tmp));
}
template<>
void MemStreamWriter::writeLE<uint32>(const uint32& v)
{
m_buffer.resize(m_buffer.size() + 4);
uint8* p = m_buffer.data() + m_buffer.size() - 4;
uint32 tmp = _LE(v);
std::memcpy(p, &tmp, sizeof(tmp));
}
| 3,167
|
C++
|
.cpp
| 143
| 20.377622
| 64
| 0.689953
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,890
|
helpers.cpp
|
cemu-project_Cemu/src/util/helpers/helpers.cpp
|
#include "helpers.h"
#include <algorithm>
#include <functional>
#include <cctype>
#include <random>
#include <wx/translation.h>
#include "config/ActiveSettings.h"
#include <boost/random/uniform_int.hpp>
#include <zlib.h>
#if BOOST_OS_WINDOWS
#include <TlHelp32.h>
#endif
std::string& ltrim(std::string& str, const std::string& chars)
{
str.erase(0, str.find_first_not_of(chars));
return str;
}
std::string& rtrim(std::string& str, const std::string& chars)
{
str.erase(str.find_last_not_of(chars) + 1);
return str;
}
std::string& trim(std::string& str, const std::string& chars)
{
return ltrim(rtrim(str, chars), chars);
}
std::string_view& ltrim(std::string_view& str, const std::string& chars)
{
str.remove_prefix(std::min(str.find_first_not_of(chars), str.size()));
return str;
}
std::string_view& rtrim(std::string_view& str, const std::string& chars)
{
str.remove_suffix(std::max(str.size() - str.find_last_not_of(chars) - 1, (size_t)0));
return str;
}
std::string_view& trim(std::string_view& str, const std::string& chars)
{
return ltrim(rtrim(str, chars), chars);
}
#if BOOST_OS_WINDOWS
std::wstring GetSystemErrorMessageW()
{
return GetSystemErrorMessageW(GetLastError());
}
std::wstring GetSystemErrorMessageW(DWORD error_code)
{
if(error_code == ERROR_SUCCESS)
return {};
LPWSTR lpMsgBuf = nullptr;
FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, error_code, 0, (LPWSTR)&lpMsgBuf, 0, nullptr);
if (lpMsgBuf)
{
std::wstring str = fmt::format(L"{}: {}", _("Error").ToStdWstring(), lpMsgBuf); // TRANSLATE
LocalFree(lpMsgBuf);
return str;
}
return fmt::format(L"{}: {:#x}", _("Error code").ToStdWstring(), error_code);
}
std::string GetSystemErrorMessage(DWORD error_code)
{
if(error_code == ERROR_SUCCESS)
return {};
LPSTR lpMsgBuf = nullptr;
FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, error_code, 0, (LPSTR)&lpMsgBuf, 0, nullptr);
if (lpMsgBuf)
{
std::string str = fmt::format("{}: {}", _("Error").ToStdString(), lpMsgBuf); // TRANSLATE
LocalFree(lpMsgBuf);
return str;
}
return fmt::format("{}: {:#x}", _("Error code").ToStdString(), error_code);
}
std::string GetSystemErrorMessage()
{
return GetSystemErrorMessage(GetLastError());
}
#else
std::string GetSystemErrorMessage()
{
return "";
}
#endif
std::string GetSystemErrorMessage(const std::exception& ex)
{
const std::string msg = GetSystemErrorMessage();
if(msg.empty())
return ex.what();
return fmt::format("{}\n{}",msg, ex.what());
}
std::string GetSystemErrorMessage(const std::error_code& ec)
{
const std::string msg = GetSystemErrorMessage();
if(msg.empty())
return ec.message();
return fmt::format("{}\n{}",msg, ec.message());
}
#if BOOST_OS_WINDOWS
const DWORD MS_VC_EXCEPTION = 0x406D1388;
#pragma pack(push,8)
typedef struct tagTHREADNAME_INFO
{
DWORD dwType; // Must be 0x1000.
LPCSTR szName; // Pointer to name (in user addr space).
DWORD dwThreadID; // Thread ID (-1=caller thread).
DWORD dwFlags; // Reserved for future use, must be zero.
} THREADNAME_INFO;
#pragma pack(pop)
#endif
void SetThreadName(const char* name)
{
#if BOOST_OS_WINDOWS
THREADNAME_INFO info;
info.dwType = 0x1000;
info.szName = name;
info.dwThreadID = GetCurrentThreadId();
info.dwFlags = 0;
#pragma warning(push)
#pragma warning(disable: 6320 6322)
__try {
RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(ULONG_PTR), (ULONG_PTR*)&info);
}
__except (EXCEPTION_EXECUTE_HANDLER) {
}
#pragma warning(pop)
#elif BOOST_OS_MACOS
pthread_setname_np(name);
#else
if(std::strlen(name) > 15)
cemuLog_log(LogType::Force, "Truncating thread name {} because it was longer than 15 characters", name);
pthread_setname_np(pthread_self(), std::string{name}.substr(0,15).c_str());
#endif
}
#if BOOST_OS_WINDOWS
std::pair<DWORD, DWORD> GetWindowsVersion()
{
using RtlGetVersion_t = LONG(*)(POSVERSIONINFOEXW);
static RtlGetVersion_t pRtlGetVersion = nullptr;
if(!pRtlGetVersion)
pRtlGetVersion = (RtlGetVersion_t)GetProcAddress(GetModuleHandleA("ntdll.dll"), "RtlGetVersion");
cemu_assert(pRtlGetVersion);
OSVERSIONINFOEXW version_info{};
pRtlGetVersion(&version_info);
return { version_info.dwMajorVersion, version_info.dwMinorVersion };
}
bool IsWindows81OrGreater()
{
const auto [major, minor] = GetWindowsVersion();
return major > 6 || (major == 6 && minor >= 3);
}
bool IsWindows10OrGreater()
{
const auto [major, minor] = GetWindowsVersion();
return major >= 10;
}
#endif
fs::path GetParentProcess()
{
fs::path result;
#if BOOST_OS_WINDOWS
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if(hSnapshot != INVALID_HANDLE_VALUE)
{
DWORD pid = GetCurrentProcessId();
PROCESSENTRY32 pe{};
pe.dwSize = sizeof(pe);
for(BOOL ret = Process32First(hSnapshot, &pe); ret; ret = Process32Next(hSnapshot, &pe))
{
if(pe.th32ProcessID == pid)
{
HANDLE hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pe.th32ParentProcessID);
if(hProcess)
{
wchar_t tmp[MAX_PATH];
DWORD size = std::size(tmp);
if (QueryFullProcessImageNameW(hProcess, 0, tmp, &size) && size > 0)
result = tmp;
CloseHandle(hProcess);
}
break;
}
}
CloseHandle(hSnapshot);
}
#else
assert_dbg();
#endif
return result;
}
std::string ltrim_copy(const std::string& s)
{
std::string result = s;
ltrim(result);
return result;
}
std::string rtrim_copy(const std::string& s)
{
std::string result = s;
rtrim(result);
return result;
}
uint32_t GetPhysicalCoreCount()
{
static uint32_t s_core_count = 0;
if (s_core_count != 0)
return s_core_count;
#if BOOST_OS_WINDOWS
auto core_count = std::thread::hardware_concurrency();
// Get physical cores
PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer = nullptr;
DWORD returnLength = 0;
GetLogicalProcessorInformation(buffer, &returnLength);
if (returnLength > 0)
{
buffer = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION)malloc(returnLength);
if (GetLogicalProcessorInformation(buffer, &returnLength))
{
uint32_t counter = 0;
for (DWORD i = 0; i < returnLength / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION); ++i)
{
if (buffer[i].Relationship == RelationProcessorCore)
++counter;
}
if (counter > 0 && counter < core_count)
core_count = counter;
}
free(buffer);
}
s_core_count = core_count;
return core_count;
#else
return std::thread::hardware_concurrency();
#endif
}
bool TestWriteAccess(const fs::path& p)
{
std::error_code ec;
// must be path and must exist
if (!fs::exists(p, ec) || !fs::is_directory(p, ec))
return false;
// retry 3 times
for (int i = 0; i < 3; ++i)
{
const auto filename = p / fmt::format("_{}.tmp", GenerateRandomString(8));
if (fs::exists(filename, ec))
continue;
std::ofstream file(filename);
if (!file.is_open()) // file couldn't be created
break;
file.close();
fs::remove(filename, ec);
return true;
}
return false;
}
// make path relative to Cemu directory
fs::path MakeRelativePath(const fs::path& base, const fs::path& path)
{
try
{
return fs::relative(path, base);
}
catch (const std::exception&)
{
return path;
}
}
#ifdef HAS_DIRECTINPUT
bool GUIDFromString(const char* string, GUID& guid)
{
unsigned long p0;
int p1, p2, p3, p4, p5, p6, p7, p8, p9, p10;
const sint32 count = sscanf_s(string, "%08lX-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X", &p0, &p1, &p2, &p3, &p4, &p5, &p6, &p7, &p8, &p9, &p10);
if (count != 11)
return false;
guid.Data1 = p0;
guid.Data2 = p1;
guid.Data3 = p2;
guid.Data4[0] = p3;
guid.Data4[1] = p4;
guid.Data4[2] = p5;
guid.Data4[3] = p6;
guid.Data4[4] = p7;
guid.Data4[5] = p8;
guid.Data4[6] = p9;
guid.Data4[7] = p10;
return count == 11;
}
std::string StringFromGUID(const GUID& guid)
{
char temp[256];
sprintf(temp, "%08lX-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X",
guid.Data1, guid.Data2, guid.Data3,
guid.Data4[0], guid.Data4[1], guid.Data4[2], guid.Data4[3], guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]);
return std::string(temp);
}
std::wstring WStringFromGUID(const GUID& guid)
{
wchar_t temp[256];
swprintf_s(temp, L"%08lX-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X",
guid.Data1, guid.Data2, guid.Data3,
guid.Data4[0], guid.Data4[1], guid.Data4[2], guid.Data4[3], guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]);
return std::wstring(temp);
}
#endif
std::vector<std::string_view> TokenizeView(std::string_view str, char delimiter)
{
std::vector<std::string_view> result;
size_t last_token_index = 0;
for (auto index = str.find(delimiter); index != std::string_view::npos; index = str.find(delimiter, index + 1))
{
const auto token = str.substr(last_token_index, index - last_token_index);
result.emplace_back(token);
last_token_index = index + 1;
}
try
{
const auto token = str.substr(last_token_index);
result.emplace_back(token);
}
catch (const std::invalid_argument&) {}
return result;
}
std::vector<std::string> Tokenize(std::string_view str, char delimiter)
{
std::vector<std::string> result;
size_t last_token_index = 0;
for (auto index = str.find(delimiter); index != std::string_view::npos; index = str.find(delimiter, index + 1))
{
const auto token = str.substr(last_token_index, index - last_token_index);
result.emplace_back(token);
last_token_index = index + 1;
}
try
{
const auto token = str.substr(last_token_index);
result.emplace_back(token);
}
catch (const std::invalid_argument&) {}
return result;
}
std::string GenerateRandomString(size_t length)
{
const std::string kCharacters{
"abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"1234567890" };
return GenerateRandomString(length, kCharacters);
}
std::string GenerateRandomString(const size_t length, const std::string_view characters)
{
assert(!characters.empty());
std::string result;
result.resize(length);
std::random_device rd;
std::mt19937 gen(rd());
// workaround for static asserts using boost
boost::random::uniform_int_distribution<decltype(characters.size())> index_dist(0, characters.size() - 1);
std::generate_n(
result.begin(),
length,
[&] { return characters[index_dist(gen)]; }
);
return result;
}
std::optional<std::vector<uint8>> zlibDecompress(const std::vector<uint8>& compressed, size_t sizeHint)
{
int err;
std::vector<uint8> decompressed;
size_t outWritten = 0;
size_t bytesPerIteration = sizeHint;
z_stream stream;
stream.zalloc = Z_NULL;
stream.zfree = Z_NULL;
stream.opaque = Z_NULL;
stream.avail_in = compressed.size();
stream.next_in = (Bytef*)compressed.data();
err = inflateInit2(&stream, 32); // 32 is a zlib magic value to enable header detection
if (err != Z_OK)
return {};
do
{
decompressed.resize(decompressed.size() + bytesPerIteration);
const auto availBefore = decompressed.size() - outWritten;
stream.avail_out = availBefore;
stream.next_out = decompressed.data() + outWritten;
err = inflate(&stream, Z_NO_FLUSH);
if (!(err == Z_OK || err == Z_STREAM_END))
{
inflateEnd(&stream);
return {};
}
outWritten += availBefore - stream.avail_out;
bytesPerIteration *= 2;
}
while (err != Z_STREAM_END);
inflateEnd(&stream);
decompressed.resize(stream.total_out);
return decompressed;
}
| 11,404
|
C++
|
.cpp
| 400
| 26.2175
| 164
| 0.716644
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,891
|
SystemInfoWin.cpp
|
cemu-project_Cemu/src/util/SystemInfo/SystemInfoWin.cpp
|
#include "util/SystemInfo/SystemInfo.h"
#include <Psapi.h>
#include <winternl.h>
#pragma comment(lib, "ntdll.lib")
uint64 QueryRamUsage()
{
PROCESS_MEMORY_COUNTERS pmc{};
pmc.cb = sizeof(pmc);
if (GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc)))
{
return pmc.WorkingSetSize;
}
else
{
return 0;
}
}
void QueryProcTime(uint64 &out_now, uint64 &out_user, uint64 &out_kernel)
{
FILETIME ftime, fkernel, fuser;
LARGE_INTEGER now, kernel, user;
GetSystemTimeAsFileTime(&ftime);
now.LowPart = ftime.dwLowDateTime;
now.HighPart = ftime.dwHighDateTime;
if (GetProcessTimes(GetCurrentProcess(), &ftime, &ftime, &fkernel, &fuser))
{
kernel.LowPart = fkernel.dwLowDateTime;
kernel.HighPart = fkernel.dwHighDateTime;
user.LowPart = fuser.dwLowDateTime;
user.HighPart = fuser.dwHighDateTime;
out_now = now.QuadPart;
out_user = user.QuadPart;
out_kernel = kernel.QuadPart;
}
else
{
out_now = 0;
out_user = 0;
out_kernel = 0;
}
}
void QueryCoreTimes(uint32 count, std::vector<ProcessorTime>& out)
{
std::vector<SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION> sppi(count);
if (NT_SUCCESS(NtQuerySystemInformation(SystemProcessorPerformanceInformation, sppi.data(), sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION) * count, nullptr)))
{
for (auto i = 0; i < out.size(); ++i)
{
out[i].idle = sppi[i].IdleTime.QuadPart;
out[i].kernel = sppi[i].KernelTime.QuadPart;
out[i].kernel -= out[i].idle;
out[i].user = sppi[i].UserTime.QuadPart;
}
}
else
{
for (auto i = 0; i < count; ++i)
{
out[i] = { };
}
}
}
| 1,573
|
C++
|
.cpp
| 62
| 23.016129
| 161
| 0.722739
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,892
|
SystemInfoLinux.cpp
|
cemu-project_Cemu/src/util/SystemInfo/SystemInfoLinux.cpp
|
#include "util/SystemInfo/SystemInfo.h"
#include <unistd.h>
uint64 QueryRamUsage()
{
static long page_size = sysconf(_SC_PAGESIZE);
if (page_size == -1)
{
return 0;
}
std::ifstream file("/proc/self/statm");
if (file)
{
file.ignore(std::numeric_limits<std::streamsize>::max(), ' ');
uint64 pages;
file >> pages;
return pages * page_size;
}
return 0;
}
void QueryCoreTimes(uint32 count, std::vector<ProcessorTime>& out)
{
std::ifstream file("/proc/stat");
if (file)
{
file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
for (auto i = 0; i < out.size(); ++i)
{
uint64 user, nice, kernel, idle;
file.ignore(std::numeric_limits<std::streamsize>::max(), ' ');
file >> user >> nice >> kernel >> idle;
file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
out[i].idle = idle;
out[i].kernel = kernel;
out[i].user = user + nice;
}
}
else
{
for (auto i = 0; i < count; ++i) out[i] = { };
}
}
| 967
|
C++
|
.cpp
| 41
| 21.02439
| 66
| 0.634385
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,893
|
SystemInfoMac.cpp
|
cemu-project_Cemu/src/util/SystemInfo/SystemInfoMac.cpp
|
#include "util/SystemInfo/SystemInfo.h"
#include <unistd.h>
#include <sys/resource.h>
#include <sys/sysctl.h>
#include <sys/types.h>
#include <mach/mach.h>
#include <mach/processor_info.h>
#include <mach/mach_host.h>
#include <mach/kern_return.h>
// borrowed from https://en.wikichip.org/wiki/resident_set_size#OS_X
uint64 QueryRamUsage()
{
mach_task_basic_info info;
mach_msg_type_number_t count = MACH_TASK_BASIC_INFO_COUNT;
if (task_info(mach_task_self(), MACH_TASK_BASIC_INFO, (task_info_t)&info, &count) == KERN_SUCCESS)
return info.resident_size;
return 0;
}
// apple official documentation is non-existsent.
// based on https://github.com/giampaolo/psutil/blob/master/psutil/_psutil_osx.c#L623
void QueryCoreTimes(uint32 count, std::vector<ProcessorTime>& out)
{
// initialize default
for (auto i = 0; i < out.size(); ++i)
{
out[i] = {};
}
natural_t cpu_count;
processor_info_array_t info_array;
mach_msg_type_number_t info_count;
kern_return_t error;
mach_port_t host_port = mach_host_self();
error = host_processor_info(host_port, PROCESSOR_CPU_LOAD_INFO, &cpu_count, &info_array, &info_count);
mach_port_deallocate(mach_task_self(), host_port);
if (error != KERN_SUCCESS)
return;
processor_cpu_load_info_data_t* cpuLoad = (processor_cpu_load_info_data_t*) info_array;
for (auto i = 0; i < cpu_count; ++i)
{
uint64 system = cpuLoad[i].cpu_ticks[CPU_STATE_SYSTEM];
uint64 user = cpuLoad[i].cpu_ticks[CPU_STATE_USER] + cpuLoad[i].cpu_ticks[CPU_STATE_NICE];
uint64 idle = cpuLoad[i].cpu_ticks[CPU_STATE_IDLE];
out[i].idle = idle;
out[i].kernel = system;
out[i].user = user;
}
int ret = vm_deallocate(mach_task_self(), (vm_address_t) info_array,
info_count * sizeof(int));
if (ret != KERN_SUCCESS)
cemuLog_log(LogType::Force, "vm_deallocate() failed");
}
| 1,819
|
C++
|
.cpp
| 51
| 33.509804
| 103
| 0.71827
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,894
|
SystemInfoUnix.cpp
|
cemu-project_Cemu/src/util/SystemInfo/SystemInfoUnix.cpp
|
#include "util/SystemInfo/SystemInfo.h"
#include <sys/times.h>
void QueryProcTime(uint64 &out_now, uint64 &out_user, uint64 &out_kernel)
{
struct tms time_info;
clock_t clock_now = times(&time_info);
clock_t clock_user = time_info.tms_utime;
clock_t clock_kernel = time_info.tms_stime;
out_now = static_cast<uint64>(clock_now);
out_user = static_cast<uint64>(clock_user);
out_kernel = static_cast<uint64>(clock_kernel);
}
| 432
|
C++
|
.cpp
| 12
| 34.166667
| 73
| 0.745803
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,895
|
SystemInfoStub.cpp
|
cemu-project_Cemu/src/util/SystemInfo/SystemInfoStub.cpp
|
#include "util/SystemInfo/SystemInfo.h"
uint64 QueryRamUsage()
{
return 0;
}
void QueryProcTime(uint64 &out_now, uint64 &out_user, uint64 &out_kernel)
{
out_now = 0;
out_user = 0;
out_kernel = 0;
}
void QueryCoreTimes(uint32 count, std::vector<ProcessorTime>& out)
{
for (auto i = 0; i < out.size(); ++i)
{
out[i] = { };
}
}
| 337
|
C++
|
.cpp
| 18
| 17.055556
| 73
| 0.683544
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,896
|
SystemInfo.cpp
|
cemu-project_Cemu/src/util/SystemInfo/SystemInfo.cpp
|
#include "util/SystemInfo/SystemInfo.h"
uint64 ProcessorTime::work()
{
return user + kernel;
}
uint64 ProcessorTime::total()
{
return idle + user + kernel;
}
double ProcessorTime::Compare(ProcessorTime &last, ProcessorTime &now)
{
auto dwork = now.work() - last.work();
auto dtotal = now.total() - last.total();
return (double)dwork / dtotal;
}
uint32 GetProcessorCount()
{
return std::thread::hardware_concurrency();
}
void QueryProcTime(ProcessorTime &out)
{
uint64 now, user, kernel;
QueryProcTime(now, user, kernel);
out.idle = now - (user + kernel);
out.kernel = kernel;
out.user = user;
}
| 612
|
C++
|
.cpp
| 27
| 21.037037
| 70
| 0.740933
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,897
|
ControllerFactory.cpp
|
cemu-project_Cemu/src/input/ControllerFactory.cpp
|
#include "input/ControllerFactory.h"
#include "input/emulated/VPADController.h"
#include "input/emulated/ProController.h"
#include "input/emulated/ClassicController.h"
#include "input/emulated/WiimoteController.h"
#include "input/api/SDL/SDLController.h"
#include "input/api/Keyboard/KeyboardController.h"
#include "input/api/DSU/DSUController.h"
#include "input/api/GameCube/GameCubeController.h"
#if BOOST_OS_WINDOWS
#include "input/api/XInput/XInputController.h"
#include "input/api/DirectInput/DirectInputController.h"
#endif
#if HAS_WIIMOTE
#include "input/api/Wiimote/NativeWiimoteController.h"
#endif
ControllerPtr ControllerFactory::CreateController(InputAPI::Type api, std::string_view uuid,
std::string_view display_name)
{
switch (api)
{
#if HAS_KEYBOARD
case InputAPI::Keyboard:
return std::make_shared<KeyboardController>();
#endif
#if HAS_DIRECTINPUT
case InputAPI::DirectInput:
{
GUID guid;
// Workaround for mouse2joystick users, which has 0 as it's uuid in it's profile and counts on Cemu applying it to the first directinput controller. GUIDFromString also doesn't allow for invalid uuids either.
if (uuid == "0")
{
const auto provider = InputManager::instance().get_api_provider(InputAPI::DirectInput);
const auto controllers = provider->get_controllers();
if (controllers.empty())
throw std::invalid_argument(fmt::format(
"can't apply non-uuid-specific directinput profile when no controllers are available"));
if (!GUIDFromString(controllers.front()->uuid().c_str(), guid))
throw std::invalid_argument(fmt::format("invalid guid format: {}", uuid));
}
else
{
if (!GUIDFromString(uuid.data(), guid))
throw std::invalid_argument(fmt::format("invalid guid format: {}", uuid));
}
return std::make_shared<DirectInputController>(guid);
}
#endif
#if HAS_XINPUT
case InputAPI::XInput:
{
const auto index = ConvertString<uint32>(uuid);
return std::make_shared<XInputController>(index);
}
#endif
#if HAS_SDL
case InputAPI::SDLController:
{
// diid_guid
const auto index = uuid.find_first_of('_');
if (index == std::string_view::npos)
throw std::invalid_argument(fmt::format("invalid sdl uuid format: {}", uuid));
const auto guid_index = ConvertString<size_t>(uuid.substr(0, index));
const auto guid = SDL_JoystickGetGUIDFromString(std::string{uuid.substr(index + 1)}.c_str());
if (display_name.empty())
return std::make_shared<SDLController>(guid, guid_index);
else
return std::make_shared<SDLController>(guid, guid_index, display_name);
}
#endif
#if HAS_DSU
case InputAPI::DSUClient:
{
const auto index = ConvertString<uint32>(uuid);
return std::make_shared<DSUController>(index);
}
#endif
#if HAS_GAMECUBE
case InputAPI::GameCube:
{
const auto index = uuid.find_first_of('_');
if (index == std::string_view::npos)
throw std::invalid_argument(fmt::format("invalid gamecube uuid format: {}", uuid));
const auto adapter = ConvertString<int>(uuid.substr(0, index));
const auto controller_index = ConvertString<int>(uuid.substr(index + 1));
return std::make_shared<GameCubeController>(adapter, controller_index);
}
#endif
#if HAS_WIIMOTE
case InputAPI::Wiimote:
{
const auto index = ConvertString<uint32>(uuid);
return std::make_shared<NativeWiimoteController>(index);
}
#endif
default:
throw std::invalid_argument(fmt::format("unhandled controller api: {}", api));
}
/*
case InputAPI::WGIGamepad: break;
case InputAPI::WGIRawController: break;
*/
}
EmulatedControllerPtr
ControllerFactory::CreateEmulatedController(size_t player_index, EmulatedController::Type type)
{
switch (type)
{
case EmulatedController::Type::VPAD:
return std::make_shared<VPADController>(player_index);
case EmulatedController::Type::Pro:
return std::make_shared<ProController>(player_index);
case EmulatedController::Type::Classic:
return std::make_shared<ClassicController>(player_index);
case EmulatedController::Type::Wiimote:
return std::make_shared<WiimoteController>(player_index);
default:
throw std::runtime_error(fmt::format("unknown emulated controller type: {}", type));
}
}
ControllerProviderPtr ControllerFactory::CreateControllerProvider(InputAPI::Type api, const ControllerProviderSettings& settings)
{
switch (api)
{
#if HAS_KEYBOARD
case InputAPI::Keyboard:
return std::make_shared<KeyboardControllerProvider>();
#endif
#if HAS_SDL
case InputAPI::SDLController:
return std::make_shared<SDLControllerProvider>();
#endif
#if HAS_XINPUT
case InputAPI::XInput:
return std::make_shared<XInputControllerProvider>();
#endif
#if HAS_DIRECTINPUT
case InputAPI::DirectInput:
return std::make_shared<DirectInputControllerProvider>();
#endif
#if HAS_DSU
case InputAPI::DSUClient:
{
try
{
const auto& dsu_settings = dynamic_cast<const DSUProviderSettings&>(settings);
return std::make_shared<DSUControllerProvider>(dsu_settings);
}
catch (const std::bad_cast&)
{
cemuLog_log(LogType::Force, "failing to cast ControllerProviderSettings class to DSUControllerProvider");
return std::make_shared<DSUControllerProvider>();
}
}
#endif
#if HAS_GAMECUBE
case InputAPI::GameCube:
return std::make_shared<GameCubeControllerProvider>();
#endif
#if HAS_WIIMOTE
case InputAPI::Wiimote:
return std::make_shared<WiimoteControllerProvider>();
#endif
default:
cemu_assert_debug(false);
return {};
}
}
| 5,498
|
C++
|
.cpp
| 168
| 29.785714
| 211
| 0.748966
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,898
|
InputManager.cpp
|
cemu-project_Cemu/src/input/InputManager.cpp
|
#include "input/InputManager.h"
#include "config/ActiveSettings.h"
#include "input/ControllerFactory.h"
#include <boost/property_tree/ini_parser.hpp>
#include <pugixml.hpp>
#include "Cafe/GameProfile/GameProfile.h"
#include "util/EventService.h"
InputManager::InputManager()
{
/*
auto create_provider = []
template <typename TProvider>
()
{
static_assert(std::is_base_of_v<ControllerProvider, TProvider>);
try
{
auto controller = std::make_shared<TProvider>();
m_api_available[controller->api()] = controller;
}
catch (const std::exception& ex)
{
cemuLog_log(LogType::Force, ex.what());
}
}
*/
#if HAS_KEYBOARD
create_provider<KeyboardControllerProvider>();
#endif
#if HAS_SDL
create_provider<SDLControllerProvider>();
#endif
#if HAS_XINPUT
create_provider<XInputControllerProvider>();
#endif
#if HAS_DIRECTINPUT
create_provider<DirectInputControllerProvider>();
#endif
#if HAS_DSU
create_provider<DSUControllerProvider>();
#endif
#if HAS_GAMECUBE
create_provider<GameCubeControllerProvider>();
#endif
#if HAS_WIIMOTE
create_provider<WiimoteControllerProvider>();
#endif
m_update_thread_shutdown.store(false);
m_update_thread = std::thread(&InputManager::update_thread, this);
}
InputManager::~InputManager()
{
m_update_thread_shutdown.store(true);
m_update_thread.join();
}
void InputManager::load() noexcept
{
for (size_t i = 0; i < kMaxController; ++i)
{
try
{
load(i);
}
catch (const std::exception& ex)
{
cemuLog_log(LogType::Force, "can't load controller profile: {}", ex.what());
}
}
}
bool InputManager::load(size_t player_index, std::string_view filename)
{
fs::path file_path;
if (filename.empty())
file_path = ActiveSettings::GetConfigPath("controllerProfiles/controller{}", player_index);
else
file_path = ActiveSettings::GetConfigPath("controllerProfiles/{}", filename);
auto old_file = file_path;
old_file.replace_extension(".txt"); // test .txt extension
file_path.replace_extension(".xml"); // force .xml extension
if (fs::exists(old_file) && !fs::exists(file_path))
migrate_config(old_file);
if (!fs::exists(file_path))
return false;
try
{
auto xmlData = FileStream::LoadIntoMemory(file_path);
if (!xmlData || xmlData->empty())
return false;
pugi::xml_document doc;
if (!doc.load_buffer(xmlData->data(), xmlData->size()))
return false;
const pugi::xml_node root = doc.document_element();
const auto type_node = root.child("type");
if (!type_node)
return false;
const auto emulate = EmulatedController::type_from_string(type_node.child_value());
auto emulated_controller = ControllerFactory::CreateEmulatedController(player_index, emulate);
if (const auto profile_name_node = root.child("profile"))
emulated_controller->m_profile_name = profile_name_node.child_value();
// custom settings
emulated_controller->load(root);
for (const auto controller_node : root.select_nodes("controller"))
{
const auto cnode = controller_node.node();
const auto api_node = cnode.child("api");
if (!api_node)
continue;
const auto uuid_node = cnode.child("uuid");
if (!uuid_node)
continue;
const auto* display_name = cnode.child_value("display_name");
try
{
const auto api = InputAPI::from_string(api_node.child_value());
auto controller = ControllerFactory::CreateController(api, uuid_node.child_value(), display_name);
emulated_controller->add_controller(controller);
// load optional settings
auto settings = controller->get_settings();
if (const auto axis_node = cnode.child("axis"))
{
if (const auto value = axis_node.child("deadzone"))
settings.axis.deadzone = ConvertString<float>(value.child_value());
if (const auto value = axis_node.child("range"))
settings.axis.range = ConvertString<float>(value.child_value());
}
if (const auto rotation_node = cnode.child("rotation"))
{
if (const auto value = rotation_node.child("deadzone"))
settings.rotation.deadzone = ConvertString<float>(value.child_value());
if (const auto value = rotation_node.child("range"))
settings.rotation.range = ConvertString<float>(value.child_value());
}
if (const auto trigger_node = cnode.child("trigger"))
{
if (const auto value = trigger_node.child("deadzone"))
settings.trigger.deadzone = ConvertString<float>(value.child_value());
if (const auto value = trigger_node.child("range"))
settings.trigger.range = ConvertString<float>(value.child_value());
}
if (const auto value = cnode.child("rumble"))
settings.rumble = ConvertString<float>(value.child_value());
if (const auto value = cnode.child("motion"))
settings.motion = ConvertString<bool>(value.child_value());
controller->set_settings(settings);
// custom settings
controller->load(cnode);
// mappings
if (const auto mappings_node = cnode.child("mappings"))
{
for (const auto& entry : mappings_node.select_nodes("entry"))
{
const auto enode = entry.node();
const auto mapping_node = enode.child("mapping");
if (!mapping_node)
continue;
const auto button_node = enode.child("button");
if (!button_node)
continue;
const auto mapping = ConvertString<uint64>(mapping_node.child_value());
const auto button = ConvertString<uint64>(button_node.child_value());
emulated_controller->set_mapping(mapping, controller, button);
}
}
}
catch (const std::exception& ex)
{
cemuLog_log(LogType::Force, "can't load controller: {}", ex.what());
}
}
set_controller(emulated_controller);
return true;
}
catch (const std::exception& ex)
{
cemuLog_log(LogType::Force, "can't load config file: {}", ex.what());
return false;
}
}
bool InputManager::migrate_config(const fs::path& file_path)
{
try
{
auto xmlData = FileStream::LoadIntoMemory(file_path);
if (!xmlData || xmlData->empty())
return false;
std::string iniDataStr((const char*)xmlData->data(), xmlData->size());
std::stringstream iniData(iniDataStr);
boost::property_tree::ptree m_data;
read_ini(iniData, m_data);
const auto emulate_string = m_data.get<std::string>("General.emulate");
const auto api_string = m_data.get<std::string>("General.api");
auto uuid_opt = m_data.get_optional<std::string>("General.controller");
const auto display_name = m_data.get_optional<std::string>("General.display");
std::string uuid;
if (api_string == to_string(InputAPI::Keyboard))
uuid = to_string(InputAPI::Keyboard);
else
{
if (!uuid_opt)
return false;
uuid = uuid_opt.value();
if (api_string == to_string(InputAPI::SDLController))
{
uuid += "_0";
}
}
fs::path out_file = file_path;
out_file.replace_extension(".xml");
pugi::xml_document doc;
auto declaration_node = doc.append_child(pugi::node_declaration);
declaration_node.append_attribute("version") = "1.0";
declaration_node.append_attribute("encoding") = "UTF-8";
auto emulated_controller = doc.append_child("emulated_controller");
emulated_controller.append_child("type").append_child(pugi::node_pcdata).set_value(emulate_string.c_str());
bool has_keyboard = api_string == to_string(InputAPI::Keyboard);
if (!has_keyboard) // test if only keyboard configured
{
auto controller = emulated_controller.append_child("controller");
controller.append_child("api").append_child(pugi::node_pcdata).set_value(api_string.c_str());
controller.append_child("uuid").append_child(pugi::node_pcdata).set_value(uuid.c_str());
if (display_name.has_value() && !display_name->empty())
controller.append_child("display_name").append_child(pugi::node_pcdata).set_value(
display_name.value().c_str());
controller.append_child("rumble").append_child(pugi::node_pcdata).set_value(
m_data.get<std::string>("Controller.rumble").c_str());
auto axis_node = controller.append_child("axis");
axis_node.append_child("deadzone").append_child(pugi::node_pcdata).set_value(
m_data.get<std::string>("Controller.leftDeadzone").c_str());
axis_node.append_child("range").append_child(pugi::node_pcdata).set_value(
m_data.get<std::string>("Controller.leftRange").c_str());
auto rotation_node = controller.append_child("rotation");
rotation_node.append_child("deadzone").append_child(pugi::node_pcdata).set_value(
m_data.get<std::string>("Controller.rightDeadzone").c_str());
rotation_node.append_child("range").append_child(pugi::node_pcdata).set_value(
m_data.get<std::string>("Controller.rightRange").c_str());
auto mappings_node = controller.append_child("mappings");
for (int i = 1; i < 28; ++i) // test all possible mappings (max is 27 for vpad controller)
{
auto mapping = m_data.get_optional<std::string>(fmt::format("Controller.{}", i));
if (!mapping || mapping->empty())
continue;
if (!boost::starts_with(mapping.value(), "button_"))
{
if (boost::starts_with(mapping.value(), "key_"))
has_keyboard = true;
continue;
}
const auto button = ConvertString<uint64>(mapping.value().substr(7), 16);
uint64 flag_bit = 0;
for (auto b = 0; b < 64; ++b)
{
if (HAS_BIT(button, b))
{
flag_bit = b;
break;
}
}
// fix old flag layout to new one for all kind of axis stuff
if (flag_bit >= 24 && flag_bit <= 31)
flag_bit += 8;
else if (flag_bit == 32) flag_bit = kTriggerXP;
else if (flag_bit == 33) flag_bit = kRotationXP;
else if (flag_bit == 34) flag_bit = kRotationYP;
else if (flag_bit == 35) flag_bit = kTriggerYP;
else if (flag_bit == 36) flag_bit = kAxisXN;
else if (flag_bit == 37) flag_bit = kAxisYN;
else if (flag_bit == 38) flag_bit = kTriggerXN;
else if (flag_bit == 39) flag_bit = kRotationXN;
else if (flag_bit == 40) flag_bit = kRotationYN;
else if (flag_bit == 41) flag_bit = kTriggerYN;
// fix old api mappings
if (api_string == to_string(InputAPI::XInput))
{
const std::unordered_map<uint64, uint64> xinput =
{
{kButton0, 12}, // XINPUT_GAMEPAD_A
{kButton1, 13}, // XINPUT_GAMEPAD_B
{kButton2, 14}, // XINPUT_GAMEPAD_X
{kButton3, 15}, // XINPUT_GAMEPAD_Y
{kButton4, 8}, // XINPUT_GAMEPAD_LEFT_SHOULDER
{kButton5, 9}, // XINPUT_GAMEPAD_LEFT_SHOULDER
{kButton6, 4}, // XINPUT_GAMEPAD_START
{kButton7, 5}, // XINPUT_GAMEPAD_BACK
{kButton8, 6}, // XINPUT_GAMEPAD_LEFT_THUMB
{kButton9, 7}, // XINPUT_GAMEPAD_RIGHT_THUMB
{kButton10, 0}, // XINPUT_GAMEPAD_DPAD_UP
{kButton11, 1}, // XINPUT_GAMEPAD_DPAD_DOWN
{kButton12, 2}, // XINPUT_GAMEPAD_DPAD_LEFT
{kButton13, 3}, // XINPUT_GAMEPAD_DPAD_RIGHT
};
const auto it = xinput.find(flag_bit);
if (it != xinput.cend())
flag_bit = it->second;
}
else if (api_string == "DSU")
{
const std::unordered_map<uint64, uint64> dsu =
{
{7, kButton0}, // ButtonSelect
{8, kButton1}, // ButtonLStick
{9, kButton2}, // ButtonRStick
{6, kButton3}, // ButtonStart
{4, kButton10}, // ButtonL
{5, kButton11}, // ButtonR
{0, kButton14}, // ButtonA
{1, kButton13}, // ButtonB
{2, kButton15}, // ButtonX
{3, kButton12}, // ButtonY
};
const auto it = dsu.find(flag_bit);
if (it != dsu.cend())
flag_bit = it->second;
}
auto entry_node = mappings_node.append_child("entry");
entry_node.append_child("mapping").append_child(pugi::node_pcdata).set_value(
fmt::format("{}", i).c_str());
entry_node.append_child("button").append_child(pugi::node_pcdata).set_value(
fmt::format("{}", flag_bit).c_str());
}
}
if (has_keyboard)
{
auto controller = emulated_controller.append_child("controller");
controller.append_child("api").append_child(pugi::node_pcdata).set_value("Keyboard");
controller.append_child("uuid").append_child(pugi::node_pcdata).set_value("Keyboard");
auto mappings_node = controller.append_child("mappings");
for (int i = 1; i < 28; ++i) // test all possible mappings (max is 27 for vpad controller)
{
auto mapping = m_data.get_optional<std::string>(fmt::format("Controller.{}", i));
if (!mapping || mapping->empty())
continue;
if (!boost::starts_with(mapping.value(), "key_"))
continue;
const auto button = ConvertString<uint64>(mapping.value().substr(4));
auto entry_node = mappings_node.append_child("entry");
entry_node.append_child("mapping").append_child(pugi::node_pcdata).set_value(
fmt::format("{}", i).c_str());
entry_node.append_child("button").append_child(pugi::node_pcdata).set_value(
fmt::format("{}", button).c_str());
}
}
std::ofstream write_file(out_file, std::ios::out | std::ios::trunc);
if (write_file.is_open())
{
doc.save(write_file);
return true;
}
}
catch (const std::exception& ex)
{
cemuLog_log(LogType::Force, "can't migrate config file {}: {}", file_path.string(), ex.what());
}
return false;
}
void InputManager::save() noexcept
{
for (size_t i = 0; i < kMaxController; ++i)
{
try
{
save(i);
}
catch (const std::exception& ex)
{
cemuLog_log(LogType::Force, "can't save controller profile: {}", ex.what());
}
}
}
bool InputManager::save(size_t player_index, std::string_view filename)
{
// dont overwrite files if set by gameprofile
if (m_is_gameprofile_set[player_index])
return true;
auto emulated_controller = get_controller(player_index);
if (!emulated_controller)
return false;
fs::path file_path = ActiveSettings::GetConfigPath("controllerProfiles");
fs::create_directories(file_path);
const auto is_default_file = filename.empty();
if (is_default_file)
file_path /= fmt::format("controller{}", player_index);
else
file_path /= _utf8ToPath(filename);
file_path.replace_extension(".xml"); // force .xml extension
pugi::xml_document doc;
auto declaration_node = doc.append_child(pugi::node_declaration);
declaration_node.append_attribute("version") = "1.0";
declaration_node.append_attribute("encoding") = "UTF-8";
auto emulated_controller_node = doc.append_child("emulated_controller");
emulated_controller_node.append_child("type").append_child(pugi::node_pcdata).set_value(std::string{
emulated_controller->type_string()
}.c_str());
if(!is_default_file)
emulated_controller->m_profile_name = std::string{filename};
if (emulated_controller->has_profile_name())
emulated_controller_node.append_child("profile").append_child(pugi::node_pcdata).set_value(
emulated_controller->get_profile_name().c_str());
// custom settings
emulated_controller->save(emulated_controller_node);
for (const auto& controller : emulated_controller->get_controllers())
{
auto controller_node = emulated_controller_node.append_child("controller");
// general
controller_node.append_child("api").append_child(pugi::node_pcdata).set_value(std::string{
controller->api_name()
}.c_str());
controller_node.append_child("uuid").append_child(pugi::node_pcdata).set_value(controller->uuid().c_str());
controller_node.append_child("display_name").append_child(pugi::node_pcdata).set_value(
controller->display_name().c_str());
// settings
const auto& settings = controller->get_settings();
if (controller->has_motion())
controller_node.append_child("motion").append_child(pugi::node_pcdata).set_value(
fmt::format("{}", settings.motion).c_str());
if (controller->has_rumble())
controller_node.append_child("rumble").append_child(pugi::node_pcdata).set_value(
fmt::format("{}", settings.rumble).c_str());
auto axis_node = controller_node.append_child("axis");
axis_node.append_child("deadzone").append_child(pugi::node_pcdata).set_value(
fmt::format("{}", settings.axis.deadzone).c_str());
axis_node.append_child("range").append_child(pugi::node_pcdata).set_value(
fmt::format("{}", settings.axis.range).c_str());
auto rotation_node = controller_node.append_child("rotation");
rotation_node.append_child("deadzone").append_child(pugi::node_pcdata).set_value(
fmt::format("{}", settings.rotation.deadzone).c_str());
rotation_node.append_child("range").append_child(pugi::node_pcdata).set_value(
fmt::format("{}", settings.rotation.range).c_str());
auto trigger_node = controller_node.append_child("trigger");
trigger_node.append_child("deadzone").append_child(pugi::node_pcdata).set_value(
fmt::format("{}", settings.trigger.deadzone).c_str());
trigger_node.append_child("range").append_child(pugi::node_pcdata).set_value(
fmt::format("{}", settings.trigger.range).c_str());
// custom settings
controller->save(controller_node);
// mappings for current controller
auto mappings_node = controller_node.append_child("mappings");
for (const auto& mapping : emulated_controller->m_mappings)
{
if (!mapping.second.controller.expired() && *controller == *mapping.second.controller.lock())
{
auto entry_node = mappings_node.append_child("entry");
entry_node.append_child("mapping").append_child(pugi::node_pcdata).set_value(
fmt::format("{}", mapping.first).c_str());
entry_node.append_child("button").append_child(pugi::node_pcdata).set_value(
fmt::format("{}", mapping.second.button).c_str());
}
}
}
FileStream* fs = FileStream::createFile2(file_path);
if (!fs)
return false;
std::stringstream xmlData;
doc.save(xmlData);
std::string xmlStr = xmlData.str();
fs->writeData(xmlStr.data(), xmlStr.size());
delete fs;
return true;
}
bool InputManager::is_gameprofile_set(size_t player_index) const
{
return m_is_gameprofile_set[player_index];
}
EmulatedControllerPtr InputManager::set_controller(EmulatedControllerPtr controller)
{
auto prev_controller = delete_controller(controller->player_index());
// assign controllers to new emulated controller if empty
if (prev_controller && controller->get_controllers().empty())
{
for (const auto& c : prev_controller->get_controllers())
{
controller->add_controller(c);
}
}
// try to connect all controllers
/*for (auto& c : controller->get_controllers())
{
c->connect();
}*/
std::scoped_lock lock(m_mutex);
switch (controller->type())
{
case EmulatedController::Type::VPAD:
for (auto& pad : m_vpad)
{
if (!pad)
{
pad.swap(controller);
return prev_controller;
}
}
break;
default:
for (auto& pad : m_wpad)
{
if (!pad)
{
pad.swap(controller);
return prev_controller;
}
}
break;
}
cemu_assert_debug(false);
return prev_controller;
}
EmulatedControllerPtr InputManager::set_controller(size_t player_index, EmulatedController::Type type)
{
try
{
auto emulated_controller = ControllerFactory::CreateEmulatedController(player_index, type);
set_controller(emulated_controller);
return emulated_controller;
}
catch (const std::exception& ex)
{
cemuLog_log(LogType::Force, "Unable to set controller type {} on player index {}: {}", type, player_index, ex.what());
}
return {};
}
EmulatedControllerPtr InputManager::set_controller(size_t player_index, EmulatedController::Type type,
const std::shared_ptr<ControllerBase>& controller)
{
auto result = set_controller(player_index, type);
if (result)
result->add_controller(controller);
return result;
}
EmulatedControllerPtr InputManager::get_controller(size_t player_index) const
{
std::shared_lock lock(m_mutex);
for (const auto& pad : m_vpad)
{
if (pad && pad->player_index() == player_index)
return pad;
}
for (const auto& pad : m_wpad)
{
if (pad && pad->player_index() == player_index)
return pad;
}
return {};
}
EmulatedControllerPtr InputManager::delete_controller(size_t player_index, bool delete_profile)
{
std::scoped_lock lock(m_mutex);
for (auto& controller : m_vpad)
{
auto result = controller;
if (result && result->player_index() == player_index)
{
controller = {};
if(delete_profile)
{
std::error_code ec{};
fs::remove(ActiveSettings::GetConfigPath("controllerProfiles/controller{}.xml", player_index), ec);
fs::remove(ActiveSettings::GetConfigPath("controllerProfiles/controller{}.txt", player_index), ec);
}
return result;
}
}
for (auto& controller : m_wpad)
{
auto result = controller;
if (result && result->player_index() == player_index)
{
controller = {};
std::error_code ec{};
fs::remove(ActiveSettings::GetConfigPath("controllerProfiles/controller{}.xml", player_index), ec);
fs::remove(ActiveSettings::GetConfigPath("controllerProfiles/controller{}.txt", player_index), ec);
return result;
}
}
return {};
}
std::shared_ptr<VPADController> InputManager::get_vpad_controller(size_t index) const
{
if (index >= m_vpad.size())
return {};
std::shared_lock lock(m_mutex);
return std::static_pointer_cast<VPADController>(m_vpad[index]);
}
std::shared_ptr<WPADController> InputManager::get_wpad_controller(size_t index) const
{
if (index >= m_wpad.size())
return {};
std::shared_lock lock(m_mutex);
return std::static_pointer_cast<WPADController>(m_wpad[index]);
}
std::pair<size_t, size_t> InputManager::get_controller_count() const
{
std::shared_lock lock(m_mutex);
const size_t vpad = std::count_if(m_vpad.cbegin(), m_vpad.cend(), [](const auto& v) { return v != nullptr; });
const size_t wpad = std::count_if(m_wpad.cbegin(), m_wpad.cend(), [](const auto& v) { return v != nullptr; });
return std::make_pair(vpad, wpad);
}
void InputManager::on_device_changed()
{
std::shared_lock lock(m_mutex);
for (auto& pad : m_vpad)
{
if (pad)
pad->connect();
}
for (auto& pad : m_wpad)
{
if (pad)
pad->connect();
}
lock.unlock();
EventService::instance().signal<Events::ControllerChanged>();
}
ControllerProviderPtr InputManager::get_api_provider(InputAPI::Type api) const
{
if(!m_api_available[api].empty())
return *(m_api_available[api].begin());
cemu_assert_debug(false);
return {};
}
ControllerProviderPtr InputManager::get_api_provider(InputAPI::Type api, const ControllerProviderSettings& settings)
{
for(const auto& p : m_api_available[api])
{
if(*p == settings)
{
return p;
}
}
const auto result = ControllerFactory::CreateControllerProvider(api, settings);
m_api_available[api].emplace_back(result);
return result;
}
void InputManager::apply_game_profile()
{
const auto& profiles = g_current_game_profile->GetControllerProfile();
for (int i = 0; i < kMaxController; ++i)
{
if (profiles[i] && !profiles[i]->empty())
{
if (load(i, profiles[i].value()))
{
m_is_gameprofile_set[i] = true;
if (const auto controller = get_controller(i))
{
if (!controller->has_profile_name())
controller->m_profile_name = profiles[i].value();
}
}
}
}
}
std::vector<std::string> InputManager::get_profiles()
{
const auto path = ActiveSettings::GetConfigPath("controllerProfiles");
if (!exists(path))
return {};
std::set<std::string> tmp;
for (const auto& entry : fs::directory_iterator(path))
{
const auto& p = entry.path();
if (p.has_extension() && (p.extension() == ".xml" || p.extension() == ".txt"))
{
auto stem = _pathToUtf8(p.filename().stem());
if (is_valid_profilename(stem))
{
tmp.emplace(stem);
}
}
}
std::vector<std::string> result;
result.reserve(tmp.size());
result.insert(result.end(), tmp.begin(), tmp.end());
return result;
}
bool InputManager::is_valid_profilename(const std::string& name)
{
if (!IsValidFilename(name))
return false;
// dont allow default profile names
for (size_t i = 0; i < kMaxController; i++)
{
if (name == fmt::format("controller{}", i))
return false;
}
return true;
}
glm::ivec2 InputManager::get_mouse_position(bool pad_window) const
{
if (pad_window)
{
std::shared_lock lock(m_pad_mouse.m_mutex);
return m_pad_mouse.position;
}
else
{
std::shared_lock lock(m_main_mouse.m_mutex);
return m_main_mouse.position;
}
}
std::optional<glm::ivec2> InputManager::get_left_down_mouse_info(bool* is_pad)
{
if (is_pad)
*is_pad = false;
{
std::shared_lock lock(m_main_mouse.m_mutex);
if (std::exchange(m_main_mouse.left_down_toggle, false))
return m_main_mouse.position;
if (m_main_mouse.left_down)
return m_main_mouse.position;
}
{
std::shared_lock lock(m_main_touch.m_mutex);
if (std::exchange(m_main_touch.left_down_toggle, false))
return m_main_touch.position;
if (m_main_touch.left_down)
return m_main_touch.position;
}
if (is_pad)
*is_pad = true;
{
std::shared_lock lock(m_pad_mouse.m_mutex);
if (std::exchange(m_pad_mouse.left_down_toggle, false))
return m_pad_mouse.position;
if (m_pad_mouse.left_down)
return m_pad_mouse.position;
}
{
std::shared_lock lock(m_pad_touch.m_mutex);
if (std::exchange(m_pad_touch.left_down_toggle, false))
return m_pad_touch.position;
if (m_pad_touch.left_down)
return m_pad_touch.position;
}
return {};
}
std::optional<glm::ivec2> InputManager::get_right_down_mouse_info(bool* is_pad)
{
if (is_pad)
*is_pad = false;
{
std::shared_lock lock(m_main_mouse.m_mutex);
if (std::exchange(m_main_mouse.right_down_toggle, false))
return m_main_mouse.position;
if (m_main_mouse.right_down)
return m_main_mouse.position;
}
{
std::shared_lock lock(m_main_touch.m_mutex);
if (std::exchange(m_main_touch.right_down_toggle, false))
return m_main_touch.position;
if (m_main_touch.right_down)
return m_main_touch.position;
}
if (is_pad)
*is_pad = true;
{
std::shared_lock lock(m_pad_mouse.m_mutex);
if (std::exchange(m_pad_mouse.right_down_toggle, false))
return m_pad_mouse.position;
if (m_pad_mouse.right_down)
return m_pad_mouse.position;
}
{
std::shared_lock lock(m_pad_touch.m_mutex);
if (std::exchange(m_pad_touch.right_down_toggle, false))
return m_pad_touch.position;
if (m_pad_touch.right_down)
return m_pad_touch.position;
}
return {};
}
void InputManager::update_thread()
{
SetThreadName("Input_update");
while (!m_update_thread_shutdown.load(std::memory_order::relaxed))
{
std::shared_lock lock(m_mutex);
for (auto& pad : m_vpad)
{
if (pad)
pad->update();
}
for (auto& pad : m_wpad)
{
if (pad)
pad->update();
}
lock.unlock();
std::this_thread::sleep_for(std::chrono::milliseconds(1));
std::this_thread::yield();
}
}
| 26,467
|
C++
|
.cpp
| 791
| 29.929204
| 120
| 0.690935
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,899
|
Controller.cpp
|
cemu-project_Cemu/src/input/api/Controller.cpp
|
#include "input/api/Controller.h"
#include "gui/guiWrapper.h"
ControllerBase::ControllerBase(std::string_view uuid, std::string_view display_name)
: m_uuid{uuid}, m_display_name{display_name}
{
}
const ControllerState& ControllerBase::update_state()
{
if (!m_is_calibrated)
calibrate();
ControllerState result = raw_state();
// ignore default buttons
result.buttons.UnsetButtons(m_default_state.buttons);
// apply deadzone and range and ignore default axis values
apply_axis_setting(result.axis, m_default_state.axis, m_settings.axis);
apply_axis_setting(result.rotation, m_default_state.rotation, m_settings.rotation);
apply_axis_setting(result.trigger, m_default_state.trigger, m_settings.trigger);
#define APPLY_AXIS_BUTTON(_axis_, _flag_) \
if (result._axis_.x < -ControllerState::kAxisThreshold) \
result.buttons.SetButtonState((_flag_) + (kAxisXN - kAxisXP), true); \
else if (result._axis_.x > ControllerState::kAxisThreshold) \
result.buttons.SetButtonState((_flag_), true); \
if (result._axis_.y < -ControllerState::kAxisThreshold) \
result.buttons.SetButtonState((_flag_) + 1 + (kAxisXN - kAxisXP), true); \
else if (result._axis_.y > ControllerState::kAxisThreshold) \
result.buttons.SetButtonState((_flag_) + 1, true);
if (result.axis.x < -ControllerState::kAxisThreshold)
result.buttons.SetButtonState((kAxisXP) + (kAxisXN - kAxisXP), true);
else if (result.axis.x > ControllerState::kAxisThreshold)
result.buttons.SetButtonState((kAxisXP), true);
if (result.axis.y < -ControllerState::kAxisThreshold)
result.buttons.SetButtonState((kAxisXP) + 1 + (kAxisXN - kAxisXP), true);
else if (result.axis.y > ControllerState::kAxisThreshold)
result.buttons.SetButtonState((kAxisXP) + 1, true);
APPLY_AXIS_BUTTON(rotation, kRotationXP);
APPLY_AXIS_BUTTON(trigger, kTriggerXP);
/*
// positive values
kAxisXP,
kAxisYP,
kRotationXP,
kRotationYP,
kTriggerXP,
kTriggerYP,
// negative values
kAxisXN,
kAxisYN,
kRotationXN,
kRotationYN,
kTriggerXN,
kTriggerYN,
*/
#undef APPLY_AXIS_BUTTON
m_last_state = std::move(result);
return m_last_state;
}
void ControllerBase::apply_axis_setting(glm::vec2& axis, const glm::vec2& default_value,
const AxisSetting& setting) const
{
constexpr float kMaxValue = 1.0f + ControllerState::kMinAxisValue;
if (setting.deadzone < 1.0f)
{
if (axis.x < default_value.x)
axis.x = (axis.x - default_value.x) / (kMaxValue + default_value.x);
else
axis.x = (axis.x - default_value.x) / (kMaxValue - default_value.x);
if (axis.y < default_value.y)
axis.y = (axis.y - default_value.y) / (kMaxValue + default_value.y);
else
axis.y = (axis.y - default_value.y) / (kMaxValue - default_value.y);
auto len = length(axis);
if (len >= setting.deadzone)
{
axis *= setting.range;
len = length(axis);
// Scaled Radial Dead Zone: stickInput = stickInput.normalized * ((stickInput.magnitude - deadzone) / (1 - deadzone));
if (len > 0)
{
axis = normalize(axis);
axis *= ((len - setting.deadzone) / (kMaxValue - setting.deadzone));
if (length(axis) > 1.0f)
axis = normalize(axis);
}
if (axis.x != 0 || axis.y != 0)
{
if (std::abs(axis.x) < ControllerState::kMinAxisValue)
axis.x = ControllerState::kMinAxisValue;
if (std::abs(axis.y) < ControllerState::kMinAxisValue)
axis.y = ControllerState::kMinAxisValue;
}
return;
}
}
axis = {0, 0};
}
bool ControllerBase::operator==(const ControllerBase& c) const
{
return api() == c.api() && uuid() == c.uuid();
}
float ControllerBase::get_axis_value(uint64 button) const
{
if (m_last_state.buttons.GetButtonState(button))
{
if (button <= kButtonNoneAxisMAX || !has_axis())
return 1.0f;
switch (button)
{
case kAxisXP:
case kAxisXN:
return std::abs(m_last_state.axis.x);
case kAxisYP:
case kAxisYN:
return std::abs(m_last_state.axis.y);
case kRotationXP:
case kRotationXN:
return std::abs(m_last_state.rotation.x);
case kRotationYP:
case kRotationYN:
return std::abs(m_last_state.rotation.y);
case kTriggerXP:
case kTriggerXN:
return std::abs(m_last_state.trigger.x);
case kTriggerYP:
case kTriggerYN:
return std::abs(m_last_state.trigger.y);
}
}
return 0;
}
const ControllerState& ControllerBase::calibrate()
{
m_default_state = raw_state();
m_is_calibrated = is_connected();
return m_default_state;
}
std::string ControllerBase::get_button_name(uint64 button) const
{
switch (button)
{
case kButtonZL: return "ZL";
case kButtonZR: return "ZR";
case kButtonUp: return "DPAD-Up";
case kButtonDown: return "DPAD-Down";
case kButtonLeft: return "DPAD-Left";
case kButtonRight: return "DPAD-Right";
case kAxisXP: return "X-Axis+";
case kAxisYP: return "Y-Axis+";
case kAxisXN: return "X-Axis-";
case kAxisYN: return "Y-Axis-";
case kRotationXP: return "X-Rotation+";
case kRotationYP: return "Y-Rotation+";
case kRotationXN: return "X-Rotation-";
case kRotationYN: return "Y-Rotation-";
case kTriggerXP: return "X-Trigger+";
case kTriggerYP: return "Y-Trigger+";
case kTriggerXN: return "X-Trigger-";
case kTriggerYN: return "y-Trigger-";
}
return fmt::format("Button {}", (uint64)button);
}
ControllerBase::Settings ControllerBase::get_settings() const
{
std::scoped_lock lock(m_settings_mutex);
return m_settings;
}
void ControllerBase::set_settings(const Settings& settings)
{
std::scoped_lock lock(m_settings_mutex);
m_settings = settings;
}
void ControllerBase::set_axis_settings(const AxisSetting& settings)
{
std::scoped_lock lock(m_settings_mutex);
m_settings.axis = settings;
}
void ControllerBase::set_rotation_settings(const AxisSetting& settings)
{
std::scoped_lock lock(m_settings_mutex);
m_settings.rotation = settings;
}
void ControllerBase::set_trigger_settings(const AxisSetting& settings)
{
std::scoped_lock lock(m_settings_mutex);
m_settings.trigger = settings;
}
void ControllerBase::set_rumble(float rumble)
{
std::scoped_lock lock(m_settings_mutex);
m_settings.rumble = rumble;
}
void ControllerBase::set_use_motion(bool state)
{
std::scoped_lock lock(m_settings_mutex);
m_settings.motion = state;
}
| 6,209
|
C++
|
.cpp
| 195
| 29.076923
| 121
| 0.725352
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.