LibCore: Put all classes in the Core namespace and remove the leading C

I've been wanting to do this for a long time. It's time we start being
consistent about how this stuff works.

The new convention is:

- "LibFoo" is a userspace library that provides the "Foo" namespace.

That's it :^) This was pretty tedious to convert and I didn't even
start on LibGUI yet. But it's coming up next.
This commit is contained in:
Andreas Kling 2020-02-02 12:34:39 +01:00
parent b7e3810b5c
commit 2d39da5405
Notes: sideshowbarker 2024-07-19 09:41:36 +09:00
265 changed files with 1380 additions and 1167 deletions

View file

@ -44,7 +44,7 @@ BoardListModel::~BoardListModel()
void BoardListModel::update() void BoardListModel::update()
{ {
CHttpRequest request; Core::HttpRequest request;
request.set_url("http://a.4cdn.org/boards.json"); request.set_url("http://a.4cdn.org/boards.json");
if (m_pending_job) if (m_pending_job)

View file

@ -51,5 +51,5 @@ private:
BoardListModel(); BoardListModel();
JsonArray m_boards; JsonArray m_boards;
RefPtr<CHttpJob> m_pending_job; RefPtr<Core::HttpJob> m_pending_job;
}; };

View file

@ -52,7 +52,7 @@ void ThreadCatalogModel::set_board(const String& board)
void ThreadCatalogModel::update() void ThreadCatalogModel::update()
{ {
CHttpRequest request; Core::HttpRequest request;
request.set_url(String::format("http://a.4cdn.org/%s/catalog.json", m_board.characters())); request.set_url(String::format("http://a.4cdn.org/%s/catalog.json", m_board.characters()));
if (m_pending_job) if (m_pending_job)

View file

@ -63,5 +63,5 @@ private:
String m_board { "g" }; String m_board { "g" };
JsonArray m_catalog; JsonArray m_catalog;
RefPtr<CHttpJob> m_pending_job; RefPtr<Core::HttpJob> m_pending_job;
}; };

View file

@ -48,7 +48,7 @@
#include <Servers/WindowServer/WSWindowManager.h> #include <Servers/WindowServer/WSWindowManager.h>
DisplayPropertiesWidget::DisplayPropertiesWidget() DisplayPropertiesWidget::DisplayPropertiesWidget()
: m_wm_config(CConfigFile::get_for_app("WindowManager")) : m_wm_config(Core::ConfigFile::get_for_app("WindowManager"))
{ {
create_resolution_list(); create_resolution_list();
create_wallpaper_list(); create_wallpaper_list();
@ -114,7 +114,7 @@ void DisplayPropertiesWidget::create_wallpaper_list()
m_selected_wallpaper = name_parts[2]; m_selected_wallpaper = name_parts[2];
} }
CDirIterator iterator("/res/wallpapers/", CDirIterator::Flags::SkipDots); Core::DirIterator iterator("/res/wallpapers/", Core::DirIterator::Flags::SkipDots);
while (iterator.has_next()) { while (iterator.has_next()) {
m_wallpapers.append(iterator.next_path()); m_wallpapers.append(iterator.next_path());

View file

@ -65,7 +65,7 @@ private:
private: private:
String m_wallpaper_path; String m_wallpaper_path;
RefPtr<CConfigFile> m_wm_config; RefPtr<Core::ConfigFile> m_wm_config;
RefPtr<GWidget> m_root_widget; RefPtr<GWidget> m_root_widget;
Vector<Size> m_resolutions; Vector<Size> m_resolutions;
Vector<String> m_wallpapers; Vector<String> m_wallpapers;

View file

@ -37,7 +37,7 @@ namespace FileUtils {
int delete_directory(String directory, String& file_that_caused_error) int delete_directory(String directory, String& file_that_caused_error)
{ {
CDirIterator iterator(directory, CDirIterator::SkipDots); Core::DirIterator iterator(directory, Core::DirIterator::SkipDots);
if (iterator.has_error()) { if (iterator.has_error()) {
file_that_caused_error = directory; file_that_caused_error = directory;
return -1; return -1;
@ -104,7 +104,7 @@ bool copy_directory(const String& src_path, const String& dst_path)
if (rc < 0) { if (rc < 0) {
return false; return false;
} }
CDirIterator di(src_path, CDirIterator::SkipDots); Core::DirIterator di(src_path, Core::DirIterator::SkipDots);
if (di.has_error()) { if (di.has_error()) {
return false; return false;
} }

View file

@ -35,7 +35,7 @@
#include <stdio.h> #include <stdio.h>
#include <unistd.h> #include <unistd.h>
PropertiesDialog::PropertiesDialog(GFileSystemModel& model, String path, bool disable_rename, CObject* parent) PropertiesDialog::PropertiesDialog(GFileSystemModel& model, String path, bool disable_rename, Core::Object* parent)
: GDialog(parent) : GDialog(parent)
, m_model(model) , m_model(model)
{ {

View file

@ -40,7 +40,7 @@ public:
virtual ~PropertiesDialog() override; virtual ~PropertiesDialog() override;
private: private:
PropertiesDialog(GFileSystemModel&, String, bool disable_rename, CObject* parent = nullptr); PropertiesDialog(GFileSystemModel&, String, bool disable_rename, Core::Object* parent = nullptr);
struct PropertyValuePair { struct PropertyValuePair {
String property; String property;

View file

@ -72,7 +72,7 @@ int main(int argc, char** argv)
return 1; return 1;
} }
RefPtr<CConfigFile> config = CConfigFile::get_for_app("FileManager"); RefPtr<Core::ConfigFile> config = Core::ConfigFile::get_for_app("FileManager");
GApplication app(argc, argv); GApplication app(argc, argv);

View file

@ -41,7 +41,7 @@ void ManualSectionNode::reify_if_needed() const
return; return;
m_reified = true; m_reified = true;
CDirIterator dir_iter { path(), CDirIterator::Flags::SkipDots }; Core::DirIterator dir_iter { path(), Core::DirIterator::Flags::SkipDots };
while (dir_iter.has_next()) { while (dir_iter.has_next()) {
FileSystemPath file_path(dir_iter.next_path()); FileSystemPath file_path(dir_iter.next_path());

View file

@ -113,10 +113,10 @@ int main(int argc, char* argv[])
dbg() << "Opening page at " << path; dbg() << "Opening page at " << path;
auto file = CFile::construct(); auto file = Core::File::construct();
file->set_filename(path); file->set_filename(path);
if (!file->open(CIODevice::OpenMode::ReadOnly)) { if (!file->open(Core::IODevice::OpenMode::ReadOnly)) {
int saved_errno = errno; int saved_errno = errno;
GMessageBox::show(strerror(saved_errno), "Failed to open man page", GMessageBox::Type::Error, GMessageBox::InputType::OK, window); GMessageBox::show(strerror(saved_errno), "Failed to open man page", GMessageBox::Type::Error, GMessageBox::InputType::OK, window);
return; return;

View file

@ -564,7 +564,7 @@ void HexEditor::paint_event(GPaintEvent& event)
} }
} }
void HexEditor::leave_event(CEvent&) void HexEditor::leave_event(Core::Event&)
{ {
ASSERT(window()); ASSERT(window());
window()->set_override_cursor(GStandardCursor::None); window()->set_override_cursor(GStandardCursor::None);

View file

@ -73,7 +73,7 @@ protected:
virtual void mousemove_event(GMouseEvent&) override; virtual void mousemove_event(GMouseEvent&) override;
virtual void keydown_event(GKeyEvent&) override; virtual void keydown_event(GKeyEvent&) override;
virtual bool accepts_focus() const override { return true; } virtual bool accepts_focus() const override { return true; }
virtual void leave_event(CEvent&) override; virtual void leave_event(Core::Event&) override;
private: private:
bool m_readonly { false }; bool m_readonly { false };

View file

@ -235,8 +235,8 @@ void HexEditorWidget::update_title()
void HexEditorWidget::open_file(const String& path) void HexEditorWidget::open_file(const String& path)
{ {
auto file = CFile::construct(path); auto file = Core::File::construct(path);
if (!file->open(CIODevice::ReadOnly)) { if (!file->open(Core::IODevice::ReadOnly)) {
GMessageBox::show(String::format("Opening \"%s\" failed: %s", path.characters(), strerror(errno)), "Error", GMessageBox::Type::Error, GMessageBox::InputType::OK, window()); GMessageBox::show(String::format("Opening \"%s\" failed: %s", path.characters(), strerror(errno)), "Error", GMessageBox::Type::Error, GMessageBox::InputType::OK, window());
return; return;
} }

View file

@ -60,9 +60,9 @@ IRCClient::IRCClient()
: m_nickname("seren1ty") : m_nickname("seren1ty")
, m_client_window_list_model(IRCWindowListModel::create(*this)) , m_client_window_list_model(IRCWindowListModel::create(*this))
, m_log(IRCLogBuffer::create()) , m_log(IRCLogBuffer::create())
, m_config(CConfigFile::get_for_app("IRCClient")) , m_config(Core::ConfigFile::get_for_app("IRCClient"))
{ {
m_socket = CTCPSocket::construct(this); m_socket = Core::TCPSocket::construct(this);
m_nickname = m_config->read_entry("User", "Nickname", "seren1ty"); m_nickname = m_config->read_entry("User", "Nickname", "seren1ty");
m_hostname = m_config->read_entry("Connection", "Server", ""); m_hostname = m_config->read_entry("Connection", "Server", "");
m_port = m_config->read_num_entry("Connection", "Port", 6667); m_port = m_config->read_num_entry("Connection", "Port", 6667);
@ -83,7 +83,7 @@ void IRCClient::set_server(const String& hostname, int port)
void IRCClient::on_socket_connected() void IRCClient::on_socket_connected()
{ {
m_notifier = CNotifier::construct(m_socket->fd(), CNotifier::Read); m_notifier = Core::Notifier::construct(m_socket->fd(), Core::Notifier::Read);
m_notifier->on_ready_to_read = [this] { receive_from_server(); }; m_notifier->on_ready_to_read = [this] { receive_from_server(); };
send_user(); send_user();

View file

@ -38,9 +38,8 @@
class IRCChannel; class IRCChannel;
class IRCQuery; class IRCQuery;
class IRCWindowListModel; class IRCWindowListModel;
class CNotifier;
class IRCClient final : public CObject { class IRCClient final : public Core::Object {
C_OBJECT(IRCClient) C_OBJECT(IRCClient)
friend class IRCChannel; friend class IRCChannel;
friend class IRCQuery; friend class IRCQuery;
@ -162,10 +161,10 @@ private:
String m_hostname; String m_hostname;
int m_port { 6667 }; int m_port { 6667 };
RefPtr<CTCPSocket> m_socket; RefPtr<Core::TCPSocket> m_socket;
String m_nickname; String m_nickname;
RefPtr<CNotifier> m_notifier; RefPtr<Core::Notifier> m_notifier;
HashMap<String, RefPtr<IRCChannel>, CaseInsensitiveStringTraits> m_channels; HashMap<String, RefPtr<IRCChannel>, CaseInsensitiveStringTraits> m_channels;
HashMap<String, RefPtr<IRCQuery>, CaseInsensitiveStringTraits> m_queries; HashMap<String, RefPtr<IRCQuery>, CaseInsensitiveStringTraits> m_queries;
@ -175,5 +174,5 @@ private:
NonnullRefPtr<IRCWindowListModel> m_client_window_list_model; NonnullRefPtr<IRCWindowListModel> m_client_window_list_model;
NonnullRefPtr<IRCLogBuffer> m_log; NonnullRefPtr<IRCLogBuffer> m_log;
NonnullRefPtr<CConfigFile> m_config; NonnullRefPtr<Core::ConfigFile> m_config;
}; };

View file

@ -37,7 +37,7 @@
SprayTool::SprayTool() SprayTool::SprayTool()
{ {
m_timer = CTimer::construct(); m_timer = Core::Timer::construct();
m_timer->on_timeout = [&]() { m_timer->on_timeout = [&]() {
paint_it(); paint_it();
}; };

View file

@ -46,7 +46,7 @@ public:
private: private:
virtual const char* class_name() const override { return "SprayTool"; } virtual const char* class_name() const override { return "SprayTool"; }
void paint_it(); void paint_it();
RefPtr<CTimer> m_timer; RefPtr<Core::Timer> m_timer;
Point m_last_pos; Point m_last_pos;
Color m_color; Color m_color;
RefPtr<GMenu> m_context_menu; RefPtr<GMenu> m_context_menu;

View file

@ -70,7 +70,7 @@ MainWidget::~MainWidget()
// FIXME: There are some unnecessary calls to update() throughout this program, // FIXME: There are some unnecessary calls to update() throughout this program,
// which are an easy target for optimization. // which are an easy target for optimization.
void MainWidget::custom_event(CCustomEvent&) void MainWidget::custom_event(Core::CustomEvent&)
{ {
m_wave_widget->update(); m_wave_widget->update();

View file

@ -27,8 +27,8 @@
#pragma once #pragma once
#include "Music.h"
#include <LibGUI/GWidget.h> #include <LibGUI/GWidget.h>
#include <Music.h>
class AudioEngine; class AudioEngine;
class WaveWidget; class WaveWidget;
@ -48,7 +48,7 @@ private:
virtual void keydown_event(GKeyEvent&) override; virtual void keydown_event(GKeyEvent&) override;
virtual void keyup_event(GKeyEvent&) override; virtual void keyup_event(GKeyEvent&) override;
virtual void custom_event(CCustomEvent&) override; virtual void custom_event(Core::CustomEvent&) override;
void note_key_action(int key_code, Switch); void note_key_action(int key_code, Switch);
void special_key_action(int key_code); void special_key_action(int key_code);

View file

@ -55,8 +55,8 @@ int main(int argc, char** argv)
window->show(); window->show();
LibThread::Thread audio_thread([&] { LibThread::Thread audio_thread([&] {
auto audio = CFile::construct("/dev/audio"); auto audio = Core::File::construct("/dev/audio");
if (!audio->open(CIODevice::WriteOnly)) { if (!audio->open(Core::IODevice::WriteOnly)) {
dbgprintf("Can't open audio device: %s", audio->error_string()); dbgprintf("Can't open audio device: %s", audio->error_string());
return 1; return 1;
} }
@ -65,8 +65,8 @@ int main(int argc, char** argv)
for (;;) { for (;;) {
audio_engine.fill_buffer(buffer); audio_engine.fill_buffer(buffer);
audio->write(reinterpret_cast<u8*>(buffer.data()), buffer_size); audio->write(reinterpret_cast<u8*>(buffer.data()), buffer_size);
CEventLoop::current().post_event(*main_widget, make<CCustomEvent>(0)); Core::EventLoop::current().post_event(*main_widget, make<Core::CustomEvent>(0));
CEventLoop::wake(); Core::EventLoop::wake();
} }
}); });
audio_thread.start(); audio_thread.start();

View file

@ -29,7 +29,7 @@
PlaybackManager::PlaybackManager(NonnullRefPtr<AClientConnection> connection) PlaybackManager::PlaybackManager(NonnullRefPtr<AClientConnection> connection)
: m_connection(connection) : m_connection(connection)
{ {
m_timer = CTimer::construct(100, [&]() { m_timer = Core::Timer::construct(100, [&]() {
if (!m_loader) if (!m_loader)
return; return;
next_buffer(); next_buffer();

View file

@ -70,5 +70,5 @@ private:
RefPtr<ABuffer> m_next_buffer; RefPtr<ABuffer> m_next_buffer;
RefPtr<ABuffer> m_current_buffer; RefPtr<ABuffer> m_current_buffer;
Vector<RefPtr<ABuffer>> m_buffers; Vector<RefPtr<ABuffer>> m_buffers;
RefPtr<CTimer> m_timer; RefPtr<Core::Timer> m_timer;
}; };

View file

@ -121,8 +121,8 @@ GVariant DevicesModel::data(const GModelIndex& index, Role) const
void DevicesModel::update() void DevicesModel::update()
{ {
auto proc_devices = CFile::construct("/proc/devices"); auto proc_devices = Core::File::construct("/proc/devices");
if (!proc_devices->open(CIODevice::OpenMode::ReadOnly)) if (!proc_devices->open(Core::IODevice::OpenMode::ReadOnly))
ASSERT_NOT_REACHED(); ASSERT_NOT_REACHED();
auto json = JsonValue::from_string(proc_devices->read_all()).as_array(); auto json = JsonValue::from_string(proc_devices->read_all()).as_array();
@ -148,7 +148,7 @@ void DevicesModel::update()
}); });
auto fill_in_paths_from_dir = [this](const String& dir) { auto fill_in_paths_from_dir = [this](const String& dir) {
CDirIterator dir_iter { dir, CDirIterator::Flags::SkipDots }; Core::DirIterator dir_iter { dir, Core::DirIterator::Flags::SkipDots };
while (dir_iter.has_next()) { while (dir_iter.has_next()) {
auto name = dir_iter.next_path(); auto name = dir_iter.next_path();
auto path = String::format("%s/%s", dir.characters(), name.characters()); auto path = String::format("%s/%s", dir.characters(), name.characters());

View file

@ -93,8 +93,8 @@ static inline size_t bytes_to_kb(size_t bytes)
void MemoryStatsWidget::refresh() void MemoryStatsWidget::refresh()
{ {
auto proc_memstat = CFile::construct("/proc/memstat"); auto proc_memstat = Core::File::construct("/proc/memstat");
if (!proc_memstat->open(CIODevice::OpenMode::ReadOnly)) if (!proc_memstat->open(Core::IODevice::OpenMode::ReadOnly))
ASSERT_NOT_REACHED(); ASSERT_NOT_REACHED();
auto file_contents = proc_memstat->read_all(); auto file_contents = proc_memstat->read_all();

View file

@ -81,7 +81,7 @@ NetworkStatisticsWidget::NetworkStatisticsWidget(GWidget* parent)
net_tcp_fields.empend("bytes_out", "Bytes Out", TextAlignment::CenterRight); net_tcp_fields.empend("bytes_out", "Bytes Out", TextAlignment::CenterRight);
m_socket_table_view->set_model(GJsonArrayModel::create("/proc/net/tcp", move(net_tcp_fields))); m_socket_table_view->set_model(GJsonArrayModel::create("/proc/net/tcp", move(net_tcp_fields)));
m_update_timer = CTimer::construct( m_update_timer = Core::Timer::construct(
1000, [this] { 1000, [this] {
update_models(); update_models();
}, },

View file

@ -42,5 +42,5 @@ private:
RefPtr<GTableView> m_adapter_table_view; RefPtr<GTableView> m_adapter_table_view;
RefPtr<GTableView> m_socket_table_view; RefPtr<GTableView> m_socket_table_view;
RefPtr<CTimer> m_update_timer; RefPtr<Core::Timer> m_update_timer;
}; };

View file

@ -73,7 +73,7 @@ ProcessMemoryMapWidget::ProcessMemoryMapWidget(GWidget* parent)
m_json_model = GJsonArrayModel::create({}, move(pid_vm_fields)); m_json_model = GJsonArrayModel::create({}, move(pid_vm_fields));
m_table_view->set_model(GSortingProxyModel::create(*m_json_model)); m_table_view->set_model(GSortingProxyModel::create(*m_json_model));
m_table_view->model()->set_key_column_and_sort_order(0, GSortOrder::Ascending); m_table_view->model()->set_key_column_and_sort_order(0, GSortOrder::Ascending);
m_timer = CTimer::construct(1000, [this] { refresh(); }, this); m_timer = Core::Timer::construct(1000, [this] { refresh(); }, this);
} }
ProcessMemoryMapWidget::~ProcessMemoryMapWidget() ProcessMemoryMapWidget::~ProcessMemoryMapWidget()

View file

@ -28,7 +28,10 @@
#include <LibGUI/GWidget.h> #include <LibGUI/GWidget.h>
class CTimer; namespace Core {
class Timer;
}
class GJsonArrayModel; class GJsonArrayModel;
class GTableView; class GTableView;
@ -45,5 +48,5 @@ private:
RefPtr<GTableView> m_table_view; RefPtr<GTableView> m_table_view;
RefPtr<GJsonArrayModel> m_json_model; RefPtr<GJsonArrayModel> m_json_model;
pid_t m_pid { -1 }; pid_t m_pid { -1 };
RefPtr<CTimer> m_timer; RefPtr<Core::Timer> m_timer;
}; };

View file

@ -335,7 +335,7 @@ GVariant ProcessModel::data(const GModelIndex& index, Role role) const
void ProcessModel::update() void ProcessModel::update()
{ {
auto all_processes = CProcessStatisticsReader::get_all(); auto all_processes = Core::ProcessStatisticsReader::get_all();
unsigned last_sum_times_scheduled = 0; unsigned last_sum_times_scheduled = 0;
for (auto& it : m_threads) for (auto& it : m_threads)

View file

@ -37,7 +37,7 @@ ProcessStacksWidget::ProcessStacksWidget(GWidget* parent)
m_stacks_editor = GTextEditor::construct(GTextEditor::Type::MultiLine, this); m_stacks_editor = GTextEditor::construct(GTextEditor::Type::MultiLine, this);
m_stacks_editor->set_readonly(true); m_stacks_editor->set_readonly(true);
m_timer = CTimer::construct(1000, [this] { refresh(); }, this); m_timer = Core::Timer::construct(1000, [this] { refresh(); }, this);
} }
ProcessStacksWidget::~ProcessStacksWidget() ProcessStacksWidget::~ProcessStacksWidget()
@ -54,8 +54,8 @@ void ProcessStacksWidget::set_pid(pid_t pid)
void ProcessStacksWidget::refresh() void ProcessStacksWidget::refresh()
{ {
auto file = CFile::construct(String::format("/proc/%d/stack", m_pid)); auto file = Core::File::construct(String::format("/proc/%d/stack", m_pid));
if (!file->open(CIODevice::ReadOnly)) { if (!file->open(Core::IODevice::ReadOnly)) {
m_stacks_editor->set_text(String::format("Unable to open %s", file->filename().characters())); m_stacks_editor->set_text(String::format("Unable to open %s", file->filename().characters()));
return; return;
} }

View file

@ -29,7 +29,9 @@
#include <LibGUI/GTextEditor.h> #include <LibGUI/GTextEditor.h>
#include <LibGUI/GWidget.h> #include <LibGUI/GWidget.h>
class CTimer; namespace Core {
class Timer;
}
class ProcessStacksWidget final : public GWidget { class ProcessStacksWidget final : public GWidget {
C_OBJECT(ProcessStacksWidget) C_OBJECT(ProcessStacksWidget)
@ -43,5 +45,5 @@ public:
private: private:
pid_t m_pid { -1 }; pid_t m_pid { -1 };
RefPtr<GTextEditor> m_stacks_editor; RefPtr<GTextEditor> m_stacks_editor;
RefPtr<CTimer> m_timer; RefPtr<Core::Timer> m_timer;
}; };

View file

@ -146,7 +146,7 @@ int main(int argc, char** argv)
toolbar->set_has_frame(false); toolbar->set_has_frame(false);
auto process_table_view = ProcessTableView::construct(process_table_container); auto process_table_view = ProcessTableView::construct(process_table_container);
auto refresh_timer = CTimer::construct(1000, [&] { auto refresh_timer = Core::Timer::construct(1000, [&] {
process_table_view->refresh(); process_table_view->refresh();
if (auto* memory_stats_widget = MemoryStatsWidget::the()) if (auto* memory_stats_widget = MemoryStatsWidget::the())
memory_stats_widget->refresh(); memory_stats_widget->refresh();

View file

@ -81,15 +81,15 @@ void TaskbarWindow::create_quick_launch_bar()
int total_width = 6; int total_width = 6;
bool first = true; bool first = true;
auto config = CConfigFile::get_for_app("Taskbar"); auto config = Core::ConfigFile::get_for_app("Taskbar");
constexpr const char* quick_launch = "QuickLaunch"; constexpr const char* quick_launch = "QuickLaunch";
// FIXME: CConfigFile does not keep the order of the entries. // FIXME: Core::ConfigFile does not keep the order of the entries.
for (auto& name : config->keys(quick_launch)) { for (auto& name : config->keys(quick_launch)) {
auto af_name = config->read_entry(quick_launch, name); auto af_name = config->read_entry(quick_launch, name);
ASSERT(!af_name.is_null()); ASSERT(!af_name.is_null());
auto af_path = String::format("/res/apps/%s", af_name.characters()); auto af_path = String::format("/res/apps/%s", af_name.characters());
auto af = CConfigFile::open(af_path); auto af = Core::ConfigFile::open(af_path);
auto app_executable = af->read_entry("App", "Executable"); auto app_executable = af->read_entry("App", "Executable");
auto app_icon_path = af->read_entry("Icons", "16x16"); auto app_icon_path = af->read_entry("Icons", "16x16");

View file

@ -195,7 +195,7 @@ int main(int argc, char** argv)
const char* command_to_execute = "/bin/Shell"; const char* command_to_execute = "/bin/Shell";
CArgsParser args_parser; Core::ArgsParser args_parser;
args_parser.add_option(command_to_execute, "Execute this command inside the terminal", nullptr, 'e', "command"); args_parser.add_option(command_to_execute, "Execute this command inside the terminal", nullptr, 'e', "command");
args_parser.parse(argc, argv); args_parser.parse(argc, argv);
@ -215,7 +215,7 @@ int main(int argc, char** argv)
window->set_background_color(Color::Black); window->set_background_color(Color::Black);
window->set_double_buffering_enabled(false); window->set_double_buffering_enabled(false);
RefPtr<CConfigFile> config = CConfigFile::get_for_app("Terminal"); RefPtr<Core::ConfigFile> config = Core::ConfigFile::get_for_app("Terminal");
auto terminal = TerminalWidget::construct(ptm_fd, true, config); auto terminal = TerminalWidget::construct(ptm_fd, true, config);
terminal->on_command_exit = [&] { terminal->on_command_exit = [&] {
app.quit(0); app.quit(0);

View file

@ -431,8 +431,8 @@ void TextEditorWidget::update_title()
void TextEditorWidget::open_sesame(const String& path) void TextEditorWidget::open_sesame(const String& path)
{ {
auto file = CFile::construct(path); auto file = Core::File::construct(path);
if (!file->open(CIODevice::ReadOnly)) { if (!file->open(Core::IODevice::ReadOnly)) {
GMessageBox::show(String::format("Opening \"%s\" failed: %s", path.characters(), strerror(errno)), "Error", GMessageBox::Type::Error, GMessageBox::InputType::OK, window()); GMessageBox::show(String::format("Opening \"%s\" failed: %s", path.characters(), strerror(errno)), "Error", GMessageBox::Type::Error, GMessageBox::InputType::OK, window());
return; return;
} }

View file

@ -101,7 +101,7 @@ private:
GLabel* stats; GLabel* stats;
virtual void paint_event(GPaintEvent&) override; virtual void paint_event(GPaintEvent&) override;
virtual void timer_event(CTimerEvent&) override; virtual void timer_event(Core::TimerEvent&) override;
virtual void mousedown_event(GMouseEvent& event) override; virtual void mousedown_event(GMouseEvent& event) override;
virtual void mousemove_event(GMouseEvent& event) override; virtual void mousemove_event(GMouseEvent& event) override;
virtual void mouseup_event(GMouseEvent& event) override; virtual void mouseup_event(GMouseEvent& event) override;
@ -148,7 +148,7 @@ Fire::~Fire()
void Fire::paint_event(GPaintEvent& event) void Fire::paint_event(GPaintEvent& event)
{ {
CElapsedTimer timer; Core::ElapsedTimer timer;
timer.start(); timer.start();
GPainter painter(*this); GPainter painter(*this);
@ -161,7 +161,7 @@ void Fire::paint_event(GPaintEvent& event)
cycles++; cycles++;
} }
void Fire::timer_event(CTimerEvent&) void Fire::timer_event(Core::TimerEvent&)
{ {
/* Update only even or odd columns per frame... */ /* Update only even or odd columns per frame... */
phase++; phase++;

View file

@ -70,7 +70,7 @@ int main(int argc, char** argv)
button2->set_enabled(false); button2->set_enabled(false);
auto progress1 = GProgressBar::construct(main_widget); auto progress1 = GProgressBar::construct(main_widget);
auto timer = CTimer::construct(100, [&] { auto timer = Core::Timer::construct(100, [&] {
progress1->set_value(progress1->value() + 1); progress1->set_value(progress1->value() + 1);
if (progress1->value() == progress1->max()) if (progress1->value() == progress1->max())
progress1->set_value(progress1->min()); progress1->set_value(progress1->min());

View file

@ -39,8 +39,8 @@ int main(int argc, char** argv)
return 0; return 0;
} }
auto file = CFile::construct(argv[1]); auto file = Core::File::construct(argv[1]);
if (!file->open(CIODevice::ReadOnly)) { if (!file->open(Core::IODevice::ReadOnly)) {
fprintf(stderr, "Error: Cannot open %s: %s\n", argv[1], file->error_string()); fprintf(stderr, "Error: Cannot open %s: %s\n", argv[1], file->error_string());
return 1; return 1;
} }

View file

@ -67,7 +67,7 @@ const EditorWrapper& Editor::wrapper() const
return static_cast<const EditorWrapper&>(*parent()); return static_cast<const EditorWrapper&>(*parent());
} }
void Editor::focusin_event(CEvent& event) void Editor::focusin_event(Core::Event& event)
{ {
wrapper().set_editor_has_focus({}, true); wrapper().set_editor_has_focus({}, true);
if (on_focus) if (on_focus)
@ -75,7 +75,7 @@ void Editor::focusin_event(CEvent& event)
GTextEditor::focusin_event(event); GTextEditor::focusin_event(event);
} }
void Editor::focusout_event(CEvent& event) void Editor::focusout_event(Core::Event& event)
{ {
wrapper().set_editor_has_focus({}, false); wrapper().set_editor_has_focus({}, false);
GTextEditor::focusout_event(event); GTextEditor::focusout_event(event);
@ -103,7 +103,7 @@ static HashMap<String, String>& man_paths()
static HashMap<String, String> paths; static HashMap<String, String> paths;
if (paths.is_empty()) { if (paths.is_empty()) {
// FIXME: This should also search man3, possibly other places.. // FIXME: This should also search man3, possibly other places..
CDirIterator it("/usr/share/man/man2", CDirIterator::Flags::SkipDots); Core::DirIterator it("/usr/share/man/man2", Core::DirIterator::Flags::SkipDots);
while (it.has_next()) { while (it.has_next()) {
auto path = String::format("/usr/share/man/man2/%s", it.next_path().characters()); auto path = String::format("/usr/share/man/man2/%s", it.next_path().characters());
auto title = FileSystemPath(path).title(); auto title = FileSystemPath(path).title();
@ -132,8 +132,8 @@ void Editor::show_documentation_tooltip_if_available(const String& hovered_token
#ifdef EDITOR_DEBUG #ifdef EDITOR_DEBUG
dbg() << "opening " << it->value; dbg() << "opening " << it->value;
#endif #endif
auto file = CFile::construct(it->value); auto file = Core::File::construct(it->value);
if (!file->open(CFile::ReadOnly)) { if (!file->open(Core::File::ReadOnly)) {
dbg() << "failed to open " << it->value << " " << file->error_string(); dbg() << "failed to open " << it->value << " " << file->error_string();
return; return;
} }

View file

@ -44,8 +44,8 @@ public:
void notify_did_rehighlight(); void notify_did_rehighlight();
private: private:
virtual void focusin_event(CEvent&) override; virtual void focusin_event(Core::Event&) override;
virtual void focusout_event(CEvent&) override; virtual void focusout_event(Core::Event&) override;
virtual void paint_event(GPaintEvent&) override; virtual void paint_event(GPaintEvent&) override;
virtual void mousemove_event(GMouseEvent&) override; virtual void mousemove_event(GMouseEvent&) override;
virtual void cursor_did_change() override; virtual void cursor_did_change() override;

View file

@ -52,7 +52,7 @@ private:
}; };
template<> template<>
inline bool is<EditorWrapper>(const CObject& object) inline bool Core::is<EditorWrapper>(const Core::Object& object)
{ {
return !strcmp(object.class_name(), "EditorWrapper"); return !strcmp(object.class_name(), "EditorWrapper");
} }

View file

@ -57,7 +57,7 @@ ProcessStateWidget::ProcessStateWidget(GWidget* parent)
memory_label_label->set_font(Font::default_bold_font()); memory_label_label->set_font(Font::default_bold_font());
m_memory_label = GLabel::construct("", this); m_memory_label = GLabel::construct("", this);
m_timer = CTimer::construct(500, [this] { m_timer = Core::Timer::construct(500, [this] {
refresh(); refresh();
}); });
} }
@ -70,7 +70,7 @@ void ProcessStateWidget::refresh()
{ {
pid_t pid = tcgetpgrp(m_tty_fd); pid_t pid = tcgetpgrp(m_tty_fd);
auto processes = CProcessStatisticsReader::get_all(); auto processes = Core::ProcessStatisticsReader::get_all();
auto child_process_data = processes.get(pid); auto child_process_data = processes.get(pid);
if (!child_process_data.has_value()) if (!child_process_data.has_value())

View file

@ -28,7 +28,10 @@
#include <LibGUI/GWidget.h> #include <LibGUI/GWidget.h>
class CTimer; namespace Core {
class Timer;
}
class GLabel; class GLabel;
class ProcessStateWidget final : public GWidget { class ProcessStateWidget final : public GWidget {
@ -48,7 +51,7 @@ private:
RefPtr<GLabel> m_cpu_label; RefPtr<GLabel> m_cpu_label;
RefPtr<GLabel> m_memory_label; RefPtr<GLabel> m_memory_label;
RefPtr<CTimer> m_timer; RefPtr<Core::Timer> m_timer;
int m_tty_fd { -1 }; int m_tty_fd { -1 };
}; };

View file

@ -190,8 +190,8 @@ Project::~Project()
OwnPtr<Project> Project::load_from_file(const String& path) OwnPtr<Project> Project::load_from_file(const String& path)
{ {
auto file = CFile::construct(path); auto file = Core::File::construct(path);
if (!file->open(CFile::ReadOnly)) if (!file->open(Core::File::ReadOnly))
return nullptr; return nullptr;
Vector<String> files; Vector<String> files;
@ -225,12 +225,12 @@ bool Project::remove_file(const String& filename)
bool Project::save() bool Project::save()
{ {
auto project_file = CFile::construct(m_path); auto project_file = Core::File::construct(m_path);
if (!project_file->open(CFile::WriteOnly)) if (!project_file->open(Core::File::WriteOnly))
return false; return false;
for (auto& file : m_files) { for (auto& file : m_files) {
// FIXME: Check for error here. CIODevice::printf() needs some work on error reporting. // FIXME: Check for error here. IODevice::printf() needs some work on error reporting.
project_file->printf("%s\n", file.name().characters()); project_file->printf("%s\n", file.name().characters());
} }

View file

@ -32,8 +32,8 @@ const GTextDocument& ProjectFile::document() const
{ {
if (!m_document) { if (!m_document) {
m_document = GTextDocument::create(nullptr); m_document = GTextDocument::create(nullptr);
auto file = CFile::construct(m_name); auto file = Core::File::construct(m_name);
if (!file->open(CFile::ReadOnly)) { if (!file->open(Core::File::ReadOnly)) {
ASSERT_NOT_REACHED(); ASSERT_NOT_REACHED();
} }
m_document->set_text(file->read_all()); m_document->set_text(file->read_all());

View file

@ -163,7 +163,7 @@ TerminalWrapper::TerminalWrapper(GWidget* parent)
{ {
set_layout(make<GVBoxLayout>()); set_layout(make<GVBoxLayout>());
RefPtr<CConfigFile> config = CConfigFile::get_for_app("Terminal"); RefPtr<Core::ConfigFile> config = Core::ConfigFile::get_for_app("Terminal");
m_terminal_widget = TerminalWidget::construct(-1, false, config); m_terminal_widget = TerminalWidget::construct(-1, false, config);
add_child(*m_terminal_widget); add_child(*m_terminal_widget);

View file

@ -180,8 +180,8 @@ int main(int argc, char** argv)
if (input_box->exec() == GInputBox::ExecCancel) if (input_box->exec() == GInputBox::ExecCancel)
return; return;
auto filename = input_box->text_value(); auto filename = input_box->text_value();
auto file = CFile::construct(filename); auto file = Core::File::construct(filename);
if (!file->open((CIODevice::OpenMode)(CIODevice::WriteOnly | CIODevice::MustBeNew))) { if (!file->open((Core::IODevice::OpenMode)(Core::IODevice::WriteOnly | Core::IODevice::MustBeNew))) {
GMessageBox::show(String::format("Failed to create '%s'", filename.characters()), "Error", GMessageBox::Type::Error, GMessageBox::InputType::OK, g_window); GMessageBox::show(String::format("Failed to create '%s'", filename.characters()), "Error", GMessageBox::Type::Error, GMessageBox::InputType::OK, g_window);
return; return;
} }

View file

@ -66,8 +66,8 @@ int main(int argc, char** argv)
return 0; return 0;
} }
auto file = CFile::construct(argv[1]); auto file = Core::File::construct(argv[1]);
if (!file->open(CIODevice::ReadOnly)) { if (!file->open(Core::IODevice::ReadOnly)) {
fprintf(stderr, "Error: Cannot open %s: %s\n", argv[1], file->error_string()); fprintf(stderr, "Error: Cannot open %s: %s\n", argv[1], file->error_string());
return 1; return 1;
} }

View file

@ -34,7 +34,7 @@
RemoteProcess::RemoteProcess(pid_t pid) RemoteProcess::RemoteProcess(pid_t pid)
: m_pid(pid) : m_pid(pid)
, m_object_graph_model(RemoteObjectGraphModel::create(*this)) , m_object_graph_model(RemoteObjectGraphModel::create(*this))
, m_socket(CLocalSocket::construct()) , m_socket(Core::LocalSocket::construct())
{ {
} }
@ -152,7 +152,7 @@ void RemoteProcess::update()
} }
}; };
auto success = m_socket->connect(CSocketAddress::local(String::format("/tmp/rpc.%d", m_pid))); auto success = m_socket->connect(Core::SocketAddress::local(String::format("/tmp/rpc.%d", m_pid)));
if (!success) { if (!success) {
fprintf(stderr, "Couldn't connect to PID %d\n", m_pid); fprintf(stderr, "Couldn't connect to PID %d\n", m_pid);
exit(1); exit(1);

View file

@ -58,6 +58,6 @@ private:
pid_t m_pid { -1 }; pid_t m_pid { -1 };
String m_process_name; String m_process_name;
NonnullRefPtr<RemoteObjectGraphModel> m_object_graph_model; NonnullRefPtr<RemoteObjectGraphModel> m_object_graph_model;
RefPtr<CLocalSocket> m_socket; RefPtr<Core::LocalSocket> m_socket;
NonnullOwnPtrVector<RemoteObject> m_roots; NonnullOwnPtrVector<RemoteObject> m_roots;
}; };

View file

@ -157,8 +157,8 @@ void Profile::rebuild_tree()
OwnPtr<Profile> Profile::load_from_file(const StringView& path) OwnPtr<Profile> Profile::load_from_file(const StringView& path)
{ {
auto file = CFile::construct(path); auto file = Core::File::construct(path);
if (!file->open(CIODevice::ReadOnly)) { if (!file->open(Core::IODevice::ReadOnly)) {
fprintf(stderr, "Unable to open %s, error: %s\n", String(path).characters(), file->error_string()); fprintf(stderr, "Unable to open %s, error: %s\n", String(path).characters(), file->error_string());
return nullptr; return nullptr;
} }

View file

@ -381,8 +381,8 @@ void VBForm::mousemove_event(GMouseEvent& event)
void VBForm::load_from_file(const String& path) void VBForm::load_from_file(const String& path)
{ {
auto file = CFile::construct(path); auto file = Core::File::construct(path);
if (!file->open(CIODevice::ReadOnly)) { if (!file->open(Core::IODevice::ReadOnly)) {
GMessageBox::show(String::format("Could not open '%s' for reading", path.characters()), "Error", GMessageBox::Type::Error, GMessageBox::InputType::OK, window()); GMessageBox::show(String::format("Could not open '%s' for reading", path.characters()), "Error", GMessageBox::Type::Error, GMessageBox::InputType::OK, window());
return; return;
} }
@ -417,8 +417,8 @@ void VBForm::load_from_file(const String& path)
void VBForm::write_to_file(const String& path) void VBForm::write_to_file(const String& path)
{ {
auto file = CFile::construct(path); auto file = Core::File::construct(path);
if (!file->open(CIODevice::WriteOnly)) { if (!file->open(Core::IODevice::WriteOnly)) {
GMessageBox::show(String::format("Could not open '%s' for writing", path.characters()), "Error", GMessageBox::Type::Error, GMessageBox::InputType::OK, window()); GMessageBox::show(String::format("Could not open '%s' for writing", path.characters()), "Error", GMessageBox::Type::Error, GMessageBox::InputType::OK, window());
return; return;
} }

View file

@ -138,7 +138,7 @@ void VBWidget::add_property(const String& name, Function<GVariant(const GWidget&
void VBWidget::setup_properties() void VBWidget::setup_properties()
{ {
VB_ADD_PROPERTY(CObject, "name", name, set_name, string); VB_ADD_PROPERTY(Core::Object, "name", name, set_name, string);
VB_ADD_PROPERTY(GWidget, "width", width, set_width, i32); VB_ADD_PROPERTY(GWidget, "width", width, set_width, i32);
VB_ADD_PROPERTY(GWidget, "height", height, set_height, i32); VB_ADD_PROPERTY(GWidget, "height", height, set_height, i32);

View file

@ -127,7 +127,7 @@ Field::Field(GLabel& flag_label, GLabel& time_label, GButton& face_button, GWidg
, m_on_size_changed(move(on_size_changed)) , m_on_size_changed(move(on_size_changed))
{ {
srand(time(nullptr)); srand(time(nullptr));
m_timer = CTimer::construct(); m_timer = Core::Timer::construct();
m_timer->on_timeout = [this] { m_timer->on_timeout = [this] {
++m_time_elapsed; ++m_time_elapsed;
m_time_label.set_text(String::format("%u.%u", m_time_elapsed / 10, m_time_elapsed % 10)); m_time_label.set_text(String::format("%u.%u", m_time_elapsed / 10, m_time_elapsed % 10));
@ -153,7 +153,7 @@ Field::Field(GLabel& flag_label, GLabel& time_label, GButton& face_button, GWidg
set_face(Face::Default); set_face(Face::Default);
{ {
auto config = CConfigFile::get_for_app("Minesweeper"); auto config = Core::ConfigFile::get_for_app("Minesweeper");
bool single_chording = config->read_num_entry("Minesweeper", "SingleChording", false); bool single_chording = config->read_num_entry("Minesweeper", "SingleChording", false);
int mine_count = config->read_num_entry("Game", "MineCount", 10); int mine_count = config->read_num_entry("Game", "MineCount", 10);
int rows = config->read_num_entry("Game", "Rows", 9); int rows = config->read_num_entry("Game", "Rows", 9);
@ -497,7 +497,7 @@ void Field::set_field_size(int rows, int columns, int mine_count)
if (m_rows == rows && m_columns == columns && m_mine_count == mine_count) if (m_rows == rows && m_columns == columns && m_mine_count == mine_count)
return; return;
{ {
auto config = CConfigFile::get_for_app("Minesweeper"); auto config = Core::ConfigFile::get_for_app("Minesweeper");
config->write_num_entry("Game", "MineCount", mine_count); config->write_num_entry("Game", "MineCount", mine_count);
config->write_num_entry("Game", "Rows", rows); config->write_num_entry("Game", "Rows", rows);
config->write_num_entry("Game", "Columns", columns); config->write_num_entry("Game", "Columns", columns);
@ -511,7 +511,7 @@ void Field::set_field_size(int rows, int columns, int mine_count)
} }
void Field::set_single_chording(bool enabled) { void Field::set_single_chording(bool enabled) {
auto config = CConfigFile::get_for_app("Minesweeper"); auto config = Core::ConfigFile::get_for_app("Minesweeper");
m_single_chording = enabled; m_single_chording = enabled;
config->write_bool_entry("Minesweeper", "SingleChording", m_single_chording); config->write_bool_entry("Minesweeper", "SingleChording", m_single_chording);
} }

View file

@ -121,7 +121,7 @@ private:
GButton& m_face_button; GButton& m_face_button;
GLabel& m_flag_label; GLabel& m_flag_label;
GLabel& m_time_label; GLabel& m_time_label;
RefPtr<CTimer> m_timer; RefPtr<Core::Timer> m_timer;
int m_time_elapsed { 0 }; int m_time_elapsed { 0 };
int m_flags_left { 0 }; int m_flags_left { 0 };
Face m_face { Face::Default }; Face m_face { Face::Default };

View file

@ -102,7 +102,7 @@ Rect SnakeGame::high_score_rect() const
return { 2, height() - font().glyph_height() - 2, high_score_width, font().glyph_height() }; return { 2, height() - font().glyph_height() - 2, high_score_width, font().glyph_height() };
} }
void SnakeGame::timer_event(CTimerEvent&) void SnakeGame::timer_event(Core::TimerEvent&)
{ {
Vector<Coordinate> dirty_cells; Vector<Coordinate> dirty_cells;

View file

@ -41,7 +41,7 @@ private:
explicit SnakeGame(GWidget* parent = nullptr); explicit SnakeGame(GWidget* parent = nullptr);
virtual void paint_event(GPaintEvent&) override; virtual void paint_event(GPaintEvent&) override;
virtual void keydown_event(GKeyEvent&) override; virtual void keydown_event(GKeyEvent&) override;
virtual void timer_event(CTimerEvent&) override; virtual void timer_event(Core::TimerEvent&) override;
struct Coordinate { struct Coordinate {
int row { 0 }; int row { 0 };

View file

@ -31,9 +31,9 @@
#include <limits> #include <limits>
AWavLoader::AWavLoader(const StringView& path) AWavLoader::AWavLoader(const StringView& path)
: m_file(CFile::construct(path)) : m_file(Core::File::construct(path))
{ {
if (!m_file->open(CIODevice::ReadOnly)) { if (!m_file->open(Core::IODevice::ReadOnly)) {
m_error_string = String::format("Can't open file: %s", m_file->error_string()); m_error_string = String::format("Can't open file: %s", m_file->error_string());
return; return;
} }
@ -75,7 +75,7 @@ void AWavLoader::reset()
bool AWavLoader::parse_header() bool AWavLoader::parse_header()
{ {
CIODeviceStreamReader stream(*m_file); Core::IODeviceStreamReader stream(*m_file);
#define CHECK_OK(msg) \ #define CHECK_OK(msg) \
do { \ do { \

View file

@ -56,11 +56,11 @@ public:
u32 sample_rate() const { return m_sample_rate; } u32 sample_rate() const { return m_sample_rate; }
u16 num_channels() const { return m_num_channels; } u16 num_channels() const { return m_num_channels; }
u16 bits_per_sample() const { return m_bits_per_sample; } u16 bits_per_sample() const { return m_bits_per_sample; }
RefPtr<CFile> file() const { return m_file; } RefPtr<Core::File> file() const { return m_file; }
private: private:
bool parse_header(); bool parse_header();
RefPtr<CFile> m_file; RefPtr<Core::File> m_file;
String m_error_string; String m_error_string;
OwnPtr<AResampleHelper> m_resampler; OwnPtr<AResampleHelper> m_resampler;

View file

@ -30,12 +30,14 @@
#include <limits.h> #include <limits.h>
#include <stdio.h> #include <stdio.h>
CArgsParser::CArgsParser() namespace Core {
ArgsParser::ArgsParser()
{ {
add_option(m_show_help, "Display this message", "help", 0); add_option(m_show_help, "Display this message", "help", 0);
} }
void CArgsParser::parse(int argc, char** argv) void ArgsParser::parse(int argc, char** argv)
{ {
auto print_usage_and_exit = [this, argv] { auto print_usage_and_exit = [this, argv] {
print_usage(stderr, argv[0]); print_usage(stderr, argv[0]);
@ -148,7 +150,7 @@ void CArgsParser::parse(int argc, char** argv)
} }
} }
void CArgsParser::print_usage(FILE* file, const char* argv0) void ArgsParser::print_usage(FILE* file, const char* argv0)
{ {
fprintf(file, "Usage:\n\t%s", argv0); fprintf(file, "Usage:\n\t%s", argv0);
@ -214,12 +216,12 @@ void CArgsParser::print_usage(FILE* file, const char* argv0)
} }
} }
void CArgsParser::add_option(Option&& option) void ArgsParser::add_option(Option&& option)
{ {
m_options.append(move(option)); m_options.append(move(option));
} }
void CArgsParser::add_option(bool& value, const char* help_string, const char* long_name, char short_name) void ArgsParser::add_option(bool& value, const char* help_string, const char* long_name, char short_name)
{ {
Option option { Option option {
false, false,
@ -236,7 +238,7 @@ void CArgsParser::add_option(bool& value, const char* help_string, const char* l
add_option(move(option)); add_option(move(option));
} }
void CArgsParser::add_option(const char*& value, const char* help_string, const char* long_name, char short_name, const char* value_name) void ArgsParser::add_option(const char*& value, const char* help_string, const char* long_name, char short_name, const char* value_name)
{ {
Option option { Option option {
true, true,
@ -252,7 +254,7 @@ void CArgsParser::add_option(const char*& value, const char* help_string, const
add_option(move(option)); add_option(move(option));
} }
void CArgsParser::add_option(int& value, const char* help_string, const char* long_name, char short_name, const char* value_name) void ArgsParser::add_option(int& value, const char* help_string, const char* long_name, char short_name, const char* value_name)
{ {
Option option { Option option {
true, true,
@ -269,12 +271,12 @@ void CArgsParser::add_option(int& value, const char* help_string, const char* lo
add_option(move(option)); add_option(move(option));
} }
void CArgsParser::add_positional_argument(Arg&& arg) void ArgsParser::add_positional_argument(Arg&& arg)
{ {
m_positional_args.append(move(arg)); m_positional_args.append(move(arg));
} }
void CArgsParser::add_positional_argument(const char*& value, const char* help_string, const char* name, Required required) void ArgsParser::add_positional_argument(const char*& value, const char* help_string, const char* name, Required required)
{ {
Arg arg { Arg arg {
help_string, help_string,
@ -289,7 +291,7 @@ void CArgsParser::add_positional_argument(const char*& value, const char* help_s
add_positional_argument(move(arg)); add_positional_argument(move(arg));
} }
void CArgsParser::add_positional_argument(int& value, const char* help_string, const char* name, Required required) void ArgsParser::add_positional_argument(int& value, const char* help_string, const char* name, Required required)
{ {
Arg arg { Arg arg {
help_string, help_string,
@ -305,7 +307,7 @@ void CArgsParser::add_positional_argument(int& value, const char* help_string, c
add_positional_argument(move(arg)); add_positional_argument(move(arg));
} }
void CArgsParser::add_positional_argument(Vector<const char*>& values, const char* help_string, const char* name, Required required) void ArgsParser::add_positional_argument(Vector<const char*>& values, const char* help_string, const char* name, Required required)
{ {
Arg arg { Arg arg {
help_string, help_string,
@ -319,3 +321,5 @@ void CArgsParser::add_positional_argument(Vector<const char*>& values, const cha
}; };
add_positional_argument(move(arg)); add_positional_argument(move(arg));
} }
}

View file

@ -31,9 +31,11 @@
#include <AK/Vector.h> #include <AK/Vector.h>
#include <stdio.h> #include <stdio.h>
class CArgsParser { namespace Core {
class ArgsParser {
public: public:
CArgsParser(); ArgsParser();
enum class Required { enum class Required {
Yes, Yes,
@ -83,3 +85,5 @@ private:
bool m_show_help { false }; bool m_show_help { false };
}; };
}

View file

@ -32,43 +32,45 @@
#include <stdio.h> #include <stdio.h>
#include <unistd.h> #include <unistd.h>
NonnullRefPtr<CConfigFile> CConfigFile::get_for_app(const String& app_name) namespace Core {
NonnullRefPtr<ConfigFile> ConfigFile::get_for_app(const String& app_name)
{ {
String home_path = get_current_user_home_path(); String home_path = get_current_user_home_path();
if (home_path == "/") if (home_path == "/")
home_path = String::format("/tmp"); home_path = String::format("/tmp");
auto path = String::format("%s/%s.ini", home_path.characters(), app_name.characters()); auto path = String::format("%s/%s.ini", home_path.characters(), app_name.characters());
return adopt(*new CConfigFile(path)); return adopt(*new ConfigFile(path));
} }
NonnullRefPtr<CConfigFile> CConfigFile::get_for_system(const String& app_name) NonnullRefPtr<ConfigFile> ConfigFile::get_for_system(const String& app_name)
{ {
auto path = String::format("/etc/%s.ini", app_name.characters()); auto path = String::format("/etc/%s.ini", app_name.characters());
return adopt(*new CConfigFile(path)); return adopt(*new ConfigFile(path));
} }
NonnullRefPtr<CConfigFile> CConfigFile::open(const String& path) NonnullRefPtr<ConfigFile> ConfigFile::open(const String& path)
{ {
return adopt(*new CConfigFile(path)); return adopt(*new ConfigFile(path));
} }
CConfigFile::CConfigFile(const String& file_name) ConfigFile::ConfigFile(const String& file_name)
: m_file_name(file_name) : m_file_name(file_name)
{ {
reparse(); reparse();
} }
CConfigFile::~CConfigFile() ConfigFile::~ConfigFile()
{ {
sync(); sync();
} }
void CConfigFile::reparse() void ConfigFile::reparse()
{ {
m_groups.clear(); m_groups.clear();
auto file = CFile::construct(m_file_name); auto file = File::construct(m_file_name);
if (!file->open(CIODevice::OpenMode::ReadOnly)) if (!file->open(IODevice::OpenMode::ReadOnly))
return; return;
HashMap<String, String>* current_group = nullptr; HashMap<String, String>* current_group = nullptr;
@ -111,10 +113,10 @@ void CConfigFile::reparse()
} }
} }
String CConfigFile::read_entry(const String& group, const String& key, const String& default_value) const String ConfigFile::read_entry(const String& group, const String& key, const String& default_value) const
{ {
if (!has_key(group, key)) { if (!has_key(group, key)) {
const_cast<CConfigFile&>(*this).write_entry(group, key, default_value); const_cast<ConfigFile&>(*this).write_entry(group, key, default_value);
return default_value; return default_value;
} }
auto it = m_groups.find(group); auto it = m_groups.find(group);
@ -122,10 +124,10 @@ String CConfigFile::read_entry(const String& group, const String& key, const Str
return jt->value; return jt->value;
} }
int CConfigFile::read_num_entry(const String& group, const String& key, int default_value) const int ConfigFile::read_num_entry(const String& group, const String& key, int default_value) const
{ {
if (!has_key(group, key)) { if (!has_key(group, key)) {
const_cast<CConfigFile&>(*this).write_num_entry(group, key, default_value); const_cast<ConfigFile&>(*this).write_num_entry(group, key, default_value);
return default_value; return default_value;
} }
@ -136,31 +138,31 @@ int CConfigFile::read_num_entry(const String& group, const String& key, int defa
return value; return value;
} }
bool CConfigFile::read_bool_entry(const String& group, const String& key, bool default_value) const bool ConfigFile::read_bool_entry(const String& group, const String& key, bool default_value) const
{ {
return read_entry(group, key, default_value ? "1" : "0") == "1"; return read_entry(group, key, default_value ? "1" : "0") == "1";
} }
void CConfigFile::write_entry(const String& group, const String& key, const String& value) void ConfigFile::write_entry(const String& group, const String& key, const String& value)
{ {
m_groups.ensure(group).ensure(key) = value; m_groups.ensure(group).ensure(key) = value;
m_dirty = true; m_dirty = true;
} }
void CConfigFile::write_num_entry(const String& group, const String& key, int value) void ConfigFile::write_num_entry(const String& group, const String& key, int value)
{ {
write_entry(group, key, String::number(value)); write_entry(group, key, String::number(value));
} }
void CConfigFile::write_bool_entry(const String& group, const String& key, bool value) void ConfigFile::write_bool_entry(const String& group, const String& key, bool value)
{ {
write_entry(group, key, value ? "1" : "0"); write_entry(group, key, value ? "1" : "0");
} }
void CConfigFile::write_color_entry(const String& group, const String& key, Color value) void ConfigFile::write_color_entry(const String& group, const String& key, Color value)
{ {
write_entry(group, key, String::format("%d,%d,%d,%d", value.red(), value.green(), value.blue(), value.alpha())); write_entry(group, key, String::format("%d,%d,%d,%d", value.red(), value.green(), value.blue(), value.alpha()));
} }
bool CConfigFile::sync() bool ConfigFile::sync()
{ {
if (!m_dirty) if (!m_dirty)
return true; return true;
@ -182,7 +184,7 @@ bool CConfigFile::sync()
return true; return true;
} }
void CConfigFile::dump() const void ConfigFile::dump() const
{ {
for (auto& it : m_groups) { for (auto& it : m_groups) {
printf("[%s]\n", it.key.characters()); printf("[%s]\n", it.key.characters());
@ -192,12 +194,12 @@ void CConfigFile::dump() const
} }
} }
Vector<String> CConfigFile::groups() const Vector<String> ConfigFile::groups() const
{ {
return m_groups.keys(); return m_groups.keys();
} }
Vector<String> CConfigFile::keys(const String& group) const Vector<String> ConfigFile::keys(const String& group) const
{ {
auto it = m_groups.find(group); auto it = m_groups.find(group);
if (it == m_groups.end()) if (it == m_groups.end())
@ -205,7 +207,7 @@ Vector<String> CConfigFile::keys(const String& group) const
return it->value.keys(); return it->value.keys();
} }
bool CConfigFile::has_key(const String& group, const String& key) const bool ConfigFile::has_key(const String& group, const String& key) const
{ {
auto it = m_groups.find(group); auto it = m_groups.find(group);
if (it == m_groups.end()) if (it == m_groups.end())
@ -213,18 +215,18 @@ bool CConfigFile::has_key(const String& group, const String& key) const
return it->value.contains(key); return it->value.contains(key);
} }
bool CConfigFile::has_group(const String& group) const bool ConfigFile::has_group(const String& group) const
{ {
return m_groups.contains(group); return m_groups.contains(group);
} }
void CConfigFile::remove_group(const String& group) void ConfigFile::remove_group(const String& group)
{ {
m_groups.remove(group); m_groups.remove(group);
m_dirty = true; m_dirty = true;
} }
void CConfigFile::remove_entry(const String& group, const String& key) void ConfigFile::remove_entry(const String& group, const String& key)
{ {
auto it = m_groups.find(group); auto it = m_groups.find(group);
if (it == m_groups.end()) if (it == m_groups.end())
@ -232,3 +234,5 @@ void CConfigFile::remove_entry(const String& group, const String& key)
it->value.remove(key); it->value.remove(key);
m_dirty = true; m_dirty = true;
} }
}

View file

@ -26,19 +26,21 @@
#pragma once #pragma once
#include <AK/String.h>
#include <AK/HashMap.h> #include <AK/HashMap.h>
#include <AK/RefPtr.h>
#include <AK/RefCounted.h> #include <AK/RefCounted.h>
#include <AK/RefPtr.h>
#include <AK/String.h>
#include <AK/Vector.h> #include <AK/Vector.h>
#include <LibDraw/Color.h> #include <LibDraw/Color.h>
class CConfigFile : public RefCounted<CConfigFile> { namespace Core {
class ConfigFile : public RefCounted<ConfigFile> {
public: public:
static NonnullRefPtr<CConfigFile> get_for_app(const String& app_name); static NonnullRefPtr<ConfigFile> get_for_app(const String& app_name);
static NonnullRefPtr<CConfigFile> get_for_system(const String& app_name); static NonnullRefPtr<ConfigFile> get_for_system(const String& app_name);
static NonnullRefPtr<CConfigFile> open(const String& path); static NonnullRefPtr<ConfigFile> open(const String& path);
~CConfigFile(); ~ConfigFile();
bool has_group(const String&) const; bool has_group(const String&) const;
bool has_key(const String& group, const String& key) const; bool has_key(const String& group, const String& key) const;
@ -67,7 +69,7 @@ public:
String file_name() const { return m_file_name; } String file_name() const { return m_file_name; }
private: private:
explicit CConfigFile(const String& file_name); explicit ConfigFile(const String& file_name);
void reparse(); void reparse();
@ -75,3 +77,5 @@ private:
HashMap<String, HashMap<String, String>> m_groups; HashMap<String, HashMap<String, String>> m_groups;
bool m_dirty { false }; bool m_dirty { false };
}; };
}

View file

@ -25,9 +25,11 @@
*/ */
#include "CDirIterator.h" #include "CDirIterator.h"
#include <cerrno> #include <errno.h>
CDirIterator::CDirIterator(const StringView& path, Flags flags) namespace Core {
DirIterator::DirIterator(const StringView& path, Flags flags)
: m_flags(flags) : m_flags(flags)
{ {
m_dir = opendir(String(path).characters()); m_dir = opendir(String(path).characters());
@ -36,7 +38,7 @@ CDirIterator::CDirIterator(const StringView& path, Flags flags)
} }
} }
CDirIterator::~CDirIterator() DirIterator::~DirIterator()
{ {
if (m_dir != nullptr) { if (m_dir != nullptr) {
closedir(m_dir); closedir(m_dir);
@ -44,7 +46,7 @@ CDirIterator::~CDirIterator()
} }
} }
bool CDirIterator::advance_next() bool DirIterator::advance_next()
{ {
if (m_dir == nullptr) if (m_dir == nullptr)
return false; return false;
@ -74,7 +76,7 @@ bool CDirIterator::advance_next()
return m_next.length() > 0; return m_next.length() > 0;
} }
bool CDirIterator::has_next() bool DirIterator::has_next()
{ {
if (!m_next.is_null()) if (!m_next.is_null())
return true; return true;
@ -82,7 +84,7 @@ bool CDirIterator::has_next()
return advance_next(); return advance_next();
} }
String CDirIterator::next_path() String DirIterator::next_path()
{ {
if (m_next.is_null()) if (m_next.is_null())
advance_next(); advance_next();
@ -91,3 +93,5 @@ String CDirIterator::next_path()
m_next = String(); m_next = String();
return tmp; return tmp;
} }
}

View file

@ -29,15 +29,17 @@
#include <AK/String.h> #include <AK/String.h>
#include <dirent.h> #include <dirent.h>
class CDirIterator { namespace Core {
class DirIterator {
public: public:
enum Flags { enum Flags {
NoFlags = 0x0, NoFlags = 0x0,
SkipDots = 0x1, SkipDots = 0x1,
}; };
CDirIterator(const StringView& path, Flags = Flags::NoFlags); DirIterator(const StringView& path, Flags = Flags::NoFlags);
~CDirIterator(); ~DirIterator();
bool has_error() const { return m_error != 0; } bool has_error() const { return m_error != 0; }
int error() const { return m_error; } int error() const { return m_error; }
@ -53,3 +55,5 @@ private:
bool advance_next(); bool advance_next();
}; };
}

View file

@ -29,13 +29,15 @@
#include <LibCore/CElapsedTimer.h> #include <LibCore/CElapsedTimer.h>
#include <sys/time.h> #include <sys/time.h>
void CElapsedTimer::start() namespace Core {
void ElapsedTimer::start()
{ {
m_valid = true; m_valid = true;
gettimeofday(&m_start_time, nullptr); gettimeofday(&m_start_time, nullptr);
} }
int CElapsedTimer::elapsed() const int ElapsedTimer::elapsed() const
{ {
ASSERT(is_valid()); ASSERT(is_valid());
struct timeval now; struct timeval now;
@ -44,3 +46,5 @@ int CElapsedTimer::elapsed() const
timeval_sub(now, m_start_time, diff); timeval_sub(now, m_start_time, diff);
return diff.tv_sec * 1000 + diff.tv_usec / 1000; return diff.tv_sec * 1000 + diff.tv_usec / 1000;
} }
}

View file

@ -28,9 +28,11 @@
#include <sys/time.h> #include <sys/time.h>
class CElapsedTimer { namespace Core {
class ElapsedTimer {
public: public:
CElapsedTimer() {} ElapsedTimer() {}
bool is_valid() const { return m_valid; } bool is_valid() const { return m_valid; }
void start(); void start();
@ -42,3 +44,5 @@ private:
0, 0 0, 0
}; };
}; };
}

View file

@ -27,13 +27,17 @@
#include <LibCore/CEvent.h> #include <LibCore/CEvent.h>
#include <LibCore/CObject.h> #include <LibCore/CObject.h>
CChildEvent::CChildEvent(Type type, CObject& child, CObject* insertion_before_child) namespace Core {
: CEvent(type)
ChildEvent::ChildEvent(Type type, Object& child, Object* insertion_before_child)
: Core::Event(type)
, m_child(child.make_weak_ptr()) , m_child(child.make_weak_ptr())
, m_insertion_before_child(insertion_before_child ? insertion_before_child->make_weak_ptr() : nullptr) , m_insertion_before_child(insertion_before_child ? insertion_before_child->make_weak_ptr() : nullptr)
{ {
} }
CChildEvent::~CChildEvent() ChildEvent::~ChildEvent()
{ {
} }
}

View file

@ -26,14 +26,16 @@
#pragma once #pragma once
#include <AK/String.h>
#include <AK/Function.h> #include <AK/Function.h>
#include <AK/String.h>
#include <AK/Types.h> #include <AK/Types.h>
#include <AK/WeakPtr.h> #include <AK/WeakPtr.h>
class CObject; namespace Core {
class CEvent { class Object;
class Event {
public: public:
enum Type { enum Type {
Invalid = 0, Invalid = 0,
@ -47,12 +49,12 @@ public:
Custom, Custom,
}; };
CEvent() {} Event() {}
explicit CEvent(unsigned type) explicit Event(unsigned type)
: m_type(type) : m_type(type)
{ {
} }
virtual ~CEvent() {} virtual ~Event() {}
unsigned type() const { return m_type; } unsigned type() const { return m_type; }
@ -65,28 +67,28 @@ private:
bool m_accepted { true }; bool m_accepted { true };
}; };
class CDeferredInvocationEvent : public CEvent { class DeferredInvocationEvent : public Event {
friend class CEventLoop; friend class EventLoop;
public: public:
CDeferredInvocationEvent(Function<void(CObject&)> invokee) DeferredInvocationEvent(Function<void(Object&)> invokee)
: CEvent(CEvent::Type::DeferredInvoke) : Event(Event::Type::DeferredInvoke)
, m_invokee(move(invokee)) , m_invokee(move(invokee))
{ {
} }
private: private:
Function<void(CObject&)> m_invokee; Function<void(Object&)> m_invokee;
}; };
class CTimerEvent final : public CEvent { class TimerEvent final : public Event {
public: public:
explicit CTimerEvent(int timer_id) explicit TimerEvent(int timer_id)
: CEvent(CEvent::Timer) : Event(Event::Timer)
, m_timer_id(timer_id) , m_timer_id(timer_id)
{ {
} }
~CTimerEvent() {} ~TimerEvent() {}
int timer_id() const { return m_timer_id; } int timer_id() const { return m_timer_id; }
@ -94,14 +96,14 @@ private:
int m_timer_id; int m_timer_id;
}; };
class CNotifierReadEvent final : public CEvent { class NotifierReadEvent final : public Event {
public: public:
explicit CNotifierReadEvent(int fd) explicit NotifierReadEvent(int fd)
: CEvent(CEvent::NotifierRead) : Event(Event::NotifierRead)
, m_fd(fd) , m_fd(fd)
{ {
} }
~CNotifierReadEvent() {} ~NotifierReadEvent() {}
int fd() const { return m_fd; } int fd() const { return m_fd; }
@ -109,14 +111,14 @@ private:
int m_fd; int m_fd;
}; };
class CNotifierWriteEvent final : public CEvent { class NotifierWriteEvent final : public Event {
public: public:
explicit CNotifierWriteEvent(int fd) explicit NotifierWriteEvent(int fd)
: CEvent(CEvent::NotifierWrite) : Event(Event::NotifierWrite)
, m_fd(fd) , m_fd(fd)
{ {
} }
~CNotifierWriteEvent() {} ~NotifierWriteEvent() {}
int fd() const { return m_fd; } int fd() const { return m_fd; }
@ -124,31 +126,31 @@ private:
int m_fd; int m_fd;
}; };
class CChildEvent final : public CEvent { class ChildEvent final : public Event {
public: public:
CChildEvent(Type, CObject& child, CObject* insertion_before_child = nullptr); ChildEvent(Type, Object& child, Object* insertion_before_child = nullptr);
~CChildEvent(); ~ChildEvent();
CObject* child() { return m_child.ptr(); } Object* child() { return m_child.ptr(); }
const CObject* child() const { return m_child.ptr(); } const Object* child() const { return m_child.ptr(); }
CObject* insertion_before_child() { return m_insertion_before_child.ptr(); } Object* insertion_before_child() { return m_insertion_before_child.ptr(); }
const CObject* insertion_before_child() const { return m_insertion_before_child.ptr(); } const Object* insertion_before_child() const { return m_insertion_before_child.ptr(); }
private: private:
WeakPtr<CObject> m_child; WeakPtr<Object> m_child;
WeakPtr<CObject> m_insertion_before_child; WeakPtr<Object> m_insertion_before_child;
}; };
class CCustomEvent : public CEvent { class CustomEvent : public Event {
public: public:
CCustomEvent(int custom_type, void* data = nullptr) CustomEvent(int custom_type, void* data = nullptr)
: CEvent(CEvent::Type::Custom) : Event(Event::Type::Custom)
, m_custom_type(custom_type) , m_custom_type(custom_type)
, m_data(data) , m_data(data)
{ {
} }
~CCustomEvent() {} ~CustomEvent() {}
int custom_type() const { return m_custom_type; } int custom_type() const { return m_custom_type; }
void* data() { return m_data; } void* data() { return m_data; }
@ -158,3 +160,5 @@ private:
int m_custom_type { 0 }; int m_custom_type { 0 };
void* m_data { nullptr }; void* m_data { nullptr };
}; };
}

View file

@ -49,21 +49,23 @@
//#define CEVENTLOOP_DEBUG //#define CEVENTLOOP_DEBUG
//#define DEFERRED_INVOKE_DEBUG //#define DEFERRED_INVOKE_DEBUG
namespace Core {
class RPCClient; class RPCClient;
static CEventLoop* s_main_event_loop; static EventLoop* s_main_event_loop;
static Vector<CEventLoop*>* s_event_loop_stack; static Vector<EventLoop*>* s_event_loop_stack;
static IDAllocator s_id_allocator; static IDAllocator s_id_allocator;
HashMap<int, NonnullOwnPtr<CEventLoop::EventLoopTimer>>* CEventLoop::s_timers; HashMap<int, NonnullOwnPtr<EventLoop::EventLoopTimer>>* EventLoop::s_timers;
HashTable<CNotifier*>* CEventLoop::s_notifiers; HashTable<Notifier*>* EventLoop::s_notifiers;
int CEventLoop::s_wake_pipe_fds[2]; int EventLoop::s_wake_pipe_fds[2];
RefPtr<CLocalServer> CEventLoop::s_rpc_server; RefPtr<LocalServer> EventLoop::s_rpc_server;
HashMap<int, RefPtr<RPCClient>> s_rpc_clients; HashMap<int, RefPtr<RPCClient>> s_rpc_clients;
class RPCClient : public CObject { class RPCClient : public Object {
C_OBJECT(RPCClient) C_OBJECT(RPCClient)
public: public:
explicit RPCClient(RefPtr<CLocalSocket> socket) explicit RPCClient(RefPtr<LocalSocket> socket)
: m_socket(move(socket)) : m_socket(move(socket))
, m_client_id(s_id_allocator.allocate()) , m_client_id(s_id_allocator.allocate())
{ {
@ -131,7 +133,7 @@ public:
JsonObject response; JsonObject response;
response.set("type", type); response.set("type", type);
JsonArray objects; JsonArray objects;
for (auto& object : CObject::all_objects()) { for (auto& object : Object::all_objects()) {
JsonObject json_object; JsonObject json_object;
object.save_to(json_object); object.save_to(json_object);
objects.append(move(json_object)); objects.append(move(json_object));
@ -154,16 +156,16 @@ public:
} }
private: private:
RefPtr<CLocalSocket> m_socket; RefPtr<LocalSocket> m_socket;
int m_client_id { -1 }; int m_client_id { -1 };
}; };
CEventLoop::CEventLoop() EventLoop::EventLoop()
{ {
if (!s_event_loop_stack) { if (!s_event_loop_stack) {
s_event_loop_stack = new Vector<CEventLoop*>; s_event_loop_stack = new Vector<EventLoop*>;
s_timers = new HashMap<int, NonnullOwnPtr<CEventLoop::EventLoopTimer>>; s_timers = new HashMap<int, NonnullOwnPtr<EventLoop::EventLoopTimer>>;
s_notifiers = new HashTable<CNotifier*>; s_notifiers = new HashTable<Notifier*>;
} }
if (!s_main_event_loop) { if (!s_main_event_loop) {
@ -185,8 +187,8 @@ CEventLoop::CEventLoop()
perror("unlink"); perror("unlink");
ASSERT_NOT_REACHED(); ASSERT_NOT_REACHED();
} }
s_rpc_server = CLocalServer::construct(); s_rpc_server = LocalServer::construct();
s_rpc_server->set_name("CEventLoop_RPC_server"); s_rpc_server->set_name("Core::EventLoop_RPC_server");
bool listening = s_rpc_server->listen(rpc_path); bool listening = s_rpc_server->listen(rpc_path);
ASSERT(listening); ASSERT(listening);
@ -196,66 +198,66 @@ CEventLoop::CEventLoop()
} }
#ifdef CEVENTLOOP_DEBUG #ifdef CEVENTLOOP_DEBUG
dbg() << getpid() << " CEventLoop constructed :)"; dbg() << getpid() << " Core::EventLoop constructed :)";
#endif #endif
} }
CEventLoop::~CEventLoop() EventLoop::~EventLoop()
{ {
} }
CEventLoop& CEventLoop::main() EventLoop& EventLoop::main()
{ {
ASSERT(s_main_event_loop); ASSERT(s_main_event_loop);
return *s_main_event_loop; return *s_main_event_loop;
} }
CEventLoop& CEventLoop::current() EventLoop& EventLoop::current()
{ {
CEventLoop* event_loop = s_event_loop_stack->last(); EventLoop* event_loop = s_event_loop_stack->last();
ASSERT(event_loop != nullptr); ASSERT(event_loop != nullptr);
return *event_loop; return *event_loop;
} }
void CEventLoop::quit(int code) void EventLoop::quit(int code)
{ {
dbg() << "CEventLoop::quit(" << code << ")"; dbg() << "Core::EventLoop::quit(" << code << ")";
m_exit_requested = true; m_exit_requested = true;
m_exit_code = code; m_exit_code = code;
} }
void CEventLoop::unquit() void EventLoop::unquit()
{ {
dbg() << "CEventLoop::unquit()"; dbg() << "Core::EventLoop::unquit()";
m_exit_requested = false; m_exit_requested = false;
m_exit_code = 0; m_exit_code = 0;
} }
struct CEventLoopPusher { struct EventLoopPusher {
public: public:
CEventLoopPusher(CEventLoop& event_loop) EventLoopPusher(EventLoop& event_loop)
: m_event_loop(event_loop) : m_event_loop(event_loop)
{ {
if (&m_event_loop != s_main_event_loop) { if (&m_event_loop != s_main_event_loop) {
m_event_loop.take_pending_events_from(CEventLoop::current()); m_event_loop.take_pending_events_from(EventLoop::current());
s_event_loop_stack->append(&event_loop); s_event_loop_stack->append(&event_loop);
} }
} }
~CEventLoopPusher() ~EventLoopPusher()
{ {
if (&m_event_loop != s_main_event_loop) { if (&m_event_loop != s_main_event_loop) {
s_event_loop_stack->take_last(); s_event_loop_stack->take_last();
CEventLoop::current().take_pending_events_from(m_event_loop); EventLoop::current().take_pending_events_from(m_event_loop);
} }
} }
private: private:
CEventLoop& m_event_loop; EventLoop& m_event_loop;
}; };
int CEventLoop::exec() int EventLoop::exec()
{ {
CEventLoopPusher pusher(*this); EventLoopPusher pusher(*this);
for (;;) { for (;;) {
if (m_exit_requested) if (m_exit_requested)
return m_exit_code; return m_exit_code;
@ -264,7 +266,7 @@ int CEventLoop::exec()
ASSERT_NOT_REACHED(); ASSERT_NOT_REACHED();
} }
void CEventLoop::pump(WaitMode mode) void EventLoop::pump(WaitMode mode)
{ {
if (m_queued_events.is_empty()) if (m_queued_events.is_empty())
wait_for_event(mode); wait_for_event(mode);
@ -284,30 +286,30 @@ void CEventLoop::pump(WaitMode mode)
auto& event = *queued_event.event; auto& event = *queued_event.event;
#ifdef CEVENTLOOP_DEBUG #ifdef CEVENTLOOP_DEBUG
if (receiver) if (receiver)
dbg() << "CEventLoop: " << *receiver << " event " << (int)event.type(); dbg() << "Core::EventLoop: " << *receiver << " event " << (int)event.type();
#endif #endif
if (!receiver) { if (!receiver) {
switch (event.type()) { switch (event.type()) {
case CEvent::Quit: case Event::Quit:
ASSERT_NOT_REACHED(); ASSERT_NOT_REACHED();
return; return;
default: default:
dbg() << "Event type " << event.type() << " with no receiver :("; dbg() << "Event type " << event.type() << " with no receiver :(";
} }
} else if (event.type() == CEvent::Type::DeferredInvoke) { } else if (event.type() == Event::Type::DeferredInvoke) {
#ifdef DEFERRED_INVOKE_DEBUG #ifdef DEFERRED_INVOKE_DEBUG
printf("DeferredInvoke: receiver=%s{%p}\n", receiver->class_name(), receiver); printf("DeferredInvoke: receiver=%s{%p}\n", receiver->class_name(), receiver);
#endif #endif
static_cast<CDeferredInvocationEvent&>(event).m_invokee(*receiver); static_cast<DeferredInvocationEvent&>(event).m_invokee(*receiver);
} else { } else {
NonnullRefPtr<CObject> protector(*receiver); NonnullRefPtr<Object> protector(*receiver);
receiver->dispatch_event(event); receiver->dispatch_event(event);
} }
if (m_exit_requested) { if (m_exit_requested) {
LOCKER(m_lock); LOCKER(m_lock);
#ifdef CEVENTLOOP_DEBUG #ifdef CEVENTLOOP_DEBUG
dbg() << "CEventLoop: Exit requested. Rejigging " << (events.size() - i) << " events."; dbg() << "Core::EventLoop: Exit requested. Rejigging " << (events.size() - i) << " events.";
#endif #endif
decltype(m_queued_events) new_event_queue; decltype(m_queued_events) new_event_queue;
new_event_queue.ensure_capacity(m_queued_events.size() + events.size()); new_event_queue.ensure_capacity(m_queued_events.size() + events.size());
@ -320,16 +322,16 @@ void CEventLoop::pump(WaitMode mode)
} }
} }
void CEventLoop::post_event(CObject& receiver, NonnullOwnPtr<CEvent>&& event) void EventLoop::post_event(Object& receiver, NonnullOwnPtr<Event>&& event)
{ {
LOCKER(m_lock); LOCKER(m_lock);
#ifdef CEVENTLOOP_DEBUG #ifdef CEVENTLOOP_DEBUG
dbg() << "CEventLoop::post_event: {" << m_queued_events.size() << "} << receiver=" << receiver << ", event=" << event; dbg() << "Core::EventLoop::post_event: {" << m_queued_events.size() << "} << receiver=" << receiver << ", event=" << event;
#endif #endif
m_queued_events.append({ receiver.make_weak_ptr(), move(event) }); m_queued_events.append({ receiver.make_weak_ptr(), move(event) });
} }
void CEventLoop::wait_for_event(WaitMode mode) void EventLoop::wait_for_event(WaitMode mode)
{ {
fd_set rfds; fd_set rfds;
fd_set wfds; fd_set wfds;
@ -347,11 +349,11 @@ void CEventLoop::wait_for_event(WaitMode mode)
add_fd_to_set(s_wake_pipe_fds[0], rfds); add_fd_to_set(s_wake_pipe_fds[0], rfds);
max_fd = max(max_fd, max_fd_added); max_fd = max(max_fd, max_fd_added);
for (auto& notifier : *s_notifiers) { for (auto& notifier : *s_notifiers) {
if (notifier->event_mask() & CNotifier::Read) if (notifier->event_mask() & Notifier::Read)
add_fd_to_set(notifier->fd(), rfds); add_fd_to_set(notifier->fd(), rfds);
if (notifier->event_mask() & CNotifier::Write) if (notifier->event_mask() & Notifier::Write)
add_fd_to_set(notifier->fd(), wfds); add_fd_to_set(notifier->fd(), wfds);
if (notifier->event_mask() & CNotifier::Exceptional) if (notifier->event_mask() & Notifier::Exceptional)
ASSERT_NOT_REACHED(); ASSERT_NOT_REACHED();
} }
@ -401,9 +403,9 @@ void CEventLoop::wait_for_event(WaitMode mode)
continue; continue;
} }
#ifdef CEVENTLOOP_DEBUG #ifdef CEVENTLOOP_DEBUG
dbg() << "CEventLoop: Timer " << timer.timer_id << " has expired, sending CTimerEvent to " << timer.owner; dbg() << "Core::EventLoop: Timer " << timer.timer_id << " has expired, sending Core::TimerEvent to " << timer.owner;
#endif #endif
post_event(*timer.owner, make<CTimerEvent>(timer.timer_id)); post_event(*timer.owner, make<TimerEvent>(timer.timer_id));
if (timer.should_reload) { if (timer.should_reload) {
timer.reload(now); timer.reload(now);
} else { } else {
@ -418,28 +420,28 @@ void CEventLoop::wait_for_event(WaitMode mode)
for (auto& notifier : *s_notifiers) { for (auto& notifier : *s_notifiers) {
if (FD_ISSET(notifier->fd(), &rfds)) { if (FD_ISSET(notifier->fd(), &rfds)) {
if (notifier->on_ready_to_read) if (notifier->on_ready_to_read)
post_event(*notifier, make<CNotifierReadEvent>(notifier->fd())); post_event(*notifier, make<NotifierReadEvent>(notifier->fd()));
} }
if (FD_ISSET(notifier->fd(), &wfds)) { if (FD_ISSET(notifier->fd(), &wfds)) {
if (notifier->on_ready_to_write) if (notifier->on_ready_to_write)
post_event(*notifier, make<CNotifierWriteEvent>(notifier->fd())); post_event(*notifier, make<NotifierWriteEvent>(notifier->fd()));
} }
} }
} }
bool CEventLoop::EventLoopTimer::has_expired(const timeval& now) const bool EventLoop::EventLoopTimer::has_expired(const timeval& now) const
{ {
return now.tv_sec > fire_time.tv_sec || (now.tv_sec == fire_time.tv_sec && now.tv_usec >= fire_time.tv_usec); return now.tv_sec > fire_time.tv_sec || (now.tv_sec == fire_time.tv_sec && now.tv_usec >= fire_time.tv_usec);
} }
void CEventLoop::EventLoopTimer::reload(const timeval& now) void EventLoop::EventLoopTimer::reload(const timeval& now)
{ {
fire_time = now; fire_time = now;
fire_time.tv_sec += interval / 1000; fire_time.tv_sec += interval / 1000;
fire_time.tv_usec += (interval % 1000) * 1000; fire_time.tv_usec += (interval % 1000) * 1000;
} }
void CEventLoop::get_next_timer_expiration(timeval& soonest) void EventLoop::get_next_timer_expiration(timeval& soonest)
{ {
ASSERT(!s_timers->is_empty()); ASSERT(!s_timers->is_empty());
bool has_checked_any = false; bool has_checked_any = false;
@ -456,7 +458,7 @@ void CEventLoop::get_next_timer_expiration(timeval& soonest)
} }
} }
int CEventLoop::register_timer(CObject& object, int milliseconds, bool should_reload, TimerShouldFireWhenNotVisible fire_when_not_visible) int EventLoop::register_timer(Object& object, int milliseconds, bool should_reload, TimerShouldFireWhenNotVisible fire_when_not_visible)
{ {
ASSERT(milliseconds >= 0); ASSERT(milliseconds >= 0);
auto timer = make<EventLoopTimer>(); auto timer = make<EventLoopTimer>();
@ -473,7 +475,7 @@ int CEventLoop::register_timer(CObject& object, int milliseconds, bool should_re
return timer_id; return timer_id;
} }
bool CEventLoop::unregister_timer(int timer_id) bool EventLoop::unregister_timer(int timer_id)
{ {
s_id_allocator.deallocate(timer_id); s_id_allocator.deallocate(timer_id);
auto it = s_timers->find(timer_id); auto it = s_timers->find(timer_id);
@ -483,22 +485,24 @@ bool CEventLoop::unregister_timer(int timer_id)
return true; return true;
} }
void CEventLoop::register_notifier(Badge<CNotifier>, CNotifier& notifier) void EventLoop::register_notifier(Badge<Notifier>, Notifier& notifier)
{ {
s_notifiers->set(&notifier); s_notifiers->set(&notifier);
} }
void CEventLoop::unregister_notifier(Badge<CNotifier>, CNotifier& notifier) void EventLoop::unregister_notifier(Badge<Notifier>, Notifier& notifier)
{ {
s_notifiers->remove(&notifier); s_notifiers->remove(&notifier);
} }
void CEventLoop::wake() void EventLoop::wake()
{ {
char ch = '!'; char ch = '!';
int nwritten = write(s_wake_pipe_fds[1], &ch, 1); int nwritten = write(s_wake_pipe_fds[1], &ch, 1);
if (nwritten < 0) { if (nwritten < 0) {
perror("CEventLoop::wake: write"); perror("EventLoop::wake: write");
ASSERT_NOT_REACHED(); ASSERT_NOT_REACHED();
} }
} }
}

View file

@ -38,13 +38,15 @@
#include <sys/time.h> #include <sys/time.h>
#include <time.h> #include <time.h>
class CObject; namespace Core {
class CNotifier;
class CEventLoop { class Object;
class Notifier;
class EventLoop {
public: public:
CEventLoop(); EventLoop();
~CEventLoop(); ~EventLoop();
int exec(); int exec();
@ -57,23 +59,23 @@ public:
// this should really only be used for integrating with other event loops // this should really only be used for integrating with other event loops
void pump(WaitMode = WaitMode::WaitForEvents); void pump(WaitMode = WaitMode::WaitForEvents);
void post_event(CObject& receiver, NonnullOwnPtr<CEvent>&&); void post_event(Object& receiver, NonnullOwnPtr<Event>&&);
static CEventLoop& main(); static EventLoop& main();
static CEventLoop& current(); static EventLoop& current();
bool was_exit_requested() const { return m_exit_requested; } bool was_exit_requested() const { return m_exit_requested; }
static int register_timer(CObject&, int milliseconds, bool should_reload, TimerShouldFireWhenNotVisible); static int register_timer(Object&, int milliseconds, bool should_reload, TimerShouldFireWhenNotVisible);
static bool unregister_timer(int timer_id); static bool unregister_timer(int timer_id);
static void register_notifier(Badge<CNotifier>, CNotifier&); static void register_notifier(Badge<Notifier>, Notifier&);
static void unregister_notifier(Badge<CNotifier>, CNotifier&); static void unregister_notifier(Badge<Notifier>, Notifier&);
void quit(int); void quit(int);
void unquit(); void unquit();
void take_pending_events_from(CEventLoop& other) void take_pending_events_from(EventLoop& other)
{ {
m_queued_events.append(move(other.m_queued_events)); m_queued_events.append(move(other.m_queued_events));
} }
@ -85,8 +87,8 @@ private:
void get_next_timer_expiration(timeval&); void get_next_timer_expiration(timeval&);
struct QueuedEvent { struct QueuedEvent {
WeakPtr<CObject> receiver; WeakPtr<Object> receiver;
NonnullOwnPtr<CEvent> event; NonnullOwnPtr<Event> event;
}; };
Vector<QueuedEvent, 64> m_queued_events; Vector<QueuedEvent, 64> m_queued_events;
@ -104,7 +106,7 @@ private:
timeval fire_time { 0, 0 }; timeval fire_time { 0, 0 };
bool should_reload { false }; bool should_reload { false };
TimerShouldFireWhenNotVisible fire_when_not_visible { TimerShouldFireWhenNotVisible::No }; TimerShouldFireWhenNotVisible fire_when_not_visible { TimerShouldFireWhenNotVisible::No };
WeakPtr<CObject> owner; WeakPtr<Object> owner;
void reload(const timeval& now); void reload(const timeval& now);
bool has_expired(const timeval& now) const; bool has_expired(const timeval& now) const;
@ -112,7 +114,9 @@ private:
static HashMap<int, NonnullOwnPtr<EventLoopTimer>>* s_timers; static HashMap<int, NonnullOwnPtr<EventLoopTimer>>* s_timers;
static HashTable<CNotifier*>* s_notifiers; static HashTable<Notifier*>* s_notifiers;
static RefPtr<CLocalServer> s_rpc_server; static RefPtr<LocalServer> s_rpc_server;
}; };
}

View file

@ -30,19 +30,21 @@
#include <stdio.h> #include <stdio.h>
#include <unistd.h> #include <unistd.h>
CFile::CFile(const StringView& filename, CObject* parent) namespace Core {
: CIODevice(parent)
File::File(const StringView& filename, Object* parent)
: IODevice(parent)
, m_filename(filename) , m_filename(filename)
{ {
} }
CFile::~CFile() File::~File()
{ {
if (m_should_close_file_descriptor == ShouldCloseFileDescription::Yes && mode() != NotOpen) if (m_should_close_file_descriptor == ShouldCloseFileDescription::Yes && mode() != NotOpen)
close(); close();
} }
bool CFile::open(int fd, CIODevice::OpenMode mode, ShouldCloseFileDescription should_close) bool File::open(int fd, IODevice::OpenMode mode, ShouldCloseFileDescription should_close)
{ {
set_fd(fd); set_fd(fd);
set_mode(mode); set_mode(mode);
@ -50,25 +52,25 @@ bool CFile::open(int fd, CIODevice::OpenMode mode, ShouldCloseFileDescription sh
return true; return true;
} }
bool CFile::open(CIODevice::OpenMode mode) bool File::open(IODevice::OpenMode mode)
{ {
ASSERT(!m_filename.is_null()); ASSERT(!m_filename.is_null());
int flags = 0; int flags = 0;
if ((mode & CIODevice::ReadWrite) == CIODevice::ReadWrite) { if ((mode & IODevice::ReadWrite) == IODevice::ReadWrite) {
flags |= O_RDWR | O_CREAT; flags |= O_RDWR | O_CREAT;
} else if (mode & CIODevice::ReadOnly) { } else if (mode & IODevice::ReadOnly) {
flags |= O_RDONLY; flags |= O_RDONLY;
} else if (mode & CIODevice::WriteOnly) { } else if (mode & IODevice::WriteOnly) {
flags |= O_WRONLY | O_CREAT; flags |= O_WRONLY | O_CREAT;
bool should_truncate = !((mode & CIODevice::Append) || (mode & CIODevice::MustBeNew)); bool should_truncate = !((mode & IODevice::Append) || (mode & IODevice::MustBeNew));
if (should_truncate) if (should_truncate)
flags |= O_TRUNC; flags |= O_TRUNC;
} }
if (mode & CIODevice::Append) if (mode & IODevice::Append)
flags |= O_APPEND; flags |= O_APPEND;
if (mode & CIODevice::Truncate) if (mode & IODevice::Truncate)
flags |= O_TRUNC; flags |= O_TRUNC;
if (mode & CIODevice::MustBeNew) if (mode & IODevice::MustBeNew)
flags |= O_EXCL; flags |= O_EXCL;
int fd = ::open(m_filename.characters(), flags, 0666); int fd = ::open(m_filename.characters(), flags, 0666);
if (fd < 0) { if (fd < 0) {
@ -80,3 +82,5 @@ bool CFile::open(CIODevice::OpenMode mode)
set_mode(mode); set_mode(mode);
return true; return true;
} }
}

View file

@ -29,29 +29,33 @@
#include <AK/String.h> #include <AK/String.h>
#include <LibCore/CIODevice.h> #include <LibCore/CIODevice.h>
class CFile final : public CIODevice { namespace Core {
C_OBJECT(CFile)
class File final : public IODevice {
C_OBJECT(File)
public: public:
virtual ~CFile() override; virtual ~File() override;
String filename() const { return m_filename; } String filename() const { return m_filename; }
void set_filename(const StringView& filename) { m_filename = filename; } void set_filename(const StringView& filename) { m_filename = filename; }
virtual bool open(CIODevice::OpenMode) override; virtual bool open(IODevice::OpenMode) override;
enum class ShouldCloseFileDescription { enum class ShouldCloseFileDescription {
No = 0, No = 0,
Yes Yes
}; };
bool open(int fd, CIODevice::OpenMode, ShouldCloseFileDescription); bool open(int fd, IODevice::OpenMode, ShouldCloseFileDescription);
private: private:
CFile(CObject* parent = nullptr) File(Object* parent = nullptr)
: CIODevice(parent) : IODevice(parent)
{ {
} }
explicit CFile(const StringView&, CObject* parent = nullptr); explicit File(const StringView&, Object* parent = nullptr);
String m_filename; String m_filename;
ShouldCloseFileDescription m_should_close_file_descriptor { ShouldCloseFileDescription::Yes }; ShouldCloseFileDescription m_should_close_file_descriptor { ShouldCloseFileDescription::Yes };
}; };
}

View file

@ -33,6 +33,8 @@
//#define CHTTPJOB_DEBUG //#define CHTTPJOB_DEBUG
namespace Core {
static ByteBuffer handle_content_encoding(const ByteBuffer& buf, const String& content_encoding) static ByteBuffer handle_content_encoding(const ByteBuffer& buf, const String& content_encoding)
{ {
#ifdef CHTTPJOB_DEBUG #ifdef CHTTPJOB_DEBUG
@ -66,16 +68,16 @@ static ByteBuffer handle_content_encoding(const ByteBuffer& buf, const String& c
return buf; return buf;
} }
CHttpJob::CHttpJob(const CHttpRequest& request) HttpJob::HttpJob(const HttpRequest& request)
: m_request(request) : m_request(request)
{ {
} }
CHttpJob::~CHttpJob() HttpJob::~HttpJob()
{ {
} }
void CHttpJob::on_socket_connected() void HttpJob::on_socket_connected()
{ {
auto raw_request = m_request.to_raw_request(); auto raw_request = m_request.to_raw_request();
#if 0 #if 0
@ -85,7 +87,7 @@ void CHttpJob::on_socket_connected()
bool success = m_socket->send(raw_request); bool success = m_socket->send(raw_request);
if (!success) if (!success)
return deferred_invoke([this](auto&) { did_fail(CNetworkJob::Error::TransmissionFailed); }); return deferred_invoke([this](auto&) { did_fail(NetworkJob::Error::TransmissionFailed); });
m_socket->on_ready_to_read = [&] { m_socket->on_ready_to_read = [&] {
if (is_cancelled()) if (is_cancelled())
@ -96,18 +98,18 @@ void CHttpJob::on_socket_connected()
auto line = m_socket->read_line(PAGE_SIZE); auto line = m_socket->read_line(PAGE_SIZE);
if (line.is_null()) { if (line.is_null()) {
fprintf(stderr, "CHttpJob: Expected HTTP status\n"); fprintf(stderr, "CHttpJob: Expected HTTP status\n");
return deferred_invoke([this](auto&) { did_fail(CNetworkJob::Error::TransmissionFailed); }); return deferred_invoke([this](auto&) { did_fail(NetworkJob::Error::TransmissionFailed); });
} }
auto parts = String::copy(line, Chomp).split(' '); auto parts = String::copy(line, Chomp).split(' ');
if (parts.size() < 3) { if (parts.size() < 3) {
fprintf(stderr, "CHttpJob: Expected 3-part HTTP status, got '%s'\n", line.data()); fprintf(stderr, "CHttpJob: Expected 3-part HTTP status, got '%s'\n", line.data());
return deferred_invoke([this](auto&) { did_fail(CNetworkJob::Error::ProtocolFailed); }); return deferred_invoke([this](auto&) { did_fail(NetworkJob::Error::ProtocolFailed); });
} }
bool ok; bool ok;
m_code = parts[1].to_uint(ok); m_code = parts[1].to_uint(ok);
if (!ok) { if (!ok) {
fprintf(stderr, "CHttpJob: Expected numeric HTTP status\n"); fprintf(stderr, "CHttpJob: Expected numeric HTTP status\n");
return deferred_invoke([this](auto&) { did_fail(CNetworkJob::Error::ProtocolFailed); }); return deferred_invoke([this](auto&) { did_fail(NetworkJob::Error::ProtocolFailed); });
} }
m_state = State::InHeaders; m_state = State::InHeaders;
return; return;
@ -118,7 +120,7 @@ void CHttpJob::on_socket_connected()
auto line = m_socket->read_line(PAGE_SIZE); auto line = m_socket->read_line(PAGE_SIZE);
if (line.is_null()) { if (line.is_null()) {
fprintf(stderr, "CHttpJob: Expected HTTP header\n"); fprintf(stderr, "CHttpJob: Expected HTTP header\n");
return did_fail(CNetworkJob::Error::ProtocolFailed); return did_fail(NetworkJob::Error::ProtocolFailed);
} }
auto chomped_line = String::copy(line, Chomp); auto chomped_line = String::copy(line, Chomp);
if (chomped_line.is_empty()) { if (chomped_line.is_empty()) {
@ -128,12 +130,12 @@ void CHttpJob::on_socket_connected()
auto parts = chomped_line.split(':'); auto parts = chomped_line.split(':');
if (parts.is_empty()) { if (parts.is_empty()) {
fprintf(stderr, "CHttpJob: Expected HTTP header with key/value\n"); fprintf(stderr, "CHttpJob: Expected HTTP header with key/value\n");
return deferred_invoke([this](auto&) { did_fail(CNetworkJob::Error::ProtocolFailed); }); return deferred_invoke([this](auto&) { did_fail(NetworkJob::Error::ProtocolFailed); });
} }
auto name = parts[0]; auto name = parts[0];
if (chomped_line.length() < name.length() + 2) { if (chomped_line.length() < name.length() + 2) {
fprintf(stderr, "CHttpJob: Malformed HTTP header: '%s' (%zu)\n", chomped_line.characters(), chomped_line.length()); fprintf(stderr, "CHttpJob: Malformed HTTP header: '%s' (%zu)\n", chomped_line.characters(), chomped_line.length());
return deferred_invoke([this](auto&) { did_fail(CNetworkJob::Error::ProtocolFailed); }); return deferred_invoke([this](auto&) { did_fail(NetworkJob::Error::ProtocolFailed); });
} }
auto value = chomped_line.substring(name.length() + 2, chomped_line.length() - name.length() - 2); auto value = chomped_line.substring(name.length() + 2, chomped_line.length() - name.length() - 2);
m_headers.set(name, value); m_headers.set(name, value);
@ -148,7 +150,7 @@ void CHttpJob::on_socket_connected()
if (!payload) { if (!payload) {
if (m_socket->eof()) if (m_socket->eof())
return finish_up(); return finish_up();
return deferred_invoke([this](auto&) { did_fail(CNetworkJob::Error::ProtocolFailed); }); return deferred_invoke([this](auto&) { did_fail(NetworkJob::Error::ProtocolFailed); });
} }
m_received_buffers.append(payload); m_received_buffers.append(payload);
m_received_size += payload.size(); m_received_size += payload.size();
@ -162,7 +164,7 @@ void CHttpJob::on_socket_connected()
}; };
} }
void CHttpJob::finish_up() void HttpJob::finish_up()
{ {
m_state = State::Finished; m_state = State::Finished;
auto flattened_buffer = ByteBuffer::create_uninitialized(m_received_size); auto flattened_buffer = ByteBuffer::create_uninitialized(m_received_size);
@ -178,16 +180,16 @@ void CHttpJob::finish_up()
flattened_buffer = handle_content_encoding(flattened_buffer, content_encoding.value()); flattened_buffer = handle_content_encoding(flattened_buffer, content_encoding.value());
} }
auto response = CHttpResponse::create(m_code, move(m_headers), move(flattened_buffer)); auto response = HttpResponse::create(m_code, move(m_headers), move(flattened_buffer));
deferred_invoke([this, response](auto&) { deferred_invoke([this, response](auto&) {
did_finish(move(response)); did_finish(move(response));
}); });
} }
void CHttpJob::start() void HttpJob::start()
{ {
ASSERT(!m_socket); ASSERT(!m_socket);
m_socket = CTCPSocket::construct(this); m_socket = TCPSocket::construct(this);
m_socket->on_connected = [this] { m_socket->on_connected = [this] {
#ifdef CHTTPJOB_DEBUG #ifdef CHTTPJOB_DEBUG
dbg() << "CHttpJob: on_connected callback"; dbg() << "CHttpJob: on_connected callback";
@ -197,12 +199,12 @@ void CHttpJob::start()
bool success = m_socket->connect(m_request.url().host(), m_request.url().port()); bool success = m_socket->connect(m_request.url().host(), m_request.url().port());
if (!success) { if (!success) {
deferred_invoke([this](auto&) { deferred_invoke([this](auto&) {
return did_fail(CNetworkJob::Error::ConnectionFailed); return did_fail(NetworkJob::Error::ConnectionFailed);
}); });
} }
} }
void CHttpJob::shutdown() void HttpJob::shutdown()
{ {
if (!m_socket) if (!m_socket)
return; return;
@ -211,3 +213,4 @@ void CHttpJob::shutdown()
remove_child(*m_socket); remove_child(*m_socket);
m_socket = nullptr; m_socket = nullptr;
} }
}

View file

@ -31,19 +31,21 @@
#include <LibCore/CHttpResponse.h> #include <LibCore/CHttpResponse.h>
#include <LibCore/CNetworkJob.h> #include <LibCore/CNetworkJob.h>
class CTCPSocket; namespace Core {
class CHttpJob final : public CNetworkJob { class TCPSocket;
C_OBJECT(CHttpJob)
class HttpJob final : public NetworkJob {
C_OBJECT(HttpJob)
public: public:
explicit CHttpJob(const CHttpRequest&); explicit HttpJob(const HttpRequest&);
virtual ~CHttpJob() override; virtual ~HttpJob() override;
virtual void start() override; virtual void start() override;
virtual void shutdown() override; virtual void shutdown() override;
CHttpResponse* response() { return static_cast<CHttpResponse*>(CNetworkJob::response()); } HttpResponse* response() { return static_cast<HttpResponse*>(NetworkJob::response()); }
const CHttpResponse* response() const { return static_cast<const CHttpResponse*>(CNetworkJob::response()); } const HttpResponse* response() const { return static_cast<const HttpResponse*>(NetworkJob::response()); }
private: private:
void on_socket_connected(); void on_socket_connected();
@ -56,11 +58,13 @@ private:
Finished, Finished,
}; };
CHttpRequest m_request; HttpRequest m_request;
RefPtr<CTCPSocket> m_socket; RefPtr<TCPSocket> m_socket;
State m_state { State::InStatus }; State m_state { State::InStatus };
int m_code { -1 }; int m_code { -1 };
HashMap<String, String> m_headers; HashMap<String, String> m_headers;
Vector<ByteBuffer> m_received_buffers; Vector<ByteBuffer> m_received_buffers;
size_t m_received_size { 0 }; size_t m_received_size { 0 };
}; };
}

View file

@ -28,22 +28,24 @@
#include <LibCore/CHttpJob.h> #include <LibCore/CHttpJob.h>
#include <LibCore/CHttpRequest.h> #include <LibCore/CHttpRequest.h>
CHttpRequest::CHttpRequest() namespace Core {
HttpRequest::HttpRequest()
{ {
} }
CHttpRequest::~CHttpRequest() HttpRequest::~HttpRequest()
{ {
} }
RefPtr<CNetworkJob> CHttpRequest::schedule() RefPtr<NetworkJob> HttpRequest::schedule()
{ {
auto job = CHttpJob::construct(*this); auto job = HttpJob::construct(*this);
job->start(); job->start();
return job; return job;
} }
String CHttpRequest::method_name() const String HttpRequest::method_name() const
{ {
switch (m_method) { switch (m_method) {
case Method::GET: case Method::GET:
@ -57,7 +59,7 @@ String CHttpRequest::method_name() const
} }
} }
ByteBuffer CHttpRequest::to_raw_request() const ByteBuffer HttpRequest::to_raw_request() const
{ {
StringBuilder builder; StringBuilder builder;
builder.append(method_name()); builder.append(method_name());
@ -68,3 +70,5 @@ ByteBuffer CHttpRequest::to_raw_request() const
builder.append("\r\n\r\n"); builder.append("\r\n\r\n");
return builder.to_byte_buffer(); return builder.to_byte_buffer();
} }
}

View file

@ -29,9 +29,11 @@
#include <AK/String.h> #include <AK/String.h>
#include <AK/URL.h> #include <AK/URL.h>
class CNetworkJob; namespace Core {
class CHttpRequest { class NetworkJob;
class HttpRequest {
public: public:
enum Method { enum Method {
Invalid, Invalid,
@ -40,8 +42,8 @@ public:
POST POST
}; };
CHttpRequest(); HttpRequest();
~CHttpRequest(); ~HttpRequest();
const URL& url() const { return m_url; } const URL& url() const { return m_url; }
void set_url(const URL& url) { m_url = url; } void set_url(const URL& url) { m_url = url; }
@ -52,9 +54,11 @@ public:
String method_name() const; String method_name() const;
ByteBuffer to_raw_request() const; ByteBuffer to_raw_request() const;
RefPtr<CNetworkJob> schedule(); RefPtr<NetworkJob> schedule();
private: private:
URL m_url; URL m_url;
Method m_method { GET }; Method m_method { GET };
}; };
}

View file

@ -26,13 +26,17 @@
#include <LibCore/CHttpResponse.h> #include <LibCore/CHttpResponse.h>
CHttpResponse::CHttpResponse(int code, HashMap<String, String>&& headers, ByteBuffer&& payload) namespace Core {
: CNetworkResponse(move(payload))
HttpResponse::HttpResponse(int code, HashMap<String, String>&& headers, ByteBuffer&& payload)
: NetworkResponse(move(payload))
, m_code(code) , m_code(code)
, m_headers(move(headers)) , m_headers(move(headers))
{ {
} }
CHttpResponse::~CHttpResponse() HttpResponse::~HttpResponse()
{ {
} }
}

View file

@ -26,24 +26,28 @@
#pragma once #pragma once
#include <AK/String.h>
#include <AK/HashMap.h> #include <AK/HashMap.h>
#include <AK/String.h>
#include <LibCore/CNetworkResponse.h> #include <LibCore/CNetworkResponse.h>
class CHttpResponse : public CNetworkResponse { namespace Core {
class HttpResponse : public NetworkResponse {
public: public:
virtual ~CHttpResponse() override; virtual ~HttpResponse() override;
static NonnullRefPtr<CHttpResponse> create(int code, HashMap<String, String>&& headers, ByteBuffer&& payload) static NonnullRefPtr<HttpResponse> create(int code, HashMap<String, String>&& headers, ByteBuffer&& payload)
{ {
return adopt(*new CHttpResponse(code, move(headers), move(payload))); return adopt(*new HttpResponse(code, move(headers), move(payload)));
} }
int code() const { return m_code; } int code() const { return m_code; }
const HashMap<String, String>& headers() const { return m_headers; } const HashMap<String, String>& headers() const { return m_headers; }
private: private:
CHttpResponse(int code, HashMap<String, String>&&, ByteBuffer&&); HttpResponse(int code, HashMap<String, String>&&, ByteBuffer&&);
int m_code { 0 }; int m_code { 0 };
HashMap<String, String> m_headers; HashMap<String, String> m_headers;
}; };
}

View file

@ -34,21 +34,23 @@
#include <sys/time.h> #include <sys/time.h>
#include <unistd.h> #include <unistd.h>
CIODevice::CIODevice(CObject* parent) namespace Core {
: CObject(parent)
IODevice::IODevice(Object* parent)
: Object(parent)
{ {
} }
CIODevice::~CIODevice() IODevice::~IODevice()
{ {
} }
const char* CIODevice::error_string() const const char* IODevice::error_string() const
{ {
return strerror(m_error); return strerror(m_error);
} }
int CIODevice::read(u8* buffer, int length) int IODevice::read(u8* buffer, int length)
{ {
auto read_buffer = read(length); auto read_buffer = read(length);
if (read_buffer.is_null()) if (read_buffer.is_null())
@ -57,7 +59,7 @@ int CIODevice::read(u8* buffer, int length)
return read_buffer.size(); return read_buffer.size();
} }
ByteBuffer CIODevice::read(int max_size) ByteBuffer IODevice::read(int max_size)
{ {
if (m_fd < 0) if (m_fd < 0)
return {}; return {};
@ -99,7 +101,7 @@ ByteBuffer CIODevice::read(int max_size)
return buffer; return buffer;
} }
bool CIODevice::can_read_from_fd() const bool IODevice::can_read_from_fd() const
{ {
// FIXME: Can we somehow remove this once CSocket is implemented using non-blocking sockets? // FIXME: Can we somehow remove this once CSocket is implemented using non-blocking sockets?
fd_set rfds; fd_set rfds;
@ -111,13 +113,13 @@ bool CIODevice::can_read_from_fd() const
int rc = CSyscallUtils::safe_syscall(select, m_fd + 1, &rfds, nullptr, nullptr, &timeout); int rc = CSyscallUtils::safe_syscall(select, m_fd + 1, &rfds, nullptr, nullptr, &timeout);
if (rc < 0) { if (rc < 0) {
// NOTE: We don't set m_error here. // NOTE: We don't set m_error here.
perror("CIODevice::can_read: select"); perror("IODevice::can_read: select");
return false; return false;
} }
return FD_ISSET(m_fd, &rfds); return FD_ISSET(m_fd, &rfds);
} }
bool CIODevice::can_read_line() bool IODevice::can_read_line()
{ {
if (m_eof && !m_buffered_data.is_empty()) if (m_eof && !m_buffered_data.is_empty())
return true; return true;
@ -129,12 +131,12 @@ bool CIODevice::can_read_line()
return m_buffered_data.contains_slow('\n'); return m_buffered_data.contains_slow('\n');
} }
bool CIODevice::can_read() const bool IODevice::can_read() const
{ {
return !m_buffered_data.is_empty() || can_read_from_fd(); return !m_buffered_data.is_empty() || can_read_from_fd();
} }
ByteBuffer CIODevice::read_all() ByteBuffer IODevice::read_all()
{ {
off_t file_size = 0; off_t file_size = 0;
struct stat st; struct stat st;
@ -168,7 +170,7 @@ ByteBuffer CIODevice::read_all()
return ByteBuffer::copy(data.data(), data.size()); return ByteBuffer::copy(data.data(), data.size());
} }
ByteBuffer CIODevice::read_line(int max_size) ByteBuffer IODevice::read_line(int max_size)
{ {
if (m_fd < 0) if (m_fd < 0)
return {}; return {};
@ -178,7 +180,7 @@ ByteBuffer CIODevice::read_line(int max_size)
return {}; return {};
if (m_eof) { if (m_eof) {
if (m_buffered_data.size() > max_size) { if (m_buffered_data.size() > max_size) {
dbgprintf("CIODevice::read_line: At EOF but there's more than max_size(%d) buffered\n", max_size); dbgprintf("IODevice::read_line: At EOF but there's more than max_size(%d) buffered\n", max_size);
return {}; return {};
} }
auto buffer = ByteBuffer::copy(m_buffered_data.data(), m_buffered_data.size()); auto buffer = ByteBuffer::copy(m_buffered_data.data(), m_buffered_data.size());
@ -202,7 +204,7 @@ ByteBuffer CIODevice::read_line(int max_size)
return {}; return {};
} }
bool CIODevice::populate_read_buffer() bool IODevice::populate_read_buffer()
{ {
if (m_fd < 0) if (m_fd < 0)
return false; return false;
@ -220,7 +222,7 @@ bool CIODevice::populate_read_buffer()
return true; return true;
} }
bool CIODevice::close() bool IODevice::close()
{ {
if (fd() < 0 || mode() == NotOpen) if (fd() < 0 || mode() == NotOpen)
return false; return false;
@ -230,11 +232,11 @@ bool CIODevice::close()
return false; return false;
} }
set_fd(-1); set_fd(-1);
set_mode(CIODevice::NotOpen); set_mode(IODevice::NotOpen);
return true; return true;
} }
bool CIODevice::seek(i64 offset, SeekMode mode, off_t* pos) bool IODevice::seek(i64 offset, SeekMode mode, off_t* pos)
{ {
int m = SEEK_SET; int m = SEEK_SET;
switch (mode) { switch (mode) {
@ -262,18 +264,18 @@ bool CIODevice::seek(i64 offset, SeekMode mode, off_t* pos)
return true; return true;
} }
bool CIODevice::write(const u8* data, int size) bool IODevice::write(const u8* data, int size)
{ {
int rc = ::write(m_fd, data, size); int rc = ::write(m_fd, data, size);
if (rc < 0) { if (rc < 0) {
perror("CIODevice::write: write"); perror("IODevice::write: write");
set_error(errno); set_error(errno);
return false; return false;
} }
return rc == size; return rc == size;
} }
int CIODevice::printf(const char* format, ...) int IODevice::printf(const char* format, ...)
{ {
va_list ap; va_list ap;
va_start(ap, format); va_start(ap, format);
@ -286,7 +288,7 @@ int CIODevice::printf(const char* format, ...)
return ret; return ret;
} }
void CIODevice::set_fd(int fd) void IODevice::set_fd(int fd)
{ {
if (m_fd == fd) if (m_fd == fd)
return; return;
@ -294,3 +296,4 @@ void CIODevice::set_fd(int fd)
m_fd = fd; m_fd = fd;
did_update_fd(fd); did_update_fd(fd);
} }
}

View file

@ -30,8 +30,10 @@
#include <AK/StringView.h> #include <AK/StringView.h>
#include <LibCore/CObject.h> #include <LibCore/CObject.h>
class CIODevice : public CObject { namespace Core {
C_OBJECT_ABSTRACT(CIODevice)
class IODevice : public Object {
C_OBJECT_ABSTRACT(IODevice)
public: public:
enum OpenMode { enum OpenMode {
NotOpen = 0, NotOpen = 0,
@ -43,7 +45,7 @@ public:
MustBeNew = 16, MustBeNew = 16,
}; };
virtual ~CIODevice() override; virtual ~IODevice() override;
int fd() const { return m_fd; } int fd() const { return m_fd; }
unsigned mode() const { return m_mode; } unsigned mode() const { return m_mode; }
@ -55,7 +57,6 @@ public:
bool has_error() const { return m_error != 0; } bool has_error() const { return m_error != 0; }
int read(u8* buffer, int length); int read(u8* buffer, int length);
ByteBuffer read(int max_size); ByteBuffer read(int max_size);
@ -78,13 +79,13 @@ public:
bool seek(i64, SeekMode = SeekMode::SetPosition, off_t* = nullptr); bool seek(i64, SeekMode = SeekMode::SetPosition, off_t* = nullptr);
virtual bool open(CIODevice::OpenMode) = 0; virtual bool open(IODevice::OpenMode) = 0;
virtual bool close(); virtual bool close();
int printf(const char*, ...); int printf(const char*, ...);
protected: protected:
explicit CIODevice(CObject* parent = nullptr); explicit IODevice(Object* parent = nullptr);
void set_fd(int); void set_fd(int);
void set_mode(OpenMode mode) { m_mode = mode; } void set_mode(OpenMode mode) { m_mode = mode; }
@ -103,3 +104,5 @@ private:
OpenMode m_mode { NotOpen }; OpenMode m_mode { NotOpen };
Vector<u8> m_buffered_data; Vector<u8> m_buffered_data;
}; };
}

View file

@ -29,9 +29,11 @@
#include <AK/StdLibExtras.h> #include <AK/StdLibExtras.h>
#include <LibCore/CIODevice.h> #include <LibCore/CIODevice.h>
class CIODeviceStreamReader { namespace Core {
class IODeviceStreamReader {
public: public:
CIODeviceStreamReader(CIODevice& device) IODeviceStreamReader(IODevice& device)
: m_device(device) : m_device(device)
{ {
} }
@ -42,7 +44,7 @@ public:
} }
template<typename T> template<typename T>
CIODeviceStreamReader& operator>>(T& value) IODeviceStreamReader& operator>>(T& value)
{ {
int nread = m_device.read((u8*)&value, sizeof(T)); int nread = m_device.read((u8*)&value, sizeof(T));
ASSERT(nread == sizeof(T)); ASSERT(nread == sizeof(T));
@ -52,6 +54,8 @@ public:
} }
private: private:
CIODevice& m_device; IODevice& m_device;
bool m_had_failure { false }; bool m_had_failure { false };
}; };
}

View file

@ -35,16 +35,18 @@
#include <sys/ioctl.h> #include <sys/ioctl.h>
#endif #endif
CLocalServer::CLocalServer(CObject* parent) namespace Core {
: CObject(parent)
LocalServer::LocalServer(Object* parent)
: Object(parent)
{ {
} }
CLocalServer::~CLocalServer() LocalServer::~LocalServer()
{ {
} }
bool CLocalServer::take_over_from_system_server() bool LocalServer::take_over_from_system_server()
{ {
if (m_listening) if (m_listening)
return false; return false;
@ -84,16 +86,16 @@ bool CLocalServer::take_over_from_system_server()
return false; return false;
} }
void CLocalServer::setup_notifier() void LocalServer::setup_notifier()
{ {
m_notifier = CNotifier::construct(m_fd, CNotifier::Event::Read, this); m_notifier = Notifier::construct(m_fd, Notifier::Event::Read, this);
m_notifier->on_ready_to_read = [this] { m_notifier->on_ready_to_read = [this] {
if (on_ready_to_accept) if (on_ready_to_accept)
on_ready_to_accept(); on_ready_to_accept();
}; };
} }
bool CLocalServer::listen(const String& address) bool LocalServer::listen(const String& address)
{ {
if (m_listening) if (m_listening)
return false; return false;
@ -116,7 +118,7 @@ bool CLocalServer::listen(const String& address)
ASSERT_NOT_REACHED(); ASSERT_NOT_REACHED();
} }
auto socket_address = CSocketAddress::local(address); auto socket_address = SocketAddress::local(address);
auto un = socket_address.to_sockaddr_un(); auto un = socket_address.to_sockaddr_un();
rc = ::bind(m_fd, (const sockaddr*)&un, sizeof(un)); rc = ::bind(m_fd, (const sockaddr*)&un, sizeof(un));
if (rc < 0) { if (rc < 0) {
@ -135,7 +137,7 @@ bool CLocalServer::listen(const String& address)
return true; return true;
} }
RefPtr<CLocalSocket> CLocalServer::accept() RefPtr<LocalSocket> LocalServer::accept()
{ {
ASSERT(m_listening); ASSERT(m_listening);
sockaddr_un un; sockaddr_un un;
@ -146,5 +148,7 @@ RefPtr<CLocalSocket> CLocalServer::accept()
return nullptr; return nullptr;
} }
return CLocalSocket::construct(accepted_fd); return LocalSocket::construct(accepted_fd);
}
} }

View file

@ -29,27 +29,31 @@
#include <LibCore/CNotifier.h> #include <LibCore/CNotifier.h>
#include <LibCore/CObject.h> #include <LibCore/CObject.h>
class CLocalSocket; namespace Core {
class CLocalServer : public CObject { class LocalSocket;
C_OBJECT(CLocalServer)
class LocalServer : public Object {
C_OBJECT(LocalServer)
public: public:
virtual ~CLocalServer() override; virtual ~LocalServer() override;
bool take_over_from_system_server(); bool take_over_from_system_server();
bool is_listening() const { return m_listening; } bool is_listening() const { return m_listening; }
bool listen(const String& address); bool listen(const String& address);
RefPtr<CLocalSocket> accept(); RefPtr<LocalSocket> accept();
Function<void()> on_ready_to_accept; Function<void()> on_ready_to_accept;
private: private:
explicit CLocalServer(CObject* parent = nullptr); explicit LocalServer(Object* parent = nullptr);
void setup_notifier(); void setup_notifier();
int m_fd { -1 }; int m_fd { -1 };
bool m_listening { false }; bool m_listening { false };
RefPtr<CNotifier> m_notifier; RefPtr<Notifier> m_notifier;
}; };
}

View file

@ -25,25 +25,27 @@
*/ */
#include <LibCore/CLocalSocket.h> #include <LibCore/CLocalSocket.h>
#include <sys/socket.h>
#include <errno.h> #include <errno.h>
#include <sys/socket.h>
#ifndef SOCK_NONBLOCK #ifndef SOCK_NONBLOCK
#include <sys/ioctl.h> # include <sys/ioctl.h>
#endif #endif
CLocalSocket::CLocalSocket(int fd, CObject* parent) namespace Core {
: CSocket(CSocket::Type::Local, parent)
LocalSocket::LocalSocket(int fd, Object* parent)
: Socket(Socket::Type::Local, parent)
{ {
// NOTE: This constructor is used by CLocalServer::accept(), so the socket is already connected. // NOTE: This constructor is used by CLocalServer::accept(), so the socket is already connected.
m_connected = true; m_connected = true;
set_fd(fd); set_fd(fd);
set_mode(CIODevice::ReadWrite); set_mode(IODevice::ReadWrite);
set_error(0); set_error(0);
} }
CLocalSocket::CLocalSocket(CObject* parent) LocalSocket::LocalSocket(Object* parent)
: CSocket(CSocket::Type::Local, parent) : Socket(Socket::Type::Local, parent)
{ {
#ifdef SOCK_NONBLOCK #ifdef SOCK_NONBLOCK
@ -59,11 +61,13 @@ CLocalSocket::CLocalSocket(CObject* parent)
set_error(errno); set_error(errno);
} else { } else {
set_fd(fd); set_fd(fd);
set_mode(CIODevice::ReadWrite); set_mode(IODevice::ReadWrite);
set_error(0); set_error(0);
} }
} }
CLocalSocket::~CLocalSocket() LocalSocket::~LocalSocket()
{ {
} }
}

View file

@ -29,14 +29,18 @@
#include <AK/Badge.h> #include <AK/Badge.h>
#include <LibCore/CSocket.h> #include <LibCore/CSocket.h>
class CLocalServer; namespace Core {
class CLocalSocket final : public CSocket { class LocalServer;
C_OBJECT(CLocalSocket)
class LocalSocket final : public Socket {
C_OBJECT(LocalSocket)
public: public:
virtual ~CLocalSocket() override; virtual ~LocalSocket() override;
private: private:
explicit CLocalSocket(CObject* parent = nullptr); explicit LocalSocket(Object* parent = nullptr);
CLocalSocket(int fd, CObject* parent = nullptr); LocalSocket(int fd, Object* parent = nullptr);
}; };
}

View file

@ -30,19 +30,21 @@
//#define CNETWORKJOB_DEBUG //#define CNETWORKJOB_DEBUG
CNetworkJob::CNetworkJob() namespace Core {
NetworkJob::NetworkJob()
{ {
} }
CNetworkJob::~CNetworkJob() NetworkJob::~NetworkJob()
{ {
} }
void CNetworkJob::did_finish(NonnullRefPtr<CNetworkResponse>&& response) void NetworkJob::did_finish(NonnullRefPtr<NetworkResponse>&& response)
{ {
// NOTE: We protect ourselves here, since the on_finish callback may otherwise // NOTE: We protect ourselves here, since the on_finish callback may otherwise
// trigger destruction of this job somehow. // trigger destruction of this job somehow.
NonnullRefPtr<CNetworkJob> protector(*this); NonnullRefPtr<NetworkJob> protector(*this);
m_response = move(response); m_response = move(response);
#ifdef CNETWORKJOB_DEBUG #ifdef CNETWORKJOB_DEBUG
@ -53,11 +55,11 @@ void CNetworkJob::did_finish(NonnullRefPtr<CNetworkResponse>&& response)
shutdown(); shutdown();
} }
void CNetworkJob::did_fail(Error error) void NetworkJob::did_fail(Error error)
{ {
// NOTE: We protect ourselves here, since the on_finish callback may otherwise // NOTE: We protect ourselves here, since the on_finish callback may otherwise
// trigger destruction of this job somehow. // trigger destruction of this job somehow.
NonnullRefPtr<CNetworkJob> protector(*this); NonnullRefPtr<NetworkJob> protector(*this);
m_error = error; m_error = error;
#ifdef CNETWORKJOB_DEBUG #ifdef CNETWORKJOB_DEBUG
@ -68,18 +70,20 @@ void CNetworkJob::did_fail(Error error)
shutdown(); shutdown();
} }
const char* to_string(CNetworkJob::Error error) const char* to_string(NetworkJob::Error error)
{ {
switch (error) { switch (error) {
case CNetworkJob::Error::ProtocolFailed: case NetworkJob::Error::ProtocolFailed:
return "ProtocolFailed"; return "ProtocolFailed";
case CNetworkJob::Error::ConnectionFailed: case NetworkJob::Error::ConnectionFailed:
return "ConnectionFailed"; return "ConnectionFailed";
case CNetworkJob::Error::TransmissionFailed: case NetworkJob::Error::TransmissionFailed:
return "TransmissionFailed"; return "TransmissionFailed";
case CNetworkJob::Error::Cancelled: case NetworkJob::Error::Cancelled:
return "Cancelled"; return "Cancelled";
default: default:
return "(Unknown error)"; return "(Unknown error)";
} }
} }
}

View file

@ -29,10 +29,12 @@
#include <AK/Function.h> #include <AK/Function.h>
#include <LibCore/CObject.h> #include <LibCore/CObject.h>
class CNetworkResponse; namespace Core {
class CNetworkJob : public CObject { class NetworkResponse;
C_OBJECT(CNetworkJob)
class NetworkJob : public Object {
C_OBJECT_ABSTRACT(NetworkJob)
public: public:
enum class Error { enum class Error {
None, None,
@ -41,15 +43,15 @@ public:
ProtocolFailed, ProtocolFailed,
Cancelled, Cancelled,
}; };
virtual ~CNetworkJob() override; virtual ~NetworkJob() override;
Function<void(bool success)> on_finish; Function<void(bool success)> on_finish;
bool is_cancelled() const { return m_error == Error::Cancelled; } bool is_cancelled() const { return m_error == Error::Cancelled; }
bool has_error() const { return m_error != Error::None; } bool has_error() const { return m_error != Error::None; }
Error error() const { return m_error; } Error error() const { return m_error; }
CNetworkResponse* response() { return m_response.ptr(); } NetworkResponse* response() { return m_response.ptr(); }
const CNetworkResponse* response() const { return m_response.ptr(); } const NetworkResponse* response() const { return m_response.ptr(); }
virtual void start() = 0; virtual void start() = 0;
virtual void shutdown() = 0; virtual void shutdown() = 0;
@ -61,13 +63,15 @@ public:
} }
protected: protected:
CNetworkJob(); NetworkJob();
void did_finish(NonnullRefPtr<CNetworkResponse>&&); void did_finish(NonnullRefPtr<NetworkResponse>&&);
void did_fail(Error); void did_fail(Error);
private: private:
RefPtr<CNetworkResponse> m_response; RefPtr<NetworkResponse> m_response;
Error m_error { Error::None }; Error m_error { Error::None };
}; };
const char* to_string(CNetworkJob::Error); const char* to_string(NetworkJob::Error);
}

View file

@ -26,11 +26,15 @@
#include <LibCore/CNetworkResponse.h> #include <LibCore/CNetworkResponse.h>
CNetworkResponse::CNetworkResponse(ByteBuffer&& payload) namespace Core {
NetworkResponse::NetworkResponse(ByteBuffer&& payload)
: m_payload(payload) : m_payload(payload)
{ {
} }
CNetworkResponse::~CNetworkResponse() NetworkResponse::~NetworkResponse()
{ {
} }
}

View file

@ -29,16 +29,20 @@
#include <AK/ByteBuffer.h> #include <AK/ByteBuffer.h>
#include <AK/RefCounted.h> #include <AK/RefCounted.h>
class CNetworkResponse : public RefCounted<CNetworkResponse> { namespace Core {
class NetworkResponse : public RefCounted<NetworkResponse> {
public: public:
virtual ~CNetworkResponse(); virtual ~NetworkResponse();
bool is_error() const { return m_error; } bool is_error() const { return m_error; }
const ByteBuffer& payload() const { return m_payload; } const ByteBuffer& payload() const { return m_payload; }
protected: protected:
explicit CNetworkResponse(ByteBuffer&&); explicit NetworkResponse(ByteBuffer&&);
bool m_error { false }; bool m_error { false };
ByteBuffer m_payload; ByteBuffer m_payload;
}; };
}

View file

@ -28,34 +28,38 @@
#include <LibCore/CEventLoop.h> #include <LibCore/CEventLoop.h>
#include <LibCore/CNotifier.h> #include <LibCore/CNotifier.h>
CNotifier::CNotifier(int fd, unsigned event_mask, CObject* parent) namespace Core {
: CObject(parent)
Notifier::Notifier(int fd, unsigned event_mask, Object* parent)
: Object(parent)
, m_fd(fd) , m_fd(fd)
, m_event_mask(event_mask) , m_event_mask(event_mask)
{ {
set_enabled(true); set_enabled(true);
} }
CNotifier::~CNotifier() Notifier::~Notifier()
{ {
set_enabled(false); set_enabled(false);
} }
void CNotifier::set_enabled(bool enabled) void Notifier::set_enabled(bool enabled)
{ {
if (enabled) if (enabled)
CEventLoop::register_notifier({}, *this); Core::EventLoop::register_notifier({}, *this);
else else
CEventLoop::unregister_notifier({}, *this); Core::EventLoop::unregister_notifier({}, *this);
} }
void CNotifier::event(CEvent& event) void Notifier::event(Core::Event& event)
{ {
if (event.type() == CEvent::NotifierRead && on_ready_to_read) { if (event.type() == Core::Event::NotifierRead && on_ready_to_read) {
on_ready_to_read(); on_ready_to_read();
} else if (event.type() == CEvent::NotifierWrite && on_ready_to_write) { } else if (event.type() == Core::Event::NotifierWrite && on_ready_to_write) {
on_ready_to_write(); on_ready_to_write();
} else { } else {
CObject::event(event); Object::event(event);
} }
} }
}

View file

@ -29,8 +29,10 @@
#include <AK/Function.h> #include <AK/Function.h>
#include <LibCore/CObject.h> #include <LibCore/CObject.h>
class CNotifier : public CObject { namespace Core {
C_OBJECT(CNotifier)
class Notifier : public Object {
C_OBJECT(Notifier)
public: public:
enum Event { enum Event {
None = 0, None = 0,
@ -39,7 +41,7 @@ public:
Exceptional = 4, Exceptional = 4,
}; };
virtual ~CNotifier() override; virtual ~Notifier() override;
void set_enabled(bool); void set_enabled(bool);
@ -50,11 +52,13 @@ public:
unsigned event_mask() const { return m_event_mask; } unsigned event_mask() const { return m_event_mask; }
void set_event_mask(unsigned event_mask) { m_event_mask = event_mask; } void set_event_mask(unsigned event_mask) { m_event_mask = event_mask; }
void event(CEvent&) override; void event(Core::Event&) override;
private: private:
CNotifier(int fd, unsigned event_mask, CObject* parent = nullptr); Notifier(int fd, unsigned event_mask, Object* parent = nullptr);
int m_fd { -1 }; int m_fd { -1 };
unsigned m_event_mask { 0 }; unsigned m_event_mask { 0 };
}; };
}

View file

@ -32,13 +32,15 @@
#include <LibCore/CObject.h> #include <LibCore/CObject.h>
#include <stdio.h> #include <stdio.h>
IntrusiveList<CObject, &CObject::m_all_objects_list_node>& CObject::all_objects() namespace Core {
IntrusiveList<Object, &Object::m_all_objects_list_node>& Object::all_objects()
{ {
static IntrusiveList<CObject, &CObject::m_all_objects_list_node> objects; static IntrusiveList<Object, &Object::m_all_objects_list_node> objects;
return objects; return objects;
} }
CObject::CObject(CObject* parent, bool is_widget) Object::Object(Object* parent, bool is_widget)
: m_parent(parent) : m_parent(parent)
, m_widget(is_widget) , m_widget(is_widget)
{ {
@ -47,7 +49,7 @@ CObject::CObject(CObject* parent, bool is_widget)
m_parent->add_child(*this); m_parent->add_child(*this);
} }
CObject::~CObject() Object::~Object()
{ {
// NOTE: We move our children out to a stack vector to prevent other // NOTE: We move our children out to a stack vector to prevent other
// code from trying to iterate over them. // code from trying to iterate over them.
@ -63,89 +65,89 @@ CObject::~CObject()
m_parent->remove_child(*this); m_parent->remove_child(*this);
} }
void CObject::event(CEvent& event) void Object::event(Core::Event& event)
{ {
switch (event.type()) { switch (event.type()) {
case CEvent::Timer: case Core::Event::Timer:
return timer_event(static_cast<CTimerEvent&>(event)); return timer_event(static_cast<TimerEvent&>(event));
case CEvent::ChildAdded: case Core::Event::ChildAdded:
case CEvent::ChildRemoved: case Core::Event::ChildRemoved:
return child_event(static_cast<CChildEvent&>(event)); return child_event(static_cast<ChildEvent&>(event));
case CEvent::Invalid: case Core::Event::Invalid:
ASSERT_NOT_REACHED(); ASSERT_NOT_REACHED();
break; break;
case CEvent::Custom: case Core::Event::Custom:
return custom_event(static_cast<CCustomEvent&>(event)); return custom_event(static_cast<CustomEvent&>(event));
default: default:
break; break;
} }
} }
void CObject::add_child(CObject& object) void Object::add_child(Object& object)
{ {
// FIXME: Should we support reparenting objects? // FIXME: Should we support reparenting objects?
ASSERT(!object.parent() || object.parent() == this); ASSERT(!object.parent() || object.parent() == this);
object.m_parent = this; object.m_parent = this;
m_children.append(object); m_children.append(object);
event(*make<CChildEvent>(CEvent::ChildAdded, object)); event(*make<Core::ChildEvent>(Core::Event::ChildAdded, object));
} }
void CObject::insert_child_before(CObject& new_child, CObject& before_child) void Object::insert_child_before(Object& new_child, Object& before_child)
{ {
// FIXME: Should we support reparenting objects? // FIXME: Should we support reparenting objects?
ASSERT(!new_child.parent() || new_child.parent() == this); ASSERT(!new_child.parent() || new_child.parent() == this);
new_child.m_parent = this; new_child.m_parent = this;
m_children.insert_before_matching(new_child, [&](auto& existing_child) { return existing_child.ptr() == &before_child; }); m_children.insert_before_matching(new_child, [&](auto& existing_child) { return existing_child.ptr() == &before_child; });
event(*make<CChildEvent>(CEvent::ChildAdded, new_child, &before_child)); event(*make<Core::ChildEvent>(Core::Event::ChildAdded, new_child, &before_child));
} }
void CObject::remove_child(CObject& object) void Object::remove_child(Object& object)
{ {
for (int i = 0; i < m_children.size(); ++i) { for (int i = 0; i < m_children.size(); ++i) {
if (m_children.ptr_at(i).ptr() == &object) { if (m_children.ptr_at(i).ptr() == &object) {
// NOTE: We protect the child so it survives the handling of ChildRemoved. // NOTE: We protect the child so it survives the handling of ChildRemoved.
NonnullRefPtr<CObject> protector = object; NonnullRefPtr<Object> protector = object;
object.m_parent = nullptr; object.m_parent = nullptr;
m_children.remove(i); m_children.remove(i);
event(*make<CChildEvent>(CEvent::ChildRemoved, object)); event(*make<Core::ChildEvent>(Core::Event::ChildRemoved, object));
return; return;
} }
} }
ASSERT_NOT_REACHED(); ASSERT_NOT_REACHED();
} }
void CObject::timer_event(CTimerEvent&) void Object::timer_event(Core::TimerEvent&)
{ {
} }
void CObject::child_event(CChildEvent&) void Object::child_event(Core::ChildEvent&)
{ {
} }
void CObject::custom_event(CCustomEvent&) void Object::custom_event(CustomEvent&)
{ {
} }
void CObject::start_timer(int ms, TimerShouldFireWhenNotVisible fire_when_not_visible) void Object::start_timer(int ms, TimerShouldFireWhenNotVisible fire_when_not_visible)
{ {
if (m_timer_id) { if (m_timer_id) {
dbgprintf("CObject{%p} already has a timer!\n", this); dbgprintf("Object{%p} already has a timer!\n", this);
ASSERT_NOT_REACHED(); ASSERT_NOT_REACHED();
} }
m_timer_id = CEventLoop::register_timer(*this, ms, true, fire_when_not_visible); m_timer_id = Core::EventLoop::register_timer(*this, ms, true, fire_when_not_visible);
} }
void CObject::stop_timer() void Object::stop_timer()
{ {
if (!m_timer_id) if (!m_timer_id)
return; return;
bool success = CEventLoop::unregister_timer(m_timer_id); bool success = Core::EventLoop::unregister_timer(m_timer_id);
ASSERT(success); ASSERT(success);
m_timer_id = 0; m_timer_id = 0;
} }
void CObject::dump_tree(int indent) void Object::dump_tree(int indent)
{ {
for (int i = 0; i < indent; ++i) { for (int i = 0; i < indent; ++i) {
printf(" "); printf(" ");
@ -158,12 +160,12 @@ void CObject::dump_tree(int indent)
}); });
} }
void CObject::deferred_invoke(Function<void(CObject&)> invokee) void Object::deferred_invoke(Function<void(Object&)> invokee)
{ {
CEventLoop::current().post_event(*this, make<CDeferredInvocationEvent>(move(invokee))); Core::EventLoop::current().post_event(*this, make<Core::DeferredInvocationEvent>(move(invokee)));
} }
void CObject::save_to(JsonObject& json) void Object::save_to(JsonObject& json)
{ {
json.set("class_name", class_name()); json.set("class_name", class_name());
json.set("address", String::format("%p", this)); json.set("address", String::format("%p", this));
@ -171,7 +173,7 @@ void CObject::save_to(JsonObject& json)
json.set("parent", String::format("%p", parent())); json.set("parent", String::format("%p", parent()));
} }
bool CObject::is_ancestor_of(const CObject& other) const bool Object::is_ancestor_of(const Object& other) const
{ {
if (&other == this) if (&other == this)
return false; return false;
@ -182,7 +184,7 @@ bool CObject::is_ancestor_of(const CObject& other) const
return false; return false;
} }
void CObject::dispatch_event(CEvent& e, CObject* stay_within) void Object::dispatch_event(Core::Event& e, Object* stay_within)
{ {
ASSERT(!stay_within || stay_within == this || stay_within->is_ancestor_of(*this)); ASSERT(!stay_within || stay_within == this || stay_within->is_ancestor_of(*this));
auto* target = this; auto* target = this;
@ -197,9 +199,11 @@ void CObject::dispatch_event(CEvent& e, CObject* stay_within)
} while (target && !e.is_accepted()); } while (target && !e.is_accepted());
} }
bool CObject::is_visible_for_timer_purposes() const bool Object::is_visible_for_timer_purposes() const
{ {
if (parent()) if (parent())
return parent()->is_visible_for_timer_purposes(); return parent()->is_visible_for_timer_purposes();
return true; return true;
} }
}

View file

@ -40,16 +40,18 @@ namespace AK {
class JsonObject; class JsonObject;
} }
namespace Core {
enum class TimerShouldFireWhenNotVisible { enum class TimerShouldFireWhenNotVisible {
No = 0, No = 0,
Yes Yes
}; };
class CEvent; class ChildEvent;
class CEventLoop; class CustomEvent;
class CChildEvent; class Event;
class CCustomEvent; class EventLoop;
class CTimerEvent; class TimerEvent;
#define C_OBJECT(klass) \ #define C_OBJECT(klass) \
public: \ public: \
@ -64,26 +66,26 @@ public: \
public: \ public: \
virtual const char* class_name() const override { return #klass; } virtual const char* class_name() const override { return #klass; }
class CObject class Object
: public RefCounted<CObject> : public RefCounted<Object>
, public Weakable<CObject> { , public Weakable<Object> {
// NOTE: No C_OBJECT macro for CObject itself. // NOTE: No C_OBJECT macro for Core::Object itself.
AK_MAKE_NONCOPYABLE(CObject) AK_MAKE_NONCOPYABLE(Object)
AK_MAKE_NONMOVABLE(CObject) AK_MAKE_NONMOVABLE(Object)
public: public:
IntrusiveListNode m_all_objects_list_node; IntrusiveListNode m_all_objects_list_node;
virtual ~CObject(); virtual ~Object();
virtual const char* class_name() const = 0; virtual const char* class_name() const = 0;
virtual void event(CEvent&); virtual void event(Core::Event&);
const String& name() const { return m_name; } const String& name() const { return m_name; }
void set_name(const StringView& name) { m_name = name; } void set_name(const StringView& name) { m_name = name; }
NonnullRefPtrVector<CObject>& children() { return m_children; } NonnullRefPtrVector<Object>& children() { return m_children; }
const NonnullRefPtrVector<CObject>& children() const { return m_children; } const NonnullRefPtrVector<Object>& children() const { return m_children; }
template<typename Callback> template<typename Callback>
void for_each_child(Callback callback) void for_each_child(Callback callback)
@ -97,22 +99,22 @@ public:
template<typename T, typename Callback> template<typename T, typename Callback>
void for_each_child_of_type(Callback callback); void for_each_child_of_type(Callback callback);
bool is_ancestor_of(const CObject&) const; bool is_ancestor_of(const Object&) const;
CObject* parent() { return m_parent; } Object* parent() { return m_parent; }
const CObject* parent() const { return m_parent; } const Object* parent() const { return m_parent; }
void start_timer(int ms, TimerShouldFireWhenNotVisible = TimerShouldFireWhenNotVisible::No); void start_timer(int ms, TimerShouldFireWhenNotVisible = TimerShouldFireWhenNotVisible::No);
void stop_timer(); void stop_timer();
bool has_timer() const { return m_timer_id; } bool has_timer() const { return m_timer_id; }
void add_child(CObject&); void add_child(Object&);
void insert_child_before(CObject& new_child, CObject& before_child); void insert_child_before(Object& new_child, Object& before_child);
void remove_child(CObject&); void remove_child(Object&);
void dump_tree(int indent = 0); void dump_tree(int indent = 0);
void deferred_invoke(Function<void(CObject&)>); void deferred_invoke(Function<void(Object&)>);
bool is_widget() const { return m_widget; } bool is_widget() const { return m_widget; }
virtual bool is_action() const { return false; } virtual bool is_action() const { return false; }
@ -120,9 +122,9 @@ public:
virtual void save_to(AK::JsonObject&); virtual void save_to(AK::JsonObject&);
static IntrusiveList<CObject, &CObject::m_all_objects_list_node>& all_objects(); static IntrusiveList<Object, &Object::m_all_objects_list_node>& all_objects();
void dispatch_event(CEvent&, CObject* stay_within = nullptr); void dispatch_event(Core::Event&, Object* stay_within = nullptr);
void remove_from_parent() void remove_from_parent()
{ {
@ -133,41 +135,41 @@ public:
virtual bool is_visible_for_timer_purposes() const; virtual bool is_visible_for_timer_purposes() const;
protected: protected:
explicit CObject(CObject* parent = nullptr, bool is_widget = false); explicit Object(Object* parent = nullptr, bool is_widget = false);
virtual void timer_event(CTimerEvent&); virtual void timer_event(TimerEvent&);
virtual void custom_event(CCustomEvent&); virtual void custom_event(CustomEvent&);
// NOTE: You may get child events for children that are not yet fully constructed! // NOTE: You may get child events for children that are not yet fully constructed!
virtual void child_event(CChildEvent&); virtual void child_event(ChildEvent&);
private: private:
CObject* m_parent { nullptr }; Object* m_parent { nullptr };
String m_name; String m_name;
int m_timer_id { 0 }; int m_timer_id { 0 };
bool m_widget { false }; bool m_widget { false };
NonnullRefPtrVector<CObject> m_children; NonnullRefPtrVector<Object> m_children;
}; };
template<typename T> template<typename T>
inline bool is(const CObject&) { return false; } inline bool is(const Object&) { return false; }
template<typename T> template<typename T>
inline T& to(CObject& object) inline T& to(Object& object)
{ {
ASSERT(is<typename RemoveConst<T>::Type>(object)); ASSERT(is<typename RemoveConst<T>::Type>(object));
return static_cast<T&>(object); return static_cast<T&>(object);
} }
template<typename T> template<typename T>
inline const T& to(const CObject& object) inline const T& to(const Object& object)
{ {
ASSERT(is<typename RemoveConst<T>::Type>(object)); ASSERT(is<typename RemoveConst<T>::Type>(object));
return static_cast<const T&>(object); return static_cast<const T&>(object);
} }
template<typename T, typename Callback> template<typename T, typename Callback>
inline void CObject::for_each_child_of_type(Callback callback) inline void Object::for_each_child_of_type(Callback callback)
{ {
for_each_child([&](auto& child) { for_each_child([&](auto& child) {
if (is<T>(child)) if (is<T>(child))
@ -176,7 +178,9 @@ inline void CObject::for_each_child_of_type(Callback callback)
}); });
} }
inline const LogStream& operator<<(const LogStream& stream, const CObject& object) inline const LogStream& operator<<(const LogStream& stream, const Object& object)
{ {
return stream << object.class_name() << '{' << &object << '}'; return stream << object.class_name() << '{' << &object << '}';
} }
}

View file

@ -32,23 +32,25 @@
#include <pwd.h> #include <pwd.h>
#include <stdio.h> #include <stdio.h>
HashMap<uid_t, String> CProcessStatisticsReader::s_usernames; namespace Core {
HashMap<pid_t, CProcessStatistics> CProcessStatisticsReader::get_all() HashMap<uid_t, String> ProcessStatisticsReader::s_usernames;
HashMap<pid_t, Core::ProcessStatistics> ProcessStatisticsReader::get_all()
{ {
auto file = CFile::construct("/proc/all"); auto file = Core::File::construct("/proc/all");
if (!file->open(CIODevice::ReadOnly)) { if (!file->open(Core::IODevice::ReadOnly)) {
fprintf(stderr, "CProcessStatisticsReader: Failed to open /proc/all: %s\n", file->error_string()); fprintf(stderr, "CProcessStatisticsReader: Failed to open /proc/all: %s\n", file->error_string());
return {}; return {};
} }
HashMap<pid_t, CProcessStatistics> map; HashMap<pid_t, Core::ProcessStatistics> map;
auto file_contents = file->read_all(); auto file_contents = file->read_all();
auto json = JsonValue::from_string({ file_contents.data(), (size_t)file_contents.size() }); auto json = JsonValue::from_string({ file_contents.data(), (size_t)file_contents.size() });
json.as_array().for_each([&](auto& value) { json.as_array().for_each([&](auto& value) {
const JsonObject& process_object = value.as_object(); const JsonObject& process_object = value.as_object();
CProcessStatistics process; Core::ProcessStatistics process;
// kernel data first // kernel data first
process.pid = process_object.get("pid").to_u32(); process.pid = process_object.get("pid").to_u32();
@ -76,7 +78,7 @@ HashMap<pid_t, CProcessStatistics> CProcessStatisticsReader::get_all()
process.threads.ensure_capacity(thread_array.size()); process.threads.ensure_capacity(thread_array.size());
thread_array.for_each([&](auto& value) { thread_array.for_each([&](auto& value) {
auto& thread_object = value.as_object(); auto& thread_object = value.as_object();
CThreadStatistics thread; Core::ThreadStatistics thread;
thread.tid = thread_object.get("tid").to_u32(); thread.tid = thread_object.get("tid").to_u32();
thread.times_scheduled = thread_object.get("times_scheduled").to_u32(); thread.times_scheduled = thread_object.get("times_scheduled").to_u32();
thread.name = thread_object.get("name").to_string(); thread.name = thread_object.get("name").to_string();
@ -105,7 +107,7 @@ HashMap<pid_t, CProcessStatistics> CProcessStatisticsReader::get_all()
return map; return map;
} }
String CProcessStatisticsReader::username_from_uid(uid_t uid) String ProcessStatisticsReader::username_from_uid(uid_t uid)
{ {
if (s_usernames.is_empty()) { if (s_usernames.is_empty()) {
setpwent(); setpwent();
@ -119,3 +121,4 @@ String CProcessStatisticsReader::username_from_uid(uid_t uid)
return (*it).value; return (*it).value;
return String::number(uid); return String::number(uid);
} }
}

View file

@ -30,7 +30,9 @@
#include <AK/String.h> #include <AK/String.h>
#include <unistd.h> #include <unistd.h>
struct CThreadStatistics { namespace Core {
struct ThreadStatistics {
int tid; int tid;
unsigned times_scheduled; unsigned times_scheduled;
unsigned ticks; unsigned ticks;
@ -50,7 +52,7 @@ struct CThreadStatistics {
String name; String name;
}; };
struct CProcessStatistics { struct ProcessStatistics {
// Keep this in sync with /proc/all. // Keep this in sync with /proc/all.
// From the kernel side: // From the kernel side:
pid_t pid; pid_t pid;
@ -74,17 +76,19 @@ struct CProcessStatistics {
size_t amount_purgeable_nonvolatile; size_t amount_purgeable_nonvolatile;
int icon_id; int icon_id;
Vector<CThreadStatistics> threads; Vector<Core::ThreadStatistics> threads;
// synthetic // synthetic
String username; String username;
}; };
class CProcessStatisticsReader { class ProcessStatisticsReader {
public: public:
static HashMap<pid_t, CProcessStatistics> get_all(); static HashMap<pid_t, Core::ProcessStatistics> get_all();
private: private:
static String username_from_uid(uid_t); static String username_from_uid(uid_t);
static HashMap<uid_t, String> s_usernames; static HashMap<uid_t, String> s_usernames;
}; };
}

View file

@ -38,33 +38,35 @@
//#define CSOCKET_DEBUG //#define CSOCKET_DEBUG
CSocket::CSocket(Type type, CObject* parent) namespace Core {
: CIODevice(parent)
Socket::Socket(Type type, Object* parent)
: IODevice(parent)
, m_type(type) , m_type(type)
{ {
} }
CSocket::~CSocket() Socket::~Socket()
{ {
close(); close();
} }
bool CSocket::connect(const String& hostname, int port) bool Socket::connect(const String& hostname, int port)
{ {
auto* hostent = gethostbyname(hostname.characters()); auto* hostent = gethostbyname(hostname.characters());
if (!hostent) { if (!hostent) {
dbg() << "CSocket::connect: Unable to resolve '" << hostname << "'"; dbg() << "Socket::connect: Unable to resolve '" << hostname << "'";
return false; return false;
} }
IPv4Address host_address((const u8*)hostent->h_addr_list[0]); IPv4Address host_address((const u8*)hostent->h_addr_list[0]);
#ifdef CSOCKET_DEBUG #ifdef CSOCKET_DEBUG
dbg() << "CSocket::connect: Resolved '" << hostname << "' to " << host_address; dbg() << "Socket::connect: Resolved '" << hostname << "' to " << host_address;
#endif #endif
return connect(host_address, port); return connect(host_address, port);
} }
void CSocket::set_blocking(bool blocking) void Socket::set_blocking(bool blocking)
{ {
int flags = fcntl(fd(), F_GETFL, 0); int flags = fcntl(fd(), F_GETFL, 0);
ASSERT(flags >= 0); ASSERT(flags >= 0);
@ -75,10 +77,10 @@ void CSocket::set_blocking(bool blocking)
ASSERT(flags == 0); ASSERT(flags == 0);
} }
bool CSocket::connect(const CSocketAddress& address, int port) bool Socket::connect(const SocketAddress& address, int port)
{ {
ASSERT(!is_connected()); ASSERT(!is_connected());
ASSERT(address.type() == CSocketAddress::Type::IPv4); ASSERT(address.type() == SocketAddress::Type::IPv4);
#ifdef CSOCKET_DEBUG #ifdef CSOCKET_DEBUG
dbg() << *this << " connecting to " << address << "..."; dbg() << *this << " connecting to " << address << "...";
#endif #endif
@ -98,10 +100,10 @@ bool CSocket::connect(const CSocketAddress& address, int port)
return common_connect((struct sockaddr*)&addr, sizeof(addr)); return common_connect((struct sockaddr*)&addr, sizeof(addr));
} }
bool CSocket::connect(const CSocketAddress& address) bool Socket::connect(const SocketAddress& address)
{ {
ASSERT(!is_connected()); ASSERT(!is_connected());
ASSERT(address.type() == CSocketAddress::Type::Local); ASSERT(address.type() == SocketAddress::Type::Local);
#ifdef CSOCKET_DEBUG #ifdef CSOCKET_DEBUG
dbg() << *this << " connecting to " << address << "..."; dbg() << *this << " connecting to " << address << "...";
#endif #endif
@ -113,7 +115,7 @@ bool CSocket::connect(const CSocketAddress& address)
return common_connect((const sockaddr*)&saddr, sizeof(saddr)); return common_connect((const sockaddr*)&saddr, sizeof(saddr));
} }
bool CSocket::common_connect(const struct sockaddr* addr, socklen_t addrlen) bool Socket::common_connect(const struct sockaddr* addr, socklen_t addrlen)
{ {
int rc = ::connect(fd(), addr, addrlen); int rc = ::connect(fd(), addr, addrlen);
if (rc < 0) { if (rc < 0) {
@ -121,20 +123,20 @@ bool CSocket::common_connect(const struct sockaddr* addr, socklen_t addrlen)
#ifdef CSOCKET_DEBUG #ifdef CSOCKET_DEBUG
dbg() << *this << " connection in progress (EINPROGRESS)"; dbg() << *this << " connection in progress (EINPROGRESS)";
#endif #endif
m_notifier = CNotifier::construct(fd(), CNotifier::Event::Write, this); m_notifier = Notifier::construct(fd(), Notifier::Event::Write, this);
m_notifier->on_ready_to_write = [this] { m_notifier->on_ready_to_write = [this] {
#ifdef CSOCKET_DEBUG #ifdef CSOCKET_DEBUG
dbg() << *this << " connected!"; dbg() << *this << " connected!";
#endif #endif
m_connected = true; m_connected = true;
ensure_read_notifier(); ensure_read_notifier();
m_notifier->set_event_mask(CNotifier::Event::None); m_notifier->set_event_mask(Notifier::Event::None);
if (on_connected) if (on_connected)
on_connected(); on_connected();
}; };
return true; return true;
} }
perror("CSocket::common_connect: connect"); perror("Socket::common_connect: connect");
return false; return false;
} }
#ifdef CSOCKET_DEBUG #ifdef CSOCKET_DEBUG
@ -147,7 +149,7 @@ bool CSocket::common_connect(const struct sockaddr* addr, socklen_t addrlen)
return true; return true;
} }
ByteBuffer CSocket::receive(int max_size) ByteBuffer Socket::receive(int max_size)
{ {
auto buffer = read(max_size); auto buffer = read(max_size);
if (eof()) { if (eof()) {
@ -157,7 +159,7 @@ ByteBuffer CSocket::receive(int max_size)
return buffer; return buffer;
} }
bool CSocket::send(const ByteBuffer& data) bool Socket::send(const ByteBuffer& data)
{ {
int nsent = ::send(fd(), data.data(), data.size(), 0); int nsent = ::send(fd(), data.data(), data.size(), 0);
if (nsent < 0) { if (nsent < 0) {
@ -168,7 +170,7 @@ bool CSocket::send(const ByteBuffer& data)
return true; return true;
} }
void CSocket::did_update_fd(int fd) void Socket::did_update_fd(int fd)
{ {
if (fd < 0) { if (fd < 0) {
m_read_notifier = nullptr; m_read_notifier = nullptr;
@ -182,12 +184,14 @@ void CSocket::did_update_fd(int fd)
} }
} }
void CSocket::ensure_read_notifier() void Socket::ensure_read_notifier()
{ {
ASSERT(m_connected); ASSERT(m_connected);
m_read_notifier = CNotifier::construct(fd(), CNotifier::Event::Read, this); m_read_notifier = Notifier::construct(fd(), Notifier::Event::Read, this);
m_read_notifier->on_ready_to_read = [this] { m_read_notifier->on_ready_to_read = [this] {
if (on_ready_to_read) if (on_ready_to_read)
on_ready_to_read(); on_ready_to_read();
}; };
} }
}

View file

@ -29,10 +29,12 @@
#include <LibCore/CIODevice.h> #include <LibCore/CIODevice.h>
#include <LibCore/CSocketAddress.h> #include <LibCore/CSocketAddress.h>
class CNotifier; namespace Core {
class CSocket : public CIODevice { class Notifier;
C_OBJECT(CSocket)
class Socket : public IODevice {
C_OBJECT(Socket)
public: public:
enum class Type { enum class Type {
Invalid, Invalid,
@ -40,13 +42,13 @@ public:
UDP, UDP,
Local, Local,
}; };
virtual ~CSocket() override; virtual ~Socket() override;
Type type() const { return m_type; } Type type() const { return m_type; }
bool connect(const String& hostname, int port); bool connect(const String& hostname, int port);
bool connect(const CSocketAddress&, int port); bool connect(const SocketAddress&, int port);
bool connect(const CSocketAddress&); bool connect(const SocketAddress&);
ByteBuffer receive(int max_size); ByteBuffer receive(int max_size);
bool send(const ByteBuffer&); bool send(const ByteBuffer&);
@ -54,20 +56,20 @@ public:
bool is_connected() const { return m_connected; } bool is_connected() const { return m_connected; }
void set_blocking(bool blocking); void set_blocking(bool blocking);
CSocketAddress source_address() const { return m_source_address; } SocketAddress source_address() const { return m_source_address; }
int source_port() const { return m_source_port; } int source_port() const { return m_source_port; }
CSocketAddress destination_address() const { return m_source_address; } SocketAddress destination_address() const { return m_source_address; }
int destination_port() const { return m_destination_port; } int destination_port() const { return m_destination_port; }
Function<void()> on_connected; Function<void()> on_connected;
Function<void()> on_ready_to_read; Function<void()> on_ready_to_read;
protected: protected:
CSocket(Type, CObject* parent); Socket(Type, Object* parent);
CSocketAddress m_source_address; SocketAddress m_source_address;
CSocketAddress m_destination_address; SocketAddress m_destination_address;
int m_source_port { -1 }; int m_source_port { -1 };
int m_destination_port { -1 }; int m_destination_port { -1 };
bool m_connected { false }; bool m_connected { false };
@ -75,11 +77,13 @@ protected:
virtual void did_update_fd(int) override; virtual void did_update_fd(int) override;
private: private:
virtual bool open(CIODevice::OpenMode) override { ASSERT_NOT_REACHED(); } virtual bool open(IODevice::OpenMode) override { ASSERT_NOT_REACHED(); }
bool common_connect(const struct sockaddr*, socklen_t); bool common_connect(const struct sockaddr*, socklen_t);
void ensure_read_notifier(); void ensure_read_notifier();
Type m_type { Type::Invalid }; Type m_type { Type::Invalid };
RefPtr<CNotifier> m_notifier; RefPtr<Notifier> m_notifier;
RefPtr<CNotifier> m_read_notifier; RefPtr<Notifier> m_read_notifier;
}; };
}

Some files were not shown because too many files have changed in this diff Show more