diff --git a/src/app.cpp b/src/app.cpp index 8780491..0454ed8 100644 --- a/src/app.cpp +++ b/src/app.cpp @@ -58,16 +58,23 @@ void Application::add_on_state_change_event(std::function on /* * Use this method if you want to send an email from currently selected email address. */ -void Application::send_email(const MessageToSend& email){ +bool Application::send_email(const MessageToSend& email){ logging::log("app_send_email"); if(email.recipient.empty() || email.subject.empty() || email.body.empty()){ - return; + return false; } - Mailbox mailbox = get_current_mailbox(); - - mailbox.send(email); + try { + Mailbox mailbox = get_current_mailbox(); + if(!mailbox.send(email)){ + return false; + } + } catch (const std::exception& e) { + logging::log(std::string("Error sending email: ") + e.what()); + return false; + } logging::log("email sent"); + return true; } void Application::synchronize() diff --git a/src/app.hpp b/src/app.hpp index fa2efc2..694cabe 100644 --- a/src/app.hpp +++ b/src/app.hpp @@ -24,7 +24,8 @@ class Application { void add_on_state_change_event(std::function); void set_current_email_address(std::string new_address); std::string get_current_email_address(); - void send_email(const MessageToSend& email); + // Returns false if the email could not be sent + bool send_email(const MessageToSend& email); void synchronize(); std::vector fetch_email_headers(); std::string get_email_body(const std::string& uid, const std::string& folder_path); diff --git a/src/backend/mailbox.cpp b/src/backend/mailbox.cpp index 77e8e8c..d3106a0 100644 --- a/src/backend/mailbox.cpp +++ b/src/backend/mailbox.cpp @@ -17,7 +17,7 @@ Mailbox::Mailbox(Account account) : account(account) {} -void Mailbox::send(const MessageToSend &message) noexcept +bool Mailbox::send(const MessageToSend &message) noexcept { logging::log("mailbox_send"); try { @@ -46,12 +46,15 @@ void Mailbox::send(const MessageToSend &message) noexcept transport->disconnect(); MailStorage::save_sent_email(message, account.username); + return true; } catch (vmime::exception& e) { logging::log("Error sending email: " + (std::string)e.what()); + return false; } catch (std::exception& e) { logging::log("General error: " + (std::string)e.what()); + return false; } } diff --git a/src/backend/mailbox.h b/src/backend/mailbox.h index a2a0a4f..bcf959a 100644 --- a/src/backend/mailbox.h +++ b/src/backend/mailbox.h @@ -9,7 +9,8 @@ class Mailbox { public: Mailbox(Account account); - void send(const MessageToSend& message) noexcept; + // Returns false if the message could not be sent (details go to the log) + bool send(const MessageToSend& message) noexcept; void synchronize() noexcept; std::vector get_email_headers() noexcept; std::string get_email_body(const std::string& uid, const std::string& folder_path) noexcept; diff --git a/src/frontend/CMakeLists.txt b/src/frontend/CMakeLists.txt index 862cafc..ee08124 100644 --- a/src/frontend/CMakeLists.txt +++ b/src/frontend/CMakeLists.txt @@ -1,10 +1,16 @@ -target_sources(email_client_core - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/app_frontend.cpp - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/email_window.cpp - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/login_dialog.cpp - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/new_account_dialog.cpp - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/TPasswordInputLine.cpp - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/inbox_window.cpp - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/app_theme.cpp +set(FRONTEND_SOURCES + ${CMAKE_CURRENT_SOURCE_DIR}/app_frontend.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/email_window.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/login_dialog.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/new_account_dialog.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/TPasswordInputLine.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/inbox_window.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/app_theme.cpp +) +target_sources(email_client_core PRIVATE ${FRONTEND_SOURCES}) + +# Warnings only for the frontend sources, so the rest of the project is not +# flooded. (add_compile_options() here had no effect: the target already exists.) +set_source_files_properties(${FRONTEND_SOURCES} TARGET_DIRECTORY email_client_core + PROPERTIES COMPILE_OPTIONS "-Wall;-Wextra;-Wpedantic" ) -add_compile_options(-Wall -Wextra -Wpedantic) diff --git a/src/frontend/app_frontend.cpp b/src/frontend/app_frontend.cpp index ea0025e..439ae04 100644 --- a/src/frontend/app_frontend.cpp +++ b/src/frontend/app_frontend.cpp @@ -6,8 +6,7 @@ Application_frontend::Application_frontend(Application& app) : TProgInit(&Application_frontend::initStatusLine, &Application_frontend::initMenuBar, &Application_frontend::initDeskTop), - app(app), loginSucceeded(false){ - deskTop->insert(new EmailWindow(deskTop->getExtent(), app)); + loginSucceeded(false), app(app) { } @@ -17,6 +16,7 @@ TStatusLine* Application_frontend::initStatusLine(TRect r){ return new TStatusLine(r, *new TStatusDef(0, 0xFFFF) + *new TStatusItem("~Alt-X~ Exit", kbAltX, cmQuit) + + *new TStatusItem("~F2~ New email", kbF2, cmNewMail) + *new TStatusItem(0, kbF10, cmMenu) ); } diff --git a/src/frontend/app_theme.hpp b/src/frontend/app_theme.hpp index 8037ce4..c876824 100644 --- a/src/frontend/app_theme.hpp +++ b/src/frontend/app_theme.hpp @@ -1,3 +1,4 @@ +#pragma once #include #include #include diff --git a/src/frontend/email_window.cpp b/src/frontend/email_window.cpp index c7b4bce..256a9cd 100644 --- a/src/frontend/email_window.cpp +++ b/src/frontend/email_window.cpp @@ -6,8 +6,8 @@ #include "commands.hpp" EmailWindow::EmailWindow(const TRect &bounds, Application& app) : - TWindow(bounds, "Compose Email", wnNoNumber), TWindowInit(&EmailWindow::initFrame), + TWindow(bounds, "Compose Email", wnNoNumber), app(app) { int margin = 2; @@ -25,7 +25,9 @@ EmailWindow::EmailWindow(const TRect &bounds, Application& app) : insert(new TLabel(TRect(margin, y, margin + labelW, y + 1), "~F~rom:", this)); fromField = new TInputLine(TRect(inputX, y, rightEdge, y + 1), 128); - strcpy(fromField->data, app.get_current_email_address().c_str()); + strnzcpy(fromField->data, app.get_current_email_address(), 128); + // Mail is always sent from the logged in account, so the field is read-only + fromField->options &= ~ofSelectable; insert(fromField); y += 2; @@ -72,27 +74,68 @@ EmailWindow::EmailWindow(const TRect &bounds, Application& app) : insert(new TButton(TRect(startX, btnY, startX + btnW, btnY + 2), "~C~ancel", cmCancel, bfNormal)); + + // Start in the "To" field, not on the last inserted button + toField->select(); +} + +// TEditor keeps the text in a gap buffer, so `buffer` is not a plain string: +// after editing in the middle it holds the gap and may not end with '\0'. +std::string EmailWindow::bodyText() const { + std::string text; + text.reserve(bodyEditor->bufLen); + for (uint i = 0; i < bodyEditor->bufLen; ++i) { + text += bodyEditor->bufChar(i); + } + return text; +} + +void EmailWindow::send() { + MessageToSend outgoing; + outgoing.recipient = toField->data; + outgoing.subject = subjectField->data; + outgoing.body = bodyText(); + + if (outgoing.recipient.empty()) { + messageBox("Enter the recipient (To).", mfError | mfOKButton); + toField->select(); + return; + } + if (outgoing.subject.empty()) { + messageBox("Enter the subject.", mfError | mfOKButton); + subjectField->select(); + return; + } + if (outgoing.body.empty()) { + messageBox("The message is empty.", mfError | mfOKButton); + bodyEditor->select(); + return; + } + + if (!app.send_email(outgoing)) { + // Keep the window open so the user does not lose the text + messageBox("Could not send the email. Check the recipient address and your connection.", + mfError | mfOKButton); + return; + } + // TODO: also copy_to Sent mails (need backend fix) + + messageBox("Email sent.", mfInformation | mfOKButton); + close(); } void EmailWindow::handleEvent(TEvent& event){ TWindow::handleEvent(event); if (event.what == evCommand) { if(event.message.command == cmSend){ - MessageToSend outgoing; - outgoing.recipient = toField->data; - outgoing.subject = subjectField->data; - outgoing.body = bodyEditor->buffer; - - app.send_email(outgoing); - // TODO: also copy_to Sent mails (need backend fix) - - close(); clearEvent(event); + send(); return; } else if(event.message.command == cmCancel){ - close(); + // close() deletes this window, so nothing may touch it afterwards clearEvent(event); + close(); return; } } diff --git a/src/frontend/email_window.hpp b/src/frontend/email_window.hpp index bfe94a4..0e0cac8 100644 --- a/src/frontend/email_window.hpp +++ b/src/frontend/email_window.hpp @@ -1,3 +1,4 @@ +#pragma once #include "app.hpp" #define Uses_TWindow #define Uses_TInputLine @@ -5,6 +6,7 @@ #define Uses_TLabel #define Uses_TScrollBar #define Uses_TButton +#define Uses_MsgBox #include @@ -18,6 +20,8 @@ class EmailWindow : public TWindow { TScrollBar *vScroll, *hScroll; virtual TColorAttr mapColor(uchar index) noexcept override; + std::string bodyText() const; + void send(); public: EmailWindow(const TRect &bounds, Application& app); diff --git a/src/frontend/inbox_window.cpp b/src/frontend/inbox_window.cpp index b554b41..8535849 100644 --- a/src/frontend/inbox_window.cpp +++ b/src/frontend/inbox_window.cpp @@ -16,10 +16,10 @@ class UnsortedStringCollection : public TStringCollection { }; InboxWindow::InboxWindow(const TRect& bounds, Application& app) : - TWindow(bounds, "Inbox", wnNoNumber), TWindowInit(&InboxWindow::initFrame), - currentContentView(nullptr), - app(app) + TWindow(bounds, "Inbox", wnNoNumber), + app(app), + currentContentView(nullptr) { fetchMailData(); @@ -135,8 +135,6 @@ void InboxWindow::handleEvent(TEvent& event) { } } } - - TWindow::handleEvent(event); } TColorAttr InboxWindow::mapColor(uchar index) noexcept { diff --git a/src/frontend/inbox_window.hpp b/src/frontend/inbox_window.hpp index ab46577..ef1db71 100644 --- a/src/frontend/inbox_window.hpp +++ b/src/frontend/inbox_window.hpp @@ -1,3 +1,4 @@ +#pragma once #include "app.hpp" #include "backend/mail_types.h" #define Uses_TWindow diff --git a/src/frontend/login_dialog.cpp b/src/frontend/login_dialog.cpp index 8311d73..bd7b132 100644 --- a/src/frontend/login_dialog.cpp +++ b/src/frontend/login_dialog.cpp @@ -3,15 +3,14 @@ #include "account_helper.hpp" LoginDialog::LoginDialog(TRect r, Application& app) : - TDialog(r, "Login"), TWindowInit(&TDialog::initFrame), + TDialog(r, "Login"), app(app) { options |= ofCentered; int marginX = 2; int topY = 2; int bottomY = size.y - 4; - int listWidth = size.x - (2 * marginX); insert(new TLabel(TRect(marginX, 1, size.x, 2), "Choose account:", this)); @@ -51,15 +50,20 @@ LoginDialog::LoginDialog(TRect r, Application& app) : insert(new TButton(TRect(startX, btnY, startX + wCancel, btnY + 2), "Exit", cmCancel, bfNormal)); + + // Start with the account list focused. Otherwise the last inserted view + // ("Exit") has the focus and pressing Enter closes the application. + list->select(); } std::string LoginDialog::username() const { if(list == nullptr || list->range == 0 || list->focused < 0 || list->focused >= list->range){ return ""; } - int idx=list->focused; - char* user = new char[50]; - list->getText(user, idx, 50); + // TListBox::getText() writes the terminating '\0' at dest[maxLen], + // so pass one less than the buffer size + char user[256]; + list->getText(user, list->focused, sizeof(user) - 1); return std::string(user); } @@ -71,6 +75,14 @@ void LoginDialog::handleEvent(TEvent& event){ } TDialog::handleEvent(event); + + // Double click or Space on an account works like "Choose" + // (Enter already does, through the default button). + if (event.what == evBroadcast && event.message.command == cmListItemSelected + && event.message.infoPtr == list) { + clearEvent(event); + endModal(cmOK); + } } Boolean LoginDialog::valid(ushort command){ @@ -82,30 +94,45 @@ Boolean LoginDialog::valid(ushort command){ std::string selected_user = username(); if(selected_user.empty()){ - return false; + messageBox("No account selected. Create one with \"New account\".", + mfInformation | mfOKButton); + return false; } - app.set_current_email_address(selected_user); + try { + app.set_current_email_address(selected_user); + } catch (const std::exception& e) { + logging::log(std::string("Login failed: ") + e.what()); + messageBox(std::string("Could not log in:\n") + e.what(), mfError | mfOKButton); + return false; + } } return true; } std::vector LoginDialog::get_accounts(){ + std::vector accounts; + std::ifstream configFile(Application::get_config_path()); if (!configFile){ logging::log("Failed to open config.json"); + return accounts; } - nlohmann::json config; - configFile >> config; - - std::vector emails_passwords; - for(auto& account : config) { - emails_passwords.push_back(accountFromJson(account)); + // A broken config.json used to crash the whole application here + try { + nlohmann::json config; + configFile >> config; + for(auto& account : config) { + accounts.push_back(accountFromJson(account)); + } + } catch (const std::exception& e) { + logging::log(std::string("Failed to read config.json: ") + e.what()); + accounts.clear(); } - return emails_passwords; + return accounts; } TColorAttr LoginDialog::mapColor(uchar index) noexcept { diff --git a/src/frontend/login_dialog.hpp b/src/frontend/login_dialog.hpp index cbb55a7..edcb966 100644 --- a/src/frontend/login_dialog.hpp +++ b/src/frontend/login_dialog.hpp @@ -1,3 +1,4 @@ +#pragma once #include "backend/account.h" #define Uses_TDialog #define Uses_TInputLine @@ -9,6 +10,7 @@ #define Uses_TStringCollection #define Uses_TProgram #define Uses_TDeskTop +#define Uses_MsgBox #include #include #include @@ -33,6 +35,6 @@ class LoginDialog : public TDialog { virtual Boolean valid(ushort command) override; public: - LoginDialog(TRect r, Application& app);; + LoginDialog(TRect r, Application& app); std::string username() const; }; diff --git a/src/frontend/new_account_dialog.cpp b/src/frontend/new_account_dialog.cpp index 4d98c3e..74ff0b1 100644 --- a/src/frontend/new_account_dialog.cpp +++ b/src/frontend/new_account_dialog.cpp @@ -1,18 +1,26 @@ #include "new_account_dialog.hpp" #include "app_theme.hpp" #include "account_helper.hpp" +#include + +namespace { + // One length limit for every field; hosts and app passwords can be long + constexpr int fieldMaxLen = 256; +} NewAccountDialog::NewAccountDialog(TRect r, Application& app) : - TDialog(r, "Create new account"), TWindowInit(&TDialog::initFrame), + TDialog(r, "Create new account"), app(app) { options |= ofCentered; - int labelW = 6; - int inputW = 26; + int labelW = 11; // fits the longest label, "SMTP Host:" + int inputW = 40; int gap = 1; int formTotalWidth = labelW + gap + inputW; int formStartX = (size.x - formTotalWidth) / 2; + if (formStartX < 1) formStartX = 1; + int inputX = formStartX + labelW + gap; int wCreate = 12; int wLogin = 17; @@ -20,39 +28,32 @@ NewAccountDialog::NewAccountDialog(TRect r, Application& app) : int rowBtnWidth = wCreate + btnGap + wLogin; int rowBtnX = (size.x - rowBtnWidth) / 2; - int groupHeight = 6; + int groupHeight = 10; // 4 fields every 2 rows + buttons int availableHeight = size.y - 3; int y = (availableHeight - groupHeight) / 2; if (y < 1) y = 1; - insert(new TLabel(TRect(formStartX, y, formStartX + labelW, y + 1), "User:", this)); - user = new TInputLine(TRect(formStartX + labelW + gap, y, formStartX + labelW + gap + inputW, y + 1), 40); - insert(user); - - y += 2; + auto addField = [&](const char* label, TInputLine* input) { + insert(new TLabel(TRect(formStartX, y, formStartX + labelW, y + 1), label, input)); + insert(input); + y += 2; + }; - insert(new TLabel(TRect(formStartX, y, formStartX + labelW, y + 1), "Pass:", this)); - pass = new TPasswordInputLine(TRect(formStartX + labelW + gap, y, formStartX + labelW + gap + inputW, y + 1), 100); - insert(pass); + user = new TInputLine(TRect(inputX, y, inputX + inputW, y + 1), fieldMaxLen); + addField("~U~ser:", user); - y += 2; + pass = new TPasswordInputLine(TRect(inputX, y, inputX + inputW, y + 1), fieldMaxLen); + addField("~P~ass:", pass); - insert(new TLabel(TRect(formStartX, y, formStartX + labelW, y + 1), "SMTP Host:", this)); - smtpHost = new TInputLine(TRect(formStartX + labelW + gap, y, formStartX + labelW + gap + inputW, y + 1), 100); - strcpy(smtpHost->data, "smtps://smtp.gmail.com:465"); - insert(smtpHost); - - y += 1; - - insert(new TLabel(TRect(formStartX, y, formStartX + labelW, y + 1), "IMAP Host:", this)); - imapHost = new TInputLine(TRect(formStartX + labelW + gap, y, formStartX + labelW + gap + inputW, y + 1), 40); - strcpy(imapHost->data, "imaps://imap.gmail.com:993"); - insert(imapHost); - - y += 2; + smtpHost = new TInputLine(TRect(inputX, y, inputX + inputW, y + 1), fieldMaxLen); + strnzcpy(smtpHost->data, "smtps://smtp.gmail.com:465", fieldMaxLen); + addField("~S~MTP Host:", smtpHost); + imapHost = new TInputLine(TRect(inputX, y, inputX + inputW, y + 1), fieldMaxLen); + strnzcpy(imapHost->data, "imaps://imap.gmail.com:993", fieldMaxLen); + addField("~I~MAP Host:", imapHost); insert(new TButton(TRect(rowBtnX, y, rowBtnX + wCreate, y + 2), "~C~reate", cmOK, bfDefault)); @@ -68,6 +69,9 @@ NewAccountDialog::NewAccountDialog(TRect r, Application& app) : insert(new TButton(TRect(exitX, bottomY, exitX + wExit, bottomY + 2), "Exit", cmCancel, bfNormal)); + + // Start typing in the first field instead of having "Exit" focused + user->select(); } @@ -81,37 +85,103 @@ Account NewAccountDialog::account() const { } void NewAccountDialog::handleEvent(TEvent& event){ - if (event.what == evCommand){ - switch (event.message.command) { - case cmOK: - add_account(account()); - app.set_current_email_address(account().username); - break; - case cmLogin: - endModal(cmLogin); - break; - } + if (event.what == evCommand && event.message.command == cmLogin){ + endModal(cmLogin); + clearEvent(event); + return; } TDialog::handleEvent(event); } -void NewAccountDialog::add_account(const Account& new_account){ - std::ifstream configFile(Application::get_config_path()); - if (!configFile){ - logging::log("Failed to open config.json"); - return; +// "Create" ends the dialog only after the form is valid and the account is saved +Boolean NewAccountDialog::valid(ushort command){ + if(!TDialog::valid(command)){ + return false; + } + if(command != cmOK){ + return true; + } + + Account new_account = account(); + if(!validate(new_account) || !add_account(new_account)){ + return false; + } + + try { + app.set_current_email_address(new_account.username); + } catch (const std::exception& e) { + logging::log(std::string("Login failed: ") + e.what()); + messageBox(std::string("Could not log in:\n") + e.what(), mfError | mfOKButton); + return false; } + return true; +} - nlohmann::json config; - configFile >> config; +bool NewAccountDialog::validate(const Account& account){ + auto fail = [](const char* msg) { + messageBox(msg, mfError | mfOKButton); + return false; + }; - nlohmann::json new_account_json = accountToJson(new_account); - config.push_back(new_account_json); + if(account.username.empty() || account.password.empty() + || account.smtpHost.empty() || account.imapHost.empty()){ + return fail("All fields are required."); + } + if(account.username.find('@') == std::string::npos){ + return fail("User must be an email address, e.g. alice@example.com."); + } + if(account.smtpHost.find("://") == std::string::npos){ + return fail("SMTP host must be a URL, e.g. smtps://smtp.gmail.com:465."); + } + if(account.imapHost.find("://") == std::string::npos){ + return fail("IMAP host must be a URL, e.g. imaps://imap.gmail.com:993."); + } + return true; +} + +bool NewAccountDialog::add_account(const Account& new_account){ + const std::string path = Application::get_config_path(); - configFile.close(); - std::ofstream new_config_file(Application::get_config_path(), std::ios::trunc); + nlohmann::json config = nlohmann::json::array(); + try { + std::ifstream configFile(path); + if (configFile){ + configFile >> config; + } + } catch (const std::exception& e) { + logging::log(std::string("Failed to read config.json: ") + e.what()); + messageBox("config.json is damaged, the account was not saved.", mfError | mfOKButton); + return false; + } + + for (const auto& existing : config) { + if (existing.value("username", "") == new_account.username) { + messageBox("This account already exists.", mfError | mfOKButton); + return false; + } + } + + config.push_back(accountToJson(new_account)); + + std::ofstream new_config_file(path, std::ios::trunc); new_config_file << config; + new_config_file.close(); + if (!new_config_file) { + logging::log("Failed to write config.json"); + messageBox("Could not save config.json.", mfError | mfOKButton); + return false; + } + + // The file holds passwords: readable only by the user (was 0664) + std::error_code ec; + std::filesystem::permissions(path, + std::filesystem::perms::owner_read | std::filesystem::perms::owner_write, + std::filesystem::perm_options::replace, ec); + if (ec) { + logging::log("Failed to set config.json permissions: " + ec.message()); + } + return true; } TColorAttr NewAccountDialog::mapColor(uchar index) noexcept { diff --git a/src/frontend/new_account_dialog.hpp b/src/frontend/new_account_dialog.hpp index d049392..8b6eed4 100644 --- a/src/frontend/new_account_dialog.hpp +++ b/src/frontend/new_account_dialog.hpp @@ -1,8 +1,10 @@ +#pragma once #define Uses_TDialog #define Uses_TInputLine #define Uses_TLabel #define Uses_TButton #define Uses_TEvent +#define Uses_MsgBox #include #include #include @@ -20,12 +22,15 @@ class NewAccountDialog : public TDialog { TInputLine *smtpHost; TInputLine *imapHost; - void add_account(const Account& new_account); + bool add_account(const Account& new_account); + bool validate(const Account& account); virtual TColorAttr mapColor(uchar) noexcept override; virtual void handleEvent(TEvent& event) override; + virtual Boolean valid(ushort command) override; + public: NewAccountDialog(TRect r, Application& app); Account account() const;