This commit is contained in:
Mars 2024-06-21 03:34:33 -04:00
parent b09839ff6a
commit 269122d30c
Signed by: pupbrained
GPG key ID: 0FF5B8826803F895
10 changed files with 68 additions and 69 deletions

View file

@ -3,7 +3,6 @@ AlignArrayOfStructures: Right
AlignConsecutiveAssignments: true AlignConsecutiveAssignments: true
AlignConsecutiveDeclarations: true AlignConsecutiveDeclarations: true
AllowShortBlocksOnASingleLine: Always AllowShortBlocksOnASingleLine: Always
AllowShortCompoundRequirementOnASingleLine: true
AllowShortEnumsOnASingleLine: true AllowShortEnumsOnASingleLine: true
AllowShortFunctionsOnASingleLine: All AllowShortFunctionsOnASingleLine: All
AllowShortLoopsOnASingleLine: true AllowShortLoopsOnASingleLine: true

View file

@ -1,18 +1,16 @@
#pragma once #pragma once
#include <cstdlib>
#include <rfl.hpp> #include <rfl.hpp>
#include <rfl/Field.hpp> #include <rfl/Field.hpp>
#include <rfl/default.hpp>
#include <string>
#include "../util/macros.h" #include "../util/macros.h"
#include "../util/types.h"
#include "weather.h" #include "weather.h"
using Location = std::variant<std::string, Coords>; using Location = std::variant<string, Coords>;
struct General { struct General {
rfl::Field<"name", std::string> name = "user"; rfl::Field<"name", string> name = "user";
}; };
struct NowPlaying { struct NowPlaying {
@ -21,8 +19,8 @@ struct NowPlaying {
struct Weather { struct Weather {
Location location; Location location;
std::string api_key; string api_key;
std::string units; string units;
[[nodiscard]] fn getWeatherInfo() const -> WeatherOutput; [[nodiscard]] fn getWeatherInfo() const -> WeatherOutput;
}; };

View file

@ -46,18 +46,18 @@ fn WriteCacheToFile(const WeatherOutput& data) -> Result<> {
return Ok(); return Ok();
} }
fn WriteCallback(void* contents, size_t size, size_t nmemb, std::string* str) -> size_t { fn WriteCallback(void* contents, size_t size, size_t nmemb, string* str) -> size_t {
size_t totalSize = size * nmemb; size_t totalSize = size * nmemb;
str->append(static_cast<char*>(contents), totalSize); str->append(static_cast<char*>(contents), totalSize);
return totalSize; return totalSize;
} }
// Function to make API request // Function to make API request
fn MakeApiRequest(const std::string& url) -> Result<WeatherOutput> { fn MakeApiRequest(const string& url) -> Result<WeatherOutput> {
fmt::println("Making API request to URL: {}", url); fmt::println("Making API request to URL: {}", url);
CURL* curl = curl_easy_init(); CURL* curl = curl_easy_init();
std::string responseBuffer; string responseBuffer;
if (curl) { if (curl) {
curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
@ -103,14 +103,14 @@ fn Weather::getWeatherInfo() const -> WeatherOutput {
WeatherOutput result; WeatherOutput result;
if (holds_alternative<std::string>(location)) { if (holds_alternative<string>(location)) {
const std::string city = get<std::string>(location); const string city = get<string>(location);
const char* loc = curl_easy_escape(nullptr, city.c_str(), static_cast<int>(city.length())); const char* loc = curl_easy_escape(nullptr, city.c_str(), static_cast<int>(city.length()));
fmt::println("City: {}", loc); fmt::println("City: {}", loc);
const std::string apiUrl = fmt::format( const string apiUrl = fmt::format(
"https://api.openweathermap.org/data/2.5/" "https://api.openweathermap.org/data/2.5/"
"weather?q={}&appid={}&units={}", "weather?q={}&appid={}&units={}",
loc, loc,
@ -124,7 +124,7 @@ fn Weather::getWeatherInfo() const -> WeatherOutput {
fmt::println("Coordinates: lat = {:.3f}, lon = {:.3f}", lat, lon); fmt::println("Coordinates: lat = {:.3f}, lon = {:.3f}", lat, lon);
const std::string apiUrl = fmt::format( const string apiUrl = fmt::format(
"https://api.openweathermap.org/data/2.5/" "https://api.openweathermap.org/data/2.5/"
"weather?lat={:.3f}&lon={:.3f}&appid={}&units={}", "weather?lat={:.3f}&lon={:.3f}&appid={}&units={}",
lat, lat,

View file

@ -1,19 +1,18 @@
#pragma once #pragma once
#include <fmt/core.h>
#include <rfl.hpp> #include <rfl.hpp>
#include <rfl/toml.hpp> #include <rfl/toml.hpp>
#include <string> #include <string>
#include "../util/numtypes.h" #include "../util/types.h"
using degrees = rfl::Validator<u16, rfl::Minimum<0>, rfl::Maximum<360>>; using degrees = rfl::Validator<u16, rfl::Minimum<0>, rfl::Maximum<360>>;
using percentage = rfl::Validator<i8, rfl::Minimum<0>, rfl::Maximum<100>>; using percentage = rfl::Validator<i8, rfl::Minimum<0>, rfl::Maximum<100>>;
struct Condition { struct Condition {
std::string description; string description;
std::string icon; string icon;
std::string main; string main;
usize id; usize id;
}; };
@ -40,7 +39,7 @@ struct Precipitation {
}; };
struct Sys { struct Sys {
std::string country; string country;
usize id; usize id;
usize sunrise; usize sunrise;
usize sunset; usize sunset;
@ -64,8 +63,8 @@ struct WeatherOutput {
rfl::Rename<"coord", Coords> coords; rfl::Rename<"coord", Coords> coords;
std::optional<Precipitation> rain; std::optional<Precipitation> rain;
std::optional<Precipitation> snow; std::optional<Precipitation> snow;
std::string base; string base;
std::string name; string name;
std::vector<Condition> weather; std::vector<Condition> weather;
Sys sys; Sys sys;
usize cod; usize cod;

View file

@ -6,9 +6,6 @@
#include "config/config.h" #include "config/config.h"
#include "os/os.h" #include "os/os.h"
using std::future;
using std::string;
struct BytesToGiB { struct BytesToGiB {
u64 value; u64 value;
}; };
@ -28,10 +25,10 @@ struct fmt::formatter<BytesToGiB> : formatter<double> {
} }
}; };
fn GetDate() -> std::string { fn GetDate() -> string {
const std::tm localTime = fmt::localtime(time(nullptr)); const std::tm localTime = fmt::localtime(time(nullptr));
std::string date = fmt::format("{:%e}", localTime); string date = fmt::format("{:%e}", localTime);
if (!date.empty() && std::isspace(date.front())) if (!date.empty() && std::isspace(date.front()))
date.erase(date.begin()); date.erase(date.begin());
@ -48,7 +45,9 @@ fn GetDate() -> std::string {
return fmt::format("{:%B} {}, {:%-I:%0M %p}", localTime, date, localTime); return fmt::format("{:%B} {}, {:%-I:%0M %p}", localTime, date, localTime);
} }
fn main() -> int { fn main() -> i32 {
using std::future;
const Config& config = Config::getInstance(); const Config& config = Config::getInstance();
auto weatherFuture = auto weatherFuture =
@ -68,13 +67,13 @@ fn main() -> int {
const bool nowPlayingEnabled = nowPlayingEnabledFuture.get(); const bool nowPlayingEnabled = nowPlayingEnabledFuture.get();
const char* version = osVersionFuture.get(); const char* version = osVersionFuture.get();
const string date = dateFuture.get(); const string date = dateFuture.get();
const std::string name = config.general.get().name.get(); const string name = config.general.get().name.get();
const u64 mem = memInfoFuture.get(); const u64 mem = memInfoFuture.get();
fmt::println("Hello {}!", name); fmt::println("Hello {}!", name);
fmt::println("Today is: {}", date); fmt::println("Today is: {}", date);
fmt::println("It is {}°F in {}", temp, townName); fmt::println("It is {}°F in {}", temp, townName);
fmt::println("Installed RAM: {:.2f} GiB", BytesToGiB(mem)); fmt::println("Installed RAM: {:.2f}", BytesToGiB(mem));
fmt::println("{}", version); fmt::println("{}", version);
if (nowPlayingEnabled) if (nowPlayingEnabled)

View file

@ -8,8 +8,6 @@
#include "os.h" #include "os.h"
using std::string;
fn ParseLineAsNumber(const string& input) -> u64 { fn ParseLineAsNumber(const string& input) -> u64 {
// Find the first number // Find the first number
string::size_type start = 0; string::size_type start = 0;
@ -49,12 +47,12 @@ fn GetOSVersion() -> const char* {
return nullptr; return nullptr;
} }
std::string line; string line;
const std::string prefix = "PRETTY_NAME="; const string prefix = "PRETTY_NAME=";
while (std::getline(file, line)) { while (std::getline(file, line)) {
if (line.find(prefix) == 0) { if (line.find(prefix) == 0) {
std::string prettyName = line.substr(prefix.size()); string prettyName = line.substr(prefix.size());
// Remove surrounding quotes if present // Remove surrounding quotes if present
if (!prettyName.empty() && prettyName.front() == '"' && prettyName.back() == '"') if (!prettyName.empty() && prettyName.front() == '"' && prettyName.back() == '"')
@ -71,18 +69,18 @@ fn GetOSVersion() -> const char* {
return nullptr; return nullptr;
} }
fn GetMprisPlayers(sdbus::IConnection& connection) -> std::vector<std::string> { fn GetMprisPlayers(sdbus::IConnection& connection) -> std::vector<string> {
const char *dbusInterface = "org.freedesktop.DBus", *dbusObjectPath = "/org/freedesktop/DBus", const char *dbusInterface = "org.freedesktop.DBus", *dbusObjectPath = "/org/freedesktop/DBus",
*dbusMethodListNames = "ListNames"; *dbusMethodListNames = "ListNames";
const std::unique_ptr<sdbus::IProxy> dbusProxy = const std::unique_ptr<sdbus::IProxy> dbusProxy =
createProxy(connection, dbusInterface, dbusObjectPath); createProxy(connection, dbusInterface, dbusObjectPath);
std::vector<std::string> names; std::vector<string> names;
dbusProxy->callMethod(dbusMethodListNames).onInterface(dbusInterface).storeResultsTo(names); dbusProxy->callMethod(dbusMethodListNames).onInterface(dbusInterface).storeResultsTo(names);
std::vector<std::string> mprisPlayers; std::vector<string> mprisPlayers;
for (const std::basic_string<char>& name : names) for (const std::basic_string<char>& name : names)
if (const char* mprisInterfaceName = "org.mpris.MediaPlayer2"; if (const char* mprisInterfaceName = "org.mpris.MediaPlayer2";
@ -92,26 +90,26 @@ fn GetMprisPlayers(sdbus::IConnection& connection) -> std::vector<std::string> {
return mprisPlayers; return mprisPlayers;
} }
fn GetActivePlayer(const std::vector<std::string>& mprisPlayers) -> std::string { fn GetActivePlayer(const std::vector<string>& mprisPlayers) -> string {
if (!mprisPlayers.empty()) if (!mprisPlayers.empty())
return mprisPlayers.front(); return mprisPlayers.front();
return ""; return "";
} }
fn GetNowPlaying() -> std::string { fn GetNowPlaying() -> string {
try { try {
const char *playerObjectPath = "/org/mpris/MediaPlayer2", const char *playerObjectPath = "/org/mpris/MediaPlayer2",
*playerInterfaceName = "org.mpris.MediaPlayer2.Player"; *playerInterfaceName = "org.mpris.MediaPlayer2.Player";
std::unique_ptr<sdbus::IConnection> connection = sdbus::createSessionBusConnection(); std::unique_ptr<sdbus::IConnection> connection = sdbus::createSessionBusConnection();
std::vector<std::string> mprisPlayers = GetMprisPlayers(*connection); std::vector<string> mprisPlayers = GetMprisPlayers(*connection);
if (mprisPlayers.empty()) if (mprisPlayers.empty())
return ""; return "";
std::string activePlayer = GetActivePlayer(mprisPlayers); string activePlayer = GetActivePlayer(mprisPlayers);
if (activePlayer.empty()) if (activePlayer.empty())
return ""; return "";
@ -119,13 +117,13 @@ fn GetNowPlaying() -> std::string {
std::unique_ptr<sdbus::IProxy> playerProxy = std::unique_ptr<sdbus::IProxy> playerProxy =
sdbus::createProxy(*connection, activePlayer, playerObjectPath); sdbus::createProxy(*connection, activePlayer, playerObjectPath);
std::map<std::string, sdbus::Variant> metadata = std::map<string, sdbus::Variant> metadata =
playerProxy->getProperty("Metadata").onInterface(playerInterfaceName); playerProxy->getProperty("Metadata").onInterface(playerInterfaceName);
if (const auto iter = metadata.find("xesam:title"); if (const auto iter = metadata.find("xesam:title");
iter != metadata.end() && iter->second.containsValueOfType<std::string>()) iter != metadata.end() && iter->second.containsValueOfType<string>())
return iter->second.get<std::string>(); return iter->second.get<string>();
} catch (const sdbus::Error& e) { std::cerr << "Error: " << e.what() << '\n'; } } catch (const sdbus::Error& e) { std::cerr << "Error: " << e.what() << '\n'; }
return ""; return "";

View file

@ -14,9 +14,9 @@ fn GetMemInfo() -> u64 {
return mem; return mem;
} }
fn GetNowPlaying() -> std::string { fn GetNowPlaying() -> string {
if (const char* title = GetCurrentPlayingTitle(); const char* artist = GetCurrentPlayingArtist()) if (const char* title = GetCurrentPlayingTitle(); const char* artist = GetCurrentPlayingArtist())
return "Now Playing: " + std::string(artist) + " - " + std::string(title); return "Now Playing: " + string(artist) + " - " + string(title);
return "No song playing"; return "No song playing";
} }

View file

@ -1,9 +1,7 @@
#pragma once #pragma once
#include <string>
#include "../util/macros.h" #include "../util/macros.h"
#include "../util/numtypes.h" #include "../util/types.h"
/** /**
* @brief Get the amount of installed RAM in bytes. * @brief Get the amount of installed RAM in bytes.
@ -13,7 +11,7 @@ fn GetMemInfo() -> u64;
/** /**
* @brief Get the currently playing song metadata. * @brief Get the currently playing song metadata.
*/ */
fn GetNowPlaying() -> std::string; fn GetNowPlaying() -> string;
/** /**
* @brief Get the OS version. * @brief Get the OS version.

View file

@ -1,11 +1,11 @@
#pragma once #pragma once
#include <stdexcept> #include <stdexcept>
#include <string>
#include <utility> #include <utility>
#include <variant> #include <variant>
#include "macros.h" #include "macros.h"
#include "types.h"
/** /**
* @class Error * @class Error
@ -19,16 +19,16 @@ class Error {
* @brief Constructs an Error with a message. * @brief Constructs an Error with a message.
* @param message The error message. * @param message The error message.
*/ */
explicit Error(std::string message) : m_Message(std::move(message)) {} explicit Error(string message) : m_Message(std::move(message)) {}
/** /**
* @brief Retrieves the error message. * @brief Retrieves the error message.
* @return A constant reference to the error message string. * @return A constant reference to the error message string.
*/ */
[[nodiscard]] fn message() const -> const std::string& { return m_Message; } [[nodiscard]] fn message() const -> const string& { return m_Message; }
private: private:
std::string m_Message; ///< The error message. string m_Message; ///< The error message.
}; };
// Primary template for Result with a default type of void // Primary template for Result with a default type of void

View file

@ -2,6 +2,7 @@
#include <cstddef> #include <cstddef>
#include <cstdint> #include <cstdint>
#include <string>
/** /**
* @typedef u8 * @typedef u8
@ -117,3 +118,10 @@ using usize = std::size_t;
* subtracting two pointers. * subtracting two pointers.
*/ */
using isize = std::ptrdiff_t; using isize = std::ptrdiff_t;
/**
* @typedef string
* @brief Represents a string.
*/
using string = std::string;