diff options
author | Murray Cumming <murrayc@murrayc.com> | 2016-02-26 10:45:15 +0100 |
---|---|---|
committer | Murray Cumming <murrayc@murrayc.com> | 2016-02-26 10:45:15 +0100 |
commit | 249bdd539ab05aab98bc417f579524b4e988faef (patch) | |
tree | c98b5ae0b6068d1c33a6e6040928fc25ad748163 | |
parent | 942cdcb3d74ba9cd4fc702153715b503d63aa395 (diff) | |
download | glibmm-249bdd539ab05aab98bc417f579524b4e988faef.tar.gz |
Run clang-format on the examples.
-rw-r--r-- | examples/child_watch/main.cc | 29 | ||||
-rw-r--r-- | examples/compose/main.cc | 35 | ||||
-rw-r--r-- | examples/dbus/client_bus_listnames.cc | 30 | ||||
-rw-r--r-- | examples/dbus/server_without_bus.cc | 102 | ||||
-rw-r--r-- | examples/dbus/session_bus_service.cc | 89 | ||||
-rw-r--r-- | examples/iochannel_stream/fdstream.cc | 137 | ||||
-rw-r--r-- | examples/iochannel_stream/fdstream.h | 17 | ||||
-rw-r--r-- | examples/iochannel_stream/main.cc | 28 | ||||
-rw-r--r-- | examples/keyfile/main.cc | 15 | ||||
-rw-r--r-- | examples/markup/parser.cc | 75 | ||||
-rw-r--r-- | examples/network/resolver.cc | 617 | ||||
-rw-r--r-- | examples/network/socket-client.cc | 434 | ||||
-rw-r--r-- | examples/network/socket-server.cc | 395 | ||||
-rw-r--r-- | examples/options/main.cc | 121 | ||||
-rw-r--r-- | examples/properties/properties_example.cc | 97 | ||||
-rw-r--r-- | examples/regex/main.cc | 23 | ||||
-rw-r--r-- | examples/settings/settings.cc | 40 | ||||
-rw-r--r-- | examples/thread/dispatcher.cc | 89 | ||||
-rw-r--r-- | examples/thread/dispatcher2.cc | 100 | ||||
-rw-r--r-- | examples/thread/thread.cc | 77 | ||||
-rw-r--r-- | examples/thread/threadpool.cc | 31 |
21 files changed, 1276 insertions, 1305 deletions
diff --git a/examples/child_watch/main.cc b/examples/child_watch/main.cc index 010992e3..77389048 100644 --- a/examples/child_watch/main.cc +++ b/examples/child_watch/main.cc @@ -16,51 +16,52 @@ */ #include <glibmm.h> +#include <iostream> #include <sys/types.h> #include <unistd.h> -#include <iostream> using namespace std; class ChildWatch : public sigc::trackable { public: - ChildWatch(const Glib::RefPtr<Glib::MainLoop>& mainLoop) - : m_mainLoop(mainLoop) - {} + ChildWatch(const Glib::RefPtr<Glib::MainLoop>& mainLoop) : m_mainLoop(mainLoop) {} - void on_child_exited(GPid pid,int status); + void on_child_exited(GPid pid, int status); void run(); // fork a child and call signal_child_watch private: Glib::RefPtr<Glib::MainLoop> m_mainLoop; }; -void ChildWatch::run() +void +ChildWatch::run() { GPid pid = fork(); - - if(!pid) + + if (!pid) { sleep(5); exit(0); } - - std:: cout << "Child " << pid << " created" << std::endl; - + + std::cout << "Child " << pid << " created" << std::endl; + Glib::signal_child_watch().connect(sigc::mem_fun(*this, &ChildWatch::on_child_exited), pid); } -void ChildWatch::on_child_exited(GPid pid, int status) +void +ChildWatch::on_child_exited(GPid pid, int status) { std::cout << "Child " << pid << " exited with status " << status << std::endl; m_mainLoop->quit(); } -int main() +int +main() { auto mainLoop = Glib::MainLoop::create(); - + ChildWatch cwatch(mainLoop); cwatch.run(); mainLoop->run(); diff --git a/examples/compose/main.cc b/examples/compose/main.cc index d8c9484c..79952bbf 100644 --- a/examples/compose/main.cc +++ b/examples/compose/main.cc @@ -23,35 +23,34 @@ namespace { -void show_examples() +void +show_examples() { using Glib::ustring; const double a = 3456.78; const double b = 7890.12; - const int i = int(a / (a + b) * 40.0); - - std::cout - << ustring::compose("%1 is lower than %2.", a, b) - << std::endl - << ustring::compose("%2 is greater than %1.", a, b) - << std::endl - // ustring::format does only work with std::fixed with MSVC2008 or above. - // See https://bugzilla.gnome.org/show_bug.cgi?id=599340 + const int i = int(a / (a + b) * 40.0); + + std::cout << ustring::compose("%1 is lower than %2.", a, b) << std::endl + << ustring::compose("%2 is greater than %1.", a, b) << std::endl +// ustring::format does only work with std::fixed with MSVC2008 or above. +// See https://bugzilla.gnome.org/show_bug.cgi?id=599340 #if !defined(_MSC_VER) || _MSC_VER >= 1500 - << ustring::compose("%1 € are %3 %% of %2 €.", a, b, - ustring::format(std::fixed, std::setprecision(1), a / b * 100.0)) - << std::endl + << ustring::compose("%1 € are %3 %% of %2 €.", a, b, + ustring::format(std::fixed, std::setprecision(1), a / b * 100.0)) + << std::endl #endif - << ustring::compose("a : b = [%1|%2]", - ustring::format(std::setfill(L'a'), std::setw(i), ""), - ustring::format(std::setfill(L'b'), std::setw(40 - i), "")) - << std::endl; + << ustring::compose("a : b = [%1|%2]", + ustring::format(std::setfill(L'a'), std::setw(i), ""), + ustring::format(std::setfill(L'b'), std::setw(40 - i), "")) + << std::endl; } } // anonymous namespace -int main(int, char**) +int +main(int, char**) { std::locale::global(std::locale("")); std::cout.imbue(std::locale()); diff --git a/examples/dbus/client_bus_listnames.cc b/examples/dbus/client_bus_listnames.cc index 7b9adad6..c9a644fe 100644 --- a/examples/dbus/client_bus_listnames.cc +++ b/examples/dbus/client_bus_listnames.cc @@ -23,7 +23,8 @@ Glib::RefPtr<Glib::MainLoop> loop; // A main loop idle callback to quit when the main loop is idle. -bool on_main_loop_idle() +bool +on_main_loop_idle() { loop->quit(); return false; @@ -32,14 +33,16 @@ bool on_main_loop_idle() // A callback to finish creating a DBus::Proxy that was asynchronously created // for the user session's bus and then try to call the well known 'ListNames' // method. -void on_dbus_proxy_available(Glib::RefPtr<Gio::AsyncResult>& result) +void +on_dbus_proxy_available(Glib::RefPtr<Gio::AsyncResult>& result) { const auto proxy = Gio::DBus::Proxy::create_finish(result); - if(!proxy) + if (!proxy) { std::cerr << "The proxy to the user's session bus was not successfully " - "created." << std::endl; + "created." + << std::endl; loop->quit(); return; } @@ -52,7 +55,7 @@ void on_dbus_proxy_available(Glib::RefPtr<Gio::AsyncResult>& result) // Now extract the single item in the variant container which is the // array of strings (the names). - Glib::Variant< std::vector<Glib::ustring>> names_variant; + Glib::Variant<std::vector<Glib::ustring>> names_variant; call_result.get_child(names_variant); // Get the vector of strings. @@ -60,10 +63,10 @@ void on_dbus_proxy_available(Glib::RefPtr<Gio::AsyncResult>& result) std::cout << "The names on the message bus are:" << std::endl; - for(const auto& i : names) + for (const auto& i : names) std::cout << i << "." << std::endl; } - catch(const Glib::Error& error) + catch (const Glib::Error& error) { std::cerr << "Got an error: '" << error.what() << "'." << std::endl; } @@ -73,7 +76,8 @@ void on_dbus_proxy_available(Glib::RefPtr<Gio::AsyncResult>& result) Glib::signal_idle().connect(sigc::ptr_fun(&on_main_loop_idle)); } -int main(int, char**) +int +main(int, char**) { std::locale::global(std::locale("")); Gio::init(); @@ -81,20 +85,18 @@ int main(int, char**) loop = Glib::MainLoop::create(); // Get the user session bus connection. - auto connection = - Gio::DBus::Connection::get_sync(Gio::DBus::BUS_TYPE_SESSION); + auto connection = Gio::DBus::Connection::get_sync(Gio::DBus::BUS_TYPE_SESSION); // Check for an unavailable connection. - if(!connection) + if (!connection) { std::cerr << "The user's session bus is not available." << std::endl; return 1; } // Create the proxy to the bus asynchronously. - Gio::DBus::Proxy::create(connection, "org.freedesktop.DBus", - "/org/freedesktop/DBus", "org.freedesktop.DBus", - sigc::ptr_fun(&on_dbus_proxy_available)); + Gio::DBus::Proxy::create(connection, "org.freedesktop.DBus", "/org/freedesktop/DBus", + "org.freedesktop.DBus", sigc::ptr_fun(&on_dbus_proxy_available)); loop->run(); diff --git a/examples/dbus/server_without_bus.cc b/examples/dbus/server_without_bus.cc index 6002c149..953fd26b 100644 --- a/examples/dbus/server_without_bus.cc +++ b/examples/dbus/server_without_bus.cc @@ -35,17 +35,16 @@ namespace static Glib::RefPtr<Gio::DBus::NodeInfo> introspection_data; -static Glib::ustring introspection_xml = - "<node>" - " <interface name='org.glibmm.DBus.Clock'>" - " <method name='GetTime'>" - " <arg type='s' name='iso8601' direction='out'/>" - " </method>" - " <method name='SetAlarm'>" - " <arg type='s' name='iso8601' direction='in'/>" - " </method>" - " </interface>" - "</node>"; +static Glib::ustring introspection_xml = "<node>" + " <interface name='org.glibmm.DBus.Clock'>" + " <method name='GetTime'>" + " <arg type='s' name='iso8601' direction='out'/>" + " </method>" + " <method name='SetAlarm'>" + " <arg type='s' name='iso8601' direction='in'/>" + " </method>" + " </interface>" + "</node>"; // Stores the current alarm. static Glib::TimeVal curr_alarm; @@ -56,33 +55,32 @@ static Glib::RefPtr<Gio::DBus::Connection> current_connection; } // anonymous namespace -static void on_method_call(const Glib::RefPtr<Gio::DBus::Connection>& /* connection */, +static void +on_method_call(const Glib::RefPtr<Gio::DBus::Connection>& /* connection */, const Glib::ustring& /* sender */, const Glib::ustring& /* object_path */, const Glib::ustring& /* interface_name */, const Glib::ustring& method_name, const Glib::VariantContainerBase& parameters, const Glib::RefPtr<Gio::DBus::MethodInvocation>& invocation) { - if(method_name == "GetTime") + if (method_name == "GetTime") { Glib::TimeVal curr_time; curr_time.assign_current_time(); const Glib::ustring time_str = curr_time.as_iso8601(); - const auto time_var = - Glib::Variant<Glib::ustring>::create(time_str); + const auto time_var = Glib::Variant<Glib::ustring>::create(time_str); // Create the tuple. - Glib::VariantContainerBase response = - Glib::VariantContainerBase::create_tuple(time_var); + Glib::VariantContainerBase response = Glib::VariantContainerBase::create_tuple(time_var); // Return the tuple with the included time. invocation->return_value(response); } - else if(method_name == "SetAlarm") + else if (method_name == "SetAlarm") { // Get the parameter tuple. - //Glib::VariantContainerBase parameters; - //invocation->get_parameters(parameters); + // Glib::VariantContainerBase parameters; + // invocation->get_parameters(parameters); // Get the variant string. Glib::Variant<Glib::ustring> param; @@ -91,51 +89,52 @@ static void on_method_call(const Glib::RefPtr<Gio::DBus::Connection>& /* connect // Get the time string. const Glib::ustring time_str = param.get(); - if(!curr_alarm.assign_from_iso8601(time_str)) + if (!curr_alarm.assign_from_iso8601(time_str)) { // If setting alarm was not successful, return an error. - Gio::DBus::Error error(Gio::DBus::Error::INVALID_ARGS, - "Alarm string is not in ISO8601 format."); + Gio::DBus::Error error( + Gio::DBus::Error::INVALID_ARGS, "Alarm string is not in ISO8601 format."); invocation->return_error(error); } } else { // Non-existent method on the interface. - Gio::DBus::Error error(Gio::DBus::Error::UNKNOWN_METHOD, - "Method does not exist."); + Gio::DBus::Error error(Gio::DBus::Error::UNKNOWN_METHOD, "Method does not exist."); invocation->return_error(error); } } -//This must be a global instance. See the InterfaceVTable documentation. -//TODO: Make that unnecessary. +// This must be a global instance. See the InterfaceVTable documentation. +// TODO: Make that unnecessary. const Gio::DBus::InterfaceVTable interface_vtable(sigc::ptr_fun(&on_method_call)); -bool on_server_new_connection(const Glib::RefPtr<Gio::DBus::Connection>& connection) +bool +on_server_new_connection(const Glib::RefPtr<Gio::DBus::Connection>& connection) { - auto credentials = - connection->get_peer_credentials(); + auto credentials = connection->get_peer_credentials(); std::string credentials_str; - if(!credentials) + if (!credentials) credentials_str = "(no credentials received)"; else credentials_str = credentials->to_string(); - std::cout << - "Client connected." << std::endl << - "Peer credentials: " << credentials_str << std::endl << - "Negotiated capabilities: unix-fd-passing=" << (connection->get_capabilities() & Gio::DBus::CAPABILITY_FLAGS_UNIX_FD_PASSING) << std::endl; + std::cout << "Client connected." << std::endl + << "Peer credentials: " << credentials_str << std::endl + << "Negotiated capabilities: unix-fd-passing=" + << (connection->get_capabilities() & Gio::DBus::CAPABILITY_FLAGS_UNIX_FD_PASSING) + << std::endl; // If there is already an active connection, do not accept this new one. // There may be a better way to decide how to keep current incoming // connections. - if(current_connection && !current_connection->is_closed()) + if (current_connection && !current_connection->is_closed()) { std::cerr << "Unable to accept a new incoming connection because one is " - "already active." << std::endl; + "already active." + << std::endl; return false; } @@ -148,11 +147,10 @@ bool on_server_new_connection(const Glib::RefPtr<Gio::DBus::Connection>& connect // the repetition of the interface name: try { - connection->register_object("/org/glibmm/DBus/TestObject", - introspection_data->lookup_interface(), - interface_vtable); + connection->register_object( + "/org/glibmm/DBus/TestObject", introspection_data->lookup_interface(), interface_vtable); } - catch(const Glib::Error& ex) + catch (const Glib::Error& ex) { std::cerr << "Registration of object failed." << std::endl; return false; @@ -161,7 +159,8 @@ bool on_server_new_connection(const Glib::RefPtr<Gio::DBus::Connection>& connect return true; } -int main(int, char**) +int +main(int, char**) { std::locale::global(std::locale("")); Gio::init(); @@ -170,10 +169,9 @@ int main(int, char**) { introspection_data = Gio::DBus::NodeInfo::create_for_xml(introspection_xml); } - catch(const Glib::Error& ex) + catch (const Glib::Error& ex) { - std::cerr << "Unable to create introspection data: " << ex.what() << - "." << std::endl; + std::cerr << "Unable to create introspection data: " << ex.what() << "." << std::endl; return 1; } @@ -182,24 +180,22 @@ int main(int, char**) const Glib::ustring address = "unix:abstract=myadd"; try { - server = Gio::DBus::Server::create_sync(address, - Gio::DBus::generate_guid()); + server = Gio::DBus::Server::create_sync(address, Gio::DBus::generate_guid()); } - catch(const Glib::Error& ex) + catch (const Glib::Error& ex) { - std::cerr << "Error creating server at address: " << address << - ": " << ex.what() << "." << std::endl; + std::cerr << "Error creating server at address: " << address << ": " << ex.what() << "." + << std::endl; return EXIT_FAILURE; } server->start(); - std::cout << "Server is listening at: " << server->get_client_address() << - "." << std::endl; + std::cout << "Server is listening at: " << server->get_client_address() << "." << std::endl; server->signal_new_connection().connect(sigc::ptr_fun(&on_server_new_connection)); - //Keep the server running until the process is killed: + // Keep the server running until the process is killed: auto loop = Glib::MainLoop::create(); loop->run(); diff --git a/examples/dbus/session_bus_service.cc b/examples/dbus/session_bus_service.cc index ed320b8b..b190db3f 100644 --- a/examples/dbus/session_bus_service.cc +++ b/examples/dbus/session_bus_service.cc @@ -35,17 +35,16 @@ namespace static Glib::RefPtr<Gio::DBus::NodeInfo> introspection_data; -static Glib::ustring introspection_xml = - "<node>" - " <interface name='org.glibmm.DBusExample.Clock'>" - " <method name='GetTime'>" - " <arg type='s' name='iso8601' direction='out'/>" - " </method>" - " <method name='SetAlarm'>" - " <arg type='s' name='iso8601' direction='in'/>" - " </method>" - " </interface>" - "</node>"; +static Glib::ustring introspection_xml = "<node>" + " <interface name='org.glibmm.DBusExample.Clock'>" + " <method name='GetTime'>" + " <arg type='s' name='iso8601' direction='out'/>" + " </method>" + " <method name='SetAlarm'>" + " <arg type='s' name='iso8601' direction='in'/>" + " </method>" + " </interface>" + "</node>"; guint registered_id = 0; @@ -54,33 +53,32 @@ static Glib::TimeVal curr_alarm; } // anonymous namespace -static void on_method_call(const Glib::RefPtr<Gio::DBus::Connection>& /* connection */, +static void +on_method_call(const Glib::RefPtr<Gio::DBus::Connection>& /* connection */, const Glib::ustring& /* sender */, const Glib::ustring& /* object_path */, const Glib::ustring& /* interface_name */, const Glib::ustring& method_name, const Glib::VariantContainerBase& parameters, const Glib::RefPtr<Gio::DBus::MethodInvocation>& invocation) { - if(method_name == "GetTime") + if (method_name == "GetTime") { Glib::TimeVal curr_time; curr_time.assign_current_time(); const Glib::ustring time_str = curr_time.as_iso8601(); - const auto time_var = - Glib::Variant<Glib::ustring>::create(time_str); + const auto time_var = Glib::Variant<Glib::ustring>::create(time_str); // Create the tuple. - Glib::VariantContainerBase response = - Glib::VariantContainerBase::create_tuple(time_var); + Glib::VariantContainerBase response = Glib::VariantContainerBase::create_tuple(time_var); // Return the tuple with the included time. invocation->return_value(response); } - else if(method_name == "SetAlarm") + else if (method_name == "SetAlarm") { // Get the parameter tuple. - //Glib::VariantContainerBase parameters; - //invocation->get_parameters(parameters); + // Glib::VariantContainerBase parameters; + // invocation->get_parameters(parameters); // Get the variant string. Glib::Variant<Glib::ustring> param; @@ -89,28 +87,29 @@ static void on_method_call(const Glib::RefPtr<Gio::DBus::Connection>& /* connect // Get the time string. const Glib::ustring time_str = param.get(); - if(!curr_alarm.assign_from_iso8601(time_str)) + if (!curr_alarm.assign_from_iso8601(time_str)) { // If setting alarm was not successful, return an error. - Gio::DBus::Error error(Gio::DBus::Error::INVALID_ARGS, - "Alarm string is not in ISO8601 format."); + Gio::DBus::Error error( + Gio::DBus::Error::INVALID_ARGS, "Alarm string is not in ISO8601 format."); invocation->return_error(error); } } else { // Non-existent method on the interface. - Gio::DBus::Error error(Gio::DBus::Error::UNKNOWN_METHOD, - "Method does not exist."); + Gio::DBus::Error error(Gio::DBus::Error::UNKNOWN_METHOD, "Method does not exist."); invocation->return_error(error); } } -//This must be a global instance. See the InterfaceVTable documentation. -//TODO: Make that unnecessary. +// This must be a global instance. See the InterfaceVTable documentation. +// TODO: Make that unnecessary. const Gio::DBus::InterfaceVTable interface_vtable(sigc::ptr_fun(&on_method_call)); -void on_bus_acquired(const Glib::RefPtr<Gio::DBus::Connection>& connection, const Glib::ustring& /* name */) +void +on_bus_acquired( + const Glib::RefPtr<Gio::DBus::Connection>& connection, const Glib::ustring& /* name */) { // Export an object to the bus: @@ -118,11 +117,10 @@ void on_bus_acquired(const Glib::RefPtr<Gio::DBus::Connection>& connection, cons // the repetition of the interface name: try { - registered_id = connection->register_object("/org/glibmm/DBus/TestObject", - introspection_data->lookup_interface(), - interface_vtable); + registered_id = connection->register_object( + "/org/glibmm/DBus/TestObject", introspection_data->lookup_interface(), interface_vtable); } - catch(const Glib::Error& ex) + catch (const Glib::Error& ex) { std::cerr << "Registration of object failed." << std::endl; } @@ -130,39 +128,40 @@ void on_bus_acquired(const Glib::RefPtr<Gio::DBus::Connection>& connection, cons return; } -void on_name_acquired(const Glib::RefPtr<Gio::DBus::Connection>& /* connection */, const Glib::ustring& /* name */) +void +on_name_acquired( + const Glib::RefPtr<Gio::DBus::Connection>& /* connection */, const Glib::ustring& /* name */) { - //TODO: What is this good for? See https://bugzilla.gnome.org/show_bug.cgi?id=646427 + // TODO: What is this good for? See https://bugzilla.gnome.org/show_bug.cgi?id=646427 } -void on_name_lost(const Glib::RefPtr<Gio::DBus::Connection>& connection, const Glib::ustring& /* name */) +void +on_name_lost(const Glib::RefPtr<Gio::DBus::Connection>& connection, const Glib::ustring& /* name */) { connection->unregister_object(registered_id); } -int main(int, char**) +int +main(int, char**) { std::locale::global(std::locale("")); Gio::init(); - try + try { introspection_data = Gio::DBus::NodeInfo::create_for_xml(introspection_xml); } - catch(const Glib::Error& ex) + catch (const Glib::Error& ex) { - std::cerr << "Unable to create introspection data: " << ex.what() << - "." << std::endl; + std::cerr << "Unable to create introspection data: " << ex.what() << "." << std::endl; return 1; } - const auto id = Gio::DBus::own_name(Gio::DBus::BUS_TYPE_SESSION, - "org.glibmm.DBusExample", - sigc::ptr_fun(&on_bus_acquired), - sigc::ptr_fun(&on_name_acquired), + const auto id = Gio::DBus::own_name(Gio::DBus::BUS_TYPE_SESSION, "org.glibmm.DBusExample", + sigc::ptr_fun(&on_bus_acquired), sigc::ptr_fun(&on_name_acquired), sigc::ptr_fun(&on_name_lost)); - //Keep the service running until the process is killed: + // Keep the service running until the process is killed: auto loop = Glib::MainLoop::create(); loop->run(); diff --git a/examples/iochannel_stream/fdstream.cc b/examples/iochannel_stream/fdstream.cc index 3764546a..1c4ff95c 100644 --- a/examples/iochannel_stream/fdstream.cc +++ b/examples/iochannel_stream/fdstream.cc @@ -34,46 +34,52 @@ fdstreambuf::~fdstreambuf() sync(); } -void fdstreambuf::reset() +void +fdstreambuf::reset() { setg(putback_buffer + 1, putback_buffer + 1, putback_buffer + 1); error_condition.error = false; } -void fdstreambuf::create_iochannel(int fd, bool manage) +void +fdstreambuf::create_iochannel(int fd, bool manage) { sync(); reset(); - if(fd >= 0) + if (fd >= 0) { iochannel_ = Glib::IOChannel::create_from_fd(fd); iochannel_->set_encoding(""); - + iochannel_->set_buffered(true); iochannel_->set_close_on_unref(manage); - } + } } -void fdstreambuf::detach_fd() +void +fdstreambuf::detach_fd() { iochannel_->set_close_on_unref(false); } -void fdstreambuf::connect(const sigc::slot<bool, Glib::IOCondition>& callback, - Glib::IOCondition condition) +void +fdstreambuf::connect( + const sigc::slot<bool, Glib::IOCondition>& callback, Glib::IOCondition condition) { Glib::signal_io().connect(callback, iochannel_, condition); } -fdstream_error fdstreambuf::get_error() const +fdstream_error +fdstreambuf::get_error() const { return error_condition; } // the standard requires sync to return 0 for success and -1 for error -int fdstreambuf::sync() +int +fdstreambuf::sync() { if (!iochannel_) return -1; @@ -82,7 +88,7 @@ int fdstreambuf::sync() { iochannel_->flush(); } - catch(Glib::IOChannelError& io_error) + catch (Glib::IOChannelError& io_error) { error_condition.error = true; error_condition.code = io_error.code(); @@ -92,7 +98,8 @@ int fdstreambuf::sync() return 0; } -void fdstreambuf::close_iochannel() +void +fdstreambuf::close_iochannel() { iochannel_->set_close_on_unref(false); reset(); @@ -101,19 +108,19 @@ void fdstreambuf::close_iochannel() { iochannel_->close(true); } - catch(Glib::IOChannelError& io_error) + catch (Glib::IOChannelError& io_error) { error_condition.error = true; error_condition.code = io_error.code(); } - } // the standard requires this to return either the character // written on overflow or traits_type::eof() (= EOF with char_type == char) -fdstreambuf::traits_type::int_type fdstreambuf::overflow(int_type c) +fdstreambuf::traits_type::int_type +fdstreambuf::overflow(int_type c) { - if(!traits_type::eq_int_type(c, traits_type::eof())) + if (!traits_type::eq_int_type(c, traits_type::eof())) { try { @@ -121,7 +128,7 @@ fdstreambuf::traits_type::int_type fdstreambuf::overflow(int_type c) char write_char = c; iochannel_->write(&write_char, 1, result); } - catch(Glib::IOChannelError& io_error) + catch (Glib::IOChannelError& io_error) { error_condition.error = true; error_condition.code = io_error.code(); @@ -133,7 +140,8 @@ fdstreambuf::traits_type::int_type fdstreambuf::overflow(int_type c) // the standard requires this to return the number of characters written // (which will be 0 for stream failure - it is not correct to return EOF) -std::streamsize fdstreambuf::xsputn(const char* source, std::streamsize num) +std::streamsize +fdstreambuf::xsputn(const char* source, std::streamsize num) { gsize result = 0; @@ -145,7 +153,7 @@ std::streamsize fdstreambuf::xsputn(const char* source, std::streamsize num) { iochannel_->write(source, num, result); } - catch(Glib::IOChannelError& io_error) + catch (Glib::IOChannelError& io_error) { error_condition.error = true; error_condition.code = io_error.code(); @@ -157,13 +165,14 @@ std::streamsize fdstreambuf::xsputn(const char* source, std::streamsize num) // the standard requires this to return the first character available // on underflow or traits_type::eof() (= EOF with char_type == char) -fdstreambuf::traits_type::int_type fdstreambuf::underflow() +fdstreambuf::traits_type::int_type +fdstreambuf::underflow() { - if(gptr() < egptr()) + if (gptr() < egptr()) return traits_type::to_int_type(*gptr()); // copy the character in bump position (if any) to putback position - if(gptr() - eback()) + if (gptr() - eback()) *putback_buffer = *(gptr() - 1); // now insert a character into the bump position @@ -172,7 +181,7 @@ fdstreambuf::traits_type::int_type fdstreambuf::underflow() { iochannel_->read(putback_buffer + 1, 1, result); } - catch(Glib::IOChannelError& io_error) + catch (Glib::IOChannelError& io_error) { error_condition.error = true; error_condition.code = io_error.code(); @@ -182,11 +191,9 @@ fdstreambuf::traits_type::int_type fdstreambuf::underflow() // some other error - is this possible? In case it is, cater for it if (result == 0) return traits_type::eof(); - + // reset buffer pointers - setg(putback_buffer, - putback_buffer + 1, - putback_buffer + 2); + setg(putback_buffer, putback_buffer + 1, putback_buffer + 2); // return character in bump/peek position return traits_type::to_int_type(*gptr()); // == *(putback_buffer + 1) @@ -194,7 +201,8 @@ fdstreambuf::traits_type::int_type fdstreambuf::underflow() // the standard requires this to return the number of characters fetched // (which will be 0 for stream failure - it is not correct to return EOF) -std::streamsize fdstreambuf::xsgetn(char* dest, std::streamsize num) +std::streamsize +fdstreambuf::xsgetn(char* dest, std::streamsize num) { std::streamsize chars_read = 0; @@ -225,100 +233,95 @@ std::streamsize fdstreambuf::xsgetn(char* dest, std::streamsize num) { do { - iochannel_->read(dest + chars_read, - num - chars_read, - result); + iochannel_->read(dest + chars_read, num - chars_read, result); - if (result > 0) + if (result > 0) chars_read += result; - } - while (result > 0 && result < static_cast<gsize>(num - chars_read)); + } while (result > 0 && result < static_cast<gsize>(num - chars_read)); } - catch(Glib::IOChannelError& io_error) + catch (Glib::IOChannelError& io_error) { error_condition.error = true; - + error_condition.code = io_error.code(); return chars_read; } - if(chars_read) + if (chars_read) { // now mimic extraction of all characters by sbumpc() by putting // two characters into the buffer (if available) and resetting the // buffer pointers int putback_count = 0; - if(chars_read >= 2) + if (chars_read >= 2) { - *putback_buffer = *(dest + (chars_read - 2)); - putback_count = 2; + *putback_buffer = *(dest + (chars_read - 2)); + putback_count = 2; } else - { // if we have reached here then we have only fetched - // one character and it must have been read with - // Glib::IOChannel::read() and not taken from the - // putback buffer - otherwise we would have ended - // at the first if block in this method - // - and this also means that gptr() == egptr() - if(gptr() - eback()) - { - *putback_buffer = *(gptr() - 1); - putback_count = 2; - } - else + { // if we have reached here then we have only fetched + // one character and it must have been read with + // Glib::IOChannel::read() and not taken from the + // putback buffer - otherwise we would have ended + // at the first if block in this method + // - and this also means that gptr() == egptr() + if (gptr() - eback()) + { + *putback_buffer = *(gptr() - 1); + putback_count = 2; + } + else putback_count = 1; } *(putback_buffer + 1) = *(dest + (chars_read - 1)); // reset buffer pointers - this->setg(putback_buffer + (2 - putback_count), - putback_buffer + 2, - putback_buffer + 2); + this->setg(putback_buffer + (2 - putback_count), putback_buffer + 2, putback_buffer + 2); } } return chars_read; } fdstream::fdstream(int fd, bool manage) -: std::istream(nullptr), - std::ostream(nullptr), - buf(fd, manage) +: std::istream(nullptr), std::ostream(nullptr), buf(fd, manage) { std::istream::rdbuf(&buf); std::ostream::rdbuf(&buf); } -fdstream::fdstream() -: std::istream(nullptr), - std::ostream(nullptr) +fdstream::fdstream() : std::istream(nullptr), std::ostream(nullptr) { std::istream::rdbuf(&buf); std::ostream::rdbuf(&buf); } -void fdstream::attach(int fd, bool manage) +void +fdstream::attach(int fd, bool manage) { buf.create_iochannel(fd, manage); } -void fdstream::detach() +void +fdstream::detach() { buf.detach_fd(); } -void fdstream::close() +void +fdstream::close() { buf.close_iochannel(); } -void fdstream::connect(const sigc::slot<bool, Glib::IOCondition>& callback, - Glib::IOCondition condition) +void +fdstream::connect(const sigc::slot<bool, Glib::IOCondition>& callback, Glib::IOCondition condition) { buf.connect(callback, condition); } -fdstream_error fdstream::get_error() const +fdstream_error +fdstream::get_error() const { return buf.get_error(); } diff --git a/examples/iochannel_stream/fdstream.h b/examples/iochannel_stream/fdstream.h index 80f46757..824f96ec 100644 --- a/examples/iochannel_stream/fdstream.h +++ b/examples/iochannel_stream/fdstream.h @@ -21,7 +21,7 @@ * used with fifos, pipes and sockets, with safe temporary files * opened with mkstemp() and with files opened with other system * functions such as Unix open(). - * + * * It does not make use of the Glib::IOChannel automatic charset code * conversion facilities (which when enabled will convert from UTF-8 * to the locale codeset when writing out, and vice-versa when reading @@ -48,22 +48,21 @@ * fdstream provides both read and write facilities. */ - #ifndef GLIBMMEXAMPLE_FDSTREAM_H #define GLIBMMEXAMPLE_FDSTREAM_H +#include <glibmm/iochannel.h> #include <istream> #include <ostream> #include <streambuf> -#include <glibmm/iochannel.h> struct fdstream_error { bool error; - Glib::IOChannelError::Code code; + Glib::IOChannelError::Code code; }; -class fdstreambuf: public std::streambuf +class fdstreambuf : public std::streambuf { public: fdstreambuf(int fd, bool manage); @@ -95,12 +94,9 @@ private: void reset(); }; -class fdstream : - public std::istream, - public std::ostream +class fdstream : public std::istream, public std::ostream { public: - explicit fdstream(int fd, bool manage = true); fdstream(); @@ -110,8 +106,7 @@ public: void detach(); void close(); - void connect(const sigc::slot<bool, Glib::IOCondition>& callback, - Glib::IOCondition condition); + void connect(const sigc::slot<bool, Glib::IOCondition>& callback, Glib::IOCondition condition); fdstream_error get_error() const; private: diff --git a/examples/iochannel_stream/main.cc b/examples/iochannel_stream/main.cc index e2e670f0..45a7721c 100644 --- a/examples/iochannel_stream/main.cc +++ b/examples/iochannel_stream/main.cc @@ -15,14 +15,14 @@ * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ -#include <glibmm.h> #include <fcntl.h> -#include <unistd.h> -#include <limits.h> -#include <sys/types.h> -#include <sys/stat.h> +#include <glibmm.h> #include <iostream> +#include <limits.h> #include <string> +#include <sys/stat.h> +#include <sys/types.h> +#include <unistd.h> #include "fdstream.h" @@ -41,14 +41,15 @@ Glib::RefPtr<Glib::MainLoop> mainloop; // it will print out the message sent to the fifo // and quit the program if the message was, or began // with, 'Q' -bool MyCallback(Glib::IOCondition io_condition) +bool +MyCallback(Glib::IOCondition io_condition) { if ((io_condition & Glib::IO_IN) == 0) { std::cerr << "Invalid fifo response" << std::endl; } else - { + { // stream for stdout (does the same as std::cout // - this is an example of using fdstream for output) fdstream out(1, false); @@ -63,15 +64,14 @@ bool MyCallback(Glib::IOCondition io_condition) return true; } - -int main( /* int argc, char *argv[] */) +int main(/* int argc, char *argv[] */) { Glib::init(); // the usual Glib::Main object mainloop = Glib::MainLoop::create(); - if(access("testfifo", F_OK) == -1) + if (access("testfifo", F_OK) == -1) { // fifo doesn't exit - create it if (mkfifo("testfifo", 0666) != 0) @@ -80,9 +80,9 @@ int main( /* int argc, char *argv[] */) return -1; } } - + const auto read_fd = open("testfifo", O_RDONLY); - if(read_fd == -1) + if (read_fd == -1) { std::cerr << "error opening fifo" << std::endl; return -1; @@ -90,12 +90,12 @@ int main( /* int argc, char *argv[] */) input_stream.attach(read_fd); input_stream.connect(sigc::ptr_fun(MyCallback), Glib::IO_IN); - + // and last but not least - run the application main loop mainloop->run(); // now remove the temporary fifo - if(unlink("testfifo")) + if (unlink("testfifo")) std::cerr << "error removing fifo" << std::endl; return 0; diff --git a/examples/keyfile/main.cc b/examples/keyfile/main.cc index 33e90677..e4ddae7f 100644 --- a/examples/keyfile/main.cc +++ b/examples/keyfile/main.cc @@ -18,8 +18,8 @@ #include <glibmm.h> #include <iostream> - -int main(int, char**) +int +main(int, char**) { Glib::init(); @@ -32,7 +32,7 @@ int main(int, char**) { keyfile.load_from_file(filepath); } - catch(const Glib::Error& ex) + catch (const Glib::Error& ex) { std::cerr << "Exception while loading key file: " << ex.what() << std::endl; return 1; @@ -45,7 +45,7 @@ int main(int, char**) const Glib::ustring value = keyfile.get_value("somegroup", "somekey"); std::cout << "somekey value=" << value << std::endl; } - catch(const Glib::KeyFileError& ex) + catch (const Glib::KeyFileError& ex) { std::cerr << "Exception while getting value: " << ex.what() << std::endl; } @@ -57,7 +57,7 @@ int main(int, char**) const Glib::ustring value = keyfile.get_value("First Group", "Welcome"); std::cout << "Welcome value=" << value << std::endl; } - catch(const Glib::KeyFileError& ex) + catch (const Glib::KeyFileError& ex) { std::cerr << "Exception while getting value: " << ex.what() << std::endl; } @@ -68,14 +68,13 @@ int main(int, char**) { const auto values = keyfile.get_integer_list("Another Group", "Numbers"); - for(const auto& p : values) + for (const auto& p : values) std::cout << "Number list value: item=" << p << std::endl; } - catch(const Glib::KeyFileError& ex) + catch (const Glib::KeyFileError& ex) { std::cerr << "Exception while getting list value: " << ex.what() << std::endl; } return 0; } - diff --git a/examples/markup/parser.cc b/examples/markup/parser.cc index ef45dac0..9caaaf8e 100644 --- a/examples/markup/parser.cc +++ b/examples/markup/parser.cc @@ -19,34 +19,33 @@ #include <iomanip> #include <iostream> - namespace { - -void file_get_contents(const std::string& filename, Glib::ustring& contents) +void +file_get_contents(const std::string& filename, Glib::ustring& contents) { const auto channel = Glib::IOChannel::create_from_file(filename, "r"); channel->read_to_end(contents); } -Glib::ustring trim_whitespace(const Glib::ustring& text) +Glib::ustring +trim_whitespace(const Glib::ustring& text) { - Glib::ustring::const_iterator pbegin (text.begin()); - Glib::ustring::const_iterator pend (text.end()); + Glib::ustring::const_iterator pbegin(text.begin()); + Glib::ustring::const_iterator pend(text.end()); - while(pbegin != pend && Glib::Unicode::isspace(*pbegin)) + while (pbegin != pend && Glib::Unicode::isspace(*pbegin)) ++pbegin; - Glib::ustring::const_iterator temp (pend); + Glib::ustring::const_iterator temp(pend); - while(pbegin != temp && Glib::Unicode::isspace(*--temp)) + while (pbegin != temp && Glib::Unicode::isspace(*--temp)) pend = temp; return Glib::ustring(pbegin, pend); } - class DumpParser : public Glib::Markup::Parser { public: @@ -54,12 +53,11 @@ public: ~DumpParser() override; protected: - void on_start_element(Glib::Markup::ParseContext& context, - const Glib::ustring& element_name, - const AttributeMap& attributes) override; + void on_start_element(Glib::Markup::ParseContext& context, const Glib::ustring& element_name, + const AttributeMap& attributes) override; - void on_end_element(Glib::Markup::ParseContext& context, - const Glib::ustring& element_name) override; + void on_end_element( + Glib::Markup::ParseContext& context, const Glib::ustring& element_name) override; void on_text(Glib::Markup::ParseContext& context, const Glib::ustring& text) override; @@ -69,22 +67,22 @@ private: void indent(); }; -DumpParser::DumpParser() -: - parse_depth_ (0) -{} +DumpParser::DumpParser() : parse_depth_(0) +{ +} DumpParser::~DumpParser() -{} +{ +} -void DumpParser::on_start_element(Glib::Markup::ParseContext&, - const Glib::ustring& element_name, - const AttributeMap& attributes) +void +DumpParser::on_start_element( + Glib::Markup::ParseContext&, const Glib::ustring& element_name, const AttributeMap& attributes) { indent(); std::cout << '<' << element_name; - for(const auto& p : attributes) + for (const auto& p : attributes) { std::cout << ' ' << p.first << "=\"" << p.second << '"'; } @@ -94,7 +92,8 @@ void DumpParser::on_start_element(Glib::Markup::ParseContext&, ++parse_depth_; } -void DumpParser::on_end_element(Glib::Markup::ParseContext&, const Glib::ustring& element_name) +void +DumpParser::on_end_element(Glib::Markup::ParseContext&, const Glib::ustring& element_name) { --parse_depth_; @@ -102,40 +101,42 @@ void DumpParser::on_end_element(Glib::Markup::ParseContext&, const Glib::ustring std::cout << "</" << element_name << ">\n"; } -void DumpParser::on_text(Glib::Markup::ParseContext&, const Glib::ustring& text) +void +DumpParser::on_text(Glib::Markup::ParseContext&, const Glib::ustring& text) { const Glib::ustring trimmed_text = trim_whitespace(text); - if(!trimmed_text.empty()) + if (!trimmed_text.empty()) { indent(); std::cout << trimmed_text << '\n'; } } -void DumpParser::indent() +void +DumpParser::indent() { - if(parse_depth_ > 0) + if (parse_depth_ > 0) { std::cout << std::setw(4 * parse_depth_) - /* gcc 2.95.3 doesn't like this: << std::right */ - << ' '; + /* gcc 2.95.3 doesn't like this: << std::right */ + << ' '; } } } // anonymous namespace - -int main(int argc, char** argv) +int +main(int argc, char** argv) { - if(argc < 2) + if (argc < 2) { std::cerr << "Usage: parser filename\n"; return 1; } DumpParser parser; - Glib::Markup::ParseContext context (parser); + Glib::Markup::ParseContext context(parser); try { @@ -145,13 +146,11 @@ int main(int argc, char** argv) context.parse(contents); context.end_parse(); } - catch(const Glib::Error& error) + catch (const Glib::Error& error) { std::cerr << argv[1] << ": " << error.what() << std::endl; return 1; } - return 0; } - diff --git a/examples/network/resolver.cc b/examples/network/resolver.cc index a4f60bd0..97dc4d71 100644 --- a/examples/network/resolver.cc +++ b/examples/network/resolver.cc @@ -20,12 +20,12 @@ */ #ifndef _WIN32 -# include <config.h> +#include <config.h> #endif #include <giomm.h> -#include <thread> #include <iostream> #include <mutex> +#include <thread> #include <cerrno> #include <csignal> @@ -34,7 +34,7 @@ #include <cstring> #ifndef G_OS_WIN32 -# include <unistd.h> +#include <unistd.h> #endif #include <gio/gio.h> @@ -45,165 +45,157 @@ static Glib::RefPtr<Glib::MainLoop> loop; static int nlookups = 0; static void G_GNUC_NORETURN -usage (void) +usage(void) { - std::cerr - << "Usage: resolver [-t] [-s] [hostname | IP | service/protocol/domain ] ...\n" - << " resolver [-t] [-s] -c [hostname | IP | service/protocol/domain ]\n" - << " Use -s to do synchronous lookups.\n" - << " Use -c (and only a single resolvable argument) to test GSocketConnectable.\n"; - exit (1); + std::cerr + << "Usage: resolver [-t] [-s] [hostname | IP | service/protocol/domain ] ...\n" + << " resolver [-t] [-s] -c [hostname | IP | service/protocol/domain ]\n" + << " Use -s to do synchronous lookups.\n" + << " Use -c (and only a single resolvable argument) to test GSocketConnectable.\n"; + exit(1); } static std::mutex response_mutex; static bool -idle_quit () +idle_quit() { - loop->quit (); - return false; + loop->quit(); + return false; } static void -done_lookup (void) +done_lookup(void) { nlookups--; if (nlookups == 0) - { - /* In the sync case we need to make sure we don't call - * g_main_loop_quit before the loop is actually running... - */ - Glib::signal_idle ().connect (sigc::ptr_fun (idle_quit)); - } + { + /* In the sync case we need to make sure we don't call + * g_main_loop_quit before the loop is actually running... + */ + Glib::signal_idle().connect(sigc::ptr_fun(idle_quit)); + } } static void -print_resolved_name (const Glib::ustring& phys, - const Glib::ustring& name) +print_resolved_name(const Glib::ustring& phys, const Glib::ustring& name) { - std::lock_guard<std::mutex> lock_guard (response_mutex); - std::cout - << Glib::ustring::compose ("Address: %1\n", phys) - << Glib::ustring::compose ("Name: %1\n", name) - << std::endl; + std::lock_guard<std::mutex> lock_guard(response_mutex); + std::cout << Glib::ustring::compose("Address: %1\n", phys) + << Glib::ustring::compose("Name: %1\n", name) << std::endl; - done_lookup (); + done_lookup(); } static void -print_resolved_addresses (const Glib::ustring& name, - const std::list<Glib::RefPtr<Gio::InetAddress>>& addresses) +print_resolved_addresses( + const Glib::ustring& name, const std::list<Glib::RefPtr<Gio::InetAddress>>& addresses) { - std::lock_guard<std::mutex> lock_guard (response_mutex); - std::cout << Glib::ustring::compose ("Name: %1\n", name); - for (const auto& i : addresses) - { - std::cout << Glib::ustring::compose ("Address: %1\n", i->to_string ()); - } - std::cout << std::endl; + std::lock_guard<std::mutex> lock_guard(response_mutex); + std::cout << Glib::ustring::compose("Name: %1\n", name); + for (const auto& i : addresses) + { + std::cout << Glib::ustring::compose("Address: %1\n", i->to_string()); + } + std::cout << std::endl; - done_lookup (); + done_lookup(); } static void -print_resolved_service (const Glib::ustring& service, - const std::list<Gio::SrvTarget>& targets) +print_resolved_service(const Glib::ustring& service, const std::list<Gio::SrvTarget>& targets) { - std::lock_guard<std::mutex> lock_guard (response_mutex); - std::cout << Glib::ustring::compose ("Service: %1\n", service); - for (const auto& i : targets) - { - std::cout << - Glib::ustring::compose ("%1:%2 (pri %3, weight %4)\n", - i.get_hostname (), - i.get_port (), - i.get_priority (), - i.get_weight ()); - } - std::cout << std::endl; + std::lock_guard<std::mutex> lock_guard(response_mutex); + std::cout << Glib::ustring::compose("Service: %1\n", service); + for (const auto& i : targets) + { + std::cout << Glib::ustring::compose("%1:%2 (pri %3, weight %4)\n", i.get_hostname(), + i.get_port(), i.get_priority(), i.get_weight()); + } + std::cout << std::endl; - done_lookup (); + done_lookup(); } static std::vector<Glib::ustring> -split_service_parts (const Glib::ustring& arg) +split_service_parts(const Glib::ustring& arg) { - std::vector<Glib::ustring> parts; - std::size_t delim1 = 0; - std::size_t delim2 = 0; - delim1 = arg.find ('/', 0); - if (delim1 == std::string::npos) - return parts; - delim2 = arg.find ('/', delim1 + 1); - if (delim2 == std::string::npos) - return parts; - parts.emplace_back (arg.substr (0, delim1)); - parts.emplace_back (arg.substr (delim1 + 1, delim2 - delim1 - 1)); - parts.emplace_back (arg.substr (delim2 + 1)); - + std::vector<Glib::ustring> parts; + std::size_t delim1 = 0; + std::size_t delim2 = 0; + delim1 = arg.find('/', 0); + if (delim1 == std::string::npos) return parts; + delim2 = arg.find('/', delim1 + 1); + if (delim2 == std::string::npos) + return parts; + parts.emplace_back(arg.substr(0, delim1)); + parts.emplace_back(arg.substr(delim1 + 1, delim2 - delim1 - 1)); + parts.emplace_back(arg.substr(delim2 + 1)); + + return parts; } static void -lookup_one_sync (const Glib::ustring& arg) +lookup_one_sync(const Glib::ustring& arg) { - if (arg.find ('/') != std::string::npos) + if (arg.find('/') != std::string::npos) + { + /* service/protocol/domain */ + const auto parts = split_service_parts(arg); + if (parts.size() != 3) { - /* service/protocol/domain */ - const auto parts = split_service_parts (arg); - if (parts.size () != 3) { - usage (); - return; - } - - try - { - const auto targets = resolver->lookup_service (parts[0], parts[1], parts[2], - cancellable); - print_resolved_service (arg, targets); - } - catch (const Gio::ResolverError& err) - { - std::cerr << err.what () << std::endl; - } + usage(); + return; } - else if (Gio::hostname_is_ip_address (arg)) + + try { - auto addr = Gio::InetAddress::create (arg); - try - { - Glib::ustring name = resolver->lookup_by_address (addr, cancellable); - print_resolved_name (arg, name); - } - catch (const Gio::ResolverError& err) - { - std::cerr << err.what () << std::endl; - } + const auto targets = resolver->lookup_service(parts[0], parts[1], parts[2], cancellable); + print_resolved_service(arg, targets); } - else + catch (const Gio::ResolverError& err) + { + std::cerr << err.what() << std::endl; + } + } + else if (Gio::hostname_is_ip_address(arg)) + { + auto addr = Gio::InetAddress::create(arg); + try { - std::list<Glib::RefPtr<Gio::InetAddress> > addresses; - - try - { - addresses = resolver->lookup_by_name (arg, cancellable); - print_resolved_addresses (arg, addresses); - } - catch (const Gio::ResolverError& err) - { - std::cerr << err.what () << std::endl; - } + Glib::ustring name = resolver->lookup_by_address(addr, cancellable); + print_resolved_name(arg, name); } + catch (const Gio::ResolverError& err) + { + std::cerr << err.what() << std::endl; + } + } + else + { + std::list<Glib::RefPtr<Gio::InetAddress>> addresses; + + try + { + addresses = resolver->lookup_by_name(arg, cancellable); + print_resolved_addresses(arg, addresses); + } + catch (const Gio::ResolverError& err) + { + std::cerr << err.what() << std::endl; + } + } } static void -lookup_thread (const Glib::ustring& arg) +lookup_thread(const Glib::ustring& arg) { - lookup_one_sync (arg); + lookup_one_sync(arg); } static std::vector<std::thread*> -start_threaded_lookups (char **argv, int argc) +start_threaded_lookups(char** argv, int argc) { std::vector<std::thread*> result; for (auto i = 0; i < argc; i++) @@ -217,313 +209,294 @@ start_threaded_lookups (char **argv, int argc) } static void -lookup_by_addr_callback (Glib::RefPtr<Gio::AsyncResult> result, - const Glib::ustring& phys) +lookup_by_addr_callback(Glib::RefPtr<Gio::AsyncResult> result, const Glib::ustring& phys) { - try - { - print_resolved_name (phys, resolver->lookup_by_address_finish (result)); - } - catch (const Gio::ResolverError& err) - { - std::cerr << err.what () << std::endl; - done_lookup (); - } + try + { + print_resolved_name(phys, resolver->lookup_by_address_finish(result)); + } + catch (const Gio::ResolverError& err) + { + std::cerr << err.what() << std::endl; + done_lookup(); + } } static void -lookup_by_name_callback (Glib::RefPtr<Gio::AsyncResult> result, - const Glib::ustring& name) +lookup_by_name_callback(Glib::RefPtr<Gio::AsyncResult> result, const Glib::ustring& name) { - try - { - print_resolved_addresses (name, resolver->lookup_by_name_finish (result)); - } - catch (const Gio::ResolverError& err) - { - std::cerr << err.what () << std::endl; - } + try + { + print_resolved_addresses(name, resolver->lookup_by_name_finish(result)); + } + catch (const Gio::ResolverError& err) + { + std::cerr << err.what() << std::endl; + } } static void -lookup_service_callback (Glib::RefPtr<Gio::AsyncResult> result, - const Glib::ustring& service) +lookup_service_callback(Glib::RefPtr<Gio::AsyncResult> result, const Glib::ustring& service) { try { - print_resolved_service (service, - resolver->lookup_service_finish (result)); + print_resolved_service(service, resolver->lookup_service_finish(result)); } catch (const Gio::ResolverError& err) { - std::cerr << err.what () << std::endl; + std::cerr << err.what() << std::endl; } } static void -start_async_lookups (char **argv, int argc) +start_async_lookups(char** argv, int argc) { - for (auto i = 0; i < argc; i++) + for (auto i = 0; i < argc; i++) + { + Glib::ustring arg(argv[i]); + if (arg.find('/') != std::string::npos) { - Glib::ustring arg (argv[i]); - if (arg.find ('/') != std::string::npos) - { - /* service/protocol/domain */ - auto parts = split_service_parts (arg); - if (parts.size () != 3) { - usage (); - return; - } - - resolver->lookup_service_async (parts[0], parts[1], parts[2], - sigc::bind (sigc::ptr_fun - (lookup_service_callback), - Glib::ustring (argv[i])), - cancellable - ); - } - else if (Gio::hostname_is_ip_address (argv[i])) - { - auto addr = Gio::InetAddress::create (argv[i]); - - resolver->lookup_by_address_async (addr, - sigc::bind (sigc::ptr_fun - (lookup_by_addr_callback), - argv[i]), - cancellable); - } - else - { - resolver->lookup_by_name_async (argv[i], - sigc::bind (sigc::ptr_fun - (lookup_by_name_callback), - argv[i]), - cancellable); - } - - /* Stress-test the reloading code */ - //g_signal_emit_by_name (resolver, "reload"); - } -} - -static void -print_connectable_sockaddr (Glib::RefPtr<Gio::SocketAddress> sockaddr) -{ - Glib::ustring phys; - auto isa = - Glib::RefPtr<Gio::InetSocketAddress>::cast_dynamic (sockaddr); + /* service/protocol/domain */ + auto parts = split_service_parts(arg); + if (parts.size() != 3) + { + usage(); + return; + } - if (!isa) + resolver->lookup_service_async(parts[0], parts[1], parts[2], + sigc::bind(sigc::ptr_fun(lookup_service_callback), Glib::ustring(argv[i])), cancellable); + } + else if (Gio::hostname_is_ip_address(argv[i])) { - std::cerr << - Glib::ustring::compose ("Error: Unexpected sockaddr type '%1'\n", - g_type_name_from_instance ((GTypeInstance *)sockaddr->gobj ())); + auto addr = Gio::InetAddress::create(argv[i]); + + resolver->lookup_by_address_async( + addr, sigc::bind(sigc::ptr_fun(lookup_by_addr_callback), argv[i]), cancellable); } else { - phys = isa->get_address ()->to_string (); - std::cout << Glib::ustring::compose ("Address: %1%2%3:%4\n", - phys.find (':') != std::string::npos ? "[" : "", - phys, - phys.find (':') != std::string::npos ? "]" : "", - isa->get_port ()); + resolver->lookup_by_name_async( + argv[i], sigc::bind(sigc::ptr_fun(lookup_by_name_callback), argv[i]), cancellable); } + + /* Stress-test the reloading code */ + // g_signal_emit_by_name (resolver, "reload"); + } +} + +static void +print_connectable_sockaddr(Glib::RefPtr<Gio::SocketAddress> sockaddr) +{ + Glib::ustring phys; + auto isa = Glib::RefPtr<Gio::InetSocketAddress>::cast_dynamic(sockaddr); + + if (!isa) + { + std::cerr << Glib::ustring::compose("Error: Unexpected sockaddr type '%1'\n", + g_type_name_from_instance((GTypeInstance*)sockaddr->gobj())); + } + else + { + phys = isa->get_address()->to_string(); + std::cout << Glib::ustring::compose("Address: %1%2%3:%4\n", + phys.find(':') != std::string::npos ? "[" : "", phys, + phys.find(':') != std::string::npos ? "]" : "", isa->get_port()); + } } static void -do_sync_connectable (Glib::RefPtr<Gio::SocketAddressEnumerator> enumerator) +do_sync_connectable(Glib::RefPtr<Gio::SocketAddressEnumerator> enumerator) { - Glib::RefPtr<Gio::SocketAddress> sockaddr; + Glib::RefPtr<Gio::SocketAddress> sockaddr; - while ((sockaddr = enumerator->next (cancellable))) - print_connectable_sockaddr (sockaddr); + while ((sockaddr = enumerator->next(cancellable))) + print_connectable_sockaddr(sockaddr); - done_lookup (); + done_lookup(); } -static void do_async_connectable (Glib::RefPtr<Gio::SocketAddressEnumerator> enumerator); +static void do_async_connectable(Glib::RefPtr<Gio::SocketAddressEnumerator> enumerator); static void -got_next_async (Glib::RefPtr<Gio::AsyncResult> result, - Glib::RefPtr<Gio::SocketAddressEnumerator> enumerator) +got_next_async( + Glib::RefPtr<Gio::AsyncResult> result, Glib::RefPtr<Gio::SocketAddressEnumerator> enumerator) { - try + try + { + const auto sockaddr = enumerator->next_finish(result); + if (sockaddr) { - const auto sockaddr = enumerator->next_finish (result); - if (sockaddr) - { - print_connectable_sockaddr (sockaddr); - do_async_connectable (enumerator); - } - else - { - done_lookup (); - } + print_connectable_sockaddr(sockaddr); + do_async_connectable(enumerator); } - catch (const Gio::ResolverError& err) + else { - std::cerr << err.what () << std::endl; + done_lookup(); } + } + catch (const Gio::ResolverError& err) + { + std::cerr << err.what() << std::endl; + } } Glib::RefPtr<Gio::SocketAddressEnumerator> global_enumerator; static void -do_async_connectable (Glib::RefPtr<Gio::SocketAddressEnumerator> enumerator) +do_async_connectable(Glib::RefPtr<Gio::SocketAddressEnumerator> enumerator) { - enumerator->next_async (cancellable, - sigc::bind (sigc::ptr_fun (got_next_async), - enumerator)); + enumerator->next_async(cancellable, sigc::bind(sigc::ptr_fun(got_next_async), enumerator)); } Glib::RefPtr<Gio::SocketConnectable> global_connectable; static void -do_connectable (const std::string& arg, gboolean synchronous) +do_connectable(const std::string& arg, gboolean synchronous) { - std::vector<Glib::ustring> parts; - Glib::RefPtr<Gio::SocketConnectable> connectable; + std::vector<Glib::ustring> parts; + Glib::RefPtr<Gio::SocketConnectable> connectable; - if (arg.find ('/') != std::string::npos) + if (arg.find('/') != std::string::npos) + { + /* service/protocol/domain */ + parts = split_service_parts(arg); + if (parts.size() != 3) { - /* service/protocol/domain */ - parts = split_service_parts (arg); - if (parts.size () != 3) { - usage (); - return; - } - - connectable = Gio::NetworkService::create (parts[0], parts[1], parts[2]); + usage(); + return; } - else + + connectable = Gio::NetworkService::create(parts[0], parts[1], parts[2]); + } + else + { + std::string host, port_str; + guint16 port; + + const auto pos = arg.find(':'); + if (pos != std::string::npos) { - std::string host, port_str; - guint16 port; - - const auto pos = arg.find (':'); - if (pos != std::string::npos) - { - host = arg.substr (0, pos); - port_str = arg.substr(pos); - port = std::stoul (port_str); - } - else - port = 0; - - if (Gio::hostname_is_ip_address (host)) - { - const auto addr = Gio::InetAddress::create (host); - connectable = Gio::InetSocketAddress::create (addr, port); - } - else - connectable = Gio::NetworkAddress::create (arg, port); + host = arg.substr(0, pos); + port_str = arg.substr(pos); + port = std::stoul(port_str); } + else + port = 0; - const auto enumerator = connectable->enumerate (); - if (synchronous) - do_sync_connectable (enumerator); + if (Gio::hostname_is_ip_address(host)) + { + const auto addr = Gio::InetAddress::create(host); + connectable = Gio::InetSocketAddress::create(addr, port); + } else - do_async_connectable (enumerator); + connectable = Gio::NetworkAddress::create(arg, port); + } + + const auto enumerator = connectable->enumerate(); + if (synchronous) + do_sync_connectable(enumerator); + else + do_async_connectable(enumerator); } #ifdef G_OS_UNIX static volatile int cancel_fd; static void -interrupted (int /*sig*/) +interrupted(int /*sig*/) { const int save_errno = errno; while (write(cancel_fd, "", 1) < 0 && errno == EINTR) - {} + { + } errno = save_errno; } static bool -async_cancel (Glib::IOCondition /*cond*/, Glib::RefPtr<Gio::Cancellable> the_cancellable) +async_cancel(Glib::IOCondition /*cond*/, Glib::RefPtr<Gio::Cancellable> the_cancellable) { - the_cancellable->cancel (); - return false; + the_cancellable->cancel(); + return false; } #endif int -main (int argc, char **argv) +main(int argc, char** argv) { - auto synchronous = false; - auto use_connectable = false; + auto synchronous = false; + auto use_connectable = false; #ifdef G_OS_UNIX - Glib::RefPtr<Glib::IOChannel> chan; - sigc::connection watch_conn; + Glib::RefPtr<Glib::IOChannel> chan; + sigc::connection watch_conn; #endif - // TODO: Use Glib::OptionContext. - while (argc >= 2 && argv[1][0] == '-') - { - if (!strcmp (argv[1], "-s")) - synchronous = true; - else if (!strcmp (argv[1], "-c")) - use_connectable = true; - else - usage (); - - argv++; - argc--; - } + // TODO: Use Glib::OptionContext. + while (argc >= 2 && argv[1][0] == '-') + { + if (!strcmp(argv[1], "-s")) + synchronous = true; + else if (!strcmp(argv[1], "-c")) + use_connectable = true; + else + usage(); + + argv++; + argc--; + } - Gio::init (); + Gio::init(); - if (argc < 2 || (argc > 2 && use_connectable)) - usage (); + if (argc < 2 || (argc > 2 && use_connectable)) + usage(); - resolver = Gio::Resolver::get_default (); + resolver = Gio::Resolver::get_default(); - cancellable = Gio::Cancellable::create (); + cancellable = Gio::Cancellable::create(); #ifdef G_OS_UNIX - /* Set up cancellation; we want to cancel if the user ^C's the - * program, but we can't cancel directly from an interrupt. - */ - int cancel_fds[2]; + /* Set up cancellation; we want to cancel if the user ^C's the + * program, but we can't cancel directly from an interrupt. + */ + int cancel_fds[2]; - if (pipe (cancel_fds) < 0) - { - perror ("pipe"); - exit (1); - } - cancel_fd = cancel_fds[1]; - signal (SIGINT, interrupted); + if (pipe(cancel_fds) < 0) + { + perror("pipe"); + exit(1); + } + cancel_fd = cancel_fds[1]; + signal(SIGINT, interrupted); - chan = Glib::IOChannel::create_from_fd (cancel_fds[0]); - const auto source = chan->create_watch (Glib::IO_IN); - watch_conn = source->connect (sigc::bind (sigc::ptr_fun (async_cancel), cancellable)); + chan = Glib::IOChannel::create_from_fd(cancel_fds[0]); + const auto source = chan->create_watch(Glib::IO_IN); + watch_conn = source->connect(sigc::bind(sigc::ptr_fun(async_cancel), cancellable)); #endif - nlookups = argc - 1; - loop = Glib::MainLoop::create (true); + nlookups = argc - 1; + loop = Glib::MainLoop::create(true); - std::vector<std::thread*> threads; - if (use_connectable) - do_connectable (argv[1], synchronous); + std::vector<std::thread*> threads; + if (use_connectable) + do_connectable(argv[1], synchronous); + else + { + if (synchronous) + threads = start_threaded_lookups(argv + 1, argc - 1); else - { - if (synchronous) - threads = start_threaded_lookups (argv + 1, argc - 1); - else - start_async_lookups (argv + 1, argc - 1); - } + start_async_lookups(argv + 1, argc - 1); + } - loop->run (); + loop->run(); - //Join and delete each thread: - std::for_each(threads.begin(), threads.end(), - [] (std::thread* thread) - { - thread->join(); - delete thread; - }); + // Join and delete each thread: + std::for_each(threads.begin(), threads.end(), [](std::thread* thread) { + thread->join(); + delete thread; + }); #ifdef G_OS_UNIX - watch_conn.disconnect (); + watch_conn.disconnect(); #endif - return 0; + return 0; } diff --git a/examples/network/socket-client.cc b/examples/network/socket-client.cc index 3fdb30d5..c364d9b2 100644 --- a/examples/network/socket-client.cc +++ b/examples/network/socket-client.cc @@ -1,12 +1,12 @@ +#include <chrono> +#include <condition_variable> #include <cstring> #include <giomm.h> #include <glibmm.h> -#include <thread> -#include <mutex> -#include <condition_variable> -#include <chrono> -#include <memory> #include <iostream> +#include <memory> +#include <mutex> +#include <thread> namespace { @@ -26,8 +26,7 @@ std::condition_variable cond_thread; class ClientOptionGroup : public Glib::OptionGroup { public: - ClientOptionGroup() - : Glib::OptionGroup("client_group", "", "") + ClientOptionGroup() : Glib::OptionGroup("client_group", "", "") { Glib::OptionEntry entry; entry.set_long_name("cancel"); @@ -60,68 +59,65 @@ public: entry.set_description("Use IPv6 address family"); add_entry(entry, use_ipv6); } -}; +}; Glib::ustring -socket_address_to_string (const Glib::RefPtr<Gio::SocketAddress>& address) +socket_address_to_string(const Glib::RefPtr<Gio::SocketAddress>& address) { - Glib::RefPtr<Gio::InetAddress> inet_address; - Glib::ustring str, res; - int port; - - auto isockaddr = - Glib::RefPtr<Gio::InetSocketAddress>::cast_dynamic (address); - if (!isockaddr) - return Glib::ustring (); - inet_address = isockaddr->get_address (); - str = inet_address->to_string (); - port = isockaddr->get_port (); - res = Glib::ustring::compose ("%1:%2", str, port); - return res; + Glib::RefPtr<Gio::InetAddress> inet_address; + Glib::ustring str, res; + int port; + + auto isockaddr = Glib::RefPtr<Gio::InetSocketAddress>::cast_dynamic(address); + if (!isockaddr) + return Glib::ustring(); + inet_address = isockaddr->get_address(); + str = inet_address->to_string(); + port = isockaddr->get_port(); + res = Glib::ustring::compose("%1:%2", str, port); + return res; } -static bool -source_ready(Glib::IOCondition /*condition*/) +static bool source_ready(Glib::IOCondition /*condition*/) { - loop->quit (); + loop->quit(); return false; } static void -ensure_condition (const Glib::RefPtr<Gio::Socket>& socket, - const Glib::ustring& where, - const Glib::RefPtr<Gio::Cancellable>& cancellable, - Glib::IOCondition condition) +ensure_condition(const Glib::RefPtr<Gio::Socket>& socket, const Glib::ustring& where, + const Glib::RefPtr<Gio::Cancellable>& cancellable, Glib::IOCondition condition) { - if (!non_blocking) - return; + if (!non_blocking) + return; - if (use_source) + if (use_source) + { + auto source = socket->create_source(condition, cancellable); + source->connect(sigc::ptr_fun(&source_ready)); + source->attach(); + loop->run(); + } + else + { + try { - auto source = socket->create_source(condition, cancellable); - source->connect(sigc::ptr_fun(&source_ready)); - source->attach(); - loop->run(); + socket->condition_wait(condition, cancellable); } - else + catch (const Gio::Error& error) { - try { - socket->condition_wait (condition, cancellable); - } catch (const Gio::Error& error) - { - std::cerr << Glib::ustring::compose("condition wait error for %1: %2\n", - where, error.what ()); - exit (1); - } + std::cerr << Glib::ustring::compose("condition wait error for %1: %2\n", where, error.what()); + exit(1); } + } } static void -cancel_thread (Glib::RefPtr<Gio::Cancellable> cancellable) +cancel_thread(Glib::RefPtr<Gio::Cancellable> cancellable) { std::unique_lock<std::mutex> lock(mutex_thread); - if (!cond_thread.wait_for(lock, std::chrono::seconds(cancel_timeout), - [](){ return stop_thread; })) + if (!cond_thread.wait_for( + lock, std::chrono::seconds(cancel_timeout), []() { return stop_thread; })) { // !stop_thread, i.e. timeout std::cout << "Cancelling\n"; @@ -144,207 +140,211 @@ public: } // end anonymous namespace int -main (int argc, - char *argv[]) +main(int argc, char* argv[]) { - Glib::RefPtr<Gio::Socket> socket; - Glib::RefPtr<Gio::SocketAddress> src_address; - Glib::RefPtr<Gio::SocketAddress> address; - Gio::SocketType socket_type; - Gio::SocketFamily socket_family; - Glib::RefPtr<Gio::Cancellable> cancellable; - Glib::RefPtr<Gio::SocketAddressEnumerator> enumerator; - Glib::RefPtr<Gio::SocketConnectable> connectable; - - Gio::init (); - - Glib::OptionContext option_context(" <hostname>[:port] - Test Gio::Socket client stuff"); - option_context.set_summary("Default port: 7777\n" - "For a local test with socket-server:\n" - " ./socket-client [option...] localhost\n" - "or, if that fails\n" - " ./socket-client [option...] 127.0.0.1 (IPv4)\n" - " ./socket-client [option...] ::1 (IPv6)"); - ClientOptionGroup option_group; - option_context.set_main_group(option_group); + Glib::RefPtr<Gio::Socket> socket; + Glib::RefPtr<Gio::SocketAddress> src_address; + Glib::RefPtr<Gio::SocketAddress> address; + Gio::SocketType socket_type; + Gio::SocketFamily socket_family; + Glib::RefPtr<Gio::Cancellable> cancellable; + Glib::RefPtr<Gio::SocketAddressEnumerator> enumerator; + Glib::RefPtr<Gio::SocketConnectable> connectable; + + Gio::init(); + + Glib::OptionContext option_context(" <hostname>[:port] - Test Gio::Socket client stuff"); + option_context.set_summary("Default port: 7777\n" + "For a local test with socket-server:\n" + " ./socket-client [option...] localhost\n" + "or, if that fails\n" + " ./socket-client [option...] 127.0.0.1 (IPv4)\n" + " ./socket-client [option...] ::1 (IPv6)"); + ClientOptionGroup option_group; + option_context.set_main_group(option_group); + try + { + option_context.parse(argc, argv); + } + catch (const Glib::Error& error) + { + std::cerr << Glib::ustring::compose("%1: %2\n", argv[0], error.what()); + return 1; + } + + if (argc != 2) + { + const auto error_message = "Need to specify hostname"; + std::cerr << Glib::ustring::compose("%1: %2\n", argv[0], error_message); + return 1; + } + + std::unique_ptr<std::thread, JoinAndDelete> thread; + if (cancel_timeout) + { + cancellable = Gio::Cancellable::create(); + thread.reset(new std::thread(&cancel_thread, cancellable)); + } + + loop = Glib::MainLoop::create(); + + socket_type = use_udp ? Gio::SOCKET_TYPE_DATAGRAM : Gio::SOCKET_TYPE_STREAM; + socket_family = use_ipv6 ? Gio::SOCKET_FAMILY_IPV6 : Gio::SOCKET_FAMILY_IPV4; + + try + { + socket = Gio::Socket::create(socket_family, socket_type, Gio::SOCKET_PROTOCOL_DEFAULT); + } + catch (const Gio::Error& error) + { + std::cerr << Glib::ustring::compose("%1: %2\n", argv[0], error.what()); + return 1; + } + + try + { + connectable = Gio::NetworkAddress::parse(argv[1], 7777); + } + catch (const Gio::Error& error) + { + std::cerr << Glib::ustring::compose("%1: %2\n", argv[0], error.what()); + return 1; + } + + enumerator = connectable->enumerate(); + while (true) + { try { - option_context.parse(argc, argv); + address = enumerator->next(cancellable); + if (!address) + { + std::cerr << Glib::ustring::compose("%1: No more addresses to try\n", argv[0]); + return 1; + } } - catch (const Glib::Error& error) + catch (const Gio::Error& error) { - std::cerr << Glib::ustring::compose ("%1: %2\n", argv[0], error.what()); + std::cerr << Glib::ustring::compose("%1: %2\n", argv[0], error.what()); return 1; } - if (argc != 2) + try { - const auto error_message = "Need to specify hostname"; - std::cerr << Glib::ustring::compose ("%1: %2\n", argv[0], error_message); - return 1; + socket->connect(address, cancellable); + break; } - - std::unique_ptr<std::thread, JoinAndDelete> thread; - if (cancel_timeout) + catch (const Gio::Error& error) { - cancellable = Gio::Cancellable::create (); - thread.reset(new std::thread(&cancel_thread, cancellable)); + std::cerr << Glib::ustring::compose("%1: Connection to %2 failed: %3, trying next\n", argv[0], + socket_address_to_string(address), error.what()); } + } - loop = Glib::MainLoop::create (); + std::cout << Glib::ustring::compose("Connected to %1\n", socket_address_to_string(address)); - socket_type = use_udp ? Gio::SOCKET_TYPE_DATAGRAM : Gio::SOCKET_TYPE_STREAM; - socket_family = use_ipv6 ? Gio::SOCKET_FAMILY_IPV6 : Gio::SOCKET_FAMILY_IPV4; + /* TODO: Test non-blocking connect */ + if (non_blocking) + socket->set_blocking(false); - try { - socket = Gio::Socket::create (socket_family, socket_type, Gio::SOCKET_PROTOCOL_DEFAULT); - } catch (const Gio::Error& error) - { - std::cerr << Glib::ustring::compose ("%1: %2\n", argv[0], error.what ()); - return 1; - } + try + { + src_address = socket->get_local_address(); + } + catch (const Gio::Error& error) + { + std::cerr << Glib::ustring::compose("Error getting local address: %1\n", error.what()); + return 1; + } + std::cout << Glib::ustring::compose("local address: %1\n", socket_address_to_string(src_address)); - try { - connectable = Gio::NetworkAddress::parse (argv[1], 7777); - } catch (const Gio::Error& error) - { - std::cerr << Glib::ustring::compose ("%1: %2\n", argv[0], error.what ()); - return 1; - } + while (true) + { + gchar buffer[4096] = {}; + gssize size; + gsize to_send; + + if (!std::cin.getline(buffer, sizeof buffer - 1)) + break; - enumerator = connectable->enumerate (); - while (true) + to_send = strlen(buffer); + buffer[to_send++] = '\n'; + buffer[to_send] = '\0'; + while (to_send > 0) { - try { - address = enumerator->next (cancellable); - if (!address) { - std::cerr << Glib::ustring::compose ("%1: No more addresses to try\n", argv[0]); - return 1; - } - } catch (const Gio::Error& error) + ensure_condition(socket, "send", cancellable, Glib::IO_OUT); + try + { + if (use_udp) + size = socket->send_to(address, buffer, to_send, cancellable); + else + size = socket->send(buffer, to_send, cancellable); + } + catch (const Gio::Error& error) + { + if (error.code() == Gio::Error::WOULD_BLOCK) { - std::cerr << Glib::ustring::compose ("%1: %2\n", argv[0], error.what ()); - return 1; + std::cout << "socket send would block, handling\n"; + continue; } - - try { - socket->connect (address, cancellable); - break; - } catch (const Gio::Error& error) + else { - std::cerr << Glib::ustring::compose ("%1: Connection to %2 failed: %3, trying next\n", - argv[0], socket_address_to_string (address), - error.what ()); + std::cerr << Glib::ustring::compose("Error sending to socket: %1\n", error.what()); + return 1; } - } + } - std::cout << Glib::ustring::compose ("Connected to %1\n", - socket_address_to_string (address)); + std::cout << Glib::ustring::compose("sent %1 bytes of data\n", size); - /* TODO: Test non-blocking connect */ - if (non_blocking) - socket->set_blocking (false); - - try { - src_address = socket->get_local_address (); - } catch (const Gio::Error& error) - { - std::cerr << Glib::ustring::compose ("Error getting local address: %1\n", - error.what ()); + if (size == 0) + { + std::cerr << "Unexpected short write\n"; return 1; + } + + to_send -= size; } - std::cout << Glib::ustring::compose ("local address: %1\n", - socket_address_to_string (src_address)); - while (true) + ensure_condition(socket, "receive", cancellable, Glib::IO_IN); + try { - gchar buffer[4096] = { }; - gssize size; - gsize to_send; - - if (!std::cin.getline (buffer, sizeof buffer - 1)) - break; - - to_send = strlen (buffer); - buffer[to_send++] = '\n'; - buffer[to_send] = '\0'; - while (to_send > 0) - { - ensure_condition (socket, "send", cancellable, Glib::IO_OUT); - try { - if (use_udp) - size = socket->send_to (address, buffer, to_send, - cancellable); - else - size = socket->send (buffer, to_send, cancellable); - - } catch (const Gio::Error& error) - { - if (error.code () == Gio::Error::WOULD_BLOCK) - { - std::cout << "socket send would block, handling\n"; - continue; - } - else - { - std::cerr << Glib::ustring::compose ("Error sending to socket: %1\n", - error.what ()); - return 1; - } - } - - std::cout << Glib::ustring::compose ("sent %1 bytes of data\n", size); - - if (size == 0) - { - std::cerr << "Unexpected short write\n"; - return 1; - } - - to_send -= size; - } - - ensure_condition (socket, "receive", cancellable, Glib::IO_IN); - try { - if (use_udp) - size = socket->receive_from (src_address, buffer, sizeof buffer, - cancellable); - else - size = socket->receive (buffer, sizeof buffer, cancellable); - - } catch (const Gio::Error& error) - { - std::cerr << Glib::ustring::compose ("Error receiving from socket: %1\n", - error.what ()); - return 1; - } - - if (size == 0) - break; + if (use_udp) + size = socket->receive_from(src_address, buffer, sizeof buffer, cancellable); + else + size = socket->receive(buffer, sizeof buffer, cancellable); + } + catch (const Gio::Error& error) + { + std::cerr << Glib::ustring::compose("Error receiving from socket: %1\n", error.what()); + return 1; + } - std::cout << Glib::ustring::compose ("received %1 bytes of data", size); - if (use_udp) - std::cout << Glib::ustring::compose (" from %1", socket_address_to_string (src_address)); - std::cout << std::endl; + if (size == 0) + break; - if (verbose) - g_print ("-------------------------\n" - "%.*s" - "-------------------------\n", - (int)size, buffer); + std::cout << Glib::ustring::compose("received %1 bytes of data", size); + if (use_udp) + std::cout << Glib::ustring::compose(" from %1", socket_address_to_string(src_address)); + std::cout << std::endl; - } + if (verbose) + g_print("-------------------------\n" + "%.*s" + "-------------------------\n", + (int)size, buffer); + } - std::cout << "closing socket\n"; + std::cout << "closing socket\n"; - try { - socket->close (); - } catch (const Gio::Error& error) - { - std::cerr << Glib::ustring::compose ("Error closing master socket: %1\n", - error.what ()); - return 1; - } + try + { + socket->close(); + } + catch (const Gio::Error& error) + { + std::cerr << Glib::ustring::compose("Error closing master socket: %1\n", error.what()); + return 1; + } - return 0; + return 0; } diff --git a/examples/network/socket-server.cc b/examples/network/socket-server.cc index 835a6b73..fb9d6eaa 100644 --- a/examples/network/socket-server.cc +++ b/examples/network/socket-server.cc @@ -1,11 +1,11 @@ +#include <chrono> +#include <condition_variable> #include <giomm.h> #include <glibmm.h> -#include <thread> -#include <mutex> -#include <condition_variable> -#include <chrono> -#include <memory> #include <iostream> +#include <memory> +#include <mutex> +#include <thread> namespace { @@ -27,8 +27,7 @@ std::condition_variable cond_thread; class ServerOptionGroup : public Glib::OptionGroup { public: - ServerOptionGroup() - : Glib::OptionGroup("server_group", "", "") + ServerOptionGroup() : Glib::OptionGroup("server_group", "", "") { Glib::OptionEntry entry; entry.set_long_name("port"); @@ -71,63 +70,60 @@ public: entry.set_description("Use IPv6 address family"); add_entry(entry, use_ipv6); } -}; +}; Glib::ustring -socket_address_to_string (const Glib::RefPtr<Gio::SocketAddress>& address) +socket_address_to_string(const Glib::RefPtr<Gio::SocketAddress>& address) { - auto isockaddr = - Glib::RefPtr<Gio::InetSocketAddress>::cast_dynamic (address); + auto isockaddr = Glib::RefPtr<Gio::InetSocketAddress>::cast_dynamic(address); if (!isockaddr) - return Glib::ustring (); + return Glib::ustring(); - auto inet_address = isockaddr->get_address (); - auto str = inet_address->to_string (); - auto the_port = isockaddr->get_port (); - auto res = Glib::ustring::compose ("%1:%2", str, the_port); + auto inet_address = isockaddr->get_address(); + auto str = inet_address->to_string(); + auto the_port = isockaddr->get_port(); + auto res = Glib::ustring::compose("%1:%2", str, the_port); return res; } -static bool -source_ready(Glib::IOCondition /*condition*/) +static bool source_ready(Glib::IOCondition /*condition*/) { - loop->quit (); + loop->quit(); return false; } static void -ensure_condition (const Glib::RefPtr<Gio::Socket>& socket, - const Glib::ustring& where, - const Glib::RefPtr<Gio::Cancellable>& cancellable, - Glib::IOCondition condition) +ensure_condition(const Glib::RefPtr<Gio::Socket>& socket, const Glib::ustring& where, + const Glib::RefPtr<Gio::Cancellable>& cancellable, Glib::IOCondition condition) { - if (!non_blocking) - return; + if (!non_blocking) + return; - if (use_source) + if (use_source) + { + Gio::signal_socket().connect(sigc::ptr_fun(&source_ready), socket, condition); + loop->run(); + } + else + { + try { - Gio::signal_socket().connect(sigc::ptr_fun(&source_ready), socket, condition); - loop->run(); + socket->condition_wait(condition, cancellable); } - else + catch (const Gio::Error& error) { - try { - socket->condition_wait (condition, cancellable); - } catch (const Gio::Error& error) - { - std::cerr << Glib::ustring::compose("condition wait error for %1: %2\n", - where, error.what ()); - exit (1); - } + std::cerr << Glib::ustring::compose("condition wait error for %1: %2\n", where, error.what()); + exit(1); } + } } static void -cancel_thread (Glib::RefPtr<Gio::Cancellable> cancellable) +cancel_thread(Glib::RefPtr<Gio::Cancellable> cancellable) { std::unique_lock<std::mutex> lock(mutex_thread); - if (!cond_thread.wait_for(lock, std::chrono::seconds(cancel_timeout), - [](){ return stop_thread; })) + if (!cond_thread.wait_for( + lock, std::chrono::seconds(cancel_timeout), []() { return stop_thread; })) { // !stop_thread, i.e. timeout std::cout << "Cancelling\n"; @@ -150,202 +146,207 @@ public: } // end anonymous namespace int -main (int argc, - char *argv[]) +main(int argc, char* argv[]) { - Glib::RefPtr<Gio::Socket> socket, new_socket, recv_socket; - Glib::RefPtr<Gio::SocketAddress> address; - Glib::RefPtr<Gio::Cancellable> cancellable; + Glib::RefPtr<Gio::Socket> socket, new_socket, recv_socket; + Glib::RefPtr<Gio::SocketAddress> address; + Glib::RefPtr<Gio::Cancellable> cancellable; + + Gio::init(); + + Glib::OptionContext option_context(" - Test Gio::Socket server stuff"); + ServerOptionGroup option_group; + option_context.set_main_group(option_group); + try + { + option_context.parse(argc, argv); + } + catch (const Glib::Error& error) + { + std::cerr << Glib::ustring::compose("%1: %2\n", argv[0], error.what()); + return 1; + } - Gio::init (); + std::unique_ptr<std::thread, JoinAndDelete> thread; + if (cancel_timeout) + { + cancellable = Gio::Cancellable::create(); + thread.reset(new std::thread(&cancel_thread, cancellable)); + } + + loop = Glib::MainLoop::create(); + + auto socket_type = use_udp ? Gio::SOCKET_TYPE_DATAGRAM : Gio::SOCKET_TYPE_STREAM; + auto socket_family = use_ipv6 ? Gio::SOCKET_FAMILY_IPV6 : Gio::SOCKET_FAMILY_IPV4; + + try + { + socket = Gio::Socket::create(socket_family, socket_type, Gio::SOCKET_PROTOCOL_DEFAULT); + } + catch (const Gio::Error& error) + { + std::cerr << Glib::ustring::compose("%1: %2\n", argv[0], error.what()); + return 1; + } + + if (non_blocking) + socket->set_blocking(false); + + auto src_address = + Gio::InetSocketAddress::create(Gio::InetAddress::create_any(socket_family), port); + try + { + socket->bind(src_address, !dont_reuse_address); + } + catch (const Gio::Error& error) + { + std::cerr << Glib::ustring::compose("Can't bind socket: %1\n", error.what()); + return 1; + } - Glib::OptionContext option_context(" - Test Gio::Socket server stuff"); - ServerOptionGroup option_group; - option_context.set_main_group(option_group); + if (!use_udp) + { try { - option_context.parse(argc, argv); + socket->listen(); } - catch (const Glib::Error& error) + catch (const Gio::Error& error) { - std::cerr << Glib::ustring::compose ("%1: %2\n", argv[0], error.what()); + std::cerr << Glib::ustring::compose("Can't listen on socket: %1\n", error.what()); return 1; } - std::unique_ptr<std::thread, JoinAndDelete> thread; - if (cancel_timeout) + std::cout << Glib::ustring::compose("listening on port %1...\n", port); + + ensure_condition(socket, "accept", cancellable, Glib::IO_IN); + try { - cancellable = Gio::Cancellable::create (); - thread.reset(new std::thread(&cancel_thread, cancellable)); + new_socket = socket->accept(cancellable); } - - loop = Glib::MainLoop::create (); - - auto socket_type = use_udp ? Gio::SOCKET_TYPE_DATAGRAM : Gio::SOCKET_TYPE_STREAM; - auto socket_family = use_ipv6 ? Gio::SOCKET_FAMILY_IPV6 : Gio::SOCKET_FAMILY_IPV4; - - try { - socket = Gio::Socket::create (socket_family, socket_type, Gio::SOCKET_PROTOCOL_DEFAULT); - } catch (const Gio::Error& error) + catch (const Gio::Error& error) { - std::cerr << Glib::ustring::compose ("%1: %2\n", argv[0], error.what ()); - return 1; + std::cerr << Glib::ustring::compose("Error accepting socket: %1\n", error.what()); + return 1; } if (non_blocking) - socket->set_blocking (false); - - auto src_address = Gio::InetSocketAddress::create (Gio::InetAddress::create_any (socket_family), port); - try { - socket->bind (src_address, !dont_reuse_address); - } catch (const Gio::Error& error) { - std::cerr << Glib::ustring::compose ("Can't bind socket: %1\n", - error.what ()); - return 1; - } + new_socket->set_blocking(false); - if (!use_udp) + try { - try { - socket->listen (); - } catch (const Gio::Error& error) - { - std::cerr << Glib::ustring::compose ("Can't listen on socket: %1\n", - error.what ()); - return 1; - } - - std::cout << Glib::ustring::compose ("listening on port %1...\n", port); - - ensure_condition (socket, "accept", cancellable, Glib::IO_IN); - try { - new_socket = socket->accept (cancellable); - } catch (const Gio::Error& error) - { - std::cerr << Glib::ustring::compose ("Error accepting socket: %1\n", - error.what ()); - return 1; - } + address = new_socket->get_remote_address(); + } + catch (const Gio::Error& error) + { + std::cerr << Glib::ustring::compose("Error getting remote address: %1\n", error.what()); + return 1; + } - if (non_blocking) - new_socket->set_blocking (false); + std::cout << Glib::ustring::compose( + "got a new connection from %1\n", socket_address_to_string(address)); - try { - address = new_socket->get_remote_address (); - } catch (const Gio::Error& error) - { - std::cerr << Glib::ustring::compose ("Error getting remote address: %1\n", - error.what ()); - return 1; - } + recv_socket = new_socket; + } + else + { + recv_socket = socket; + } - std::cout << Glib::ustring::compose ("got a new connection from %1\n", - socket_address_to_string (address)); + while (true) + { + gchar buffer[4096] = {}; + gssize size; - recv_socket = new_socket; + ensure_condition(recv_socket, "receive", cancellable, Glib::IO_IN); + try + { + if (use_udp) + size = recv_socket->receive_from(address, buffer, sizeof buffer, cancellable); + else + size = recv_socket->receive(buffer, sizeof buffer, cancellable); } - else + catch (const Gio::Error& error) { - recv_socket = socket; + std::cerr << Glib::ustring::compose("Error receiving from socket: %1\n", error.what()); + return 1; } + if (size == 0) + break; - while (true) - { - gchar buffer[4096] = { }; - gssize size; - - ensure_condition (recv_socket, "receive", cancellable, Glib::IO_IN); - try { - if (use_udp) - size = recv_socket->receive_from (address, - buffer, sizeof buffer, - cancellable); - else - size = recv_socket->receive (buffer, sizeof buffer, - cancellable); - } catch (const Gio::Error& error) - { - std::cerr << Glib::ustring::compose ("Error receiving from socket: %1\n", - error.what ()); - return 1; - } + std::cout << Glib::ustring::compose("received %1 bytes of data", size); + if (use_udp) + std::cout << Glib::ustring::compose(" from %1", socket_address_to_string(address)); + std::cout << std::endl; - if (size == 0) - break; + if (verbose) + g_print("-------------------------\n" + "%.*s\n" + "-------------------------\n", + (int)size, buffer); - std::cout << Glib::ustring::compose ("received %1 bytes of data", size); + auto to_send = size; + + while (to_send > 0) + { + ensure_condition(recv_socket, "send", cancellable, Glib::IO_OUT); + try + { if (use_udp) - std::cout << Glib::ustring::compose (" from %1", socket_address_to_string (address)); - std::cout << std::endl; + size = recv_socket->send_to(address, buffer, to_send, cancellable); + else + size = recv_socket->send(buffer, to_send, cancellable); + } + catch (const Gio::Error& error) + { + if (error.code() == Gio::Error::WOULD_BLOCK) + { + std::cout << "socket send would block, handling\n"; + continue; + } + else + { + std::cerr << Glib::ustring::compose("Error sending to socket: %1\n", error.what()); + return 1; + } + } - if (verbose) - g_print ("-------------------------\n" - "%.*s\n" - "-------------------------\n", - (int)size, buffer); + std::cout << Glib::ustring::compose("sent %1 bytes of data\n", size); - auto to_send = size; + if (size == 0) + { + std::cerr << "Unexpected short write\n"; + return 1; + } - while (to_send > 0) - { - ensure_condition (recv_socket, "send", cancellable, Glib::IO_OUT); - try { - if (use_udp) - size = recv_socket->send_to (address, - buffer, to_send, cancellable); - else - size = recv_socket->send (buffer, to_send, - cancellable); - } catch (const Gio::Error& error) - { - if (error.code () == Gio::Error::WOULD_BLOCK) - { - std::cout << "socket send would block, handling\n"; - continue; - } - else - { - std::cerr << Glib::ustring::compose ("Error sending to socket: %1\n", - error.what ()); - return 1; - } - } - - std::cout << Glib::ustring::compose ("sent %1 bytes of data\n", size); - - if (size == 0) - { - std::cerr << "Unexpected short write\n"; - return 1; - } - - to_send -= size; - } + to_send -= size; } + } - std::cout << "connection closed\n"; + std::cout << "connection closed\n"; - if (new_socket) + if (new_socket) + { + try { - try { - new_socket->close (); - } catch (const Gio::Error& error) - { - std::cerr << Glib::ustring::compose ("Error closing connection socket: %1\n", - error.what ()); - return 1; - } + new_socket->close(); } - - try { - socket->close (); - } catch (const Gio::Error& error) + catch (const Gio::Error& error) { - std::cerr << Glib::ustring::compose ("Error closing master socket: %1\n", - error.what ()); - return 1; + std::cerr << Glib::ustring::compose("Error closing connection socket: %1\n", error.what()); + return 1; } + } + + try + { + socket->close(); + } + catch (const Gio::Error& error) + { + std::cerr << Glib::ustring::compose("Error closing master socket: %1\n", error.what()); + return 1; + } - return 0; + return 0; } diff --git a/examples/options/main.cc b/examples/options/main.cc index fcda4a98..45d92e98 100644 --- a/examples/options/main.cc +++ b/examples/options/main.cc @@ -19,9 +19,8 @@ #include <iomanip> #include <iostream> - class ExampleOptionGroup : public Glib::OptionGroup -{ +{ public: ExampleOptionGroup(); @@ -30,14 +29,14 @@ private: bool on_post_parse(Glib::OptionContext& context, Glib::OptionGroup& group) override; void on_error(Glib::OptionContext& context, Glib::OptionGroup& group) override; - bool on_option_arg_string(const Glib::ustring& option_name, - const Glib::ustring& value, bool has_value); - bool on_option_arg_filename(const Glib::ustring& option_name, - const std::string& value, bool has_value); + bool on_option_arg_string( + const Glib::ustring& option_name, const Glib::ustring& value, bool has_value); + bool on_option_arg_filename( + const Glib::ustring& option_name, const std::string& value, bool has_value); public: - //These members should live as long as the OptionGroup to which they are added, - //and as long as the OptionContext to which that OptionGroup is added. + // These members should live as long as the OptionGroup to which they are added, + // and as long as the OptionContext to which that OptionGroup is added. int m_arg_foo; std::string m_arg_filename; Glib::ustring m_arg_goo; @@ -49,33 +48,36 @@ public: }; ExampleOptionGroup::ExampleOptionGroup() -: Glib::OptionGroup("example_group", "description of example group", "help description of example group"), - m_arg_foo(0), m_arg_boolean(false) +: Glib::OptionGroup( + "example_group", "description of example group", "help description of example group"), + m_arg_foo(0), + m_arg_boolean(false) { Glib::OptionEntry entry1; entry1.set_long_name("foo"); entry1.set_short_name('f'); entry1.set_description("The Foo"); add_entry(entry1, m_arg_foo); - + Glib::OptionEntry entry2; entry2.set_long_name("file"); entry2.set_short_name('F'); entry2.set_description("The Filename"); add_entry_filename(entry2, m_arg_filename); - + Glib::OptionEntry entry3; entry3.set_long_name("goo"); entry3.set_short_name('g'); entry3.set_description("The Goo"); - m_arg_goo = "default-goo-value"; //We can choose a default to be used if the user doesn't specify this option. + m_arg_goo = "default-goo-value"; // We can choose a default to be used if the user doesn't specify + // this option. add_entry(entry3, m_arg_goo); - + Glib::OptionEntry entry4; entry4.set_long_name("activate_something"); entry4.set_description("Activate something"); add_entry(entry4, m_arg_boolean); - + Glib::OptionEntry entry5; entry5.set_long_name("list"); entry5.set_short_name('l'); @@ -104,82 +106,88 @@ ExampleOptionGroup::ExampleOptionGroup() add_entry(entry_remaining, m_remaining_list); } -bool ExampleOptionGroup::on_pre_parse(Glib::OptionContext& /* context */, Glib::OptionGroup& /* group */) +bool +ExampleOptionGroup::on_pre_parse(Glib::OptionContext& /* context */, Glib::OptionGroup& /* group */) { - //This is called before the m_arg_* instances are given their values. + // This is called before the m_arg_* instances are given their values. // You do not need to override this method. This is just here to show you how, // in case you want to do any extra processing. std::cout << "on_pre_parse called" << std::endl; return true; } -bool ExampleOptionGroup::on_post_parse(Glib::OptionContext& /* context */, Glib::OptionGroup& /* group */) +bool +ExampleOptionGroup::on_post_parse( + Glib::OptionContext& /* context */, Glib::OptionGroup& /* group */) { - //This is called after the m_arg_* instances are given their values. + // This is called after the m_arg_* instances are given their values. // You do not need to override this method. This is just here to show you how, // in case you want to do any extra processing. std::cout << "on_post_parse called" << std::endl; return true; } -void ExampleOptionGroup::on_error(Glib::OptionContext& /* context */, Glib::OptionGroup& /* group */) +void +ExampleOptionGroup::on_error(Glib::OptionContext& /* context */, Glib::OptionGroup& /* group */) { std::cout << "on_error called" << std::endl; } -bool ExampleOptionGroup::on_option_arg_string(const Glib::ustring& option_name, - const Glib::ustring& value, bool has_value) +bool +ExampleOptionGroup::on_option_arg_string( + const Glib::ustring& option_name, const Glib::ustring& value, bool has_value) { - if(option_name != "-x" && option_name != "--x-string") + if (option_name != "-x" && option_name != "--x-string") { m_arg_x_string = "on_option_arg_string called with unexpected option_name: " + option_name; throw Glib::OptionError(Glib::OptionError::UNKNOWN_OPTION, m_arg_x_string); } - if(!has_value) + if (!has_value) { m_arg_x_string = "no value"; return true; } - if(value.empty()) + if (value.empty()) { m_arg_x_string = "empty string"; return true; } m_arg_x_string = value; - if(value == "error") + if (value == "error") { - throw Glib::OptionError(Glib::OptionError::BAD_VALUE, - "on_option_arg_string called with value = " + m_arg_x_string); + throw Glib::OptionError( + Glib::OptionError::BAD_VALUE, "on_option_arg_string called with value = " + m_arg_x_string); } return value != "false"; } -bool ExampleOptionGroup::on_option_arg_filename(const Glib::ustring& option_name, - const std::string& value, bool has_value) +bool +ExampleOptionGroup::on_option_arg_filename( + const Glib::ustring& option_name, const std::string& value, bool has_value) { - if(option_name != "-X" && option_name != "--x-filename") + if (option_name != "-X" && option_name != "--x-filename") { m_arg_x_filename = "on_option_arg_filename called with unexpected option_name: " + option_name; throw Glib::OptionError(Glib::OptionError::UNKNOWN_OPTION, m_arg_x_filename); } - if(!has_value) + if (!has_value) { m_arg_x_filename = "no value"; return true; } - if(value.empty()) + if (value.empty()) { m_arg_x_filename = "empty string"; return true; } m_arg_x_filename = value; - if(value == "error") + if (value == "error") { throw Glib::OptionError(Glib::OptionError::BAD_VALUE, "on_option_arg_filename called with value = " + m_arg_x_filename); @@ -187,57 +195,58 @@ bool ExampleOptionGroup::on_option_arg_filename(const Glib::ustring& option_name return value != "false"; } - -int main(int argc, char** argv) +int +main(int argc, char** argv) { - //This example should be executed like so: + // This example should be executed like so: //./example --foo=1 --bar=2 --goo=abc //./example --help - + Glib::init(); - //Set up the current locale. + // Set up the current locale. setlocale(LC_ALL, ""); Glib::OptionContext context; - + ExampleOptionGroup group; context.set_main_group(group); - + try { context.parse(argc, argv); } - catch(const Glib::Error& ex) + catch (const Glib::Error& ex) { std::cout << "Exception: " << ex.what() << std::endl; } - std::cout << "parsed values: " << std::endl << - " foo = " << group.m_arg_foo << std::endl << - " filename = " << group.m_arg_filename << std::endl << - " activate_something = " << (group.m_arg_boolean ? "enabled" : "disabled") << std::endl << - " goo = " << group.m_arg_goo << std::endl << - " x-string = " << group.m_arg_x_string << std::endl << - " x-filename = " << group.m_arg_x_filename << std::endl; - - //This one shows the results of multiple instance of the same option, such as --list=1 --list=a --list=b + std::cout << "parsed values: " << std::endl + << " foo = " << group.m_arg_foo << std::endl + << " filename = " << group.m_arg_filename << std::endl + << " activate_something = " << (group.m_arg_boolean ? "enabled" : "disabled") + << std::endl + << " goo = " << group.m_arg_goo << std::endl + << " x-string = " << group.m_arg_x_string << std::endl + << " x-filename = " << group.m_arg_x_filename << std::endl; + + // This one shows the results of multiple instance of the same option, such as --list=1 --list=a + // --list=b std::cout << " list = "; - for(const auto& i : group.m_arg_list) + for (const auto& i : group.m_arg_list) { std::cout << i << ", "; } std::cout << std::endl; - //This one shows the remaining arguments on the command line, which had no name= form: + // This one shows the remaining arguments on the command line, which had no name= form: std::cout << " remaining = "; - for(const auto& i : group.m_remaining_list) + for (const auto& i : group.m_remaining_list) { std::cout << i << ", "; } std::cout << std::endl; - + return 0; } - diff --git a/examples/properties/properties_example.cc b/examples/properties/properties_example.cc index 90111408..98ef1eec 100644 --- a/examples/properties/properties_example.cc +++ b/examples/properties/properties_example.cc @@ -24,59 +24,64 @@ class Person : public Glib::Object { public: - Person () : - // to register custom properties, you must register a custom GType. If - // you don't know what that means, don't worry, just remember to add - // this Glib::ObjectBase constructor call to your class' constructor - Glib::ObjectBase (typeid (Person)), - // register the properties with the object and give them names - prop_firstname (*this, "firstname"), - prop_lastname (*this, "lastname"), - // this one has a default value - prop_age (*this, "age", 10) - {} + Person() + : // to register custom properties, you must register a custom GType. If + // you don't know what that means, don't worry, just remember to add + // this Glib::ObjectBase constructor call to your class' constructor + Glib::ObjectBase(typeid(Person)), + // register the properties with the object and give them names + prop_firstname(*this, "firstname"), + prop_lastname(*this, "lastname"), + // this one has a default value + prop_age(*this, "age", 10) + { + } - // provide proxies for the properties. The proxy allows you to connect to - // the 'changed' signal, etc. - Glib::PropertyProxy<Glib::ustring> property_firstname () - { return prop_firstname.get_proxy (); } - Glib::PropertyProxy<Glib::ustring> property_lastname () - { return prop_lastname.get_proxy (); } - Glib::PropertyProxy<int> property_age () - { return prop_age.get_proxy (); } + // provide proxies for the properties. The proxy allows you to connect to + // the 'changed' signal, etc. + Glib::PropertyProxy<Glib::ustring> property_firstname() { return prop_firstname.get_proxy(); } + Glib::PropertyProxy<Glib::ustring> property_lastname() { return prop_lastname.get_proxy(); } + Glib::PropertyProxy<int> property_age() { return prop_age.get_proxy(); } private: - Glib::Property<Glib::ustring> prop_firstname; - Glib::Property<Glib::ustring> prop_lastname; - Glib::Property<int> prop_age; + Glib::Property<Glib::ustring> prop_firstname; + Glib::Property<Glib::ustring> prop_lastname; + Glib::Property<int> prop_age; }; -void on_firstname_changed () -{ std::cout << "- firstname changed!" << std::endl; } -void on_lastname_changed () -{ std::cout << "- lastname changed!" << std::endl; } -void on_age_changed () -{ std::cout << "- age changed!" << std::endl; } +void +on_firstname_changed() +{ + std::cout << "- firstname changed!" << std::endl; +} +void +on_lastname_changed() +{ + std::cout << "- lastname changed!" << std::endl; +} +void +on_age_changed() +{ + std::cout << "- age changed!" << std::endl; +} -int main(int, char**) +int +main(int, char**) { - Glib::init (); - Person p; - // Register some handlers that will be called when the values of the - // specified parameters are changed - p.property_firstname ().signal_changed () - .connect (sigc::ptr_fun (&on_firstname_changed)); - p.property_lastname ().signal_changed () - .connect (sigc::ptr_fun (&on_lastname_changed)); - p.property_age ().signal_changed () - .connect (sigc::ptr_fun (&on_age_changed)); + Glib::init(); + Person p; + // Register some handlers that will be called when the values of the + // specified parameters are changed + p.property_firstname().signal_changed().connect(sigc::ptr_fun(&on_firstname_changed)); + p.property_lastname().signal_changed().connect(sigc::ptr_fun(&on_lastname_changed)); + p.property_age().signal_changed().connect(sigc::ptr_fun(&on_age_changed)); - // now change the properties and see that the handlers get called - std::cout << "Changing the properties of 'p'" << std::endl; - p.property_firstname () = "John"; - p.property_lastname () = "Doe"; - p.property_age () = 43; - std::cout << "Done changing the properties of 'p'" << std::endl; + // now change the properties and see that the handlers get called + std::cout << "Changing the properties of 'p'" << std::endl; + p.property_firstname() = "John"; + p.property_lastname() = "Doe"; + p.property_age() = 43; + std::cout << "Done changing the properties of 'p'" << std::endl; - return 0; + return 0; } diff --git a/examples/regex/main.cc b/examples/regex/main.cc index ed6ac567..e634fe5e 100644 --- a/examples/regex/main.cc +++ b/examples/regex/main.cc @@ -16,30 +16,25 @@ */ #include <glibmm.h> -#include <iostream> #include <iomanip> +#include <iostream> -int main(int, char**) +int +main(int, char**) { Glib::init(); /* Reusing one regex pattern: */ const auto regex = Glib::Regex::create("(a)?(b)"); - std::cout << "Pattern=" << regex->get_pattern() - << ", with string=abcd, result=" - << std::boolalpha << regex->match("abcd") - << std::endl; - std::cout << "Pattern=" << regex->get_pattern() - << ", with string=1234, result=" - << std::boolalpha << regex->match("1234") - << std::endl; + std::cout << "Pattern=" << regex->get_pattern() << ", with string=abcd, result=" << std::boolalpha + << regex->match("abcd") << std::endl; + std::cout << "Pattern=" << regex->get_pattern() << ", with string=1234, result=" << std::boolalpha + << regex->match("1234") << std::endl; std::cout << std::endl; /* Using the static function without a regex instance: */ - std::cout << "Pattern=b* with string=abcd, result=" - << std::boolalpha << Glib::Regex::match_simple("b*", "abcd") - << std::endl; + std::cout << "Pattern=b* with string=abcd, result=" << std::boolalpha + << Glib::Regex::match_simple("b*", "abcd") << std::endl; return 0; } - diff --git a/examples/settings/settings.cc b/examples/settings/settings.cc index 84df7a0e..1761e00b 100644 --- a/examples/settings/settings.cc +++ b/examples/settings/settings.cc @@ -22,47 +22,48 @@ #include <giomm.h> #include <iostream> -const char *const STRING_KEY = "test-string"; -const char *const INT_KEY = "test-int"; +const char* const STRING_KEY = "test-string"; +const char* const INT_KEY = "test-int"; -static void on_key_changed(const Glib::ustring& key, const Glib::RefPtr<Gio::Settings>& settings) +static void +on_key_changed(const Glib::ustring& key, const Glib::RefPtr<Gio::Settings>& settings) { std::cout << Glib::ustring::compose("'%1' changed\n", key); if (key == STRING_KEY) { Glib::ustring str = settings->get_string(key); - std::cout << Glib::ustring::compose("New value of '%1': '%2'\n", - key, str); - - //Or: + std::cout << Glib::ustring::compose("New value of '%1': '%2'\n", key, str); + + // Or: Glib::Variant<Glib::ustring> variant; settings->get_value(key, variant); str = variant.get(); - std::cout << Glib::ustring::compose("New value, via variant, of '%1': '%2'\n", - key, str); + std::cout << Glib::ustring::compose("New value, via variant, of '%1': '%2'\n", key, str); } else if (key == INT_KEY) { - std::cout << Glib::ustring::compose("New value of '%1': '%2'\n", - key, settings->get_int(key)); + std::cout << Glib::ustring::compose("New value of '%1': '%2'\n", key, settings->get_int(key)); } else std::cerr << "Unknown key\n"; } -static void on_key_changed_all(const Glib::ustring& key) +static void +on_key_changed_all(const Glib::ustring& key) { std::cout << "on_key_changed_all(" << key << ")\n"; } -static void on_key_changed_int(const Glib::ustring& key) +static void +on_key_changed_int(const Glib::ustring& key) { std::cout << "on_key_changed_int(" << key << ")\n"; if (key != INT_KEY) std::cerr << "Unexpected key\n"; } -int main(int, char**) +int +main(int, char**) { std::locale::global(std::locale("")); Gio::init(); @@ -75,19 +76,18 @@ int main(int, char**) Glib::setenv("GSETTINGS_SCHEMA_DIR", ".", true); Glib::setenv("GSETTINGS_BACKEND", "memory", true); - const auto settings = - Gio::Settings::create("org.gtkmm.demo"); + const auto settings = Gio::Settings::create("org.gtkmm.demo"); settings->signal_changed().connect(sigc::bind(sigc::ptr_fun(&on_key_changed), settings)); settings->signal_changed("").connect(sigc::ptr_fun(&on_key_changed_all)); settings->signal_changed(INT_KEY).connect(sigc::ptr_fun(&on_key_changed_int)); - std::cout << Glib::ustring::compose("Initial value of '%1': '%2'\n", - STRING_KEY, settings->get_string(STRING_KEY)); + std::cout << Glib::ustring::compose( + "Initial value of '%1': '%2'\n", STRING_KEY, settings->get_string(STRING_KEY)); settings->set_string(STRING_KEY, "Hoopoe"); - std::cout << Glib::ustring::compose("Initial value of '%1': '%2'\n", - INT_KEY, settings->get_int(INT_KEY)); + std::cout << Glib::ustring::compose( + "Initial value of '%1': '%2'\n", INT_KEY, settings->get_int(INT_KEY)); settings->set_int(INT_KEY, 18); return 0; diff --git a/examples/thread/dispatcher.cc b/examples/thread/dispatcher.cc index 50e3b530..9f0f56e3 100644 --- a/examples/thread/dispatcher.cc +++ b/examples/thread/dispatcher.cc @@ -12,8 +12,8 @@ #include <algorithm> #include <functional> -#include <thread> #include <iostream> +#include <thread> #include <vector> namespace @@ -33,7 +33,7 @@ public: explicit ThreadProgress(int the_id); ~ThreadProgress(); - int id() const; + int id() const; void launch(); void join(); bool unfinished() const; @@ -41,16 +41,19 @@ public: sigc::signal<void>& signal_finished(); private: - enum { ITERATIONS = 100 }; + enum + { + ITERATIONS = 100 + }; // Note that the thread does not write to the member data at all. It only // reads signal_increment_, which is only written to before the thread is // launched. Therefore, no locking is required. - std::thread* thread_; - int id_; - unsigned int progress_; - Glib::Dispatcher signal_increment_; - sigc::signal<void> signal_finished_; + std::thread* thread_; + int id_; + unsigned int progress_; + Glib::Dispatcher signal_increment_; + sigc::signal<void> signal_finished_; void progress_increment(); void thread_function(); @@ -65,8 +68,8 @@ public: void run(); private: - Glib::RefPtr<Glib::MainLoop> main_loop_; - std::vector<ThreadProgress*> progress_threads_; + Glib::RefPtr<Glib::MainLoop> main_loop_; + std::vector<ThreadProgress*> progress_threads_; void launch_threads(); void on_progress_finished(ThreadProgress* thread_progress); @@ -79,11 +82,7 @@ public: void operator()(T ptr) const { delete ptr; } }; -ThreadProgress::ThreadProgress(int the_id) -: - thread_ (nullptr), - id_ (the_id), - progress_ (0) +ThreadProgress::ThreadProgress(int the_id) : thread_(nullptr), id_(the_id), progress_(0) { // Connect to the cross-thread signal. signal_increment_.connect(sigc::mem_fun(*this, &ThreadProgress::progress_increment)); @@ -95,39 +94,41 @@ ThreadProgress::~ThreadProgress() g_return_if_fail(thread_ == nullptr); } -int ThreadProgress::id() const +int +ThreadProgress::id() const { return id_; } -void ThreadProgress::launch() +void +ThreadProgress::launch() { // Create a joinable thread. - thread_ = new std::thread( - [this] () - { - thread_function(); - }); + thread_ = new std::thread([this]() { thread_function(); }); } -void ThreadProgress::join() +void +ThreadProgress::join() { thread_->join(); delete thread_; thread_ = nullptr; } -bool ThreadProgress::unfinished() const +bool +ThreadProgress::unfinished() const { return (progress_ < ITERATIONS); } -sigc::signal<void>& ThreadProgress::signal_finished() +sigc::signal<void>& +ThreadProgress::signal_finished() { return signal_finished_; } -void ThreadProgress::progress_increment() +void +ThreadProgress::progress_increment() { ++progress_; std::cout << "Thread " << id_ << ": " << progress_ << '%' << std::endl; @@ -136,7 +137,8 @@ void ThreadProgress::progress_increment() signal_finished_(); } -void ThreadProgress::thread_function() +void +ThreadProgress::thread_function() { Glib::Rand rand; @@ -149,39 +151,35 @@ void ThreadProgress::thread_function() } } -Application::Application() -: - main_loop_ (Glib::MainLoop::create()), - progress_threads_ (5) +Application::Application() : main_loop_(Glib::MainLoop::create()), progress_threads_(5) { try { for (std::vector<ThreadProgress*>::size_type i = 0; i < progress_threads_.size(); ++i) { - ThreadProgress *const progress = new ThreadProgress(i + 1); + ThreadProgress* const progress = new ThreadProgress(i + 1); progress_threads_[i] = progress; progress->signal_finished().connect( - sigc::bind<1>(sigc::mem_fun(*this, &Application::on_progress_finished), progress)); + sigc::bind<1>(sigc::mem_fun(*this, &Application::on_progress_finished), progress)); } } catch (...) { // In your own code, you should preferably use a smart pointer // to ensure exception safety. - std::for_each(progress_threads_.begin(), progress_threads_.end(), - DeletePtr<ThreadProgress*>()); + std::for_each(progress_threads_.begin(), progress_threads_.end(), DeletePtr<ThreadProgress*>()); throw; } } Application::~Application() { - std::for_each(progress_threads_.begin(), progress_threads_.end(), - DeletePtr<ThreadProgress*>()); + std::for_each(progress_threads_.begin(), progress_threads_.end(), DeletePtr<ThreadProgress*>()); } -void Application::run() +void +Application::run() { // Install a one-shot idle handler to launch the threads. Glib::signal_idle().connect_once(sigc::mem_fun(*this, &Application::launch_threads)); @@ -189,15 +187,17 @@ void Application::run() main_loop_->run(); } -void Application::launch_threads() +void +Application::launch_threads() { std::cout << "Launching " << progress_threads_.size() << " threads:" << std::endl; - std::for_each(progress_threads_.begin(), progress_threads_.end(), - std::mem_fun(&ThreadProgress::launch)); + std::for_each( + progress_threads_.begin(), progress_threads_.end(), std::mem_fun(&ThreadProgress::launch)); } -void Application::on_progress_finished(ThreadProgress* thread_progress) +void +Application::on_progress_finished(ThreadProgress* thread_progress) { thread_progress->join(); @@ -205,7 +205,7 @@ void Application::on_progress_finished(ThreadProgress* thread_progress) // Quit if it was the last thread to be joined. if (std::find_if(progress_threads_.begin(), progress_threads_.end(), - std::mem_fun(&ThreadProgress::unfinished)) == progress_threads_.end()) + std::mem_fun(&ThreadProgress::unfinished)) == progress_threads_.end()) { main_loop_->quit(); } @@ -213,7 +213,8 @@ void Application::on_progress_finished(ThreadProgress* thread_progress) } // anonymous namespace -int main(int, char**) +int +main(int, char**) { Glib::init(); diff --git a/examples/thread/dispatcher2.cc b/examples/thread/dispatcher2.cc index 0a80bdcd..28912936 100644 --- a/examples/thread/dispatcher2.cc +++ b/examples/thread/dispatcher2.cc @@ -1,9 +1,9 @@ /* * original Glib::Dispatcher example -- cross thread signalling * by Daniel Elstner <daniel.elstner@gmx.net> - * + * * Modified by Stephan Puchegger <stephan.puchegger@ap.univie.ac.at> - * to contain 2 mainloops in 2 different threads, that communicate + * to contain 2 mainloops in 2 different threads, that communicate * via cross thread signalling in both directions. The timer thread * sends the UI thread a cross thread signal every second, which in turn * updates the label stating how many seconds have passed since the start @@ -20,13 +20,12 @@ * Copyright (c) 2002-2003 Free Software Foundation */ +#include <condition_variable> #include <glibmm.h> +#include <iostream> +#include <mutex> #include <sstream> #include <thread> -#include <mutex> -#include <condition_variable> -#include <iostream> - namespace { @@ -46,14 +45,14 @@ public: static type_signal_end& signal_end(); private: - unsigned int time_; - Glib::Dispatcher signal_increment_; + unsigned int time_; + Glib::Dispatcher signal_increment_; Glib::Dispatcher* signal_finished_ptr_; std::mutex startup_mutex_; - std::condition_variable startup_cond_; + std::condition_variable startup_cond_; std::thread* thread_; - + static type_signal_end signal_end_; void timer_increment(); @@ -74,52 +73,46 @@ private: ThreadTimer* timer_; }; -ThreadTimer::ThreadTimer() -: - time_ (0), +ThreadTimer::ThreadTimer() +: time_(0), // Create a new Glib::Dispatcher that is attached to the default main context, - signal_increment_ (), + signal_increment_(), // This pointer will be initialized later by the 2nd thread. - signal_finished_ptr_ (nullptr), - thread_ (nullptr) + signal_finished_ptr_(nullptr), + thread_(nullptr) { // Connect the cross-thread signal. signal_increment_.connect(sigc::mem_fun(*this, &ThreadTimer::timer_increment)); } ThreadTimer::~ThreadTimer() -{} +{ +} -void ThreadTimer::launch() +void +ThreadTimer::launch() { // Unfortunately, the thread creation has to be fully synchronized in // order to access the Glib::Dispatcher object instantiated by the 2nd thread. // So, let's do some kind of hand-shake using a mutex and a condition // variable. - std::unique_lock<std::mutex> lock (startup_mutex_); + std::unique_lock<std::mutex> lock(startup_mutex_); // Create a joinable thread -- it needs to be joined, otherwise its destructor will block. - thread_ = new std::thread( - [this] () - { - thread_function(); - }); + thread_ = new std::thread([this]() { thread_function(); }); // Wait for the 2nd thread's startup notification. - startup_cond_.wait(lock, - [this] () -> bool - { - return signal_finished_ptr_; - }); + startup_cond_.wait(lock, [this]() -> bool { return signal_finished_ptr_; }); } -void ThreadTimer::signal_finished_emit() +void +ThreadTimer::signal_finished_emit() { // Cause the 2nd thread's main loop to quit. signal_finished_ptr_->emit(); // wait for the thread to join - if(thread_) + if (thread_) { thread_->join(); delete thread_; @@ -129,28 +122,32 @@ void ThreadTimer::signal_finished_emit() signal_finished_ptr_ = nullptr; } -void ThreadTimer::print() const +void +ThreadTimer::print() const { std::cout << time_ << " seconds since start" << std::endl; } -sigc::signal< void >& ThreadTimer::signal_end() +sigc::signal<void>& +ThreadTimer::signal_end() { return signal_end_; } -void ThreadTimer::timer_increment() +void +ThreadTimer::timer_increment() { // another second has passed since the start of the program ++time_; print(); - if(time_ >= 10) + if (time_ >= 10) signal_finished_emit(); } // static -void ThreadTimer::finished_handler(Glib::RefPtr<Glib::MainLoop> mainloop) +void +ThreadTimer::finished_handler(Glib::RefPtr<Glib::MainLoop> mainloop) { // quit the timer thread mainloop mainloop->quit(); @@ -158,7 +155,8 @@ void ThreadTimer::finished_handler(Glib::RefPtr<Glib::MainLoop> mainloop) ThreadTimer::signal_end().emit(); } -bool ThreadTimer::timeout_handler() +bool +ThreadTimer::timeout_handler() { // inform the printing thread that another second has passed signal_increment_(); @@ -167,7 +165,8 @@ bool ThreadTimer::timeout_handler() return true; } -void ThreadTimer::thread_function() +void +ThreadTimer::thread_function() { // create a new Main Context auto context = Glib::MainContext::create(); @@ -180,19 +179,19 @@ void ThreadTimer::thread_function() // We need to lock while creating the Glib::Dispatcher instance, // in order to ensure memory visibility. - std::unique_lock<std::mutex> lock (startup_mutex_); + std::unique_lock<std::mutex> lock(startup_mutex_); // create a new dispatcher, that is connected to the newly // created MainContext - Glib::Dispatcher signal_finished (context); - + Glib::Dispatcher signal_finished(context); + signal_finished.connect(sigc::bind(sigc::ptr_fun(&ThreadTimer::finished_handler), mainloop)); signal_finished_ptr_ = &signal_finished; // Tell the launcher thread that everything is in place now. - //We unlock before notifying, because that is what the documentation suggests: - //http://en.cppreference.com/w/cpp/thread/condition_variable + // We unlock before notifying, because that is what the documentation suggests: + // http://en.cppreference.com/w/cpp/thread/condition_variable lock.unlock(); startup_cond_.notify_one(); @@ -203,9 +202,7 @@ void ThreadTimer::thread_function() // initialize static member: ThreadTimer::type_signal_end ThreadTimer::signal_end_; -ThreadDispatcher::ThreadDispatcher() -: - timer_ (nullptr) +ThreadDispatcher::ThreadDispatcher() : timer_(nullptr) { std::cout << "Thread Dispatcher Example #2" << std::endl; @@ -214,13 +211,15 @@ ThreadDispatcher::ThreadDispatcher() timer_->print(); } -void ThreadDispatcher::launch_thread() +void +ThreadDispatcher::launch_thread() { // launch the timer thread timer_->launch(); } -void ThreadDispatcher::end() +void +ThreadDispatcher::end() { // quit the main mainloop main_loop->quit(); @@ -228,8 +227,8 @@ void ThreadDispatcher::end() } // anonymous namespace - -int main(int, char**) +int +main(int, char**) { Glib::init(); main_loop = Glib::MainLoop::create(); @@ -243,4 +242,3 @@ int main(int, char**) return 0; } - diff --git a/examples/thread/thread.cc b/examples/thread/thread.cc index f535254d..7af27350 100644 --- a/examples/thread/thread.cc +++ b/examples/thread/thread.cc @@ -1,17 +1,17 @@ +#include <condition_variable> #include <iostream> -#include <thread> +#include <memory> #include <mutex> -#include <condition_variable> #include <queue> -#include <memory> -#if defined (_MSC_VER) && (_MSC_VER < 1900) +#include <thread> +#if defined(_MSC_VER) && (_MSC_VER < 1900) /* For using noexcept on Visual Studio 2013 */ #include <glibmmconfig.h> #endif +#include <glibmm/init.h> #include <glibmm/random.h> #include <glibmm/timer.h> -#include <glibmm/init.h> namespace { @@ -32,96 +32,90 @@ private: std::queue<int> queue_; }; - MessageQueue::MessageQueue() -{} +{ +} MessageQueue::~MessageQueue() -{} +{ +} -void MessageQueue::producer() +void +MessageQueue::producer() { - Glib::Rand rand (1234); + Glib::Rand rand(1234); - for(auto i = 0; i < 200; ++i) + for (auto i = 0; i < 200; ++i) { { - std::unique_lock<std::mutex> lock (mutex_); + std::unique_lock<std::mutex> lock(mutex_); - cond_pop_.wait(lock, - [this] () -> bool - { - return queue_.size() < 64; - }); + cond_pop_.wait(lock, [this]() -> bool { return queue_.size() < 64; }); queue_.push(i); std::cout << '*'; std::cout.flush(); - //We unlock before notifying, because that is what the documentation suggests: - //http://en.cppreference.com/w/cpp/thread/condition_variable + // We unlock before notifying, because that is what the documentation suggests: + // http://en.cppreference.com/w/cpp/thread/condition_variable lock.unlock(); cond_push_.notify_one(); } - if(rand.get_bool()) + if (rand.get_bool()) continue; Glib::usleep(rand.get_int_range(0, 100000)); } } -void MessageQueue::consumer() +void +MessageQueue::consumer() { - Glib::Rand rand (4567); + Glib::Rand rand(4567); - for(;;) + for (;;) { { - std::unique_lock<std::mutex> lock (mutex_); + std::unique_lock<std::mutex> lock(mutex_); - cond_push_.wait(lock, - [this] () -> bool - { - return !queue_.empty(); - }); + cond_push_.wait(lock, [this]() -> bool { return !queue_.empty(); }); const int i = queue_.front(); queue_.pop(); std::cout << "\x08 \x08"; std::cout.flush(); - //We unlock before notifying, because that is what the documentation suggests: - //http://en.cppreference.com/w/cpp/thread/condition_variable + // We unlock before notifying, because that is what the documentation suggests: + // http://en.cppreference.com/w/cpp/thread/condition_variable lock.unlock(); cond_pop_.notify_one(); - if(i >= 199) + if (i >= 199) break; } - if(rand.get_bool()) + if (rand.get_bool()) continue; Glib::usleep(rand.get_int_range(10000, 200000)); } } - } - -int main(int, char**) +int +main(int, char**) { Glib::init(); MessageQueue queue; - //TODO: Use std::make_unique() when we use C++14: - const auto producer = std::unique_ptr<std::thread>( - new std::thread(&MessageQueue::producer, &queue)); + // TODO: Use std::make_unique() when we use C++14: + const auto producer = + std::unique_ptr<std::thread>(new std::thread(&MessageQueue::producer, &queue)); - const auto consumer = std::unique_ptr<std::thread>( - new std::thread(&MessageQueue::consumer, &queue)); + const auto consumer = + std::unique_ptr<std::thread>(new std::thread(&MessageQueue::consumer, &queue)); producer->join(); consumer->join(); @@ -130,4 +124,3 @@ int main(int, char**) return 0; } - diff --git a/examples/thread/threadpool.cc b/examples/thread/threadpool.cc index 51096746..891c565d 100644 --- a/examples/thread/threadpool.cc +++ b/examples/thread/threadpool.cc @@ -1,20 +1,22 @@ #include <iostream> -#include <thread> #include <mutex> +#include <thread> -//TODO: Remove this example sometime. Glib::ThreadPool is deprecated. -//TODO: Maybe use std::async() instead? +// TODO: Remove this example sometime. Glib::ThreadPool is deprecated. +// TODO: Maybe use std::async() instead? #undef GLIBMM_DISABLE_DEPRECATED #include <glibmmconfig.h> #ifdef GLIBMM_DISABLE_DEPRECATED -int main(int, char**) +int +main(int, char**) { // If glibmm is configured with --disable-deprecated-api, // GLIBMM_DISABLE_DEPRECATED is defined in glibmmconfig.h. - std::cout << "Glib::ThreadPool not available because deprecated API has been disabled." << std::endl; + std::cout << "Glib::ThreadPool not available because deprecated API has been disabled." + << std::endl; return 77; // Tell automake's test harness to skip this test. } @@ -29,14 +31,15 @@ namespace std::mutex mutex; -void print_char(char c) +void +print_char(char c) { Glib::Rand rand; - for(auto i = 0; i < 100; ++i) + for (auto i = 0; i < 100; ++i) { { - std::lock_guard<std::mutex> lock (mutex); + std::lock_guard<std::mutex> lock(mutex); std::cout << c; std::cout.flush(); } @@ -46,20 +49,20 @@ void print_char(char c) } // anonymous namespace - -int main(int, char**) +int +main(int, char**) { - Glib::ThreadPool pool (10); + Glib::ThreadPool pool(10); - for(auto c = 'a'; c <= 'z'; ++c) + for (auto c = 'a'; c <= 'z'; ++c) { pool.push(sigc::bind<1>(sigc::ptr_fun(&print_char), c)); } - + pool.shutdown(); std::cout << std::endl; return 0; } -#endif //GLIBMM_DISABLE_DEPRECATED +#endif // GLIBMM_DISABLE_DEPRECATED |