refactor(core): Clean-up

- use "#pragma once" instead of the regular include guard
- fix errors and warnings reported by cppcheck
This commit is contained in:
Michael Carlberg 2016-05-31 05:58:58 +02:00
parent d0499d4d15
commit 39d3f61497
81 changed files with 588 additions and 730 deletions

View file

@ -98,7 +98,7 @@ set(PROJECT_LINK_LIBS
if(ENABLE_I3) if(ENABLE_I3)
find_program(I3_EXECUTABLE "i3") find_program(I3_EXECUTABLE "i3")
if(NOT I3_EXECUTABLE) if(NOT I3_EXECUTABLE)
message(WARNING "${ANSI}[41;30mDisabling \"i3 module\" support (prerequisites failed)${ANSI}[0m") message(WARNING "${ANSI}[41;1mDisabling \"i3 module\" support (prerequisites failed)${ANSI}[0m")
set(ENABLE_I3 OFF) set(ENABLE_I3 OFF)
endif() endif()
endif() endif()
@ -109,7 +109,7 @@ if(ENABLE_ALSA)
set(PROJECT_INCL_DIRS ${PROJECT_INCL_DIRS} ${ALSA_INCLUDE_DIR}) set(PROJECT_INCL_DIRS ${PROJECT_INCL_DIRS} ${ALSA_INCLUDE_DIR})
set(PROJECT_LINK_LIBS ${PROJECT_LINK_LIBS} ${ALSA_LIBRARY}) set(PROJECT_LINK_LIBS ${PROJECT_LINK_LIBS} ${ALSA_LIBRARY})
else(ALSA_FOUND) else(ALSA_FOUND)
message(WARNING "${ANSI}[41;30mDisabling \"volume module\" support (prerequisites failed)${ANSI}[0m") message(WARNING "${ANSI}[41;1mDisabling \"volume module\" support (prerequisites failed)${ANSI}[0m")
set(ENABLE_ALSA OFF) set(ENABLE_ALSA OFF)
endif() endif()
endif() endif()
@ -120,7 +120,7 @@ if(ENABLE_MPD)
set(PROJECT_INCL_DIRS ${PROJECT_INCL_DIRS} ${LIBMPDCLIENT_INCLUDE_DIR}) set(PROJECT_INCL_DIRS ${PROJECT_INCL_DIRS} ${LIBMPDCLIENT_INCLUDE_DIR})
set(PROJECT_LINK_LIBS ${PROJECT_LINK_LIBS} ${LIBMPDCLIENT_LIBRARY}) set(PROJECT_LINK_LIBS ${PROJECT_LINK_LIBS} ${LIBMPDCLIENT_LIBRARY})
else(LIBMPDCLIENT_FOUND) else(LIBMPDCLIENT_FOUND)
message(WARNING "${ANSI}[41;30mDisabling \"mpd module\" support (prerequisites failed)${ANSI}[0m") message(WARNING "${ANSI}[41;1mDisabling \"mpd module\" support (prerequisites failed)${ANSI}[0m")
set(ENABLE_MPD OFF) set(ENABLE_MPD OFF)
endif() endif()
endif() endif()
@ -131,7 +131,7 @@ if(ENABLE_NETWORK)
set(PROJECT_INCL_DIRS ${PROJECT_INCL_DIRS} ${LIBIW_INCLUDE_DIR}) set(PROJECT_INCL_DIRS ${PROJECT_INCL_DIRS} ${LIBIW_INCLUDE_DIR})
set(PROJECT_LINK_LIBS ${PROJECT_LINK_LIBS} ${LIBIW_LIBRARY}) set(PROJECT_LINK_LIBS ${PROJECT_LINK_LIBS} ${LIBIW_LIBRARY})
else(LIBIW_FOUND) else(LIBIW_FOUND)
message(WARNING "${ANSI}[41;30mDisabling \"network module\" support (prerequisites failed)${ANSI}[0m") message(WARNING "${ANSI}[41;1mDisabling \"network module\" support (prerequisites failed)${ANSI}[0m")
set(ENABLE_NETWORK OFF) set(ENABLE_NETWORK OFF)
endif() endif()
endif() endif()

View file

@ -1,5 +1,4 @@
#ifndef _BAR_HPP_ #pragma once
#define _BAR_HPP_
#include <string> #include <string>
#include <memory> #include <memory>
@ -12,7 +11,7 @@ DefineBaseException(ConfigurationError);
struct CompiledWithoutModuleSupport : public ConfigurationError struct CompiledWithoutModuleSupport : public ConfigurationError
{ {
CompiledWithoutModuleSupport(std::string module_name) explicit CompiledWithoutModuleSupport(std::string module_name)
: ConfigurationError(std::string(APP_NAME) + " was not compiled with support for module \""+ module_name +"\"") {} : ConfigurationError(std::string(APP_NAME) + " was not compiled with support for module \""+ module_name +"\"") {}
}; };
@ -96,5 +95,3 @@ class Bar
std::shared_ptr<Bar> &get_bar(); std::shared_ptr<Bar> &get_bar();
const Options& bar_opts(); const Options& bar_opts();
#endif

View file

@ -1,5 +1,4 @@
#ifndef _CONFIG_HPP_ #pragma once
#define _CONFIG_HPP_
#define APP_NAME "@PROJECT_NAME@" #define APP_NAME "@PROJECT_NAME@"
@ -22,5 +21,3 @@
#define BSPWM_STATUS_PREFIX "@SETTING_BSPWM_STATUS_PREFIX@" #define BSPWM_STATUS_PREFIX "@SETTING_BSPWM_STATUS_PREFIX@"
#define PATH_CPU_INFO "@SETTING_PATH_CPU_INFO@" #define PATH_CPU_INFO "@SETTING_PATH_CPU_INFO@"
#define PATH_MEMORY_INFO "@SETTING_PATH_MEMORY_INFO@" #define PATH_MEMORY_INFO "@SETTING_PATH_MEMORY_INFO@"
#endif // _CONFIG_HPP_

View file

@ -1,5 +1,4 @@
#ifndef _DRAWTYPES_ANIMATION_HPP_ #pragma once
#define _DRAWTYPES_ANIMATION_HPP_
#include <string> #include <string>
#include <vector> #include <vector>
@ -21,7 +20,7 @@ namespace drawtypes
public: public:
Animation(std::vector<std::unique_ptr<Icon>> &&frames, int framerate_ms = 1); Animation(std::vector<std::unique_ptr<Icon>> &&frames, int framerate_ms = 1);
Animation(int framerate_ms) explicit Animation(int framerate_ms)
: framerate_ms(framerate_ms){} : framerate_ms(framerate_ms){}
void add(std::unique_ptr<Icon> &&frame); void add(std::unique_ptr<Icon> &&frame);
@ -37,5 +36,3 @@ namespace drawtypes
std::unique_ptr<Animation> get_config_animation(const std::string& config_path, const std::string& animation_name = "animation", bool required = true); std::unique_ptr<Animation> get_config_animation(const std::string& config_path, const std::string& animation_name = "animation", bool required = true);
} }
#endif

View file

@ -1,5 +1,4 @@
#ifndef _DRAWTYPES_BAR_HPP_ #pragma once
#define _DRAWTYPES_BAR_HPP_
#include <string> #include <string>
#include <memory> #include <memory>
@ -16,7 +15,7 @@ namespace drawtypes
protected: protected:
std::unique_ptr<Builder> builder; std::unique_ptr<Builder> builder;
std::vector<std::string> colors; std::vector<std::string> colors;
bool gradient; bool gradient = false;
unsigned int width; unsigned int width;
std::string format; std::string format;
@ -25,7 +24,7 @@ namespace drawtypes
std::unique_ptr<Icon> indicator; std::unique_ptr<Icon> indicator;
public: public:
Bar(int width, const std::string& format, bool lazy_builder_closing = true); Bar(int width, const std::string& fmt, bool lazy_builder_closing = true);
Bar(int width, bool lazy_builder_closing = true) Bar(int width, bool lazy_builder_closing = true)
: Bar(width, "<fill><indicator><empty>", lazy_builder_closing){} : Bar(width, "<fill><indicator><empty>", lazy_builder_closing){}
@ -41,5 +40,3 @@ namespace drawtypes
std::unique_ptr<Bar> get_config_bar(const std::string& config_path, const std::string& bar_name = "bar", bool lazy_builder_closing = true); std::unique_ptr<Bar> get_config_bar(const std::string& config_path, const std::string& bar_name = "bar", bool lazy_builder_closing = true);
} }
#endif

View file

@ -1,5 +1,4 @@
#ifndef _DRAWTYPES_ICON_HPP_ #pragma once
#define _DRAWTYPES_ICON_HPP_
#include <string> #include <string>
#include <vector> #include <vector>
@ -37,5 +36,3 @@ namespace drawtypes
std::unique_ptr<Icon> get_config_icon(const std::string& module_name, const std::string& icon_name = "icon", bool required = true, const std::string& def = ""); std::unique_ptr<Icon> get_config_icon(const std::string& module_name, const std::string& icon_name = "icon", bool required = true, const std::string& def = "");
std::unique_ptr<Icon> get_optional_config_icon(const std::string& module_name, const std::string& icon_name = "icon", const std::string& def = ""); std::unique_ptr<Icon> get_optional_config_icon(const std::string& module_name, const std::string& icon_name = "icon", const std::string& def = "");
} }
#endif

View file

@ -1,5 +1,4 @@
#ifndef _DRAWTYPES_LABEL_HPP_ #pragma once
#define _DRAWTYPES_LABEL_HPP_
#include <string> #include <string>
#include <memory> #include <memory>
@ -29,5 +28,3 @@ namespace drawtypes
std::unique_ptr<Label> get_config_label(const std::string& module_name, const std::string& label_name = "label", bool required = true, const std::string& def = ""); std::unique_ptr<Label> get_config_label(const std::string& module_name, const std::string& label_name = "label", bool required = true, const std::string& def = "");
std::unique_ptr<Label> get_optional_config_label(const std::string& module_name, const std::string& label_name = "label", const std::string& def = ""); std::unique_ptr<Label> get_optional_config_label(const std::string& module_name, const std::string& label_name = "label", const std::string& def = "");
} }
#endif

View file

@ -1,5 +1,4 @@
#ifndef _DRAWTYPES_RAMP_HPP_ #pragma once
#define _DRAWTYPES_RAMP_HPP_
#include <string> #include <string>
#include <vector> #include <vector>
@ -17,7 +16,7 @@ namespace drawtypes
public: public:
Ramp(){} Ramp(){}
Ramp(std::vector<std::unique_ptr<Icon>> icons); explicit Ramp(std::vector<std::unique_ptr<Icon>> icons);
void add(std::unique_ptr<Icon> &&icon); void add(std::unique_ptr<Icon> &&icon);
std::unique_ptr<Icon> &get(int idx); std::unique_ptr<Icon> &get(int idx);
@ -30,5 +29,3 @@ namespace drawtypes
std::unique_ptr<Ramp> get_config_ramp(const std::string& module_name, const std::string& ramp_name = "ramp", bool required = true); std::unique_ptr<Ramp> get_config_ramp(const std::string& module_name, const std::string& ramp_name = "ramp", bool required = true);
} }
#endif

View file

@ -1,5 +1,4 @@
#ifndef _EVENTLOOP_HPP_ #pragma once
#define _EVENTLOOP_HPP_
#include <map> #include <map>
@ -46,7 +45,7 @@ class EventLoop
bool running(); bool running();
public: public:
EventLoop(std::string input_pipe); explicit EventLoop(std::string input_pipe);
void start(); void start();
void stop(); void stop();
@ -56,5 +55,3 @@ class EventLoop
void add_stdin_subscriber(const std::string& module_name); void add_stdin_subscriber(const std::string& module_name);
}; };
#endif

View file

@ -1,20 +1,16 @@
#ifndef _EXCEPTION_HPP_ #pragma once
#define _EXCEPTION_HPP_
#include <string> #include <string>
#include <stdexcept> #include <stdexcept>
struct Exception : public std::runtime_error struct Exception : public std::runtime_error
{ {
Exception(std::string const &error_message = "") explicit Exception(const std::string& error_message = "")
: std::runtime_error(error_message.c_str()) {} : std::runtime_error(error_message.c_str()) {}
}; };
#define DefineChildException(ExName, ParentEx) struct ExName : public ParentEx { \ #define DefineChildException(ExName, ParentEx) struct ExName : public ParentEx { \
ExName(std::string error_message = "") \ explicit ExName(const std::string& error_message = "") \
: ParentEx("["+ std::string(__FUNCTION__) +"] => "+ error_message) {} \ : ParentEx("["+ std::string(__FUNCTION__) +"] => "+ error_message) {} \
} }
#define DefineBaseException(ExName) DefineChildException(ExName, Exception) #define DefineBaseException(ExName) DefineChildException(ExName, Exception)
#endif

View file

@ -1,5 +1,4 @@
#ifndef _INTERFACES_ALSA_HPP_ #pragma once
#define _INTERFACES_ALSA_HPP_
#include <functional> #include <functional>
#include <string> #include <string>
@ -16,11 +15,14 @@ namespace alsa
class Exception : public ::Exception class Exception : public ::Exception
{ {
public: public:
Exception(const std::string& msg) : ::Exception("[Alsa] "+ msg){} explicit Exception(const std::string& msg) : ::Exception("[Alsa] "+ msg){}
}; };
class ControlInterfaceError : public Exception { class ControlInterfaceError : public Exception
using Exception::Exception; {
public:
ControlInterfaceError(int code, const std::string& msg)
: Exception(msg +" ["+ std::to_string(code) +"]") {}
}; };
class ControlInterface class ControlInterface
@ -36,12 +38,12 @@ namespace alsa
snd_ctl_elem_id_t *id; snd_ctl_elem_id_t *id;
public: public:
ControlInterface(int numid) throw(ControlInterfaceError); explicit ControlInterface(int numid);
~ControlInterface(); ~ControlInterface();
bool wait(int timeout = -1) throw(ControlInterfaceError); bool wait(int timeout = -1);
bool test_device_plugged() throw(ControlInterfaceError); bool test_device_plugged();
}; };
@ -57,10 +59,10 @@ namespace alsa
snd_mixer_elem_t *mixer_element = nullptr; snd_mixer_elem_t *mixer_element = nullptr;
public: public:
Mixer(const std::string& mixer_control_name) throw(MixerError); explicit Mixer(const std::string& mixer_control_name);
~Mixer(); ~Mixer();
bool wait(int timeout = -1) throw(MixerError); bool wait(int timeout = -1);
int get_volume(); int get_volume();
void set_volume(float percentage); void set_volume(float percentage);
@ -72,5 +74,3 @@ namespace alsa
void error_handler(const std::string& message); void error_handler(const std::string& message);
}; };
} }
#endif

View file

@ -1,5 +1,4 @@
#ifndef _INTERFACES_MPD_HPP_ #pragma once
#define _INTERFACES_MPD_HPP_
#include <string> #include <string>
#include <stdlib.h> #include <stdlib.h>
@ -24,7 +23,7 @@ namespace mpd
class ClientError : public Exception class ClientError : public Exception
{ {
public: public:
ClientError(const std::string& msg, mpd_error code, bool clearable) explicit ClientError(const std::string& msg, mpd_error code, bool clearable)
: Exception("[mpd::ClientError::"+ std::to_string(code) +"] "+ msg, clearable){} : Exception("[mpd::ClientError::"+ std::to_string(code) +"] "+ msg, clearable){}
}; };
@ -46,14 +45,14 @@ namespace mpd
struct Song struct Song
{ {
Song(){} Song(){}
Song(mpd_song *song); explicit Song(mpd_song *song);
std::shared_ptr<mpd_song> song; std::shared_ptr<mpd_song> song;
std::string get_artist(); std::string get_artist();
std::string get_album(); std::string get_album();
std::string get_title(); std::string get_title();
unsigned get_duration(); // unsigned get_duration();
operator bool() { operator bool() {
return this->song.get() != nullptr; return this->song.get() != nullptr;
@ -69,7 +68,7 @@ namespace mpd
} }
}; };
Status(mpd_status *status); explicit Status(mpd_status *status);
std::unique_ptr<struct mpd_status, StatusDeleter> status; std::unique_ptr<struct mpd_status, StatusDeleter> status;
std::unique_ptr<Song> song; std::unique_ptr<Song> song;
@ -92,8 +91,8 @@ namespace mpd
void update(int event); void update(int event);
void update_timer(); void update_timer();
unsigned get_total_time(); // unsigned get_total_time();
unsigned get_elapsed_time(); // unsigned get_elapsed_time();
unsigned get_elapsed_percentage(); unsigned get_elapsed_percentage();
std::string get_formatted_elapsed(); std::string get_formatted_elapsed();
std::string get_formatted_total(); std::string get_formatted_total();
@ -128,12 +127,14 @@ namespace mpd
void check_errors(); void check_errors();
public: public:
Connection() = default;
static std::shared_ptr<Connection> &get(); static std::shared_ptr<Connection> &get();
void connect(); void connect();
void disconnect(); void disconnect();
bool connected(); bool connected();
bool retry_connection(int interval = 1); // bool retry_connection(int interval = 1);
void idle(); void idle();
int noidle(); int noidle();
@ -147,15 +148,15 @@ namespace mpd
void play(); void play();
void pause(bool state); void pause(bool state);
void toggle(); // void toggle();
void stop(); void stop();
void prev(); void prev();
void next(); void next();
void seek(int percentage); void seek(int percentage);
void repeat(bool mode); void set_repeat(bool mode);
void random(bool mode); void set_random(bool mode);
void single(bool mode); void set_single(bool mode);
}; };
struct MpdStatus struct MpdStatus
@ -179,5 +180,3 @@ namespace mpd
} }
}; };
} }
#endif

View file

@ -1,5 +1,4 @@
#ifndef _INTERFACES_NET_HPP_ #pragma once
#define _INTERFACES_NET_HPP_
#include <string> #include <string>
#include <memory> #include <memory>
@ -16,13 +15,12 @@ namespace net
{ {
bool is_wireless_interface(const std::string& ifname); bool is_wireless_interface(const std::string& ifname);
//
// Network // Network
//
class NetworkException : public Exception class NetworkException : public Exception
{ {
public: public:
NetworkException(const std::string& msg) explicit NetworkException(const std::string& msg)
: Exception("[Network] "+ msg){} : Exception("[Network] "+ msg){}
}; };
@ -34,22 +32,21 @@ namespace net
struct ifreq data; struct ifreq data;
int fd; int fd;
bool test_interface() throw(NetworkException); bool test_interface();
bool test_connection() throw(NetworkException); bool test_connection();
public: public:
Network(const std::string& interface) throw(NetworkException); explicit Network(const std::string& interface);
~Network(); ~Network();
virtual bool connected(); virtual bool connected();
virtual bool test(); virtual bool test();
std::string get_ip() throw(NetworkException); std::string get_ip();
}; };
//
// WiredNetwork // WiredNetwork
//
class WiredNetworkException : public NetworkException { class WiredNetworkException : public NetworkException {
using NetworkException::NetworkException; using NetworkException::NetworkException;
}; };
@ -59,14 +56,13 @@ namespace net
int linkspeed = 0; int linkspeed = 0;
public: public:
WiredNetwork(const std::string& interface); explicit WiredNetwork(const std::string& interface);
std::string get_link_speed(); std::string get_link_speed();
}; };
//
// WirelessNetwork // WirelessNetwork
//
class WirelessNetworkException : public NetworkException { class WirelessNetworkException : public NetworkException {
using NetworkException::NetworkException; using NetworkException::NetworkException;
}; };
@ -76,14 +72,12 @@ namespace net
struct iwreq iw; struct iwreq iw;
public: public:
WirelessNetwork(const std::string& interface); explicit WirelessNetwork(const std::string& interface);
std::string get_essid() throw(WirelessNetworkException); std::string get_essid();
float get_signal_dbm() throw(WirelessNetworkException); float get_signal_dbm();
float get_signal_quality(); float get_signal_quality();
}; };
} }
#endif

View file

@ -1,5 +1,4 @@
#ifndef _LEMONBUDDY_HPP_ #pragma once
#define _LEMONBUDDY_HPP_
#include "exception.hpp" #include "exception.hpp"
@ -9,5 +8,3 @@ void register_pid(pid_t pid);
void unregister_pid(pid_t pid); void unregister_pid(pid_t pid);
void register_command_handler(const std::string& module_name); void register_command_handler(const std::string& module_name);
#endif

View file

@ -1,5 +1,4 @@
#ifndef _MODULES_BACKLIGHT_HPP_ #pragma once
#define _MODULES_BACKLIGHT_HPP_
#include "config.hpp" #include "config.hpp"
#include "modules/base.hpp" #include "modules/base.hpp"
@ -10,9 +9,9 @@ namespace modules
{ {
DefineModule(BacklightModule, InotifyModule) DefineModule(BacklightModule, InotifyModule)
{ {
const char *TAG_LABEL = "<label>"; static constexpr auto TAG_LABEL = "<label>";
const char *TAG_BAR = "<bar>"; static constexpr auto TAG_BAR = "<bar>";
const char *TAG_RAMP = "<ramp>"; static constexpr auto TAG_RAMP = "<ramp>";
std::unique_ptr<drawtypes::Bar> bar; std::unique_ptr<drawtypes::Bar> bar;
std::unique_ptr<drawtypes::Ramp> ramp; std::unique_ptr<drawtypes::Ramp> ramp;
@ -22,14 +21,17 @@ namespace modules
std::string path_val, path_max; std::string path_val, path_max;
float val = 0, max = 0; float val = 0, max = 0;
std::atomic<int> percentage; concurrency::Atomic<int> percentage;
public: public:
BacklightModule(const std::string& name); explicit BacklightModule(const std::string& name);
bool on_event(InotifyEvent *event); bool on_event(InotifyEvent *event);
bool build(Builder *builder, const std::string& tag); bool build(Builder *builder, const std::string& tag);
void idle() const
{
std::this_thread::sleep_for(25ms);
}
}; };
} }
#endif

View file

@ -1,5 +1,4 @@
#ifndef _MODULES_BASE_HPP_ #pragma once
#define _MODULES_BASE_HPP_
#include <chrono> #include <chrono>
#include <memory> #include <memory>
@ -10,24 +9,29 @@
#include <condition_variable> #include <condition_variable>
#include <map> #include <map>
#include <thread> #include <thread>
#include <atomic>
#include <algorithm> #include <algorithm>
#include "exception.hpp" #include "exception.hpp"
#include "services/builder.hpp" #include "services/builder.hpp"
#include "services/inotify.hpp" #include "services/inotify.hpp"
#include "services/logger.hpp"
#include "utils/config.hpp" #include "utils/config.hpp"
#include "utils/string.hpp" #include "utils/string.hpp"
#include "utils/concurrency.hpp" #include "utils/concurrency.hpp"
using namespace std::chrono_literals; using namespace std::chrono_literals;
#define DEFAULT_FORMAT "format" #define Concat(one, two) one ## two
#define _Stringify(expr) #expr
#define Stringify(expr) _Stringify(expr)
#define DefineModule(ModuleName, ModuleType) struct ModuleName : public ModuleType<ModuleName> #define DefineModule(ModuleName, ModuleType) struct ModuleName : public ModuleType<ModuleName>
#define CastModule(ModuleName) static_cast<ModuleName *>(this) #define CastModule(ModuleName) static_cast<ModuleName *>(this)
#define ConstCastModule(ModuleName) static_cast<ModuleName const &>(*this) #define ConstCastModule(ModuleName) static_cast<ModuleName const &>(*this)
#define DEFAULT_FORMAT "format"
DefineBaseException(ModuleError); DefineBaseException(ModuleError);
DefineChildException(UndefinedFormat, ModuleError); DefineChildException(UndefinedFormat, ModuleError);
DefineChildException(UndefinedFormatTag, ModuleError); DefineChildException(UndefinedFormatTag, ModuleError);
@ -75,10 +79,10 @@ class ModuleFormatter
std::map<std::string, std::unique_ptr<Format>> formats; std::map<std::string, std::unique_ptr<Format>> formats;
public: public:
ModuleFormatter(const std::string& module_name) explicit ModuleFormatter(const std::string& module_name)
: module_name(module_name) {} : module_name(module_name) {}
void add(const std::string& name, const std::string& fallback, std::vector<std::string> &&tags, std::vector<std::string> &&whitelist = {}) throw(UndefinedFormatTag) void add(const std::string& name, const std::string& fallback, std::vector<std::string> &&tags, std::vector<std::string> &&whitelist = {})
{ {
auto format = std::make_unique<Format>(); auto format = std::make_unique<Format>();
@ -106,7 +110,7 @@ class ModuleFormatter
this->formats.insert(std::make_pair(name, std::move(format))); this->formats.insert(std::make_pair(name, std::move(format)));
} }
std::unique_ptr<Format>& get(const std::string& format_name) throw(UndefinedFormat) std::unique_ptr<Format>& get(const std::string& format_name)
{ {
auto format = this->formats.find(format_name); auto format = this->formats.find(format_name);
if (format == this->formats.end()) if (format == this->formats.end())
@ -114,7 +118,7 @@ class ModuleFormatter
return format->second; return format->second;
} }
bool has(const std::string& tag, const std::string& format_name) throw(UndefinedFormat) bool has(const std::string& tag, const std::string& format_name)
{ {
auto format = this->formats.find(format_name); auto format = this->formats.find(format_name);
if (format == this->formats.end()) if (format == this->formats.end())
@ -168,13 +172,12 @@ namespace modules
std::vector<std::thread> threads; std::vector<std::thread> threads;
public: public:
Module(const std::string& name) Module(const std::string& name, bool lazy_builder = true)
: name_("module/"+ name), builder(std::make_unique<Builder>(lazy_builder))
{ {
this->name_ = "module/" + name;
this->enable(false); this->enable(false);
this->cache = ""; this->cache = "";
// this->builder = std::make_unique<Builder>(false); // this->builder = std::make_unique<Builder>(false);
this->builder = std::make_unique<Builder>();
this->formatter = std::make_unique<ModuleFormatter>(ConstCastModule(ModuleImpl).name()); this->formatter = std::make_unique<ModuleFormatter>(ConstCastModule(ModuleImpl).name());
} }
@ -274,15 +277,9 @@ namespace modules
template<typename ModuleImpl> template<typename ModuleImpl>
class StaticModule : public Module<ModuleImpl> class StaticModule : public Module<ModuleImpl>
{ {
protected: using Module<ModuleImpl>::Module;
std::unique_ptr<Builder> builder;
public: public:
StaticModule(const std::string& name, bool lazybuilder = true) : Module<ModuleImpl>(name)
{
this->builder = std::make_unique<Builder>(lazybuilder);
}
void start() void start()
{ {
this->enable(true); this->enable(true);
@ -385,23 +382,33 @@ namespace modules
} }
} }
void idle() const
{
// std::this_thread::sleep_for(1s);
}
void poll_events() void poll_events()
{ {
std::lock_guard<concurrency::SpinLock> lck(this->update_lock); std::lock_guard<concurrency::SpinLock> lck(this->update_lock);
std::vector<std::unique_ptr<InotifyWatch>> watches; std::vector<std::unique_ptr<InotifyWatch>> watches;
for (auto &&w : this->watch_list) { for (auto &&w : this->watch_list)
watches.emplace_back(std::make_unique<InotifyWatch>(w.first, w.second)); watches.emplace_back(std::make_unique<InotifyWatch>(w.first, w.second));
}
while (this->enabled()) { while (this->enabled()) {
ConstCastModule(ModuleImpl).idle();
for (auto &&w : watches) { for (auto &&w : watches) {
log_trace("Polling inotify event for watch at "+ (*w)()); log_trace("Polling inotify event for watch at "+ (*w)());
if (w->has_event(500 / watches.size())) { if (w->has_event(500 / watches.size())) {
std::unique_ptr<InotifyEvent> event = w->get_event(); std::unique_ptr<InotifyEvent> event = w->get_event();
watches.clear(); watches.clear();
if (CastModule(ModuleImpl)->on_event(event.get())) if (CastModule(ModuleImpl)->on_event(event.get()))
CastModule(ModuleImpl)->broadcast(); CastModule(ModuleImpl)->broadcast();
return; return;
} }
} }
@ -433,5 +440,3 @@ namespace modules
} }
}; };
} }
#endif

View file

@ -1,5 +1,4 @@
#ifndef _MODULES_BATTERY_HPP_ #pragma once
#define _MODULES_BATTERY_HPP_
#include <memory> #include <memory>
#include <string> #include <string>
@ -47,10 +46,10 @@ namespace modules
concurrency::Atomic<int> percentage; concurrency::Atomic<int> percentage;
int full_at; int full_at;
void subthread_runner(); void subthread_routine();
public: public:
BatteryModule(const std::string& name); explicit BatteryModule(const std::string& name);
void start(); void start();
@ -59,5 +58,3 @@ namespace modules
bool build(Builder *builder, const std::string& tag); bool build(Builder *builder, const std::string& tag);
}; };
} }
#endif

View file

@ -1,5 +1,4 @@
#ifndef _MODULES_BSPWM_HPP_ #pragma once
#define _MODULES_BSPWM_HPP_
#include <memory> #include <memory>
#include <string> #include <string>
@ -49,10 +48,10 @@ namespace modules
DefineModule(BspwmModule, EventModule) DefineModule(BspwmModule, EventModule)
{ {
const char *TAG_LABEL_STATE = "<label:state>"; static constexpr auto TAG_LABEL_STATE = "<label:state>";
const char *TAG_LABEL_MODE = "<label:mode>"; static constexpr auto TAG_LABEL_MODE = "<label:mode>";
const char *EVENT_CLICK = "bwm"; static constexpr auto EVENT_CLICK = "bwm";
std::map<Bspwm::Flag, std::unique_ptr<drawtypes::Label>> mode_labels; std::map<Bspwm::Flag, std::unique_ptr<drawtypes::Label>> mode_labels;
std::map<Bspwm::Flag, std::unique_ptr<drawtypes::Label>> state_labels; std::map<Bspwm::Flag, std::unique_ptr<drawtypes::Label>> state_labels;
@ -63,7 +62,7 @@ namespace modules
std::unique_ptr<drawtypes::IconMap> icons; std::unique_ptr<drawtypes::IconMap> icons;
std::string monitor; std::string monitor;
int socket_fd; int socket_fd = -1;
std::string prev_data; std::string prev_data;
public: public:
@ -77,5 +76,3 @@ namespace modules
bool handle_command(const std::string& cmd); bool handle_command(const std::string& cmd);
}; };
} }
#endif

View file

@ -1,5 +1,4 @@
#ifndef _MODULES_COUNTER_HPP_ #pragma once
#define _MODULES_COUNTER_HPP_
#include "modules/base.hpp" #include "modules/base.hpp"
@ -7,16 +6,14 @@ namespace modules
{ {
DefineModule(CounterModule, TimerModule) DefineModule(CounterModule, TimerModule)
{ {
const char *TAG_COUNTER = "<counter>"; static constexpr auto TAG_COUNTER = "<counter>";
concurrency::Atomic<int> counter; concurrency::Atomic<int> counter;
public: public:
CounterModule(const std::string& name); explicit CounterModule(const std::string& name);
bool update(); bool update();
bool build(Builder *builder, const std::string& tag); bool build(Builder *builder, const std::string& tag);
}; };
} }
#endif

View file

@ -1,5 +1,4 @@
#ifndef _MODULES_CPU_HPP_ #pragma once
#define _MODULES_CPU_HPP_
#include <memory> #include <memory>
#include <string> #include <string>
@ -23,10 +22,10 @@ namespace modules
DefineModule(CpuModule, TimerModule) DefineModule(CpuModule, TimerModule)
{ {
const char *TAG_LABEL = "<label>"; static constexpr auto TAG_LABEL = "<label>";
const char *TAG_BAR_LOAD = "<bar:load>"; static constexpr auto TAG_BAR_LOAD = "<bar:load>";
const char *TAG_RAMP_LOAD = "<ramp:load>"; static constexpr auto TAG_RAMP_LOAD = "<ramp:load>";
const char *TAG_RAMP_LOAD_PER_CORE = "<ramp:load_per_core>"; static constexpr auto TAG_RAMP_LOAD_PER_CORE = "<ramp:load_per_core>";
std::vector<std::unique_ptr<CpuTime>> cpu_times; std::vector<std::unique_ptr<CpuTime>> cpu_times;
std::vector<std::unique_ptr<CpuTime>> prev_cpu_times; std::vector<std::unique_ptr<CpuTime>> prev_cpu_times;
@ -37,18 +36,16 @@ namespace modules
std::unique_ptr<drawtypes::Label> label; std::unique_ptr<drawtypes::Label> label;
std::unique_ptr<drawtypes::Label> label_tokenized; std::unique_ptr<drawtypes::Label> label_tokenized;
float current_total_load; float current_total_load = 0;
std::vector<float> current_load; std::vector<float> current_load;
bool read_values(); bool read_values();
float get_load(int core); float get_load(int core);
public: public:
CpuModule(const std::string& name); explicit CpuModule(const std::string& name);
bool update(); bool update();
bool build(Builder *builder, const std::string& tag); bool build(Builder *builder, const std::string& tag);
}; };
} }
#endif

View file

@ -1,7 +1,4 @@
#ifndef _MODULES_DATE_HPP_ #pragma once
#define _MODULES_DATE_HPP_
#include <string>
#include "modules/base.hpp" #include "modules/base.hpp"
@ -9,20 +6,20 @@ namespace modules
{ {
DefineModule(DateModule, TimerModule) DefineModule(DateModule, TimerModule)
{ {
const char *TAG_DATE = "<date>"; static constexpr auto TAG_DATE = "<date>";
const char *EVENT_TOGGLE = "datetoggle"; static constexpr auto EVENT_TOGGLE = "datetoggle";
std::unique_ptr<Builder> builder; std::unique_ptr<Builder> builder;
std::string date; std::string date;
std::string date_detailed; std::string date_detailed;
char date_str[256]; char date_str[256] = {};
bool detailed = false; bool detailed = false;
public: public:
DateModule(const std::string& name); explicit DateModule(const std::string& name);
bool update(); bool update();
bool build(Builder *builder, const std::string& tag); bool build(Builder *builder, const std::string& tag);
@ -31,5 +28,3 @@ namespace modules
bool handle_command(const std::string& cmd); bool handle_command(const std::string& cmd);
}; };
} }
#endif

View file

@ -1,14 +1,10 @@
#ifndef _MODULES_I3_HPP_ #pragma once
#define _MODULES_I3_HPP_
#include "config.hpp"
#include <memory> #include <memory>
#include <string>
#include <unistd.h> #include <unistd.h>
#include <i3ipc++/ipc.hpp> #include <i3ipc++/ipc.hpp>
#include "config.hpp"
#include "modules/base.hpp" #include "modules/base.hpp"
#include "drawtypes/icon.hpp" #include "drawtypes/icon.hpp"
#include "drawtypes/label.hpp" #include "drawtypes/label.hpp"
@ -46,11 +42,9 @@ namespace modules
DefineModule(i3Module, EventModule) DefineModule(i3Module, EventModule)
{ {
const char *TAG_LABEL_STATE = "<label:state>"; static constexpr auto TAG_LABEL_STATE = "<label:state>";
const char *EVENT_CLICK = "i3"; static constexpr auto EVENT_CLICK = "i3";
concurrency::SpinLock update_lock;
std::unique_ptr<i3ipc::connection> ipc; std::unique_ptr<i3ipc::connection> ipc;
@ -66,7 +60,7 @@ namespace modules
bool local_workspaces = true; bool local_workspaces = true;
std::size_t workspace_name_strip_nchars = 0; std::size_t workspace_name_strip_nchars = 0;
int ipc_fd; int ipc_fd = -1;
public: public:
i3Module(const std::string& name, const std::string& monitor); i3Module(const std::string& name, const std::string& monitor);
@ -81,5 +75,3 @@ namespace modules
bool handle_command(const std::string& cmd); bool handle_command(const std::string& cmd);
}; };
} }
#endif

View file

@ -1,5 +1,4 @@
#ifndef _MODULES_MEMORY_HPP_ #pragma once
#define _MODULES_MEMORY_HPP_
#include <atomic> #include <atomic>
@ -12,9 +11,9 @@ namespace modules
{ {
DefineModule(MemoryModule, TimerModule) DefineModule(MemoryModule, TimerModule)
{ {
const char *TAG_LABEL = "<label>"; static constexpr auto TAG_LABEL = "<label>";
const char *TAG_BAR_USED = "<bar:used>"; static constexpr auto TAG_BAR_USED = "<bar:used>";
const char *TAG_BAR_FREE = "<bar:free>"; static constexpr auto TAG_BAR_FREE = "<bar:free>";
std::unique_ptr<drawtypes::Bar> bar_used; std::unique_ptr<drawtypes::Bar> bar_used;
std::unique_ptr<drawtypes::Bar> bar_free; std::unique_ptr<drawtypes::Bar> bar_free;
@ -25,11 +24,9 @@ namespace modules
std::atomic<int> percentage_free; std::atomic<int> percentage_free;
public: public:
MemoryModule(const std::string& name); explicit MemoryModule(const std::string& name);
bool update(); bool update();
bool build(Builder *builder, const std::string& tag); bool build(Builder *builder, const std::string& tag);
}; };
} }
#endif

View file

@ -1,5 +1,4 @@
#ifndef _MODULES_MENU_HPP_ #pragma once
#define _MODULES_MENU_HPP_
#include <mutex> #include <mutex>
@ -18,11 +17,11 @@ namespace modules
DefineModule(MenuModule, StaticModule) DefineModule(MenuModule, StaticModule)
{ {
const char *TAG_LABEL_TOGGLE = "<label:toggle>"; static constexpr auto TAG_LABEL_TOGGLE = "<label:toggle>";
const char *TAG_MENU = "<menu>"; static constexpr auto TAG_MENU = "<menu>";
const char *EVENT_MENU_OPEN = "menu_open:"; static constexpr auto EVENT_MENU_OPEN = "menu_open:";
const char *EVENT_MENU_CLOSE = "menu_close"; static constexpr auto EVENT_MENU_CLOSE = "menu_close";
std::mutex output_mtx; std::mutex output_mtx;
std::mutex cmd_mtx; std::mutex cmd_mtx;
@ -34,14 +33,12 @@ namespace modules
std::unique_ptr<drawtypes::Label> label_close; std::unique_ptr<drawtypes::Label> label_close;
public: public:
MenuModule(const std::string& name); explicit MenuModule(const std::string& name);
std::string get_output() throw(UndefinedFormat); std::string get_output();
bool build(Builder *builder, const std::string& tag); bool build(Builder *builder, const std::string& tag);
bool handle_command(const std::string& cmd); bool handle_command(const std::string& cmd);
}; };
} }
#endif

View file

@ -1,5 +1,4 @@
#ifndef _MODULES_MPD_HPP_ #pragma once
#define _MODULES_MPD_HPP_
#include "modules/base.hpp" #include "modules/base.hpp"
#include "interfaces/mpd.hpp" #include "interfaces/mpd.hpp"
@ -14,32 +13,32 @@ namespace modules
static const int PROGRESSBAR_THREAD_SYNC_COUNT = 10; static const int PROGRESSBAR_THREAD_SYNC_COUNT = 10;
const std::chrono::duration<double> PROGRESSBAR_THREAD_INTERVAL = 1s; const std::chrono::duration<double> PROGRESSBAR_THREAD_INTERVAL = 1s;
const char *FORMAT_ONLINE = "format:online"; static constexpr auto FORMAT_ONLINE = "format:online";
const char *TAG_BAR_PROGRESS = "<bar:progress>"; static constexpr auto TAG_BAR_PROGRESS = "<bar:progress>";
const char *TAG_TOGGLE = "<toggle>"; static constexpr auto TAG_TOGGLE = "<toggle>";
const char *TAG_LABEL_SONG = "<label:song>"; static constexpr auto TAG_LABEL_SONG = "<label:song>";
const char *TAG_LABEL_TIME = "<label:time>"; static constexpr auto TAG_LABEL_TIME = "<label:time>";
const char *TAG_ICON_RANDOM = "<icon:random>"; static constexpr auto TAG_ICON_RANDOM = "<icon:random>";
const char *TAG_ICON_REPEAT = "<icon:repeat>"; static constexpr auto TAG_ICON_REPEAT = "<icon:repeat>";
const char *TAG_ICON_REPEAT_ONE = "<icon:repeatone>"; static constexpr auto TAG_ICON_REPEAT_ONE = "<icon:repeatone>";
const char *TAG_ICON_PREV = "<icon:prev>"; static constexpr auto TAG_ICON_PREV = "<icon:prev>";
const char *TAG_ICON_STOP = "<icon:stop>"; static constexpr auto TAG_ICON_STOP = "<icon:stop>";
const char *TAG_ICON_PLAY = "<icon:play>"; static constexpr auto TAG_ICON_PLAY = "<icon:play>";
const char *TAG_ICON_PAUSE = "<icon:pause>"; static constexpr auto TAG_ICON_PAUSE = "<icon:pause>";
const char *TAG_ICON_NEXT = "<icon:next>"; static constexpr auto TAG_ICON_NEXT = "<icon:next>";
const char *FORMAT_OFFLINE = "format:offline"; static constexpr auto FORMAT_OFFLINE = "format:offline";
const char *TAG_LABEL_OFFLINE = "<label:offline>"; static constexpr auto TAG_LABEL_OFFLINE = "<label:offline>";
const char *EVENT_PLAY = "mpdplay"; static constexpr auto EVENT_PLAY = "mpdplay";
const char *EVENT_PAUSE = "mpdpause"; static constexpr auto EVENT_PAUSE = "mpdpause";
const char *EVENT_STOP = "mpdstop"; static constexpr auto EVENT_STOP = "mpdstop";
const char *EVENT_PREV = "mpdprev"; static constexpr auto EVENT_PREV = "mpdprev";
const char *EVENT_NEXT = "mpdnext"; static constexpr auto EVENT_NEXT = "mpdnext";
const char *EVENT_REPEAT = "mpdrepeat"; static constexpr auto EVENT_REPEAT = "mpdrepeat";
const char *EVENT_REPEAT_ONE = "mpdrepeatone"; static constexpr auto EVENT_REPEAT_ONE = "mpdrepeatone";
const char *EVENT_RANDOM = "mpdrandom"; static constexpr auto EVENT_RANDOM = "mpdrandom";
const char *EVENT_SEEK = "mpdseek"; static constexpr auto EVENT_SEEK = "mpdseek";
std::unique_ptr<drawtypes::Bar> bar_progress; std::unique_ptr<drawtypes::Bar> bar_progress;
std::unique_ptr<drawtypes::IconMap> icons; std::unique_ptr<drawtypes::IconMap> icons;
@ -56,13 +55,13 @@ namespace modules
std::shared_ptr<mpd::Connection> mpd; std::shared_ptr<mpd::Connection> mpd;
std::chrono::system_clock::time_point synced_at; std::chrono::system_clock::time_point synced_at;
float sync_interval; float sync_interval = 0.5f;
bool clickable_progress = false; bool clickable_progress = false;
std::string progress_fill, progress_empty, progress_indicator; std::string progress_fill, progress_empty, progress_indicator;
public: public:
MpdModule(const std::string& name); explicit MpdModule(const std::string& name);
~MpdModule(); ~MpdModule();
void start(); void start();
@ -74,5 +73,3 @@ namespace modules
bool handle_command(const std::string& cmd); bool handle_command(const std::string& cmd);
}; };
} }
#endif

View file

@ -1,5 +1,4 @@
#ifndef _MODULES_NETWORK_HPP_ #pragma once
#define _MODULES_NETWORK_HPP_
#include <atomic> #include <atomic>
#include <chrono> #include <chrono>
@ -18,15 +17,15 @@ namespace modules
{ {
DefineModule(NetworkModule, TimerModule) DefineModule(NetworkModule, TimerModule)
{ {
const char *FORMAT_CONNECTED = "format:connected"; static constexpr auto FORMAT_CONNECTED = "format:connected";
const char *FORMAT_PACKETLOSS = "format:packetloss"; static constexpr auto FORMAT_PACKETLOSS = "format:packetloss";
const char *FORMAT_DISCONNECTED = "format:disconnected"; static constexpr auto FORMAT_DISCONNECTED = "format:disconnected";
const char *TAG_RAMP_SIGNAL = "<ramp:signal>"; static constexpr auto TAG_RAMP_SIGNAL = "<ramp:signal>";
const char *TAG_LABEL_CONNECTED = "<label:connected>"; static constexpr auto TAG_LABEL_CONNECTED = "<label:connected>";
const char *TAG_LABEL_DISCONNECTED = "<label:disconnected>"; static constexpr auto TAG_LABEL_DISCONNECTED = "<label:disconnected>";
const char *TAG_LABEL_PACKETLOSS = "<label:packetloss>"; static constexpr auto TAG_LABEL_PACKETLOSS = "<label:packetloss>";
const char *TAG_ANIMATION_PACKETLOSS = "<animation:packetloss>"; static constexpr auto TAG_ANIMATION_PACKETLOSS = "<animation:packetloss>";
std::unique_ptr<net::WiredNetwork> wired_network; std::unique_ptr<net::WiredNetwork> wired_network;
std::unique_ptr<net::WirelessNetwork> wireless_network; std::unique_ptr<net::WirelessNetwork> wireless_network;
@ -51,7 +50,7 @@ namespace modules
void subthread_routine(); void subthread_routine();
public: public:
NetworkModule(const std::string& name); explicit NetworkModule(const std::string& name);
void start(); void start();
bool update(); bool update();
@ -62,5 +61,3 @@ namespace modules
}; };
} }
#endif

View file

@ -1,5 +1,4 @@
#ifndef _MODULES_SCRIPT_HPP_ #pragma once
#define _MODULES_SCRIPT_HPP_
#include "modules/base.hpp" #include "modules/base.hpp"
#include "services/command.hpp" #include "services/command.hpp"
@ -8,7 +7,7 @@ namespace modules
{ {
DefineModule(ScriptModule, TimerModule) DefineModule(ScriptModule, TimerModule)
{ {
const char *TAG_OUTPUT = "<output>"; static constexpr auto TAG_OUTPUT = "<output>";
std::unique_ptr<Builder> builder; std::unique_ptr<Builder> builder;
@ -25,12 +24,10 @@ namespace modules
protected: protected:
public: public:
ScriptModule(const std::string& name); explicit ScriptModule(const std::string& name);
bool update(); bool update();
bool build(Builder *builder, const std::string& tag); bool build(Builder *builder, const std::string& tag);
std::string get_output(); std::string get_output();
}; };
} }
#endif

View file

@ -1,5 +1,4 @@
#ifndef _MODULES_TEXT_HPP_ #pragma once
#define _MODULES_TEXT_HPP_
#include "modules/base.hpp" #include "modules/base.hpp"
@ -7,14 +6,12 @@ namespace modules
{ {
DefineModule(TextModule, StaticModule) DefineModule(TextModule, StaticModule)
{ {
const char *FORMAT = "content"; static constexpr auto FORMAT = "content";
public: public:
TextModule(const std::string& name) throw(UndefinedFormat); explicit TextModule(const std::string& name);
std::string get_format(); std::string get_format();
std::string get_output(); std::string get_output();
}; };
} }
#endif

View file

@ -1,5 +1,4 @@
#ifndef _MODULES_TORRENT_HPP_ #pragma once
#define _MODULES_TORRENT_HPP_
#include "modules/base.hpp" #include "modules/base.hpp"
#include "drawtypes/bar.hpp" #include "drawtypes/bar.hpp"
@ -19,8 +18,8 @@ namespace modules
DefineModule(TorrentModule, InotifyModule) DefineModule(TorrentModule, InotifyModule)
{ {
const char *TAG_LABEL = "<label>"; static constexpr auto TAG_LABEL = "<label>";
const char *TAG_BAR_PROGRESS = "<bar:progress>"; static constexpr auto TAG_BAR_PROGRESS = "<bar:progress>";
std::vector<std::unique_ptr<Torrent>> torrents; std::vector<std::unique_ptr<Torrent>> torrents;
std::unique_ptr<drawtypes::Label> label; std::unique_ptr<drawtypes::Label> label;
@ -31,12 +30,10 @@ namespace modules
std::vector<std::unique_ptr<Torrent>> &read_data_into(std::vector<std::unique_ptr<Torrent>> &container); std::vector<std::unique_ptr<Torrent>> &read_data_into(std::vector<std::unique_ptr<Torrent>> &container);
public: public:
TorrentModule(const std::string& name); explicit TorrentModule(const std::string& name);
void start(); void start();
bool on_event(InotifyEvent *event); bool on_event(InotifyEvent *event);
bool build(Builder *builder, const std::string& tag); bool build(Builder *builder, const std::string& tag);
}; };
} }
#endif

View file

@ -1,5 +1,4 @@
#ifndef _MODULES_VOLUME_HPP_ #pragma once
#define _MODULES_VOLUME_HPP_
#include "modules/base.hpp" #include "modules/base.hpp"
#include "interfaces/alsa.hpp" #include "interfaces/alsa.hpp"
@ -12,17 +11,17 @@ namespace modules
{ {
DefineModule(VolumeModule, EventModule) DefineModule(VolumeModule, EventModule)
{ {
const char *FORMAT_VOLUME = "format:volume"; static constexpr auto FORMAT_VOLUME = "format:volume";
const char *FORMAT_MUTED = "format:muted"; static constexpr auto FORMAT_MUTED = "format:muted";
const char *TAG_RAMP_VOLUME = "<ramp:volume>"; static constexpr auto TAG_RAMP_VOLUME = "<ramp:volume>";
const char *TAG_BAR_VOLUME = "<bar:volume>"; static constexpr auto TAG_BAR_VOLUME = "<bar:volume>";
const char *TAG_LABEL_VOLUME = "<label:volume>"; static constexpr auto TAG_LABEL_VOLUME = "<label:volume>";
const char *TAG_LABEL_MUTED = "<label:muted>"; static constexpr auto TAG_LABEL_MUTED = "<label:muted>";
const char *EVENT_VOLUME_UP = "volup"; static constexpr auto EVENT_VOLUME_UP = "volup";
const char *EVENT_VOLUME_DOWN = "voldown"; static constexpr auto EVENT_VOLUME_DOWN = "voldown";
const char *EVENT_TOGGLE_MUTE = "volmute"; static constexpr auto EVENT_TOGGLE_MUTE = "volmute";
std::unique_ptr<alsa::Mixer> master_mixer; std::unique_ptr<alsa::Mixer> master_mixer;
std::unique_ptr<alsa::Mixer> speaker_mixer; std::unique_ptr<alsa::Mixer> speaker_mixer;
@ -43,7 +42,7 @@ namespace modules
bool muted = false; bool muted = false;
public: public:
VolumeModule(const std::string& name) throw(ModuleError); explicit VolumeModule(const std::string& name);
~VolumeModule(); ~VolumeModule();
bool has_event(); bool has_event();
@ -56,5 +55,3 @@ namespace modules
bool handle_command(const std::string& cmd); bool handle_command(const std::string& cmd);
}; };
} }
#endif

View file

@ -1,22 +1,17 @@
#ifndef _REGISTRY_HPP_ #pragma once
#define _REGISTRY_HPP_
#include <condition_variable>
#include "exception.hpp"
#include "modules/base.hpp" #include "modules/base.hpp"
DefineBaseException(RegistryError); DefineBaseException(RegistryError);
DefineChildException(ModuleNotFound, RegistryError); DefineChildException(ModuleNotFound, RegistryError);
struct ModuleEntry struct RegistryModuleEntry
{ {
concurrency::Atomic<bool> warmedup; concurrency::Atomic<bool> warmedup;
std::unique_ptr<modules::ModuleInterface> module; std::unique_ptr<modules::ModuleInterface> module;
ModuleEntry(std::unique_ptr<modules::ModuleInterface> &&module) RegistryModuleEntry(std::unique_ptr<modules::ModuleInterface> &&module) : warmedup(false)
{ {
this->warmedup = false;
this->module.swap(module); this->module.swap(module);
} }
}; };
@ -34,7 +29,7 @@ class Registry
concurrency::Atomic<int> stage; concurrency::Atomic<int> stage;
std::vector<std::unique_ptr<ModuleEntry>> modules; std::vector<std::unique_ptr<RegistryModuleEntry>> modules;
std::mutex wait_mtx; std::mutex wait_mtx;
std::condition_variable wait_cv; std::condition_variable wait_cv;
@ -49,9 +44,7 @@ class Registry
bool wait(); bool wait();
void notify(const std::string& module_name); void notify(const std::string& module_name);
std::string get(const std::string& module_name); std::string get(const std::string& module_name);
std::unique_ptr<ModuleEntry>& find(const std::string& module_name) throw(ModuleNotFound); std::unique_ptr<RegistryModuleEntry>& find(const std::string& module_name);
}; };
std::shared_ptr<Registry> &get_registry(); std::shared_ptr<Registry> &get_registry();
#endif

View file

@ -1,5 +1,4 @@
#ifndef _SERVICES_BUILDER_HPP_ #pragma once
#define _SERVICES_BUILDER_HPP_
#include <string> #include <string>
#include <memory> #include <memory>
@ -43,7 +42,7 @@ class Builder
void align_right(); void align_right();
public: public:
Builder(bool lazy_closing = true) : lazy_closing(lazy_closing){} explicit Builder(bool lazy_closing = true) : lazy_closing(lazy_closing){}
void set_lazy_closing(bool mode) { this->lazy_closing = mode; } void set_lazy_closing(bool mode) { this->lazy_closing = mode; }
@ -93,10 +92,8 @@ class Builder
void underline(const std::string& color = ""); void underline(const std::string& color = "");
void underline_close(bool force = false); void underline_close(bool force = false);
void invert(); // void invert();
void cmd(int button, std::string action, bool condition = true); void cmd(int button, std::string action, bool condition = true);
void cmd_close(bool force = false); void cmd_close(bool force = false);
}; };
#endif

View file

@ -1,5 +1,4 @@
#ifndef _SERVICES_COMMAND_HPP_ #pragma once
#define _SERVICES_COMMAND_HPP_
#include <functional> #include <functional>
#include <memory> #include <memory>
@ -9,9 +8,7 @@
#include "exception.hpp" #include "exception.hpp"
#include "utils/proc.hpp" #include "utils/proc.hpp"
class CommandException : public Exception { DefineBaseException(CommandException);
using Exception::Exception;
};
class Command class Command
{ {
@ -25,21 +22,18 @@ class Command
int fork_status; int fork_status;
public: public:
Command(const std::string& cmd, int stdout[2] = nullptr, int stdin[2] = nullptr) Command(const std::string& cmd, int stdout[2] = nullptr, int stdin[2] = nullptr);
throw(CommandException); ~Command();
~Command() throw(CommandException);
int exec(bool wait_for_completion = true) throw(CommandException); int exec(bool wait_for_completion = true);
int wait() throw(CommandException); int wait();
void tail(std::function<void(std::string)> callback); void tail(std::function<void(std::string)> callback);
int writeline(const std::string& data); int writeline(const std::string& data);
int get_stdout(int); int get_stdout(int);
int get_stdin(int); // int get_stdin(int);
pid_t get_pid(); // pid_t get_pid();
int get_exit_status(); // int get_exit_status();
}; };
#endif

View file

@ -1,5 +1,4 @@
#ifndef _SERVICES_INOTIFY_HPP_ #pragma once
#define _SERVICES_INOTIFY_HPP_
#include <memory> #include <memory>
#include <sys/inotify.h> #include <sys/inotify.h>
@ -9,7 +8,7 @@
class InotifyException : public Exception class InotifyException : public Exception
{ {
public: public:
InotifyException(const std::string& msg) explicit InotifyException(const std::string& msg)
: Exception("[Inotify] "+ msg){} : Exception("[Inotify] "+ msg){}
}; };
@ -49,7 +48,7 @@ class InotifyWatch
int fd = -1, wd = -1, mask; int fd = -1, wd = -1, mask;
public: public:
InotifyWatch(const std::string& path, int mask = InotifyEvent::ALL) throw (InotifyException); explicit InotifyWatch(const std::string& path, int mask = InotifyEvent::ALL);
~InotifyWatch(); ~InotifyWatch();
std::string operator()() { std::string operator()() {
@ -59,5 +58,3 @@ class InotifyWatch
bool has_event(int timeout_ms = 1000); bool has_event(int timeout_ms = 1000);
std::unique_ptr<InotifyEvent> get_event(); std::unique_ptr<InotifyEvent> get_event();
}; };
#endif

View file

@ -1,9 +1,9 @@
#ifndef _SERVICES_LOGGER_HPP_ #pragma once
#define _SERVICES_LOGGER_HPP_
#include <memory> #include <memory>
#include <string> #include <string>
#include <mutex> #include <mutex>
#include <unistd.h>
#include "exception.hpp" #include "exception.hpp"
#include "utils/streams.hpp" #include "utils/streams.hpp"
@ -44,7 +44,7 @@ class Logger
public: public:
Logger(); Logger();
void set_level(int level); // void set_level(int level);
void add_level(int level); void add_level(int level);
void fatal(const std::string& msg); void fatal(const std::string& msg);
@ -65,5 +65,3 @@ class Logger
}; };
std::shared_ptr<Logger> &get_logger(); std::shared_ptr<Logger> &get_logger();
#endif

View file

@ -1,6 +1,9 @@
#if 0 #if 0
#ifndef _SERVICES_STORE_HPP_ #ifndef _SERVICES_STORE_HPP_
#define _SERVICES_STORE_HPP_ #define _SERVICES_STORE_HPP_
=======
#pragma once
>>>>>>> task(core): Cleanup
#include <string> #include <string>
#include <memory> #include <memory>
@ -33,6 +36,7 @@ struct Store
Store(int size); Store(int size);
~Store() {} ~Store() {}
}; };
<<<<<<< 78384e08923e669c65c68a8cdf81dba37a633d6c
#endif #endif
#endif #endif

View file

@ -1,16 +1,12 @@
#ifndef _UTILS_CLI_HPP_ #pragma once
#define _UTILS_CLI_HPP_
#include <string>
#include <vector> #include <vector>
#include "exception.hpp" #include "exception.hpp"
namespace cli namespace cli
{ {
class CommandLineError : public Exception { DefineBaseException(CommandLineError);
using Exception::Exception;
};
struct Option struct Option
{ {
@ -40,5 +36,3 @@ namespace cli
void usage(const std::string& usage, bool exit_success = true); void usage(const std::string& usage, bool exit_success = true);
} }
#endif

View file

@ -1,3 +1,5 @@
#pragma once
#include <atomic> #include <atomic>
#include <mutex> #include <mutex>
#include <thread> #include <thread>
@ -59,7 +61,7 @@ namespace concurrency
public: public:
Atomic() = default; Atomic() = default;
Atomic(T init) { explicit Atomic(T init) {
this->operator=(init); this->operator=(init);
} }
@ -96,7 +98,7 @@ namespace concurrency
public: public:
Value() = default; Value() = default;
Value(T init) { explicit Value(T init) {
this->operator=(init); this->operator=(init);
} }

View file

@ -1,62 +1,38 @@
#ifndef _UTILS_CONFIG_HPP_ #pragma once
#define _UTILS_CONFIG_HPP_
#include <string>
#include <vector>
#include <mutex> #include <mutex>
#include <boost/property_tree/ptree.hpp> #include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp> #include <boost/property_tree/ini_parser.hpp>
#include "exception.hpp" #include "exception.hpp"
#include "services/logger.hpp"
#include "utils/string.hpp" #include "utils/string.hpp"
namespace config namespace config
{ {
class ConfigException : public Exception { DefineBaseException(ConfigException);
using Exception::Exception; DefineChildException(UnexistingFileError, ConfigException);
}; DefineChildException(ParseError, ConfigException);
DefineChildException(MissingValueException, ConfigException);
class UnexistingFileError : public ConfigException { DefineChildException(MissingListValueException, ConfigException);
using ConfigException::ConfigException; DefineChildException(InvalidVariableException, ConfigException);
}; DefineChildException(InvalidReferenceException, ConfigException);
class ParseError : public ConfigException {
using ConfigException::ConfigException;
};
class MissingValueException : public ConfigException {
using ConfigException::ConfigException;
};
class MissingListValueException : public ConfigException {
using ConfigException::ConfigException;
};
class InvalidVariableException : public ConfigException {
using ConfigException::ConfigException;
};
class InvalidReferenceException : public ConfigException {
using ConfigException::ConfigException;
};
static std::recursive_mutex mtx; static std::recursive_mutex mtx;
std::string get_bar_path(); std::string get_bar_path();
void set_bar_path(const std::string& path); void set_bar_path(const std::string& path);
void load(const std::string& path) throw(UnexistingFileError, ParseError); void load(const std::string& path);
void load(const char *dir, const std::string& path); void load(const char *dir, const std::string& path);
void reload() throw(ParseError); // void reload();
boost::property_tree::ptree get_tree(); boost::property_tree::ptree get_tree();
std::string build_path(const std::string& section, const std::string& key); std::string build_path(const std::string& section, const std::string& key);
template<typename T> template<typename T>
T dereference_var(const std::string& ref_section, const std::string& ref_key, const std::string& var, const T ref_val) throw (InvalidVariableException, InvalidReferenceException) T dereference_var(const std::string& ref_section, const std::string& ref_key, const std::string& var, const T ref_val)
{ {
std::lock_guard<std::recursive_mutex> lck(config::mtx); std::lock_guard<std::recursive_mutex> lck(config::mtx);
@ -85,7 +61,7 @@ namespace config
} }
template<typename T> template<typename T>
T get(const std::string& section, const std::string& key) throw (MissingValueException) T get(const std::string& section, const std::string& key)
{ {
std::lock_guard<std::recursive_mutex> lck(config::mtx); std::lock_guard<std::recursive_mutex> lck(config::mtx);
@ -111,7 +87,7 @@ namespace config
} }
template<typename T> template<typename T>
std::vector<T> get_list(const std::string& section, const std::string& key) throw (MissingListValueException) std::vector<T> get_list(const std::string& section, const std::string& key)
{ {
std::lock_guard<std::recursive_mutex> lck(config::mtx); std::lock_guard<std::recursive_mutex> lck(config::mtx);
@ -148,5 +124,3 @@ namespace config
return vec; return vec;
} }
} }
#endif

View file

@ -1,5 +1,4 @@
#ifndef _UTILS_IO_HPP_ #pragma once
#define _UTILS_IO_HPP_
#include <string> #include <string>
#include <functional> #include <functional>
@ -30,9 +29,8 @@ namespace io
std::string mode; std::string mode;
FilePtr(const std::string& path, const std::string& mode = "a+") FilePtr(const std::string& path, const std::string& mode = "a+")
: path(std::string(path)), mode(std::string(mode))
{ {
this->path = std::string(path);
this->mode = std::string(mode);
this->fptr = fopen(this->path.c_str(), this->mode.c_str()); this->fptr = fopen(this->path.c_str(), this->mode.c_str());
} }
@ -69,12 +67,10 @@ namespace io
void tail(int read_fd, int writeback_fd); void tail(int read_fd, int writeback_fd);
bool poll_read(int fd, int timeout_ms = 1); bool poll_read(int fd, int timeout_ms = 1);
bool poll_write(int fd, int timeout_ms = 1); // bool poll_write(int fd, int timeout_ms = 1);
bool poll(int fd, short int events, int timeout_ms = 1); bool poll(int fd, short int events, int timeout_ms = 1);
int get_flags(int fd); // int get_flags(int fd);
int set_blocking(int fd); // int set_blocking(int fd);
int set_non_blocking(int fd); // int set_non_blocking(int fd);
} }
#endif

13
include/utils/macros.hpp Normal file
View file

@ -0,0 +1,13 @@
#pragma once
#define writeln(s) std::cout << s << std::endl
#define writeln_ss(s) { std::stringstream ss; ss << s; writeln(ss.str()); std::stringstream s; }
#define ToStr(s) std::string(s)
#define IntToStr(s) std::to_string(s)
#define StrErrno() ToStr(std::strerror(errno))
#define StrErrnoCustom(s) ToStr(std::strerror(s))
#define StrSignal(sig) IntToStr(sig)
#define StrSignalC(sig) strsignal(sig)

View file

@ -1,5 +1,4 @@
#ifndef _UTILS_MATH_HPP_ #pragma once
#define _UTILS_MATH_HPP_
#include <string> #include <string>
#include <algorithm> #include <algorithm>
@ -14,5 +13,3 @@ namespace math
return value; return value;
} }
} }
#endif

View file

@ -1,5 +1,4 @@
#ifndef _UTILS_MEMORY_HPP #pragma once
#define _UTILS_MEMORY_HPP
// Swap the two ints without the need of creating another tmp variable // Swap the two ints without the need of creating another tmp variable
#define int_memswap(one, two) one += two; \ #define int_memswap(one, two) one += two; \
@ -12,5 +11,3 @@
#define repeat_with(n, m) for (m = n; m--;) #define repeat_with(n, m) for (m = n; m--;)
#define repeat_i i #define repeat_i i
#define repeat_i_rev(n) (n - i - 1) #define repeat_i_rev(n) (n - i - 1)
#endif

View file

@ -1,5 +1,4 @@
#ifndef _UTILS_PROC_HPP_ #pragma once
#define _UTILS_PROC_HPP_
#include <string> #include <string>
#include <errno.h> #include <errno.h>
@ -11,13 +10,6 @@
#define PIPE_READ 0 #define PIPE_READ 0
#define PIPE_WRITE 1 #define PIPE_WRITE 1
#define STRERRNO std::string(std::strerror(errno))
#define STRERRNO_VAL(s) std::string(std::strerror(s))
#define SIGCSTR(sig) strsignal(sig)
#define SIGNSTR(sig) std::to_string(sig)
#define SIGSTR(sig) std::string(SIGCSTR(sig))
namespace proc namespace proc
{ {
class ExecFailure : public Exception { class ExecFailure : public Exception {
@ -25,14 +17,14 @@ namespace proc
}; };
pid_t get_process_id(); pid_t get_process_id();
pid_t get_parent_process_id(); // pid_t get_parent_process_id();
bool in_parent_process(pid_t pid); bool in_parent_process(pid_t pid);
bool in_forked_process(pid_t pid); bool in_forked_process(pid_t pid);
pid_t fork(); pid_t fork();
bool pipe(int fds[2]); bool pipe(int fds[2]);
void exec(const std::string& cmd) throw(ExecFailure); void exec(const std::string& cmd);
bool kill(pid_t pid, int sig = SIGTERM); bool kill(pid_t pid, int sig = SIGTERM);
@ -43,5 +35,3 @@ namespace proc
pid_t wait_for_completion_nohang(int *status); pid_t wait_for_completion_nohang(int *status);
pid_t wait_for_completion_nohang(); pid_t wait_for_completion_nohang();
} }
#endif

View file

@ -1,5 +1,5 @@
#ifndef _UTILS_STREAMS_HPP_ #if 0
#define _UTILS_STREAMS_HPP_ #pragma once
#include <iostream> #include <iostream>
#include <streambuf> #include <streambuf>
@ -43,5 +43,4 @@ namespace streams
} }
}; };
} }
#endif #endif

View file

@ -1,17 +1,13 @@
#ifndef _UTILS_STRING_HPP_ #pragma once
#define _UTILS_STRING_HPP_
#include <string> #include <string>
#include <vector> #include <vector>
#define STR(s) std::string(s)
#define STRI(s) std::to_string(s)
namespace string namespace string
{ {
bool compare(const std::string& s1, const std::string& s2); bool compare(const std::string& s1, const std::string& s2);
std::string upper(const std::string& s); // std::string upper(const std::string& s);
std::string lower(const std::string& s); std::string lower(const std::string& s);
std::string replace(const std::string& haystack, const std::string& needle, const std::string& replacement); std::string replace(const std::string& haystack, const std::string& needle, const std::string& replacement);
@ -19,7 +15,7 @@ namespace string
std::string squeeze(const std::string& haystack, const char &needle); std::string squeeze(const std::string& haystack, const char &needle);
std::string strip(const std::string& haystack, const char &needle); // std::string strip(const std::string& haystack, const char &needle);
std::string strip_trailing_newline(const std::string& s); std::string strip_trailing_newline(const std::string& s);
std::string trim(const std::string& haystack, const char &needle); std::string trim(const std::string& haystack, const char &needle);
@ -33,5 +29,3 @@ namespace string
std::size_t find_nth(const std::string& haystack, std::size_t pos, const std::string& needle, std::size_t nth); std::size_t find_nth(const std::string& haystack, std::size_t pos, const std::string& needle, std::size_t nth);
} }
#endif

View file

@ -1,10 +1,9 @@
#ifndef _UTILS_TIMER_HPP_ #if 0
#define _UTILS_TIMER_HPP_ #pragma once
namespace timer namespace timer
{ {
unsigned int seconds_to_microseconds(float seconds); // unsigned int seconds_to_microseconds(float seconds);
void sleep(float seconds); // void sleep(float seconds);
} }
#endif #endif

View file

@ -1,5 +1,4 @@
#ifndef _UTILS_XLIB_HPP_ #pragma once
#define _UTILS_XLIB_HPP_
#include <sstream> #include <sstream>
#include <memory> #include <memory>
@ -26,9 +25,7 @@ namespace xlib
} }
}; };
std::unique_ptr<Monitor> get_monitor(const std::string& monitor_name); // std::unique_ptr<Monitor> get_monitor(const std::string& monitor_name);
std::vector<std::unique_ptr<Monitor>> get_sorted_monitorlist(); std::vector<std::unique_ptr<Monitor>> get_sorted_monitorlist();
} }
#endif

View file

@ -44,14 +44,10 @@ const Options& bar_opts() {
/** /**
* Bar constructor * Bar constructor
*/ */
Bar::Bar() Bar::Bar() : config_path(config::get_bar_path()), opts(std::make_unique<Options>())
{ {
this->config_path = config::get_bar_path();
struct Options defaults; struct Options defaults;
this->opts = std::make_unique<Options>();
try { try {
this->opts->locale = config::get<std::string>(this->config_path, "locale"); this->opts->locale = config::get<std::string>(this->config_path, "locale");
std::locale::global(std::locale(this->opts->locale.c_str())); std::locale::global(std::locale(this->opts->locale.c_str()));

View file

@ -31,9 +31,9 @@ namespace drawtypes
} }
Animation::Animation(std::vector<std::unique_ptr<Icon>> &&frames, int framerate_ms) Animation::Animation(std::vector<std::unique_ptr<Icon>> &&frames, int framerate_ms)
: frames(std::move(frames))
{ {
this->framerate_ms = framerate_ms; this->framerate_ms = framerate_ms;
this->frames = std::move(frames);
this->num_frames = this->frames.size(); this->num_frames = this->frames.size();
this->updated_at = std::chrono::system_clock::now(); this->updated_at = std::chrono::system_clock::now();
} }

View file

@ -28,11 +28,10 @@ namespace drawtypes
return bar; return bar;
} }
Bar::Bar(int width, const std::string& format, bool lazy_builder_closing) Bar::Bar(int width, const std::string& fmt, bool lazy_builder_closing)
: builder(std::make_unique<Builder>(lazy_builder_closing)), format(fmt)
{ {
this->width = width; this->width = width;
this->format = format;
this->builder = std::make_unique<Builder>(lazy_builder_closing);
} }
void Bar::set_fill(std::unique_ptr<Icon> &&fill) { void Bar::set_fill(std::unique_ptr<Icon> &&fill) {
@ -63,7 +62,6 @@ namespace drawtypes
int fill_width = (int) this->width * percentage / 100 + add; int fill_width = (int) this->width * percentage / 100 + add;
int empty_width = this->width - fill_width; int empty_width = this->width - fill_width;
int color_step = this->width / this->colors.size() + 0.5f; int color_step = this->width / this->colors.size() + 0.5f;
int i = 0, j = 0;
auto output = std::string(this->format); auto output = std::string(this->format);
@ -83,9 +81,10 @@ namespace drawtypes
this->fill->fg = this->colors[color-1]; this->fill->fg = this->colors[color-1];
while (fill_width--) this->builder->node(this->fill); while (fill_width--) this->builder->node(this->fill);
} else { } else {
int i = 0;
for (auto color : this->colors) { for (auto color : this->colors) {
i += 1; i += 1;
j = 0; int j = 0;
if ((i-1) * color_step >= fill_width) break; if ((i-1) * color_step >= fill_width) break;

View file

@ -8,25 +8,23 @@
#include "eventloop.hpp" #include "eventloop.hpp"
#include "services/command.hpp" #include "services/command.hpp"
#include "utils/io.hpp" #include "utils/io.hpp"
#include "utils/macros.hpp"
EventLoop::EventLoop(std::string input_pipe) EventLoop::EventLoop(std::string input_pipe)
: bar(get_bar()),
registry(get_registry()),
logger(get_logger()),
state(STATE_STOPPED),
pipe_filename(input_pipe)
{ {
this->bar = get_bar(); if (this->pipe_filename.empty())
this->registry = get_registry(); return;
this->logger = get_logger(); if (io::file::is_fifo(this->pipe_filename))
return;
this->state = STATE_STOPPED; if (io::file::exists(this->pipe_filename))
unlink(this->pipe_filename.c_str());
this->pipe_filename = input_pipe; if (mkfifo(this->pipe_filename.c_str(), 0600) == -1)
throw EventLoopTerminate(StrErrno());
if (!this->pipe_filename.empty()) {
if (!io::file::is_fifo(this->pipe_filename)) {
if (io::file::exists(this->pipe_filename))
unlink(this->pipe_filename.c_str());
if (mkfifo(this->pipe_filename.c_str(), 0600) == -1)
throw Exception(STRERRNO);
}
}
} }
bool EventLoop::running() bool EventLoop::running()
@ -83,7 +81,7 @@ void EventLoop::wait()
sigaddset(&this->wait_mask, SIGTERM); sigaddset(&this->wait_mask, SIGTERM);
if (pthread_sigmask(SIG_BLOCK, &this->wait_mask, nullptr) == -1) if (pthread_sigmask(SIG_BLOCK, &this->wait_mask, nullptr) == -1)
logger->fatal(STRERRNO); logger->fatal(StrErrno());
// Wait for termination signal // Wait for termination signal
sigwait(&this->wait_mask, &sig); sigwait(&this->wait_mask, &sig);
@ -145,8 +143,8 @@ void EventLoop::loop_read()
{ {
while (!this->pipe_filename.empty() && this->running()) { while (!this->pipe_filename.empty() && this->running()) {
try { try {
if ((this->fd_stdin = open(this->pipe_filename.c_str(), O_RDONLY)) == -1) if ((this->fd_stdin = ::open(this->pipe_filename.c_str(), O_RDONLY)) == -1)
throw Exception(STRERRNO); throw EventLoopTerminate(StrErrno());
this->read_stdin(); this->read_stdin();
} catch (Exception &e) { } catch (Exception &e) {

View file

@ -4,10 +4,11 @@
#include "utils/config.hpp" #include "utils/config.hpp"
#include "utils/memory.hpp" #include "utils/memory.hpp"
#include "utils/proc.hpp" #include "utils/proc.hpp"
#include "utils/macros.hpp"
namespace alsa namespace alsa
{ {
ControlInterface::ControlInterface(int numid) throw(ControlInterfaceError) ControlInterface::ControlInterface(int numid)
{ {
int err; int err;
@ -19,22 +20,22 @@ namespace alsa
snd_ctl_elem_info_set_id(this->info, this->id); snd_ctl_elem_info_set_id(this->info, this->id);
if ((err = snd_ctl_open(&this->ctl, ALSA_SOUNDCARD, SND_CTL_NONBLOCK | SND_CTL_READONLY)) < 0) if ((err = snd_ctl_open(&this->ctl, ALSA_SOUNDCARD, SND_CTL_NONBLOCK | SND_CTL_READONLY)) < 0)
throw ControlInterfaceError("Could not open control \""+ STR(ALSA_SOUNDCARD) +"\": "+ STRSNDERR(err)); throw ControlInterfaceError(err, "Could not open control \""+ ToStr(ALSA_SOUNDCARD) +"\": "+ STRSNDERR(err));
if ((err = snd_ctl_elem_info(this->ctl, this->info)) < 0) if ((err = snd_ctl_elem_info(this->ctl, this->info)) < 0)
throw ControlInterfaceError("Could not get control data: "+ STRSNDERR(err)); throw ControlInterfaceError(err, "Could not get control data: "+ STRSNDERR(err));
snd_ctl_elem_info_get_id(this->info, this->id); snd_ctl_elem_info_get_id(this->info, this->id);
if ((err = snd_hctl_open(&this->hctl, ALSA_SOUNDCARD, 0)) < 0) if ((err = snd_hctl_open(&this->hctl, ALSA_SOUNDCARD, 0)) < 0)
throw ControlInterfaceError(STRSNDERR(err)); throw ControlInterfaceError(err, STRSNDERR(err));
if ((err = snd_hctl_load(this->hctl)) < 0) if ((err = snd_hctl_load(this->hctl)) < 0)
throw ControlInterfaceError(STRSNDERR(err)); throw ControlInterfaceError(err, STRSNDERR(err));
if ((elem = snd_hctl_find_elem(this->hctl, this->id)) == nullptr) if ((elem = snd_hctl_find_elem(this->hctl, this->id)) == nullptr)
throw ControlInterfaceError("Could not find control with id "+ STRI(snd_ctl_elem_id_get_numid(this->id))); throw ControlInterfaceError(err, "Could not find control with id "+ IntToStr(snd_ctl_elem_id_get_numid(this->id)));
if ((err = snd_ctl_subscribe_events(this->ctl, 1)) < 0) if ((err = snd_ctl_subscribe_events(this->ctl, 1)) < 0)
throw ControlInterfaceError("Could not subscribe to events: "+ STRI(snd_ctl_elem_id_get_numid(this->id))); throw ControlInterfaceError(err, "Could not subscribe to events: "+ IntToStr(snd_ctl_elem_id_get_numid(this->id)));
log_trace("Successfully initialized control interface"); log_trace("Successfully initialized control interface");
} }
@ -45,20 +46,23 @@ namespace alsa
snd_hctl_close(this->hctl); snd_hctl_close(this->hctl);
} }
bool ControlInterface::wait(int timeout) throw(ControlInterfaceError) bool ControlInterface::wait(int timeout)
{ {
std::lock_guard<std::mutex> lck(this->mtx); std::lock_guard<std::mutex> lck(this->mtx);
int err; int err;
if ((err = snd_ctl_wait(this->ctl, timeout)) < 0) if ((err = snd_ctl_wait(this->ctl, timeout)) < 0)
throw ControlInterfaceError("Failed to wait for events: "+ STRSNDERR(err)); throw ControlInterfaceError(err, "Failed to wait for events: "+ STRSNDERR(err));
snd_ctl_event_t *event; snd_ctl_event_t *event;
snd_ctl_event_alloca(&event); snd_ctl_event_alloca(&event);
if ((err = snd_ctl_read(this->ctl, event)) < 0) if ((err = snd_ctl_read(this->ctl, event)) < 0) {
log_trace(err);
return false; return false;
}
if (snd_ctl_event_get_type(event) != SND_CTL_EVENT_ELEM) if (snd_ctl_event_get_type(event) != SND_CTL_EVENT_ELEM)
return false; return false;
@ -67,7 +71,7 @@ namespace alsa
return mask & SND_CTL_EVENT_MASK_VALUE; return mask & SND_CTL_EVENT_MASK_VALUE;
} }
bool ControlInterface::test_device_plugged() throw(ControlInterfaceError) bool ControlInterface::test_device_plugged()
{ {
int err; int err;
@ -75,13 +79,13 @@ namespace alsa
return false; return false;
if ((err = snd_hctl_elem_read(this->elem, this->value)) < 0) if ((err = snd_hctl_elem_read(this->elem, this->value)) < 0)
throw ControlInterfaceError("Could not read control value: "+ STRSNDERR(err)); throw ControlInterfaceError(err, "Could not read control value: "+ STRSNDERR(err));
return snd_ctl_elem_value_get_boolean(this->value, 0); return snd_ctl_elem_value_get_boolean(this->value, 0);
} }
Mixer::Mixer(const std::string& mixer_control_name) throw(MixerError) Mixer::Mixer(const std::string& mixer_control_name)
{ {
snd_mixer_selem_id_t *mixer_id; snd_mixer_selem_id_t *mixer_id;
@ -112,7 +116,7 @@ namespace alsa
snd_mixer_close(this->hardware_mixer); snd_mixer_close(this->hardware_mixer);
} }
bool Mixer::wait(int timeout) throw(MixerError) bool Mixer::wait(int timeout)
{ {
std::lock_guard<std::mutex> lck(this->mtx); std::lock_guard<std::mutex> lck(this->mtx);

View file

@ -56,23 +56,23 @@ namespace mpd
return this->connection.get() != nullptr; return this->connection.get() != nullptr;
} }
bool Connection::retry_connection(int interval) // bool Connection::retry_connection(int interval)
{ // {
if (this->connected()) // if (this->connected())
return true; // return true;
//
while (true) { // while (true) {
try { // try {
this->connect(); // this->connect();
return true; // return true;
} catch (Exception &e) { // } catch (Exception &e) {
get_logger()->debug(e.what()); // get_logger()->debug(e.what());
} // }
//
std::this_thread::sleep_for( // std::this_thread::sleep_for(
std::chrono::duration<double>(interval)); // std::chrono::duration<double>(interval));
} // }
} // }
void Connection::idle() void Connection::idle()
{ {
@ -159,16 +159,16 @@ namespace mpd
} }
} }
void Connection::toggle() // void Connection::toggle()
{ // {
try { // try {
this->check_prerequisites_commands_list(); // this->check_prerequisites_commands_list();
mpd_run_toggle_pause(this->connection.get()); // mpd_run_toggle_pause(this->connection.get());
this->check_errors(); // this->check_errors();
} catch (Exception &e) { // } catch (Exception &e) {
log_error(e.what()); // log_error(e.what());
} // }
} // }
void Connection::stop() void Connection::stop()
{ {
@ -222,7 +222,7 @@ namespace mpd
} }
} }
void Connection::repeat(bool mode) void Connection::set_repeat(bool mode)
{ {
try { try {
this->check_prerequisites_commands_list(); this->check_prerequisites_commands_list();
@ -233,7 +233,7 @@ namespace mpd
} }
} }
void Connection::random(bool mode) void Connection::set_random(bool mode)
{ {
try { try {
this->check_prerequisites_commands_list(); this->check_prerequisites_commands_list();
@ -244,7 +244,7 @@ namespace mpd
} }
} }
void Connection::single(bool mode) void Connection::set_single(bool mode)
{ {
try { try {
this->check_prerequisites_commands_list(); this->check_prerequisites_commands_list();
@ -315,13 +315,13 @@ namespace mpd
this->updated_at = std::chrono::system_clock::now(); this->updated_at = std::chrono::system_clock::now();
} }
unsigned Status::get_total_time() { // unsigned Status::get_total_time() {
return this->total_time; // return this->total_time;
} // }
unsigned Status::get_elapsed_time() { // unsigned Status::get_elapsed_time() {
return this->elapsed_time; // return this->elapsed_time;
} // }
unsigned Status::get_elapsed_percentage() unsigned Status::get_elapsed_percentage()
{ {
@ -360,8 +360,9 @@ namespace mpd
return std::make_unique<Song>(song); return std::make_unique<Song>(song);
} }
Song::Song(struct mpd_song *song) { Song::Song(struct mpd_song *song)
this->song = std::shared_ptr<struct mpd_song>(song, mpd_song_free); : song(std::shared_ptr<struct mpd_song>(song, mpd_song_free))
{
} }
std::string Song::get_artist() std::string Song::get_artist()
@ -391,9 +392,9 @@ namespace mpd
return std::string(tag); return std::string(tag);
} }
unsigned Song::get_duration() // unsigned Song::get_duration()
{ // {
assert(this->song); // assert(this->song);
return mpd_song_get_duration(this->song.get()); // return mpd_song_get_duration(this->song.get());
} // }
} }

View file

@ -15,6 +15,7 @@
#include "services/logger.hpp" #include "services/logger.hpp"
#include "interfaces/net.hpp" #include "interfaces/net.hpp"
#include "utils/io.hpp" #include "utils/io.hpp"
#include "utils/macros.hpp"
#include "utils/string.hpp" #include "utils/string.hpp"
using namespace net; using namespace net;
@ -26,15 +27,14 @@ bool net::is_wireless_interface(const std::string& ifname) {
// Network // Network
Network::Network(const std::string& interface) throw(NetworkException) Network::Network(const std::string& interface)
: interface(interface)
{ {
this->interface = interface;
if (if_nametoindex(this->interface.c_str()) == 0) if (if_nametoindex(this->interface.c_str()) == 0)
throw NetworkException("Invalid network interface \""+ this->interface +"\""); throw NetworkException("Invalid network interface \""+ this->interface +"\"");
if ((this->fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) if ((this->fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
throw NetworkException("Failed to open socket: "+ STRERRNO); throw NetworkException("Failed to open socket: "+ StrErrno());
std::memset(&this->data, 0, sizeof(this->data)); std::memset(&this->data, 0, sizeof(this->data));
std::strncpy(this->data.ifr_name, this->interface.data(), IFNAMSIZ-1); std::strncpy(this->data.ifr_name, this->interface.data(), IFNAMSIZ-1);
@ -43,17 +43,18 @@ Network::Network(const std::string& interface) throw(NetworkException)
Network::~Network() Network::~Network()
{ {
if (close(this->fd) == -1) if (close(this->fd) == -1)
log_error("Failed to close Network socket FD: "+ STRERRNO); log_error("Failed to close Network socket FD: "+ StrErrno());
} }
bool Network::test_interface() throw(NetworkException) bool Network::test_interface()
{ {
if ((ioctl(this->fd, SIOCGIFFLAGS, &this->data)) == -1) if ((ioctl(this->fd, SIOCGIFFLAGS, &this->data)) == -1)
throw NetworkException(STRERRNO); throw NetworkException(StrErrno());
return this->data.ifr_flags & IFF_UP; return this->data.ifr_flags & IFF_UP;
} }
bool Network::test_connection() throw(NetworkException) { bool Network::test_connection()
{
int status = EXIT_FAILURE; int status = EXIT_FAILURE;
try { try {
@ -91,7 +92,7 @@ bool Network::connected()
} }
} }
std::string Network::get_ip() throw(NetworkException) std::string Network::get_ip()
{ {
if (!this->test_interface()) if (!this->test_interface())
throw NetworkException("Interface is not up"); throw NetworkException("Interface is not up");
@ -99,7 +100,7 @@ std::string Network::get_ip() throw(NetworkException)
this->data.ifr_addr.sa_family = AF_INET; this->data.ifr_addr.sa_family = AF_INET;
if (ioctl(this->fd, SIOCGIFADDR, &this->data) == -1) if (ioctl(this->fd, SIOCGIFADDR, &this->data) == -1)
throw NetworkException(STRERRNO); throw NetworkException(StrErrno());
return inet_ntoa(((struct sockaddr_in *) &this->data.ifr_addr)->sin_addr); return inet_ntoa(((struct sockaddr_in *) &this->data.ifr_addr)->sin_addr);
} }
@ -130,7 +131,7 @@ WirelessNetwork::WirelessNetwork(const std::string& interface) : Network(interfa
std::strcpy((char *) &this->iw.ifr_ifrn.ifrn_name, this->interface.c_str()); std::strcpy((char *) &this->iw.ifr_ifrn.ifrn_name, this->interface.c_str());
} }
std::string WirelessNetwork::get_essid() throw(WirelessNetworkException) std::string WirelessNetwork::get_essid()
{ {
char essid[IW_ESSID_MAX_SIZE+1]; char essid[IW_ESSID_MAX_SIZE+1];
@ -140,7 +141,7 @@ std::string WirelessNetwork::get_essid() throw(WirelessNetworkException)
this->iw.u.essid.length = sizeof(essid); this->iw.u.essid.length = sizeof(essid);
if (ioctl(this->fd, SIOCGIWESSID, &this->iw) == -1) if (ioctl(this->fd, SIOCGIWESSID, &this->iw) == -1)
throw WirelessNetworkException(STRERRNO); throw WirelessNetworkException(StrErrno());
return string::trim(essid, ' '); return string::trim(essid, ' ');
} }
@ -151,13 +152,13 @@ float WirelessNetwork::get_signal_quality()
return 2 * (dbm + 100); return 2 * (dbm + 100);
} }
float WirelessNetwork::get_signal_dbm() throw(WirelessNetworkException) float WirelessNetwork::get_signal_dbm()
{ {
this->iw.u.data.pointer = (iw_statistics *) std::malloc(sizeof(iw_statistics)); this->iw.u.data.pointer = (iw_statistics *) std::malloc(sizeof(iw_statistics));
this->iw.u.data.length = sizeof(iw_statistics); this->iw.u.data.length = sizeof(iw_statistics);
if (ioctl(this->fd, SIOCGIWSTATS, &this->iw) == -1) if (ioctl(this->fd, SIOCGIWSTATS, &this->iw) == -1)
throw WirelessNetworkException(STRERRNO); throw WirelessNetworkException(StrErrno());
auto signal = ((iw_statistics *) this->iw.u.data.pointer)->qual.level - 256; auto signal = ((iw_statistics *) this->iw.u.data.pointer)->qual.level - 256;

View file

@ -14,6 +14,7 @@
#include "utils/cli.hpp" #include "utils/cli.hpp"
#include "utils/config.hpp" #include "utils/config.hpp"
#include "utils/io.hpp" #include "utils/io.hpp"
#include "utils/macros.hpp"
#include "utils/proc.hpp" #include "utils/proc.hpp"
#include "utils/string.hpp" #include "utils/string.hpp"
#include "utils/timer.hpp" #include "utils/timer.hpp"
@ -25,8 +26,6 @@
* TODO: Simplify overall flow * TODO: Simplify overall flow
*/ */
#define writeln(s) std::cout << s << std::endl;
std::unique_ptr<EventLoop> eventloop; std::unique_ptr<EventLoop> eventloop;
std::mutex pid_mtx; std::mutex pid_mtx;
@ -56,7 +55,7 @@ int main(int argc, char **argv)
sigemptyset(&pipe_mask); sigemptyset(&pipe_mask);
sigaddset(&pipe_mask, SIGPIPE); sigaddset(&pipe_mask, SIGPIPE);
if (pthread_sigmask(SIG_BLOCK, &pipe_mask, nullptr) == -1) if (pthread_sigmask(SIG_BLOCK, &pipe_mask, nullptr) == -1)
logger->fatal(STRERRNO); logger->fatal(StrErrno());
try { try {
auto usage = "Usage: "+ std::string(argv[0]) + " bar_name [OPTION...]"; auto usage = "Usage: "+ std::string(argv[0]) + " bar_name [OPTION...]";
@ -169,7 +168,7 @@ int main(int argc, char **argv)
+ std::to_string(proc::get_process_id()); + std::to_string(proc::get_process_id());
auto fptr = std::make_unique<io::file::FilePtr>(pipe_file, "a+"); auto fptr = std::make_unique<io::file::FilePtr>(pipe_file, "a+");
if (!*fptr) if (!*fptr)
throw Exception(STRERRNO); throw ApplicationError(StrErrno());
} }
} }
@ -192,7 +191,7 @@ int main(int argc, char **argv)
* Terminate forked sub processes * Terminate forked sub processes
*/ */
if (!pids.empty()) { if (!pids.empty()) {
logger->info("Terminating "+ STRI(pids.size()) +" spawned process"+ (pids.size() > 1 ? "es" : "")); logger->info("Terminating "+ IntToStr(pids.size()) +" spawned process"+ (pids.size() > 1 ? "es" : ""));
for (auto &&pid : pids) for (auto &&pid : pids)
proc::kill(pid, SIGKILL); proc::kill(pid, SIGKILL);

View file

@ -6,6 +6,10 @@ using namespace modules;
BacklightModule::BacklightModule(const std::string& name_) : InotifyModule(name_) BacklightModule::BacklightModule(const std::string& name_) : InotifyModule(name_)
{ {
// Load configuration values
auto card = config::get<std::string>(name(), "card");
// Add formats and elements
this->formatter->add(DEFAULT_FORMAT, TAG_LABEL, { TAG_LABEL, TAG_BAR, TAG_RAMP }); this->formatter->add(DEFAULT_FORMAT, TAG_LABEL, { TAG_LABEL, TAG_BAR, TAG_RAMP });
if (this->formatter->has(TAG_LABEL)) if (this->formatter->has(TAG_LABEL))
@ -18,8 +22,7 @@ BacklightModule::BacklightModule(const std::string& name_) : InotifyModule(name_
if (this->label) if (this->label)
this->label_tokenized = this->label->clone(); this->label_tokenized = this->label->clone();
auto card = config::get<std::string>(name(), "card"); // Build path to the file where the current/maximum brightness value is located
this->path_val = string::replace(PATH_BACKLIGHT_VAL, "%card%", card); this->path_val = string::replace(PATH_BACKLIGHT_VAL, "%card%", card);
this->path_max = string::replace(PATH_BACKLIGHT_MAX, "%card%", card); this->path_max = string::replace(PATH_BACKLIGHT_MAX, "%card%", card);
@ -28,7 +31,8 @@ BacklightModule::BacklightModule(const std::string& name_) : InotifyModule(name_
if (!io::file::exists(this->path_max)) if (!io::file::exists(this->path_max))
throw ModuleError("[BacklightModule] The file \""+ this->path_max +"\" does not exist"); throw ModuleError("[BacklightModule] The file \""+ this->path_max +"\" does not exist");
this->watch(this->path_val); // Add inotify watch
this->watch(string::replace(PATH_BACKLIGHT_VAL, "%card%", card));
} }
bool BacklightModule::on_event(InotifyEvent *event) bool BacklightModule::on_event(InotifyEvent *event)
@ -42,13 +46,13 @@ bool BacklightModule::on_event(InotifyEvent *event)
auto max = io::file::get_contents(this->path_max); auto max = io::file::get_contents(this->path_max);
this->max = std::stoull(max.c_str(), 0, 10); this->max = std::stoull(max.c_str(), 0, 10);
this->percentage = (int) float(this->val) / float(this->max) * 100.f + 0.5f; this->percentage = (int) float(this->val) / float(this->max) * 100.0f + 0.5f;
if (!this->label) if (!this->label)
return true; return true;
this->label_tokenized->text = this->label->text; this->label_tokenized->text = this->label->text;
this->label_tokenized->replace_token("%percentage%", std::to_string(this->percentage)+"%"); this->label_tokenized->replace_token("%percentage%", std::to_string(this->percentage())+"%");
return true; return true;
} }
@ -56,9 +60,9 @@ bool BacklightModule::on_event(InotifyEvent *event)
bool BacklightModule::build(Builder *builder, const std::string& tag) bool BacklightModule::build(Builder *builder, const std::string& tag)
{ {
if (tag == TAG_BAR) if (tag == TAG_BAR)
builder->node(this->bar, this->percentage); builder->node(this->bar, this->percentage());
else if (tag == TAG_RAMP) else if (tag == TAG_RAMP)
builder->node(this->ramp, this->percentage); builder->node(this->ramp, this->percentage());
else if (tag == TAG_LABEL) else if (tag == TAG_LABEL)
builder->node(this->label_tokenized); builder->node(this->label_tokenized);
else else

View file

@ -7,6 +7,7 @@
#include "utils/config.hpp" #include "utils/config.hpp"
#include "utils/io.hpp" #include "utils/io.hpp"
#include "utils/math.hpp" #include "utils/math.hpp"
#include "utils/macros.hpp"
#include "utils/string.hpp" #include "utils/string.hpp"
using namespace modules; using namespace modules;
@ -68,10 +69,10 @@ BatteryModule::BatteryModule(const std::string& name_) : InotifyModule(name_)
void BatteryModule::start() void BatteryModule::start()
{ {
this->InotifyModule::start(); this->InotifyModule::start();
this->threads.emplace_back(std::thread(&BatteryModule::subthread_runner, this)); this->threads.emplace_back(std::thread(&BatteryModule::subthread_routine, this));
} }
void BatteryModule::subthread_runner() void BatteryModule::subthread_routine()
{ {
std::this_thread::yield(); std::this_thread::yield();
@ -149,13 +150,13 @@ bool BatteryModule::on_event(InotifyEvent *event)
this->label_full_tokenized = this->label_full->clone(); this->label_full_tokenized = this->label_full->clone();
this->label_charging_tokenized->text = this->label_charging->text; this->label_charging_tokenized->text = this->label_charging->text;
this->label_charging_tokenized->replace_token("%percentage%", std::to_string(percentage) + "%"); this->label_charging_tokenized->replace_token("%percentage%", IntToStr(percentage) + "%");
this->label_discharging_tokenized->text = this->label_discharging->text; this->label_discharging_tokenized->text = this->label_discharging->text;
this->label_discharging_tokenized->replace_token("%percentage%", std::to_string(percentage) + "%"); this->label_discharging_tokenized->replace_token("%percentage%", IntToStr(percentage) + "%");
this->label_full_tokenized->text = this->label_full->text; this->label_full_tokenized->text = this->label_full->text;
this->label_full_tokenized->replace_token("%percentage%", std::to_string(percentage) + "%"); this->label_full_tokenized->replace_token("%percentage%", IntToStr(percentage) + "%");
this->state = state; this->state = state;
this->percentage = percentage; this->percentage = percentage;

View file

@ -17,10 +17,9 @@ using namespace Bspwm;
#define DEFAULT_WS_ICON "workspace_icon:default" #define DEFAULT_WS_ICON "workspace_icon:default"
#define DEFAULT_WS_LABEL "%icon% %name%" #define DEFAULT_WS_LABEL "%icon% %name%"
BspwmModule::BspwmModule(const std::string& name_, const std::string& monitor) : EventModule(name_) BspwmModule::BspwmModule(const std::string& name_, const std::string& monitor)
: EventModule(name_), monitor(monitor)
{ {
this->monitor = monitor;
this->formatter->add(DEFAULT_FORMAT, TAG_LABEL_STATE, { TAG_LABEL_STATE }, { TAG_LABEL_MODE }); this->formatter->add(DEFAULT_FORMAT, TAG_LABEL_STATE, { TAG_LABEL_STATE }, { TAG_LABEL_MODE });
if (this->formatter->has(TAG_LABEL_STATE)) { if (this->formatter->has(TAG_LABEL_STATE)) {
@ -86,25 +85,29 @@ bool BspwmModule::update()
if (data.empty()) if (data.empty())
return false; return false;
auto prefix = std::string(BSPWM_STATUS_PREFIX); const auto prefix = std::string(BSPWM_STATUS_PREFIX);
if (data.find(prefix) != 0) { if (data.compare(0, prefix.length(), prefix) != 0) {
log_error("Received unknown status -> "+ data); log_error("Received unknown status -> "+ data);
return false; return false;
} }
const auto needle_active = "M"+ this->monitor +":";
const auto needle_inactive = "m"+ this->monitor +":";
// Cut out the relevant section for the current monitor // Cut out the relevant section for the current monitor
if ((n = data.find(prefix +"M"+ this->monitor +":")) != std::string::npos) { if ((n = data.find(prefix + needle_active)) != std::string::npos) {
if ((m = data.find(":m")) != std::string::npos) data = data.substr(n, m); if ((m = data.find(":m")) != std::string::npos) data = data.substr(n, m);
} else if ((n = data.find(prefix +"m"+ this->monitor +":")) != std::string::npos) { } else if ((n = data.find(prefix + needle_inactive)) != std::string::npos) {
if ((m = data.find(":M")) != std::string::npos) data = data.substr(n, m); if ((m = data.find(":M")) != std::string::npos) data = data.substr(n, m);
} else if ((n = data.find("M"+ this->monitor +":")) != std::string::npos) { } else if ((n = data.find(needle_active)) != std::string::npos) {
data.erase(0, n); data.erase(0, n);
} else if ((n = data.find("m"+ this->monitor +":")) != std::string::npos) { } else if ((n = data.find(needle_inactive)) != std::string::npos) {
data.erase(0, n); data.erase(0, n);
} }
if (data.find(prefix) == 0) data.erase(0, 1); if (data.compare(0, prefix.length(), prefix) == 0)
data.erase(0, 1);
log_trace(data); log_trace(data);

View file

@ -89,9 +89,10 @@ bool CpuModule::read_values()
std::ifstream in(PATH_CPU_INFO); std::ifstream in(PATH_CPU_INFO);
std::string str; std::string str;
while (std::getline(in, str) && str.find("cpu") == 0) { while (std::getline(in, str) && str.compare(0, 3, "cpu") == 0) {
// skip the accumulated line // skip the accumulated line
if (str.find("cpu ") == 0) continue; if (str.compare(0, 4, "cpu ") == 0)
continue;
auto values = string::split(str, ' '); auto values = string::split(str, ' ');
auto cpu = std::make_unique<CpuTime>(); auto cpu = std::make_unique<CpuTime>();

View file

@ -6,9 +6,9 @@
using namespace modules; using namespace modules;
DateModule::DateModule(const std::string& name_) : TimerModule(name_, 1s) DateModule::DateModule(const std::string& name_)
: TimerModule(name_, 1s), builder(std::make_unique<Builder>())
{ {
this->builder = std::make_unique<Builder>();
this->interval = std::chrono::duration<double>( this->interval = std::chrono::duration<double>(
config::get<float>(name(), "interval", 1)); config::get<float>(name(), "interval", 1));

View file

@ -11,6 +11,7 @@
#include "modules/i3.hpp" #include "modules/i3.hpp"
#include "utils/config.hpp" #include "utils/config.hpp"
#include "utils/io.hpp" #include "utils/io.hpp"
#include "utils/macros.hpp"
#include "utils/string.hpp" #include "utils/string.hpp"
using namespace modules; using namespace modules;
@ -128,7 +129,7 @@ bool i3Module::update()
// if (!monitor_focused) // if (!monitor_focused)
// flag = i3::WORKSPACE_DIMMED; // flag = i3::WORKSPACE_DIMMED;
auto workspace_name = STR(ws->name); auto workspace_name = ToStr(ws->name);
if (this->workspace_name_strip_nchars > 0 && workspace_name.length() > this->workspace_name_strip_nchars) if (this->workspace_name_strip_nchars > 0 && workspace_name.length() > this->workspace_name_strip_nchars)
workspace_name.erase(0, this->workspace_name_strip_nchars); workspace_name.erase(0, this->workspace_name_strip_nchars);

View file

@ -1,6 +1,7 @@
#include "config.hpp" #include "config.hpp"
#include "modules/memory.hpp" #include "modules/memory.hpp"
#include "utils/config.hpp" #include "utils/config.hpp"
#include "utils/macros.hpp"
using namespace modules; using namespace modules;
@ -48,7 +49,7 @@ bool MemoryModule::update()
kbytes_total = 0; kbytes_total = 0;
// kbytes_free = 0; // kbytes_free = 0;
kbytes_available = 0; kbytes_available = 0;
log_error("Failed to read memory values: "+ STR(e.what())); log_error("Failed to read memory values: "+ ToStr(e.what()));
} }
if (kbytes_total > 0) if (kbytes_total > 0)

View file

@ -52,7 +52,7 @@ MenuModule::MenuModule(const std::string& name_) : StaticModule(name_)
register_command_handler(name()); register_command_handler(name());
} }
std::string MenuModule::get_output() throw(UndefinedFormat) std::string MenuModule::get_output()
{ {
this->builder->node(this->Module::get_output()); this->builder->node(this->Module::get_output());
@ -98,7 +98,7 @@ bool MenuModule::handle_command(const std::string& cmd)
{ {
std::lock_guard<std::mutex> lck(this->cmd_mtx); std::lock_guard<std::mutex> lck(this->cmd_mtx);
if (cmd.find(EVENT_MENU_OPEN) == 0) { if (cmd.compare(0, std::strlen(EVENT_MENU_OPEN), EVENT_MENU_OPEN) == 0) {
auto level = cmd.substr(std::strlen(EVENT_MENU_OPEN)); auto level = cmd.substr(std::strlen(EVENT_MENU_OPEN));
if (level.empty()) if (level.empty())

View file

@ -10,10 +10,9 @@
using namespace modules; using namespace modules;
using namespace mpd; using namespace mpd;
MpdModule::MpdModule(const std::string& name_) : EventModule(name_) MpdModule::MpdModule(const std::string& name_)
: EventModule(name_), icons(std::make_unique<drawtypes::IconMap>())
{ {
this->icons = std::make_unique<drawtypes::IconMap>();
this->formatter->add(FORMAT_ONLINE, TAG_LABEL_SONG, { this->formatter->add(FORMAT_ONLINE, TAG_LABEL_SONG, {
TAG_BAR_PROGRESS, TAG_TOGGLE, TAG_LABEL_SONG, TAG_LABEL_TIME, TAG_BAR_PROGRESS, TAG_TOGGLE, TAG_LABEL_SONG, TAG_LABEL_TIME,
TAG_ICON_RANDOM, TAG_ICON_REPEAT, TAG_ICON_REPEAT_ONE, TAG_ICON_PREV, TAG_ICON_RANDOM, TAG_ICON_REPEAT, TAG_ICON_REPEAT_ONE, TAG_ICON_PREV,
@ -69,7 +68,7 @@ void MpdModule::start()
this->mpd = mpd::Connection::get(); this->mpd = mpd::Connection::get();
this->synced_at = std::chrono::system_clock::now(); this->synced_at = std::chrono::system_clock::now();
this->sync_interval = config::get<float>(name(), "interval", 0.5) * 1000; this->sync_interval = config::get<float>(name(), "interval", this->sync_interval) * 1000;
try { try {
mpd->connect(); mpd->connect();
@ -273,22 +272,20 @@ bool MpdModule::handle_command(const std::string& cmd)
mpd->next(); mpd->next();
else if (cmd == EVENT_REPEAT_ONE) else if (cmd == EVENT_REPEAT_ONE)
if (this->status) if (this->status)
mpd->single(!this->status->single); mpd->set_single(!this->status->single);
else else
mpd->single(true); mpd->set_single(true);
else if (cmd == EVENT_REPEAT) else if (cmd == EVENT_REPEAT)
if (this->status) if (this->status)
#undef repeat mpd->set_repeat(!this->status->repeat);
mpd->repeat(!this->status->repeat);
else else
mpd->repeat(true); mpd->set_repeat(true);
#define repeat _repeat(n)
else if (cmd == EVENT_RANDOM) else if (cmd == EVENT_RANDOM)
if (this->status) if (this->status)
mpd->random(!this->status->random); mpd->set_random(!this->status->random);
else else
mpd->random(true); mpd->set_random(true);
else if (cmd.find(EVENT_SEEK) == 0) { else if (cmd.compare(0, std::strlen(EVENT_SEEK), EVENT_SEEK) == 0) {
auto s = cmd.substr(std::strlen(EVENT_SEEK)); auto s = cmd.substr(std::strlen(EVENT_SEEK));
int perc = 0; int perc = 0;
if (s.empty()) if (s.empty())

View file

@ -12,7 +12,8 @@ using namespace modules;
// TODO: Add up-/download speed (check how ifconfig read the bytes) // TODO: Add up-/download speed (check how ifconfig read the bytes)
NetworkModule::NetworkModule(const std::string& name_) : TimerModule(name_, 1s) NetworkModule::NetworkModule(const std::string& name_)
: TimerModule(name_, 1s), connected(false), conseq_packetloss(false)
{ {
static const auto DEFAULT_FORMAT_CONNECTED = TAG_LABEL_CONNECTED; static const auto DEFAULT_FORMAT_CONNECTED = TAG_LABEL_CONNECTED;
static const auto DEFAULT_FORMAT_DISCONNECTED = TAG_LABEL_DISCONNECTED; static const auto DEFAULT_FORMAT_DISCONNECTED = TAG_LABEL_DISCONNECTED;
@ -22,9 +23,6 @@ NetworkModule::NetworkModule(const std::string& name_) : TimerModule(name_, 1s)
static const auto DEFAULT_LABEL_DISCONNECTED = ""; static const auto DEFAULT_LABEL_DISCONNECTED = "";
static const auto DEFAULT_LABEL_PACKETLOSS = ""; static const auto DEFAULT_LABEL_PACKETLOSS = "";
this->connected = false;
this->conseq_packetloss = false;
// Load configuration values // Load configuration values
this->interface = config::get<std::string>(name(), "interface"); this->interface = config::get<std::string>(name(), "interface");
this->interval = std::chrono::duration<double>(config::get<float>(name(), "interval", 1)); this->interval = std::chrono::duration<double>(config::get<float>(name(), "interval", 1));
@ -147,7 +145,6 @@ bool NetworkModule::update()
if (this->wired_network) { if (this->wired_network) {
label->replace_token("%linkspeed%", linkspeed); label->replace_token("%linkspeed%", linkspeed);
} else if (this->wireless_network) { } else if (this->wireless_network) {
// label->replace_token("%essid%", essid);
label->replace_token("%essid%", !essid.empty() ? essid : "No network"); label->replace_token("%essid%", !essid.empty() ? essid : "No network");
label->replace_token("%signal%", std::to_string(signal_quality)+"%"); label->replace_token("%signal%", std::to_string(signal_quality)+"%");
} }

View file

@ -6,11 +6,9 @@
using namespace modules; using namespace modules;
ScriptModule::ScriptModule(const std::string& name_) : TimerModule(name_, 1s) ScriptModule::ScriptModule(const std::string& name_)
: TimerModule(name_, 1s), builder(std::make_unique<Builder>(true)), counter(0)
{ {
this->counter = 0;
this->builder = std::make_unique<Builder>(true);
this->exec = config::get<std::string>(name(), "exec"); this->exec = config::get<std::string>(name(), "exec");
this->interval = std::chrono::duration<double>( this->interval = std::chrono::duration<double>(

View file

@ -5,7 +5,7 @@
using namespace modules; using namespace modules;
TextModule::TextModule(const std::string& name_) throw(UndefinedFormat) : StaticModule(name_) { TextModule::TextModule(const std::string& name_) : StaticModule(name_) {
this->formatter->add(FORMAT, "", {}); this->formatter->add(FORMAT, "", {});
if (this->formatter->get(FORMAT)->value.empty()) if (this->formatter->get(FORMAT)->value.empty())
throw UndefinedFormat(FORMAT); throw UndefinedFormat(FORMAT);

View file

@ -1,15 +1,12 @@
#include <thread>
#include "lemonbuddy.hpp" #include "lemonbuddy.hpp"
#include "bar.hpp" #include "bar.hpp"
#include "services/builder.hpp"
#include "utils/config.hpp"
#include "utils/math.hpp" #include "utils/math.hpp"
#include "utils/macros.hpp"
#include "modules/volume.hpp" #include "modules/volume.hpp"
using namespace modules; using namespace modules;
VolumeModule::VolumeModule(const std::string& name_) throw(ModuleError) : EventModule(name_) VolumeModule::VolumeModule(const std::string& name_) : EventModule(name_)
{ {
auto speaker_mixer = config::get<std::string>(name(), "speaker_mixer", ""); auto speaker_mixer = config::get<std::string>(name(), "speaker_mixer", "");
auto headphone_mixer = config::get<std::string>(name(), "headphone_mixer", ""); auto headphone_mixer = config::get<std::string>(name(), "headphone_mixer", "");
@ -33,7 +30,7 @@ VolumeModule::VolumeModule(const std::string& name_) throw(ModuleError) : EventM
try { try {
mixer = std::make_unique<alsa::Mixer>(mixer_name); mixer = std::make_unique<alsa::Mixer>(mixer_name);
} catch (alsa::MixerError &e) { } catch (alsa::MixerError &e) {
log_error("Failed to open \""+ mixer_name +"\" mixer => "+ STR(e.what())); log_error("Failed to open \""+ mixer_name +"\" mixer => "+ ToStr(e.what()));
mixer.reset(); mixer.reset();
} }
@ -56,7 +53,7 @@ VolumeModule::VolumeModule(const std::string& name_) throw(ModuleError) : EventM
try { try {
this->headphone_ctrl = std::make_unique<alsa::ControlInterface>(this->headphone_ctrl_numid); this->headphone_ctrl = std::make_unique<alsa::ControlInterface>(this->headphone_ctrl_numid);
} catch (alsa::ControlInterfaceError &e) { } catch (alsa::ControlInterfaceError &e) {
log_error("Failed to open headphone control interface => "+ STR(e.what())); log_error("Failed to open headphone control interface => "+ ToStr(e.what()));
this->headphone_ctrl.reset(); this->headphone_ctrl.reset();
} }
} }

View file

@ -30,7 +30,7 @@ bool Registry::ready()
void Registry::insert(std::unique_ptr<modules::ModuleInterface> &&module) void Registry::insert(std::unique_ptr<modules::ModuleInterface> &&module)
{ {
log_trace("Inserting module: "+ module->name()); log_trace("Inserting module: "+ module->name());
this->modules.emplace_back(std::make_unique<ModuleEntry>(std::move(module))); this->modules.emplace_back(std::make_unique<RegistryModuleEntry>(std::move(module)));
} }
void Registry::load() void Registry::load()
@ -149,7 +149,7 @@ std::string Registry::get(const std::string& module_name)
return (*this->find(module_name)->module)(); return (*this->find(module_name)->module)();
} }
std::unique_ptr<ModuleEntry>& Registry::find(const std::string& module_name) throw(ModuleNotFound) std::unique_ptr<RegistryModuleEntry>& Registry::find(const std::string& module_name)
{ {
for (auto &&entry : this->modules) for (auto &&entry : this->modules)
if (entry->module->name() == module_name) if (entry->module->name() == module_name)

View file

@ -287,9 +287,9 @@ void Builder::remove_trailing_space(int width)
this->output = this->output.substr(0, this->output.length()-spacing); this->output = this->output.substr(0, this->output.length()-spacing);
} }
void Builder::invert() { // void Builder::invert() {
this->tag_open('R', ""); // this->tag_open('R', "");
} // }
// Fonts // Fonts

View file

@ -8,8 +8,9 @@
#include "lemonbuddy.hpp" #include "lemonbuddy.hpp"
#include "services/command.hpp" #include "services/command.hpp"
#include "services/logger.hpp" #include "services/logger.hpp"
#include "utils/string.hpp"
#include "utils/io.hpp" #include "utils/io.hpp"
#include "utils/macros.hpp"
#include "utils/string.hpp"
/** /**
* auto cmd = std::make_unique<Command>("cat /etc/rc.local"); * auto cmd = std::make_unique<Command>("cat /etc/rc.local");
@ -25,10 +26,9 @@
* std::cout << cmd->readline(); //---> 1 * std::cout << cmd->readline(); //---> 1
* std::cout << cmd->readline() << cmd->readline(); //---> 23 * std::cout << cmd->readline() << cmd->readline(); //---> 23
*/ */
Command::Command(const std::string& cmd, int stdout[2], int stdin[2]) throw(CommandException) Command::Command(const std::string& cmd, int stdout[2], int stdin[2])
: cmd(cmd)
{ {
this->cmd = cmd;
if (stdin != nullptr) { if (stdin != nullptr) {
this->stdin[PIPE_READ] = stdin[PIPE_READ]; this->stdin[PIPE_READ] = stdin[PIPE_READ];
this->stdin[PIPE_WRITE] = stdin[PIPE_WRITE]; this->stdin[PIPE_WRITE] = stdin[PIPE_WRITE];
@ -40,29 +40,29 @@ Command::Command(const std::string& cmd, int stdout[2], int stdin[2]) throw(Comm
this->stdout[PIPE_WRITE] = stdout[PIPE_WRITE]; this->stdout[PIPE_WRITE] = stdout[PIPE_WRITE];
} else if (false == proc::pipe(this->stdout)) { } else if (false == proc::pipe(this->stdout)) {
if ((this->stdin[PIPE_READ] = close(this->stdin[PIPE_READ])) == -1) if ((this->stdin[PIPE_READ] = close(this->stdin[PIPE_READ])) == -1)
throw CommandException("Failed to close fd: "+ STRERRNO); throw CommandException("Failed to close fd: "+ StrErrno());
if ((this->stdin[PIPE_WRITE] = close(this->stdin[PIPE_WRITE])) == -1) if ((this->stdin[PIPE_WRITE] = close(this->stdin[PIPE_WRITE])) == -1)
throw CommandException("Failed to close fd: "+ STRERRNO); throw CommandException("Failed to close fd: "+ StrErrno());
throw CommandException("Failed to allocate pipe"); throw CommandException("Failed to allocate pipe");
} }
} }
Command::~Command() throw(CommandException) Command::~Command()
{ {
if (this->stdin[PIPE_READ] > 0 && (close(this->stdin[PIPE_READ]) == -1)) if (this->stdin[PIPE_READ] > 0 && (close(this->stdin[PIPE_READ]) == -1))
throw CommandException("Failed to close fd: "+ STRERRNO); log_error("Failed to close fd: "+ StrErrno());
if (this->stdin[PIPE_WRITE] > 0 && (close(this->stdin[PIPE_WRITE]) == -1)) if (this->stdin[PIPE_WRITE] > 0 && (close(this->stdin[PIPE_WRITE]) == -1))
throw CommandException("Failed to close fd: "+ STRERRNO); log_error("Failed to close fd: "+ StrErrno());
if (this->stdout[PIPE_READ] > 0 && (close(this->stdout[PIPE_READ]) == -1)) if (this->stdout[PIPE_READ] > 0 && (close(this->stdout[PIPE_READ]) == -1))
throw CommandException("Failed to close fd: "+ STRERRNO); log_error("Failed to close fd: "+ StrErrno());
if (this->stdout[PIPE_WRITE] > 0 && (close(this->stdout[PIPE_WRITE]) == -1)) if (this->stdout[PIPE_WRITE] > 0 && (close(this->stdout[PIPE_WRITE]) == -1))
throw CommandException("Failed to close fd: "+ STRERRNO); log_error("Failed to close fd: "+ StrErrno());
} }
int Command::exec(bool wait_for_completion) throw(CommandException) int Command::exec(bool wait_for_completion)
{ {
if ((this->fork_pid = proc::fork()) == -1) if ((this->fork_pid = proc::fork()) == -1)
throw CommandException("Failed to fork process: "+ STRERRNO); throw CommandException("Failed to fork process: "+ StrErrno());
if (proc::in_forked_process(this->fork_pid)) { if (proc::in_forked_process(this->fork_pid)) {
if (dup2(this->stdin[PIPE_READ], STDIN_FILENO) == -1) if (dup2(this->stdin[PIPE_READ], STDIN_FILENO) == -1)
@ -74,13 +74,13 @@ int Command::exec(bool wait_for_completion) throw(CommandException)
// Close file descriptors that won't be used by forked process // Close file descriptors that won't be used by forked process
if ((this->stdin[PIPE_READ] = close(this->stdin[PIPE_READ])) == -1) if ((this->stdin[PIPE_READ] = close(this->stdin[PIPE_READ])) == -1)
throw CommandException("Failed to close fd: "+ STRERRNO); throw CommandException("Failed to close fd: "+ StrErrno());
if ((this->stdin[PIPE_WRITE] = close(this->stdin[PIPE_WRITE])) == -1) if ((this->stdin[PIPE_WRITE] = close(this->stdin[PIPE_WRITE])) == -1)
throw CommandException("Failed to close fd: "+ STRERRNO); throw CommandException("Failed to close fd: "+ StrErrno());
if ((this->stdout[PIPE_READ] = close(this->stdout[PIPE_READ])) == -1) if ((this->stdout[PIPE_READ] = close(this->stdout[PIPE_READ])) == -1)
throw CommandException("Failed to close fd: "+ STRERRNO); throw CommandException("Failed to close fd: "+ StrErrno());
if ((this->stdout[PIPE_WRITE] = close(this->stdout[PIPE_WRITE])) == -1) if ((this->stdout[PIPE_WRITE] = close(this->stdout[PIPE_WRITE])) == -1)
throw CommandException("Failed to close fd: "+ STRERRNO); throw CommandException("Failed to close fd: "+ StrErrno());
// Replace the forked process with the given command // Replace the forked process with the given command
proc::exec(cmd); proc::exec(cmd);
@ -90,9 +90,9 @@ int Command::exec(bool wait_for_completion) throw(CommandException)
// Close file descriptors that won't be used by parent process // Close file descriptors that won't be used by parent process
if ((this->stdin[PIPE_READ] = close(this->stdin[PIPE_READ])) == -1) if ((this->stdin[PIPE_READ] = close(this->stdin[PIPE_READ])) == -1)
throw CommandException("Failed to close fd: "+ STRERRNO); throw CommandException("Failed to close fd: "+ StrErrno());
if ((this->stdout[PIPE_WRITE] = close(this->stdout[PIPE_WRITE])) == -1) if ((this->stdout[PIPE_WRITE] = close(this->stdout[PIPE_WRITE])) == -1)
throw CommandException("Failed to close fd: "+ STRERRNO); throw CommandException("Failed to close fd: "+ StrErrno());
if (wait_for_completion) if (wait_for_completion)
return this->wait(); return this->wait();
@ -101,7 +101,7 @@ int Command::exec(bool wait_for_completion) throw(CommandException)
return EXIT_SUCCESS; return EXIT_SUCCESS;
} }
int Command::wait() throw(CommandException) int Command::wait()
{ {
// Wait for the child processs to finish // Wait for the child processs to finish
do { do {
@ -110,19 +110,19 @@ int Command::wait() throw(CommandException)
if ((pid = proc::wait_for_completion(this->fork_pid, &this->fork_status, WCONTINUED | WUNTRACED)) == -1) { if ((pid = proc::wait_for_completion(this->fork_pid, &this->fork_status, WCONTINUED | WUNTRACED)) == -1) {
unregister_pid(this->fork_pid); unregister_pid(this->fork_pid);
throw CommandException("Process did not finish successfully ("+ STRI(this->fork_status) +")"); throw CommandException("Process did not finish successfully ("+ IntToStr(this->fork_status) +")");
} }
if WIFEXITED(this->fork_status) if (WIFEXITED(this->fork_status))
sprintf(msg, "exited with status %d", WEXITSTATUS(this->fork_status)); sprintf(msg, "exited with status %d", WEXITSTATUS(this->fork_status));
else if WIFSIGNALED(this->fork_status) else if (WIFSIGNALED(this->fork_status))
sprintf(msg, "got killed by signal %d (%s)", WTERMSIG(this->fork_status), SIGCSTR(WTERMSIG(this->fork_status))); sprintf(msg, "got killed by signal %d (%s)", WTERMSIG(this->fork_status), StrSignalC(WTERMSIG(this->fork_status)));
else if WIFSTOPPED(this->fork_status) else if (WIFSTOPPED(this->fork_status))
sprintf(msg, "stopped by signal %d (%s)", WSTOPSIG(this->fork_status), SIGCSTR(WSTOPSIG(this->fork_status))); sprintf(msg, "stopped by signal %d (%s)", WSTOPSIG(this->fork_status), StrSignalC(WSTOPSIG(this->fork_status)));
else if WIFCONTINUED(this->fork_status) else if (WIFCONTINUED(this->fork_status))
sprintf(msg, "continued"); sprintf(msg, "continued");
get_logger()->debug("Command "+ STR(msg)); get_logger()->debug("Command "+ ToStr(msg));
} while (!WIFEXITED(this->fork_status) && !WIFSIGNALED(this->fork_status)); } while (!WIFEXITED(this->fork_status) && !WIFSIGNALED(this->fork_status));
unregister_pid(this->fork_pid); unregister_pid(this->fork_pid);
@ -142,14 +142,14 @@ int Command::get_stdout(int c) {
return this->stdout[c]; return this->stdout[c];
} }
int Command::get_stdin(int c) { // int Command::get_stdin(int c) {
return this->stdin[c]; // return this->stdin[c];
} // }
pid_t Command::get_pid() { // pid_t Command::get_pid() {
return this->fork_pid; // return this->fork_pid;
} // }
int Command::get_exit_status() { // int Command::get_exit_status() {
return this->fork_status; // return this->fork_status;
} // }

View file

@ -5,16 +5,17 @@
#include "services/inotify.hpp" #include "services/inotify.hpp"
#include "services/logger.hpp" #include "services/logger.hpp"
#include "utils/io.hpp" #include "utils/io.hpp"
#include "utils/macros.hpp"
#include "utils/proc.hpp" #include "utils/proc.hpp"
InotifyWatch::InotifyWatch(const std::string& path, int mask) throw (InotifyException) InotifyWatch::InotifyWatch(const std::string& path, int mask)
{ {
log_trace("Installing watch at: "+ path); log_trace("Installing watch at: "+ path);
if ((this->fd = inotify_init()) < 0) if ((this->fd = inotify_init()) < 0)
throw InotifyException(STRERRNO); throw InotifyException(StrErrno());
if ((this->wd = inotify_add_watch(this->fd, path.c_str(), mask)) < 0) if ((this->wd = inotify_add_watch(this->fd, path.c_str(), mask)) < 0)
throw InotifyException(STRERRNO); throw InotifyException(StrErrno());
this->path = path; this->path = path;
this->mask = mask; this->mask = mask;
@ -25,10 +26,10 @@ InotifyWatch::~InotifyWatch()
log_trace("Uninstalling watch at: "+ this->path); log_trace("Uninstalling watch at: "+ this->path);
if ((this->fd > 0 || this->wd > 0) && inotify_rm_watch(this->fd, this->wd) == -1) if ((this->fd > 0 || this->wd > 0) && inotify_rm_watch(this->fd, this->wd) == -1)
log_error("Failed to remove inotify watch: "+ STRERRNO); log_error("Failed to remove inotify watch: "+ StrErrno());
if (this->fd > 0 && close(this->fd) == -1) if (this->fd > 0 && close(this->fd) == -1)
log_error("Failed to close inotify watch fd: "+ STRERRNO); log_error("Failed to close inotify watch fd: "+ StrErrno());
} }
bool InotifyWatch::has_event(int timeout_ms) { bool InotifyWatch::has_event(int timeout_ms) {

View file

@ -21,10 +21,10 @@ Logger::Logger()
} }
} }
void Logger::set_level(int mask) // void Logger::set_level(int mask)
{ // {
this->level = mask; // this->level = mask;
} // }
void Logger::add_level(int mask) void Logger::add_level(int mask)
{ {

View file

@ -88,9 +88,10 @@ namespace cli
void usage(const std::string& usage, bool exit_success) void usage(const std::string& usage, bool exit_success)
{ {
int longest_n = 0, n; int longest_n = 0;
for (auto &o : options) { for (auto &o : options) {
int n;
if ((n = o.flag_long.length() + o.placeholder.length() + 1) > longest_n) if ((n = o.flag_long.length() + o.placeholder.length() + 1) > longest_n)
longest_n = n; longest_n = n;
} }

View file

@ -1,3 +1,4 @@
#include "services/logger.hpp"
#include "utils/config.hpp" #include "utils/config.hpp"
#include "utils/io.hpp" #include "utils/io.hpp"
@ -17,7 +18,7 @@ namespace config
return bar_path; return bar_path;
} }
void load(const std::string& path) throw(UnexistingFileError, ParseError) void load(const std::string& path)
{ {
if (!io::file::exists(path)) { if (!io::file::exists(path)) {
throw UnexistingFileError("Could not find configuration file \""+ path + "\""); throw UnexistingFileError("Could not find configuration file \""+ path + "\"");
@ -38,14 +39,14 @@ namespace config
load(std::string(dir != nullptr ? dir : "") +"/"+ path); load(std::string(dir != nullptr ? dir : "") +"/"+ path);
} }
void reload() throw(ParseError) // void reload()
{ // {
try { // try {
boost::property_tree::read_ini(file_path, pt); // boost::property_tree::read_ini(file_path, pt);
} catch (std::exception &e) { // } catch (std::exception &e) {
throw ParseError(e.what()); // throw ParseError(e.what());
} // }
} // }
boost::property_tree::ptree get_tree() { boost::property_tree::ptree get_tree() {
return pt; return pt;

View file

@ -12,6 +12,7 @@
#include "utils/io.hpp" #include "utils/io.hpp"
#include "utils/proc.hpp" #include "utils/proc.hpp"
#include "utils/string.hpp" #include "utils/string.hpp"
#include "utils/macros.hpp"
namespace io namespace io
{ {
@ -23,7 +24,7 @@ namespace io
struct sockaddr_un sock_addr; struct sockaddr_un sock_addr;
if ((fd = ::socket(AF_UNIX, SOCK_STREAM, 0)) == -1) { if ((fd = ::socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
log_error("[io::socket::open] Error opening socket: "+ STRERRNO); log_error("[io::socket::open] Error opening socket: "+ StrErrno());
return -1; return -1;
} }
@ -31,7 +32,7 @@ namespace io
std::snprintf(sock_addr.sun_path, sizeof(sock_addr.sun_path), "%s", path.c_str()); std::snprintf(sock_addr.sun_path, sizeof(sock_addr.sun_path), "%s", path.c_str());
if (connect(fd, (struct sockaddr *) &sock_addr, sizeof(sock_addr)) == -1) { if (connect(fd, (struct sockaddr *) &sock_addr, sizeof(sock_addr)) == -1) {
log_error("[io::socket::open] Error connecting to socket: "+ STRERRNO); log_error("[io::socket::open] Error connecting to socket: "+ StrErrno());
return -1; return -1;
} }
@ -42,7 +43,7 @@ namespace io
{ {
int bytes = ::send(fd, data.c_str(), data.size()+1, flags); int bytes = ::send(fd, data.c_str(), data.size()+1, flags);
if (bytes == -1) if (bytes == -1)
log_error("[io::socket::send] Error sending data: "+ STRERRNO); log_error("[io::socket::send] Error sending data: "+ StrErrno());
return bytes; return bytes;
} }
@ -52,7 +53,7 @@ namespace io
if (bytes > 0) if (bytes > 0)
buffer[bytes] = 0; buffer[bytes] = 0;
else if (bytes == -1) else if (bytes == -1)
log_error("[io::socket::recv] Error receiving data: "+ STRERRNO); log_error("[io::socket::recv] Error receiving data: "+ StrErrno());
return bytes; return bytes;
} }
} }
@ -93,7 +94,6 @@ namespace io
std::size_t write(io::file::FilePtr *fptr, const std::string& data) { std::size_t write(io::file::FilePtr *fptr, const std::string& data) {
auto buf = data.c_str(); auto buf = data.c_str();
return fwrite(buf, sizeof(char), sizeof(buf), (*fptr)()); return fwrite(buf, sizeof(char), sizeof(buf), (*fptr)());
return 0;
} }
std::size_t write(const std::string& fpath, const std::string& data) { std::size_t write(const std::string& fpath, const std::string& data) {
@ -111,7 +111,7 @@ namespace io
status_loc = 0; status_loc = 0;
if ((bytes_read_loc = ::read(read_fd, &buffer, bytes_to_read)) > 0) { if ((bytes_read_loc = ::read(read_fd, &buffer, bytes_to_read)) > 0) {
buffer[bytes_read_loc] = 0; // buffer[bytes_read_loc] = 0;
} else if (bytes_read_loc == 0) { } else if (bytes_read_loc == 0) {
get_logger()->debug("Reached EOF"); get_logger()->debug("Reached EOF");
status_loc = -1; status_loc = -1;
@ -184,9 +184,9 @@ namespace io
return poll(fd, POLLIN, timeout_ms); return poll(fd, POLLIN, timeout_ms);
} }
bool poll_write(int fd, int timeout_ms) { // bool poll_write(int fd, int timeout_ms) {
return poll(fd, POLLOUT, timeout_ms); // return poll(fd, POLLOUT, timeout_ms);
} // }
bool poll(int fd, short int events, int timeout_ms) bool poll(int fd, short int events, int timeout_ms)
{ {
@ -202,19 +202,19 @@ namespace io
return fds[0].revents & events; return fds[0].revents & events;
} }
int get_flags(int fd) // int get_flags(int fd)
{ // {
int flags; // int flags;
if ((flags = fcntl(fd, F_GETFL, 0)) == -1) // if ((flags = fcntl(fd, F_GETFL, 0)) == -1)
return 0; // return 0;
return flags; // return flags;
} // }
int set_blocking(int fd) { // int set_blocking(int fd) {
return fcntl(fd, F_SETFL, io::get_flags(fd) & ~O_NONBLOCK); // return fcntl(fd, F_SETFL, io::get_flags(fd) & ~O_NONBLOCK);
} // }
int set_non_blocking(int fd) { // int set_non_blocking(int fd) {
return fcntl(fd, F_SETFL, io::get_flags(fd) | O_NONBLOCK); // return fcntl(fd, F_SETFL, io::get_flags(fd) | O_NONBLOCK);
} // }
} }

View file

@ -3,6 +3,7 @@
#include <sys/wait.h> #include <sys/wait.h>
#include "services/logger.hpp" #include "services/logger.hpp"
#include "utils/macros.hpp"
#include "utils/proc.hpp" #include "utils/proc.hpp"
#include "utils/string.hpp" #include "utils/string.hpp"
@ -12,9 +13,9 @@ namespace proc
return getpid(); return getpid();
} }
pid_t get_parent_process_id() { // pid_t get_parent_process_id() {
return getppid(); // return getppid();
} // }
bool in_parent_process(pid_t pid) { bool in_parent_process(pid_t pid) {
return pid != -1 && pid != 0; return pid != -1 && pid != 0;
@ -29,7 +30,7 @@ namespace proc
pid_t pid = ::fork(); pid_t pid = ::fork();
if (pid < 0) { if (pid < 0) {
log_error("Failed to fork process: "+ STRERRNO +" ("+ std::to_string(errno) +")"); log_error("Failed to fork process: "+ StrErrno() +" ("+ std::to_string(errno) +")");
return -1; return -1;
} }
@ -50,7 +51,7 @@ namespace proc
return true; return true;
} }
void exec(const std::string& cmd) throw(ExecFailure) void exec(const std::string& cmd)
{ {
// log_trace(string::replace_all(cmd, "\n", " ")); // log_trace(string::replace_all(cmd, "\n", " "));
@ -71,7 +72,7 @@ namespace proc
::execvp(c_args[0], c_args.data()); ::execvp(c_args[0], c_args.data());
throw ExecFailure("Failed to execute command:\n-> "+ STRERRNO+ " ("+ std::to_string(errno) + ")"); throw ExecFailure("Failed to execute command:\n-> "+ StrErrno()+ " ("+ std::to_string(errno) + ")");
} }
bool kill(pid_t pid, int sig) { bool kill(pid_t pid, int sig) {

View file

@ -8,13 +8,13 @@ namespace string
return lower(s1) == lower(s2); return lower(s1) == lower(s2);
} }
std::string upper(const std::string& s) // std::string upper(const std::string& s)
{ // {
std::string str(s); // std::string str(s);
for (auto &c : str) // for (auto &c : str)
c = std::toupper(c); // c = std::toupper(c);
return str; // return str;
} // }
std::string lower(const std::string& s) std::string lower(const std::string& s)
{ {
@ -41,14 +41,14 @@ namespace string
return replace_all(haystack, {needle, needle}, {needle}); return replace_all(haystack, {needle, needle}, {needle});
} }
std::string strip(const std::string& haystack, const char &needle) // std::string strip(const std::string& haystack, const char &needle)
{ // {
std::string str(haystack); // std::string str(haystack);
std::string::size_type pos; // std::string::size_type pos;
while ((pos = str.find(needle)) != std::string::npos) // while ((pos = str.find(needle)) != std::string::npos)
str.erase(pos, 1); // str.erase(pos, 1);
return str; // return str;
} // }
std::string strip_trailing_newline(const std::string& haystack) std::string strip_trailing_newline(const std::string& haystack)
{ {

View file

@ -1,3 +1,4 @@
#if 0
#include <unistd.h> #include <unistd.h>
#include "utils/timer.hpp" #include "utils/timer.hpp"
@ -12,3 +13,4 @@ namespace timer
usleep(seconds_to_microseconds(seconds)); usleep(seconds_to_microseconds(seconds));
} }
} }
#endif

View file

@ -1,8 +1,7 @@
#include <string>
#include <algorithm> #include <algorithm>
#include <cstring> // #include <cstring>
#include <X11/Xos.h> // #include <X11/Xos.h>
#include <X11/Xutil.h> // #include <X11/Xutil.h>
#include <X11/extensions/Xrandr.h> #include <X11/extensions/Xrandr.h>
#include "utils/memory.hpp" #include "utils/memory.hpp"
@ -63,37 +62,37 @@ namespace xlib
return monitors; return monitors;
} }
std::unique_ptr<Monitor> get_monitor(const std::string& n_monitorsame) // std::unique_ptr<Monitor> get_monitor(const std::string& n_monitorsame)
{ // {
auto monitor = std::make_unique<Monitor>(); // auto monitor = std::make_unique<Monitor>();
int n_monitors; // int n_monitors;
//
Display *display = XOpenDisplay(nullptr); // Display *display = XOpenDisplay(nullptr);
int screen = XDefaultScreen(display); // int screen = XDefaultScreen(display);
Window root = XRootWindow(display, screen); // Window root = XRootWindow(display, screen);
XRRMonitorInfo *info = XRRGetMonitors(display, root, 1, &n_monitors); // XRRMonitorInfo *info = XRRGetMonitors(display, root, 1, &n_monitors);
//
repeat(n_monitors) // repeat(n_monitors)
{ // {
char *name = XGetAtomName(display, info[repeat_i_rev(n_monitors)].name); // char *name = XGetAtomName(display, info[repeat_i_rev(n_monitors)].name);
//
if (std::strcmp(name, n_monitorsame.c_str()) != 0) { // if (std::strcmp(name, n_monitorsame.c_str()) != 0) {
continue; // continue;
} // }
//
monitor->name = std::string(name); // monitor->name = std::string(name);
monitor->width = info[repeat_i_rev(n_monitors)].width; // monitor->width = info[repeat_i_rev(n_monitors)].width;
monitor->height = info[repeat_i_rev(n_monitors)].height; // monitor->height = info[repeat_i_rev(n_monitors)].height;
monitor->x = info[repeat_i_rev(n_monitors)].x; // monitor->x = info[repeat_i_rev(n_monitors)].x;
monitor->y = info[repeat_i_rev(n_monitors)].y; // monitor->y = info[repeat_i_rev(n_monitors)].y;
//
std::free(name); // std::free(name);
} // }
//
std::free(info); // std::free(info);
//
XCloseDisplay(display); // XCloseDisplay(display);
//
return monitor; // return monitor;
} // }
} }