Code modernization and cleanups.

This commit is contained in:
Alexander Shaduri
2022-01-14 15:06:07 +04:00
parent 3e4cefb04f
commit 534dcd129e
32 changed files with 305 additions and 186 deletions
+2 -2
View File
@@ -64,13 +64,13 @@ class AppBuilderWidget : public WidgetType, public WindowInstanceManager<Child,
AppBuilderWidget(const AppBuilderWidget& other) = delete;
/// Disallow
AppBuilderWidget(const AppBuilderWidget&& other) = delete;
AppBuilderWidget(AppBuilderWidget&& other) = delete;
/// Disallow
AppBuilderWidget& operator=(const AppBuilderWidget& other) = delete;
/// Disallow
AppBuilderWidget& operator=(const AppBuilderWidget&& other) = delete;
AppBuilderWidget& operator=(AppBuilderWidget&& other) = delete;
/// Default
~AppBuilderWidget() = default;
+1 -1
View File
@@ -110,7 +110,7 @@ namespace {
Glib::ustring app_ustring_from_gchar(gchar* str)
{
if (!str) {
return Glib::ustring();
return {};
}
Glib::ustring ustr(str);
g_free(str);
+4 -4
View File
@@ -39,13 +39,13 @@ class AsyncCommandExecutor : public hz::ErrorHolder {
AsyncCommandExecutor(const AsyncCommandExecutor& other) = delete;
/// Deleted
AsyncCommandExecutor(const AsyncCommandExecutor&& other) = delete;
AsyncCommandExecutor(AsyncCommandExecutor&& other) = delete;
/// Deleted
AsyncCommandExecutor& operator=(const AsyncCommandExecutor& other) = delete;
/// Deleted
AsyncCommandExecutor& operator=(const AsyncCommandExecutor&& other) = delete;
AsyncCommandExecutor& operator=(AsyncCommandExecutor&& other) = delete;
/// Destructor. Don't destroy this object unless the child has exited. It will leak stuff
@@ -196,8 +196,8 @@ class AsyncCommandExecutor : public hz::ErrorHolder {
GIOChannel* channel_stdout_ = nullptr; ///< stdout channel
GIOChannel* channel_stderr_ = nullptr; ///< stderr channel
gsize channel_stdout_buffer_size_ = 100 * 1024; ///< stdout channel buffer size. NOT affected by cleanup_members(). 100K.
gsize channel_stderr_buffer_size_ = 10 * 1024; ///< stderr channel buffer size. NOT affected by cleanup_members(). 10K.
gsize channel_stdout_buffer_size_ = 100UL * 1024UL; ///< stdout channel buffer size. NOT affected by cleanup_members(). 100K.
gsize channel_stderr_buffer_size_ = 10UL * 1024UL; ///< stderr channel buffer size. NOT affected by cleanup_members(). 10K.
guint event_source_id_stdout_ = 0; ///< IO watcher event source ID for stdout
guint event_source_id_stderr_ = 0; ///< IO watcher event source ID for stderr
+4 -4
View File
@@ -1110,11 +1110,11 @@ namespace {
// search by ID first
auto id_iter = id_db.find(id);
if (id_iter == id_db.end()) {
return AttributeDescription(); // not found
return {}; // not found
}
DBG_ASSERT(!id_iter->second.empty());
if (id_iter->second.empty()) {
return AttributeDescription(); // invalid DB?
return {}; // invalid DB?
}
std::vector<AttributeDescription> type_matched;
@@ -1124,7 +1124,7 @@ namespace {
}
}
if (type_matched.empty()) {
return AttributeDescription(); // not found
return {}; // not found
}
// search by smartctl name in ID-supplied vector
@@ -1371,7 +1371,7 @@ namespace {
// search by ID first
auto iter = devstat_db.find(reported_name);
if (iter == devstat_db.end()) {
return StatisticDescription(); // not found
return {}; // not found
}
return iter->second;
}
+3 -3
View File
@@ -34,9 +34,9 @@ CommandExecutor::CommandExecutor(std::string command_name, std::string command_a
CommandExecutor::CommandExecutor()
// Translators: {command} will be replaced by command name.
: running_msg_(_("Running {command}..."))
{
/// Translators: {command} will be replaced by command name.
running_msg_ = _("Running {command}...");
set_error_header(std::string(_("An error occurred while executing command:")) + "\n\n");
}
@@ -131,7 +131,7 @@ bool CommandExecutor::execute()
g_main_context_iteration(nullptr, FALSE);
}
const gulong sleep_us = 50*1000; // 50 msec. avoids 100% CPU usage.
const gulong sleep_us = 50UL * 1000UL; // 50 msec. avoids 100% CPU usage.
g_usleep(sleep_us);
}
+2 -2
View File
@@ -70,13 +70,13 @@ class CommandExecutor : public sigc::trackable {
CommandExecutor(const CommandExecutor& other) = delete;
/// Deleted
CommandExecutor(const CommandExecutor&& other) = delete;
CommandExecutor(CommandExecutor&& other) = delete;
/// Deleted
CommandExecutor& operator=(CommandExecutor& other) = delete;
/// Deleted
CommandExecutor& operator=(const CommandExecutor&& other) = delete;
CommandExecutor& operator=(CommandExecutor&& other) = delete;
/// Virtual destructor
+1 -1
View File
@@ -55,7 +55,7 @@ bool gui_show_text_entry_dialog(const std::string& title, const std::string& mes
/// \c result is filled with the user-entered string on success.
/// \return false if Cancel was clicked.
bool gui_show_text_entry_dialog(const std::string& title, const std::string& message, const std::string& sec_message,
std::string& result, const std::string& default_str, Gtk::Window* parent = 0, bool sec_msg_markup = false);
std::string& result, const std::string& default_str, Gtk::Window* parent = nullptr, bool sec_msg_markup = false);
+6 -8
View File
@@ -89,14 +89,12 @@ bool SelfTest::is_supported() const
if (!drive_)
return false;
if (type_ == TestType::immediate_offline) // disable this for now - it's unsupported.
return false;
std::string prop_name;
switch(type_) {
case TestType::immediate_offline:
prop_name = "iodc_support";
break;
// prop_name = "iodc_support";
// break;
return false; // disable this for now - it's unsupported.
case TestType::short_test:
case TestType::long_test: // same for short and long
prop_name = "selftest_support";
@@ -168,7 +166,7 @@ std::string SelfTest::start(const std::shared_ptr<CommandExecutor>& smartctl_ex)
drive_->set_test_is_active(true);
return std::string(); // everything ok
return {}; // everything ok
}
@@ -221,7 +219,7 @@ std::string SelfTest::force_stop(const std::shared_ptr<CommandExecutor>& smartct
if (!error_msg.empty()) // update can error out too.
return error_msg;
return std::string(); // everything ok
return {}; // everything ok
}
@@ -309,7 +307,7 @@ std::string SelfTest::update(const std::shared_ptr<CommandExecutor>& smartctl_ex
drive_->set_test_is_active(active);
return std::string(); // everything ok
return {}; // everything ok
}
+1 -1
View File
@@ -365,7 +365,7 @@ std::string SmartctlAtaTextParser::parse_byte_size(const std::string& str, int64
" [" + hz::format_size(static_cast<uint64_t>(v), false) + ", " + hz::number_to_string_locale(v) + " bytes]" : "");
}
return std::string();
return {};
}
+1 -1
View File
@@ -129,7 +129,7 @@ std::string execute_smartctl(const std::string& device, const std::string& devic
return _("Smartctl returned an empty output.");
}
return std::string();
return {};
}
+4 -4
View File
@@ -65,7 +65,7 @@ inline std::string execute_tw_cli(const CommandExecutorFactoryPtr& ex_factory, c
return _("tw_cli returned an empty output.");
}
return std::string();
return {};
}
@@ -107,7 +107,7 @@ inline std::string tw_cli_get_drives(const std::string& dev, int controller,
}
}
return std::string();
return {};
}
@@ -144,7 +144,7 @@ inline std::string tw_cli_get_controllers(const CommandExecutorFactoryPtr& ex_fa
// are sorted in the end anyway.
std::sort(controllers.begin(), controllers.end());
return std::string();
return {};
}
@@ -191,7 +191,7 @@ inline std::string smartctl_scan_drives_sequentially(const std::string& dev, con
}
}
return std::string();
return {};
}
+10 -10
View File
@@ -143,7 +143,7 @@ inline std::error_code read_proc_file(const hz::fs::path& file, std::string& con
auto& cache = get_read_file_cache_ref();
if (auto iter = cache.find(file); iter != cache.end()) {
contents = iter->second;
return std::error_code();
return {};
}
auto ec = hz::fs_file_get_contents_unseekable(file, contents);
@@ -157,7 +157,7 @@ inline std::error_code read_proc_file(const hz::fs::path& file, std::string& con
debug_out_dump("app", DBG_FUNC_MSG << "File contents (\"" << file.string() << "\"):\n" << contents << "\n");
debug_end();
return std::error_code();
return {};
}
@@ -196,7 +196,7 @@ inline std::string read_proc_partitions_file(std::vector<std::string>& lines)
return ec.message();
}
return std::string();
return {};
}
@@ -221,7 +221,7 @@ inline std::string read_proc_devices_file(std::vector<std::string>& lines)
return ec.message();
}
return std::string();
return {};
}
@@ -267,7 +267,7 @@ inline std::string read_proc_scsi_scsi_file(std::vector< std::pair<int, std::str
}
}
return std::string();
return {};
}
@@ -315,7 +315,7 @@ inline std::string read_proc_scsi_sg_devices_file(std::vector<std::vector<int>>&
}
}
return std::string();
return {};
}
@@ -434,7 +434,7 @@ inline std::string detect_drives_linux_proc_partitions(std::vector<StorageDevice
}
}
return std::string();
return {};
}
@@ -499,7 +499,7 @@ inline std::string detect_drives_linux_3ware(std::vector<StorageDevicePtr>& driv
if (!twa_found && !twe_found && !twl_found) {
debug_out_info("app", DBG_FUNC_MSG << "No 3ware-specific entries found in devices file.\n");
return std::string(); // no controllers
return {}; // no controllers
}
lines.clear();
@@ -621,7 +621,7 @@ inline std::string detect_drives_linux_adaptec(std::vector<StorageDevicePtr>& dr
}
if (!aac_found) {
debug_out_info("app", DBG_FUNC_MSG << "No Adaptec-specific entries found in devices file.\n");
return std::string(); // no controllers
return {}; // no controllers
}
lines.clear();
@@ -903,7 +903,7 @@ inline std::string detect_drives_linux_cciss(std::vector<StorageDevicePtr>& driv
}
if (controllers.empty()) {
debug_out_info("app", DBG_FUNC_MSG << "No cciss-specific entries found in devices file.\n");
return std::string(); // no controllers
return {}; // no controllers
}
std::shared_ptr<CommandExecutor> smartctl_ex = ex_factory->create_executor(CommandExecutorFactory::ExecutorType::Smartctl);
+10 -11
View File
@@ -59,10 +59,9 @@ std::string StorageDevice::get_status_displayable_name(Status status)
StorageDevice::StorageDevice(std::string dev_or_vfile, bool is_virtual)
: is_virtual_(is_virtual)
{
is_virtual_ = is_virtual;
if (is_virtual) {
if (is_virtual_) {
virtual_file_ = hz::fs::u8path(dev_or_vfile);
} else {
device_ = std::move(dev_or_vfile);
@@ -249,7 +248,7 @@ std::string StorageDevice::parse_basic_data(bool do_set_properties, bool emit_si
if (emit_signal)
signal_changed().emit(this); // notify listeners
return std::string();
return {};
}
@@ -320,7 +319,7 @@ std::string StorageDevice::parse_data()
signal_changed().emit(this); // notify listeners
return std::string();
return {};
}
// Don't show any GUI warnings on parse failure - it may just be an unsupported
@@ -334,7 +333,7 @@ std::string StorageDevice::parse_data()
return ps.get_error_msg(); // return full parser's error messages - they are more detailed.
}
return std::string(); // return ok if at least the info was ok.
return {}; // return ok if at least the info was ok.
}
@@ -374,7 +373,7 @@ A mandatory SMART command failed: exiting. To continue, add one or more '-T perm
// search at line start, because they are sometimes present in other sentences too.
if (app_pcre_match("/^SMART Enabled/mi", output) || app_pcre_match("/^SMART Disabled/mi", output)) {
return std::string(); // success
return {}; // success
}
if (app_pcre_match("/^A mandatory SMART command failed/mi", output)) {
@@ -409,7 +408,7 @@ A mandatory SMART command failed: exiting. To continue, add one or more '-T perm
return error_msg;
if (app_pcre_match("/Testing Enabled/mi", output) || app_pcre_match("/Testing Disabled/mi", output)) {
return std::string(); // success
return {}; // success
}
if (app_pcre_match("/^A mandatory SMART command failed/mi", output)) {
@@ -668,7 +667,7 @@ AtaStorageProperty StorageDevice::lookup_property(const std::string& generic_nam
if (p.generic_name == generic_name)
return p;
}
return AtaStorageProperty(); // check with .empty()
return {}; // check with .empty()
}
@@ -781,7 +780,7 @@ std::string StorageDevice::get_device_options() const
{
if (is_virtual_) {
debug_out_warn("app", DBG_FUNC_MSG << "Cannot get device options of a virtual device.\n");
return std::string();
return {};
}
// If we have some special type or option, specify it on the command line (like "-d scsi").
@@ -838,7 +837,7 @@ std::string StorageDevice::execute_device_smartctl(const std::string& command_op
return error_msg;
}
return std::string();
return {};
}
+2 -2
View File
@@ -85,13 +85,13 @@ inline AppDeviceOptionMap app_config_get_device_option_map()
inline std::string app_get_device_option(const std::string& dev, const std::string& type_arg)
{
if (dev.empty())
return std::string();
return {};
auto devmap = app_config_get_device_option_map().value;
if (auto iter = devmap.find(std::pair(dev, type_arg)); iter != devmap.end()) {
return iter->second;
}
return std::string();
return {};
}
+1 -1
View File
@@ -85,7 +85,7 @@ inline std::string storage_property_get_warning_reason(const AtaStorageProperty&
return Glib::ustring::compose(_("%1ALERT:%2 %3"), start, stop, p.warning_reason);
}
return std::string();
return {};
}
+4 -4
View File
@@ -73,13 +73,13 @@ class WindowInstanceManager {
WindowInstanceManager(const WindowInstanceManager& other) = delete;
/// Deleted
WindowInstanceManager(const WindowInstanceManager&& other) = delete;
WindowInstanceManager(WindowInstanceManager&& other) = delete;
/// Deleted
WindowInstanceManager& operator=(const WindowInstanceManager&) = delete;
/// Deleted
WindowInstanceManager& operator=(const WindowInstanceManager&&) = delete;
WindowInstanceManager& operator=(WindowInstanceManager&&) = delete;
/// Default, must be polymorphic for casts to succeed
virtual ~WindowInstanceManager() = default;
@@ -125,13 +125,13 @@ class WindowInstanceManager<Child, false> {
WindowInstanceManager(const WindowInstanceManager& other) = delete;
/// Deleted
WindowInstanceManager(const WindowInstanceManager&& other) = delete;
WindowInstanceManager(WindowInstanceManager&& other) = delete;
/// Deleted
WindowInstanceManager& operator=(const WindowInstanceManager&) = delete;
/// Deleted
WindowInstanceManager& operator=(const WindowInstanceManager&&) = delete;
WindowInstanceManager& operator=(WindowInstanceManager&&) = delete;
/// Default, must be polymorphic for casts to succeed
virtual ~WindowInstanceManager() = default;
+10 -11
View File
@@ -66,7 +66,7 @@ class GscMainWindowIconView : public Gtk::IconView {
/// Constructor, GtkBuilder needs this.
GscMainWindowIconView(BaseObjectType* gtkcobj, [[maybe_unused]] const Glib::RefPtr<Gtk::Builder>& ref_ui)
[[maybe_unused]] GscMainWindowIconView(BaseObjectType* gtkcobj, [[maybe_unused]] const Glib::RefPtr<Gtk::Builder>& ref_ui)
: Gtk::IconView(gtkcobj)
{
columns.add(col_name); // we can use the col_name variable by value after this.
@@ -358,16 +358,15 @@ class GscMainWindowIconView : public Gtk::IconView {
if (icon) {
icon = icon->copy(); // work on a copy
if (icon->get_colorspace() == Gdk::COLORSPACE_RGB && icon->get_bits_per_sample() == 8) {
int n_channels = icon->get_n_channels();
int icon_width = icon->get_width();
int icon_height = icon->get_height();
int rowstride = icon->get_rowstride();
std::ptrdiff_t n_channels = icon->get_n_channels();
std::ptrdiff_t icon_width = icon->get_width();
std::ptrdiff_t icon_height = icon->get_height();
std::ptrdiff_t rowstride = icon->get_rowstride();
guint8* pixels = icon->get_pixels();
guint8* p = nullptr;
for (int y = 0; y < icon_height; ++y) {
for (int x = 0; x < icon_width; ++x) {
p = pixels + y * rowstride + x * n_channels;
for (std::ptrdiff_t y = 0; y < icon_height; ++y) {
for (std::ptrdiff_t x = 0; x < icon_width; ++x) {
guint8* p = pixels + y * rowstride + x * n_channels;
auto avg = static_cast<uint8_t>(std::floor((p[0] * 0.30) + (p[1] * 0.59) + (p[2] * 0.11) + 0.001 + 0.5));
p[0] = avg; // R
p[1] = 0; // G
@@ -459,7 +458,7 @@ class GscMainWindowIconView : public Gtk::IconView {
if (drive == row.get_value(col_drive_ptr).get())
return ref_list_model->get_path(row);
}
return Gtk::TreePath(); // check with .empty()
return {}; // check with .empty()
}
@@ -530,7 +529,7 @@ class GscMainWindowIconView : public Gtk::IconView {
Gtk::CellRenderer* cell = nullptr;
if (this->get_cursor(cell) && cell) {
// gtkmm's set_cursor() is undefined (but declared) in 2.8, so use gtk variant.
gtk_icon_view_set_cursor(GTK_ICON_VIEW(this->gobj()), tpath.gobj(), cell->gobj(), false);
gtk_icon_view_set_cursor(GTK_ICON_VIEW(this->gobj()), tpath.gobj(), cell->gobj(), FALSE);
}
// select the icon
+20 -7
View File
@@ -36,7 +36,7 @@ class bad_cast_except : public std::exception { // from <exception>
/// \param error_msg error message
bad_cast_except(const std::type_info& src, const std::type_info& dest,
const char* self_name = nullptr, const char* error_msg = nullptr)
: src_type(src), dest_type(dest),
: src_type_(src), dest_type_(dest),
self_name_(self_name ? self_name : "bad_cast_except"),
error_msg_(error_msg ? error_msg : "Type cast failed from \"%s\" to \"%s\".") // still need %s here for correct arg count for printf
{ }
@@ -49,24 +49,37 @@ class bad_cast_except : public std::exception { // from <exception>
// an out-of-memory exception, what the heck.
std::string who = (self_name_.empty() ? "[unknown]" : self_name_);
std::string from = (src_type == typeid(void) ? "[unknown]" : hz::type_name_demangle(src_type.name()));
std::string from = (src_type_ == typeid(void) ? "[unknown]" : hz::type_name_demangle(src_type_.name()));
if (from.empty())
from = src_type.name();
from = src_type_.name();
std::string to = (dest_type == typeid(void) ? "[unknown]" : hz::type_name_demangle(dest_type.name()));
std::string to = (dest_type_ == typeid(void) ? "[unknown]" : hz::type_name_demangle(dest_type_.name()));
if (to.empty())
to = dest_type.name();
to = dest_type_.name();
return (msg_ = hz::string_sprintf((who + ": " + error_msg_).c_str(), from.c_str(), to.c_str())).c_str();
}
const std::type_info& src_type; ///< Cast source type info. Can be a reference since type_info objects are guaranteed to live forever.
const std::type_info& dest_type; ///< Cast destination type info
/// Get source type
const std::type_info& src_type() const
{
return src_type_;
}
/// Get destination type
const std::type_info& dest_type() const
{
return dest_type_;
}
private:
const std::type_info& src_type_; ///< Cast source type info. Can be a reference since type_info objects are guaranteed to live forever.
const std::type_info& dest_type_; ///< Cast destination type info
mutable std::string msg_; ///< This must be a member to avoid its destruction on function call return. use what().
std::string self_name_; ///< The exception class name
+9 -10
View File
@@ -50,7 +50,7 @@ inline std::vector<fs::path> data_file_get_search_directories(const std::string&
if (DataFileStaticHolder::search_directories.count(domain) > 0) {
return DataFileStaticHolder::search_directories.at(domain);
}
return std::vector<fs::path>();
return {};
}
@@ -68,19 +68,19 @@ inline void data_file_set_search_directories(const std::string& domain, std::vec
inline fs::path data_file_find(const std::string& domain, const std::string& filename, bool allow_to_be_directory = false)
{
if (filename.empty())
return fs::path();
return {};
if (fs::u8path(filename).is_absolute()) { // shouldn't happen
debug_print_error("app", "%s: Data file \"%s\" must be relative.\n",
DBG_FUNC, filename.c_str());
return fs::path();
return {};
}
auto dirs = data_file_get_search_directories(domain);
if (dirs.empty()) { // shouldn't happen
debug_print_error("app", "%s: No search directories registered for domain \"%s\".\n",
DBG_FUNC, domain.c_str());
return fs::path();
return {};
}
for (const auto& dir : dirs) {
@@ -91,7 +91,7 @@ inline fs::path data_file_find(const std::string& domain, const std::string& fil
if (!allow_to_be_directory && fs::is_directory(file_path, ec)) {
debug_print_error("app", "%s: Data file \"[%s:]%s\" file found at \"%s\", but it is a directory.\n",
DBG_FUNC, domain.c_str(), file_path.string().c_str(), dir.string().c_str());
return fs::path();
return {};
}
debug_print_info("app", "%s: Data file \"[%s:]%s\" found at \"%s\".\n",
DBG_FUNC, domain.c_str(), file_path.string().c_str(), dir.string().c_str());
@@ -101,7 +101,7 @@ inline fs::path data_file_find(const std::string& domain, const std::string& fil
debug_print_error("app", "%s: Data file \"[%s:]%s\" not found.\n",
DBG_FUNC, domain.c_str(), filename.c_str());
return fs::path();
return {};
}
@@ -115,12 +115,11 @@ inline std::string data_file_get_contents(const std::string& domain, const std::
auto ec = hz::fs_file_get_contents(file, contents, max_size);
if (!ec) {
return contents;
} else {
debug_print_error("app", "%s: Data file \"[%s:]%s\" cannot be loaded: %s.\n",
DBG_FUNC, domain.c_str(), filename.c_str(), ec.message().c_str());
}
debug_print_error("app", "%s: Data file \"[%s:]%s\" cannot be loaded: %s.\n",
DBG_FUNC, domain.c_str(), filename.c_str(), ec.message().c_str());
}
return std::string();
return {};
}
+1 -1
View File
@@ -157,7 +157,7 @@ inline bool env_set_value(const std::string& name, const std::string& value, boo
// glib version may be thread-unsafe on win32, so don't use it there.
#elif defined ENABLE_GLIB && ENABLE_GLIB
return g_setenv(name.c_str(), value.c_str(), overwrite) != 0; // may be thread-unsafe
return g_setenv(name.c_str(), value.c_str(), static_cast<gboolean>(overwrite)) != 0; // may be thread-unsafe
#elif defined HAVE_SETENV && HAVE_SETENV
+91 -49
View File
@@ -66,32 +66,46 @@ class ErrorBase {
/// Constructor
ErrorBase(std::string type_, ErrorLevel level_, std::string msg)
: type(std::move(type_)), level(level_), message(std::move(msg))
ErrorBase(std::string type, ErrorLevel level, std::string message)
: type_(std::move(type)), level_(level), message_(std::move(message))
{ }
/// Constructor
ErrorBase(std::string type_, ErrorLevel level_)
: type(std::move(type_)), level(level_)
ErrorBase(std::string type, ErrorLevel level)
: type_(std::move(type)), level_(level)
{ }
/// Defaulted
ErrorBase(const ErrorBase& other) = default;
/// Defaulted
ErrorBase(ErrorBase&& other) = default;
/// Defaulted
ErrorBase& operator=(const ErrorBase&) = default;
/// Defaulted
ErrorBase& operator=(ErrorBase&&) = default;
/// Virtual destructor
virtual ~ErrorBase() = default;
/// Clone this object
[[nodiscard]] virtual ErrorBase* clone() = 0; // needed for copying by base pointers
/// Get std::type_info for the error code type.
[[nodiscard]] virtual const std::type_info& get_code_type() const = 0;
[[nodiscard]] virtual const std::type_info& get_code_type_info() const = 0;
/// Get error code of type \c CodeMemberType
template<class CodeMemberType>
CodeMemberType get_code() const // this may throw on bad cast!
{
if (get_code_type() != typeid(CodeMemberType))
throw type_mismatch(get_code_type(), typeid(CodeMemberType));
if (get_code_type_info() != typeid(CodeMemberType))
throw type_mismatch(get_code_type_info(), typeid(CodeMemberType));
return static_cast<const Error<CodeMemberType>*>(this)->code;
}
@@ -99,9 +113,9 @@ class ErrorBase {
template<class CodeMemberType>
bool get_code(CodeMemberType& put_it_here) const // this doesn't throw
{
if (get_code_type() != typeid(CodeMemberType))
if (get_code_type_info() != typeid(CodeMemberType))
return false;
put_it_here = static_cast<const Error<CodeMemberType>*>(this)->code;
put_it_here = static_cast<const Error<CodeMemberType>*>(this)->get_code_member();
return true;
}
@@ -109,47 +123,67 @@ class ErrorBase {
/// Increase the level (severity) of the error
ErrorLevel level_inc()
{
if (level == ErrorLevel::fatal)
return level;
return (level = static_cast<ErrorLevel>(static_cast<int>(level) << 1));
if (level_ == ErrorLevel::fatal)
return level_;
return (level_ = static_cast<ErrorLevel>(static_cast<int>(level_) << 1));
}
/// Decrease the level (severity) of the error
ErrorLevel level_dec()
{
if (level == ErrorLevel::none)
return level;
return (level = static_cast<ErrorLevel>(static_cast<int>(level) >> 1));
if (level_ == ErrorLevel::none)
return level_;
return (level_ = static_cast<ErrorLevel>(static_cast<int>(level_) >> 1));
}
/// Get error level (severity)
[[nodiscard]] ErrorLevel get_level() const
{
return level;
return level_;
}
/// Get error type
[[nodiscard]] std::string get_type() const
{
return type;
return type_;
}
/// Get error message
[[nodiscard]] std::string get_message() const
{
return message;
return message_;
}
// no set_type, set_message - we don't allow changing those.
protected:
std::string type; ///< Error type
ErrorLevel level = ErrorLevel::none; ///< Error severity
std::string message; ///< Error message
/// Set error type
void set_type(std::string type)
{
type_ = std::move(type);
}
/// Set error level
void set_level(ErrorLevel level)
{
level_ = level;
}
/// Set error message
void set_message(std::string message)
{
message_ = std::move(message);
}
private:
std::string type_; ///< Error type
ErrorLevel level_ = ErrorLevel::none; ///< Error severity
std::string message_; ///< Error message
};
@@ -163,25 +197,33 @@ class ErrorCodeHolder : public ErrorBase {
protected:
/// Constructor
ErrorCodeHolder(const std::string& type_, ErrorLevel level_, const CodeType& code_,
ErrorCodeHolder(const std::string& type, ErrorLevel level, const CodeType& code,
const std::string& msg)
: ErrorBase(type_, level_, msg), code(code_)
: ErrorBase(type, level, msg), code_(code)
{ }
/// Constructor
ErrorCodeHolder(const std::string& type_, ErrorLevel level_, const CodeType& code_)
: ErrorBase(type_, level_), code(code_)
ErrorCodeHolder(const std::string& type, ErrorLevel level, const CodeType& code)
: ErrorBase(type, level), code_(code)
{ }
public:
// Reimplemented from ErrorBase
[[nodiscard]] const std::type_info& get_code_type() const override
[[nodiscard]] const std::type_info& get_code_type_info() const override
{
return typeid(CodeType);
}
CodeType code = CodeType(); ///< Error code. We have a class specialization for references too
// Reimplemented from ErrorBase
[[nodiscard]] const CodeType& get_code_member() const
{
return code_;
}
private:
CodeType code_ = CodeType(); ///< Error code. We have a class specialization for references too
};
@@ -193,14 +235,14 @@ class ErrorCodeHolder<void> : public ErrorBase {
protected:
/// Constructor
ErrorCodeHolder(const std::string& type_, ErrorLevel level_, const std::string& msg)
: ErrorBase(type_, level_, msg)
ErrorCodeHolder(const std::string& type, ErrorLevel level, const std::string& msg)
: ErrorBase(type, level, msg)
{ }
public:
// Reimplemented from ErrorBase
[[nodiscard]] const std::type_info& get_code_type() const override
[[nodiscard]] const std::type_info& get_code_type_info() const override
{
return typeid(void);
}
@@ -219,16 +261,16 @@ class Error : public ErrorCodeHolder<CodeType> {
public:
/// Constructor
Error(const std::string& type_, ErrorLevel level_, const CodeType& code_,
Error(const std::string& type, ErrorLevel level, const CodeType& code,
const std::string& msg)
: ErrorCodeHolder<CodeType>(type_, level_, code_, msg)
: ErrorCodeHolder<CodeType>(type, level, code, msg)
{ }
// Reimplemented from ErrorBase
ErrorBase* clone() override
{
return new Error(ErrorCodeHolder<CodeType>::type, ErrorCodeHolder<CodeType>::level,
ErrorCodeHolder<CodeType>::code, ErrorCodeHolder<CodeType>::message);
return new Error(ErrorCodeHolder<CodeType>::get_type(), ErrorCodeHolder<CodeType>::get_level(),
ErrorCodeHolder<CodeType>::get_code_member(), ErrorCodeHolder<CodeType>::get_message());
}
};
@@ -240,15 +282,15 @@ template<>
class Error<void> : public ErrorCodeHolder<void> {
public:
Error(const std::string& type_, ErrorLevel level_, const std::string& msg)
: ErrorCodeHolder<void>(type_, level_, msg)
Error(const std::string& type, ErrorLevel level, const std::string& msg)
: ErrorCodeHolder<void>(type, level, msg)
{ }
// Reimplemented from ErrorBase
ErrorBase* clone() override
{
return new Error(ErrorCodeHolder<void>::type, ErrorCodeHolder<void>::level,
ErrorCodeHolder<void>::message);
return new Error(ErrorCodeHolder<void>::get_type(), ErrorCodeHolder<void>::get_level(),
ErrorCodeHolder<void>::get_message());
}
};
@@ -262,20 +304,20 @@ class Error<int> : public ErrorCodeHolder<int> {
public:
/// Constructor
Error(const std::string& type_, ErrorLevel level_, int code_, const std::string& msg)
: ErrorCodeHolder<int>(type_, level_, code_, msg)
Error(const std::string& type, ErrorLevel level, int code, const std::string& msg)
: ErrorCodeHolder<int>(type, level, code, msg)
{ }
/// Constructor
Error(const std::string& type_, ErrorLevel level_, int code_)
: ErrorCodeHolder<int>(type_, level_, code_)
Error(const std::string& type, ErrorLevel level, int code)
: ErrorCodeHolder<int>(type, level, code)
{
if (type == "errno") {
message = std::error_code(code_, std::system_category()).message();
this->set_message(std::error_code(code, std::system_category()).message());
} else if (type == "signal") {
// hz::signal_string should be translated already
message = "Child exited with signal: " + hz::signal_to_string(code_);
this->set_message("Child exited with signal: " + hz::signal_to_string(code));
} else { // nothing else supported here. use constructor with a message.
DBG_ASSERT(0);
@@ -285,8 +327,8 @@ class Error<int> : public ErrorCodeHolder<int> {
// Reimplemented from ErrorBase
ErrorBase* clone() override
{
return new Error(ErrorCodeHolder<int>::type, ErrorCodeHolder<int>::level,
ErrorCodeHolder<int>::code, ErrorCodeHolder<int>::message);
return new Error(ErrorCodeHolder<int>::get_type(), ErrorCodeHolder<int>::get_level(),
ErrorCodeHolder<int>::get_code_member(), ErrorCodeHolder<int>::get_message());
}
};
+16 -1
View File
@@ -30,6 +30,21 @@ class ErrorHolder {
using error_list_t = std::vector<std::shared_ptr<ErrorBase>>; ///< A list of ErrorBase* pointers
/// Defaulted
ErrorHolder() = default;
/// Deleted
ErrorHolder(const ErrorHolder& other) = delete;
/// Deleted
ErrorHolder(ErrorHolder&& other) = delete;
/// Deleted
ErrorHolder& operator=(const ErrorHolder&) = delete;
/// Deleted
ErrorHolder& operator=(ErrorHolder&&) = delete;
/// Virtual destructor
virtual ~ErrorHolder() = default;
@@ -85,7 +100,7 @@ class ErrorHolder {
}
protected:
private:
error_list_t errors_; ///< Error list. The newest errors at the end.
+12 -10
View File
@@ -177,12 +177,13 @@ inline std::string format_time_length(std::chrono::seconds secs)
std::vector<std::string>{"{days}", "{hours}"},
std::vector<std::string>{std::to_string(days.count()), std::to_string(hours)});
} else { // display days only
return hz::string_replace_copy(C_("time", "{days} d"),
"{days}", std::to_string(days.count()));
}
// display days only
return hz::string_replace_copy(C_("time", "{days} d"),
"{days}", std::to_string(days.count()));
}
} else if (secs >= 100min) {
if (secs >= 100min) {
auto hours = std::chrono::round<std::chrono::hours>(secs);
std::chrono::seconds sec_diff = secs - hours;
@@ -195,11 +196,12 @@ inline std::string format_time_length(std::chrono::seconds secs)
std::vector<std::string>{"{hours}", "{minutes}"},
std::vector<std::string>{std::to_string(hours.count()), std::to_string(minutes)});
} else { // display hours only
return std::to_string(hours.count()) + " " + "h";
}
// display hours only
return std::to_string(hours.count()) + " " + "h";
}
} else if (secs >= 100s) {
if (secs >= 100s) {
auto minutes = std::chrono::round<std::chrono::minutes>(secs);
return hz::string_replace_copy(C_("time", "{minutes} min"),
"{minutes}", std::to_string(minutes.count()));
@@ -222,7 +224,7 @@ inline std::string format_time_length(std::chrono::seconds secs)
inline std::string format_date(const std::string& format, const struct std::tm* ltmp, bool use_classic_locale)
{
if (!ltmp || format.empty())
return std::string();
return {};
std::ostringstream ss;
if (!use_classic_locale) {
@@ -250,7 +252,7 @@ inline std::string format_date(const std::string& format, std::time_t timet, boo
#else
struct std::tm ltm = {};
if (!localtime_r(&timet, &ltm)) // use reentrant localtime_r (posix/bsd and related)
return std::string();
return {};
const struct std::tm* ltmp = &ltm;
#endif
@@ -265,7 +267,7 @@ inline std::string format_date(const std::string& format, bool use_classic_local
{
const std::time_t timet = std::time(nullptr);
if (timet == static_cast<std::time_t>(-1))
return std::string();
return {};
return format_date(format, timet, use_classic_locale);
}
+12 -11
View File
@@ -19,6 +19,7 @@ Copyright:
#include <cstdio> // std::FILE, std::fopen() and friends
#include <stdio.h> // off_t, fileno(), _fileno(), _wfopen()
#include <limits>
#include <array>
#ifdef _WIN32
#include <io.h> // _waccess*()
@@ -161,7 +162,7 @@ inline std::error_code fs_file_get_contents_noalloc(const fs::path& file, unsign
std::FILE* f = fs_platform_fopen(file, "rb");
if (!f) {
return std::error_code(errno, std::system_category());
return {errno, std::system_category()};
}
std::error_code ec;
@@ -271,19 +272,19 @@ inline std::error_code fs_file_get_contents_unseekable(const hz::fs::path& file,
{
std::FILE* fp = fs_platform_fopen(file, "rb");
if (!fp) {
return std::error_code(errno, std::system_category());;
return {errno, std::system_category()};
}
put_data_here.clear();
char line[1024] = {0};
while (std::fgets(line, static_cast<int>(sizeof(line)), fp) != nullptr) {
if (*line != '\0')
put_data_here += line; // line contains the terminating newline as well
std::array<char, 1024> line = {};
while (std::fgets(line.data(), static_cast<int>(line.size()), fp) != nullptr) {
if (line[0] != '\0')
put_data_here += line.data(); // line contains the terminating newline as well
}
std::fclose(fp);
return std::error_code();
return {};
}
@@ -299,7 +300,7 @@ inline std::error_code fs_file_put_contents(const fs::path& file, const unsigned
std::FILE* f = fs_platform_fopen(file, "wb");
if (!f) {
return std::error_code(errno, std::system_category());
return {errno, std::system_category()};
}
// We write in chunks to support large files.
@@ -328,9 +329,9 @@ inline std::error_code fs_file_put_contents(const fs::path& file, const unsigned
}
if (std::fclose(f) != 0)
return std::error_code(errno, std::system_category());
return {errno, std::system_category()};
return std::error_code();
return {};
}
@@ -386,7 +387,7 @@ inline fs::path fs_get_home_dir()
return fs::temp_directory_path(ec);
}
return fs::path(dir); // native encoding
return {dir}; // native encoding
#endif
}
+3 -3
View File
@@ -51,10 +51,10 @@ inline std::string launch_url([[maybe_unused]] GtkWindow* window, const std::str
GError* error = nullptr;
#if GTK_CHECK_VERSION(3, 22, 0)
bool status = gtk_show_uri_on_window(window, link.c_str(), GDK_CURRENT_TIME, &error);
bool status = static_cast<bool>(gtk_show_uri_on_window(window, link.c_str(), GDK_CURRENT_TIME, &error));
#else
GdkScreen* screen = (window ? gtk_window_get_screen(window) : nullptr);
bool status = (bool)gtk_show_uri(screen, link.c_str(), GDK_CURRENT_TIME, &error);
bool status = static_cast<bool>(gtk_show_uri(screen, link.c_str(), GDK_CURRENT_TIME, &error));
#endif
std::unique_ptr<GError, decltype(&g_error_free)> uerror(error, &g_error_free);
@@ -62,7 +62,7 @@ inline std::string launch_url([[maybe_unused]] GtkWindow* window, const std::str
return std::string("Cannot open URL: ")
+ ((error && error->message) ? (std::string(": ") + error->message) : ".");
}
return std::string();
return {};
#endif
}
+28 -1
View File
@@ -191,7 +191,7 @@ std::string locale_cpp_get<std::string>()
template<> inline
std::locale locale_cpp_get<std::locale>()
{
return std::locale();
return {};
}
@@ -219,6 +219,19 @@ class ScopedCLocale {
}
}
/// Deleted
ScopedCLocale(const ScopedCLocale& other) = delete;
/// Deleted
ScopedCLocale(ScopedCLocale&& other) = delete;
/// Deleted
ScopedCLocale& operator=(const ScopedCLocale&) = delete;
/// Deleted
ScopedCLocale& operator=(ScopedCLocale&&) = delete;
/// Change back the locale
~ScopedCLocale()
{
@@ -287,12 +300,26 @@ class ScopedCppLocale {
}
}
/// Deleted
ScopedCppLocale(const ScopedCppLocale& other) = delete;
/// Deleted
ScopedCppLocale(ScopedCppLocale&& other) = delete;
/// Deleted
ScopedCppLocale& operator=(const ScopedCppLocale&) = delete;
/// Deleted
ScopedCppLocale& operator=(ScopedCppLocale&&) = delete;
/// Change the locale back to the old one
~ScopedCppLocale()
{
this->restore();
}
/// Get the old locale
[[nodiscard]] std::locale old() const
{
+1 -1
View File
@@ -34,7 +34,7 @@ int main_exception_wrapper(MainImplFunc main_impl) noexcept
return main_impl();
}
catch(std::exception& e) {
// don't use anything other than cerr here, it's the most safe option.
// don't use anything other than cerr here, it's the safest option.
std::cerr << "main(): Unhandled exception: " << e.what() << std::endl;
if (const auto* ex_type = get_current_exception_type()) {
std::cerr << "Type of exception: " << type_name_demangle(ex_type->name()) << std::endl;
+10 -11
View File
@@ -51,9 +51,8 @@ void string_split(const std::string& str, char delimiter,
if (++num == limit) {
append_here.push_back(str.substr(last, std::string::npos));
break;
} else {
append_here.push_back(str.substr(last, (curr == std::string::npos ? curr : (curr - last))));
}
append_here.push_back(str.substr(last, (curr == std::string::npos ? curr : (curr - last))));
}
if (curr == std::string::npos)
@@ -98,9 +97,8 @@ void string_split(const std::string& str, const std::string& delimiter,
if (++num == limit) {
append_here.push_back(str.substr(last, std::string::npos));
break;
} else {
append_here.push_back(component);
}
append_here.push_back(component);
}
if (curr == std::string::npos)
@@ -137,9 +135,8 @@ void string_split_by_chars(const std::string& str, const std::string& delimiter_
if (++num == limit) {
append_here.push_back(str.substr(last, std::string::npos));
break;
} else {
append_here.push_back(str.substr(last, (curr == std::string::npos ? curr : (curr - last))));
}
append_here.push_back(str.substr(last, (curr == std::string::npos ? curr : (curr - last))));
}
if (curr == std::string::npos)
@@ -203,10 +200,11 @@ inline bool string_trim(std::string& s, const std::string& trim_chars = " \t\r\n
s.erase(index + 1); // from index+1 to the end
index = s.find_first_not_of(trim_chars);
if (index != std::string::npos)
if (index != std::string::npos) {
s.erase(0, index);
else
} else {
s.clear();
}
return s_size != s.size(); // true if s was modified
}
@@ -234,10 +232,11 @@ inline bool string_trim_left(std::string& s, const std::string& trim_chars = " \
const auto s_size = s.size();
std::string::size_type index = s.find_first_not_of(trim_chars);
if (index != std::string::npos)
if (index != std::string::npos) {
s.erase(0, index);
else
} else {
s.clear();
}
return s_size != s.size(); // true if s was modified
}
@@ -359,7 +358,7 @@ inline bool string_remove_adjacent_duplicates(std::string& s, char c, std::size_
return false;
bool changed = false;
std::string::size_type pos1 = 0, pos2;
std::string::size_type pos1 = 0, pos2 = 0;
while ((pos1 = s.find(c, pos1)) != std::string::npos) {
pos2 = s.find_first_not_of(c, pos1);
+5 -4
View File
@@ -202,7 +202,7 @@ namespace internal {
return false;
const char* str = s.c_str();
if (boolalpha_enabled) {
if (boolalpha_enabled != 0) {
// skip spaces. won't do anything in strict mode (we already ruled out spaces there)
while (std::isspace(*str, loc)) {
++str;
@@ -345,7 +345,7 @@ namespace internal {
inline std::string number_to_string_impl_bool(bool number, int boolalpha_enabled)
{
if (boolalpha_enabled)
if (boolalpha_enabled != 0)
return (number ? "true" : "false");
return (number ? "1" : "0");
}
@@ -357,7 +357,8 @@ namespace internal {
if (number == 0) {
if (base == 16) {
return "0x" + std::string(sizeof(T) * 2, '0'); // 0 doesn't print as 0x0000, but as 000000. fix that.
} else if (base == 8) { // same here, 0 prints as 0.
}
if (base == 8) { // same here, 0 prints as 0.
return "00"; // better than simply 0 (at least it's clearly octal).
}
// base 10 can possibly have some funny formatting, so continue...
@@ -420,7 +421,7 @@ namespace internal {
return internal::number_to_string_impl_floating(number, boolalpha_or_base_or_precision, fixed_prec, use_classic_locale);
}
// unreachable
return std::string();
return {};
}
+15
View File
@@ -33,6 +33,21 @@ using DebugChannelBasePtr = std::shared_ptr<DebugChannelBase>;
class DebugChannelBase {
public:
/// Defaulted
DebugChannelBase() = default;
/// Deleted
DebugChannelBase(const DebugChannelBase& other) = delete;
/// Deleted
DebugChannelBase(DebugChannelBase&& other) = delete;
/// Deleted
DebugChannelBase& operator=(const DebugChannelBase&) = delete;
/// Deleted
DebugChannelBase& operator=(DebugChannelBase&&) = delete;
/// Virtual destructor
virtual ~DebugChannelBase() = default;
+11 -2
View File
@@ -66,8 +66,17 @@ namespace debug_internal {
}
/// Disallow copying
DebugStreamBuf(const DebugStreamBuf& from) = delete;
/// Deleted
DebugStreamBuf(const DebugStreamBuf& other) = delete;
/// Deleted
DebugStreamBuf(DebugStreamBuf&& other) = delete;
/// Deleted
DebugStreamBuf& operator=(const DebugStreamBuf&) = delete;
/// Deleted
DebugStreamBuf& operator=(DebugStreamBuf&&) = delete;
/// Virtual destructor
+5 -5
View File
@@ -51,7 +51,7 @@ extern "C" {
bool force = (bool)data;
if (!force && !impl::autosave_enabled) // no more autosaves
return false; // remove timeout, disable autosave for real.
return FALSE; // remove timeout, disable autosave for real.
auto file = impl::autosave_config_file;
debug_print_info("rconfig", "Autosaving config to \"%s\".\n", file.u8string().c_str());
@@ -59,14 +59,14 @@ extern "C" {
std::error_code ec;
if ((hz::fs::exists(file, ec) && !hz::fs::is_regular_file(file, ec)) || !hz::fs_path_is_writable(file, ec)) {
debug_out_error("rconfig", "Autosave failed: Cannot write to file: " << ec.message() << "\n");
return !force; // if manual, return failure. else, don't stop the timeout.
return static_cast<gboolean>(force); // if manual, return failure. else, don't stop the timeout.
}
bool status = rconfig::save_to_file(impl::autosave_config_file);
if (force)
return status; // return status to caller
return static_cast<gboolean>(status); // return status to caller
return true; // continue timeouts
return TRUE; // continue timeouts
}
}
@@ -123,7 +123,7 @@ inline void autosave_stop()
/// Forcibly save the config now.
inline bool autosave_force_now()
{
return static_cast<bool>(autosave_timeout_callback((void*)true)); // anyone tell me what is the C++ variant of this?
return static_cast<bool>(autosave_timeout_callback(reinterpret_cast<void*>(true))); // anyone tell me what is the C++ variant of this?
}