diff --git a/module-apps/Application.cpp b/module-apps/Application.cpp index a29aa2666..3b4925a30 100644 --- a/module-apps/Application.cpp +++ b/module-apps/Application.cpp @@ -8,9 +8,9 @@ */ #include #include -//module-utils +// module-utils #include "log/log.hpp" -//module-services +// module-services #include "service-gui/messages/DrawMessage.hpp" #include "service-appmgr/messages/APMMessage.hpp" #include "service-evtmgr/messages/EVMessages.hpp" @@ -18,10 +18,10 @@ #include "service-db/api/DBServiceAPI.hpp" #include "service-cellular/ServiceCellular.hpp" #include "service-cellular/api/CellularServiceAPI.hpp" -//module-gui +// module-gui #include "gui/core/DrawCommand.hpp" #include "gui/input/InputEvent.hpp" -//module-sys +// module-sys #include "SystemManager/SystemManager.hpp" #include "Application.hpp" @@ -33,12 +33,12 @@ #include "common_data/EventStore.hpp" -namespace app { +namespace app +{ const char *Application::stateStr(Application::State st) { - switch (st) - { + switch (st) { case State::NONE: return "NONE"; case State::DEACTIVATED: @@ -58,571 +58,570 @@ namespace app { } } - Application::Application(std::string name, std::string parent, bool startBackground, uint32_t stackDepth, sys::ServicePriority priority) - : Service(name, parent, stackDepth, priority), longPressTimer(CreateAppTimer( - key_timer_ms, true, [&]() { longPressTimerCallback(); }, "longPressTimer")), + Application::Application( + std::string name, std::string parent, bool startBackground, uint32_t stackDepth, sys::ServicePriority priority) + : Service(name, parent, stackDepth, priority), + longPressTimer(CreateAppTimer( + key_timer_ms, true, [&]() { longPressTimerCallback(); }, "longPressTimer")), startBackground{startBackground} { keyTranslator = std::make_unique(); busChannels.push_back(sys::BusChannels::ServiceCellularNotifications); - if (startBackground) - { + if (startBackground) { setState(State::ACTIVE_BACKGROUND); } longPressTimer.restart(); -} - -Application::~Application() -{ - for (auto it = windows.begin(); it != windows.end(); it++) - { - delete it->second; } - windows.clear(); -} -Application::State Application::getState() -{ - return state; -} + Application::~Application() + { + for (auto it = windows.begin(); it != windows.end(); it++) { + delete it->second; + } + windows.clear(); + } -void Application::setState(State st) -{ + Application::State Application::getState() + { + return state; + } + + void Application::setState(State st) + { #if DEBUG_APPLICATION_MANAGEMENT == 1 - LOG_DEBUG("[%s] (%s) -> (%s)", GetName().c_str(), stateStr(state), stateStr(st)); + LOG_DEBUG("[%s] (%s) -> (%s)", GetName().c_str(), stateStr(state), stateStr(st)); #endif - state = st; -} + state = st; + } -void Application::TickHandler(uint32_t id) -{ - auto appTimer = std::find(appTimers.begin(), appTimers.end(), id); - if (appTimer != appTimers.end()) + void Application::TickHandler(uint32_t id) { - appTimer->runCallback(); - } - else{ - LOG_ERROR("Requested timer doesn't exist here (ID: %s)\n", std::to_string(id).c_str()); // either timer was deleted or this id should not arrive. - } -} - -void Application::DeleteTimer(AppTimer &timer) -{ - Service::DeleteTimer(timer.getID()); // remove the real FreeRTOS timer - auto timerOnTheList = std::find(appTimers.begin(), appTimers.end(), timer); - if (timerOnTheList != appTimers.end()) - { - appTimers.erase(timerOnTheList); - } -} - -[[deprecated("only for compatibility")]] -void Application::DeleteTimer(uint32_t id) -{ - auto found = std::find(appTimers.begin(), appTimers.end(), id); - if (found != appTimers.end()){ - DeleteTimer(*found); - } -} - -void Application::longPressTimerCallback() -{ - // TODO if(check widget type long press trigger) - uint32_t time = xTaskGetTickCount(); - if (keyTranslator->timeout(time)) - { - // previous key press was over standard keypress timeout - send long press - gui::InputEvent iev = keyTranslator->translate(time); - messageInputEventApplication(this, this->GetName(), iev); - // clean previous key - keyTranslator->prev_key_press = {}; - } -} - -void Application::render( gui::RefreshModes mode ) { - if (getCurrentWindow() == nullptr) - { - LOG_ERROR("Current window is not defined"); - return; - } - - //send drawing commands only when if application is in active and visible. - if( state == State::ACTIVE_FORGROUND ) { - auto currwin = getCurrentWindow(); - if (Store::Battery::get().state == Store::Battery::State::Charging) - { - currwin->batteryCharging(true); + auto appTimer = std::find(appTimers.begin(), appTimers.end(), id); + if (appTimer != appTimers.end()) { + appTimer->runCallback(); } - else - { - currwin->updateBatteryLevel(Store::Battery::get().level); - } - currwin->setSIM(); - currwin->updateSignalStrength(); - - std::list commandsList = currwin->buildDrawList(); - - if( shutdownInProgress ) { - auto msg = std::make_shared(commandsList, mode, sgui::DrawMessage::DrawCommand::SHUTDOWN ); - sys::Bus::SendUnicast(msg, "ServiceGUI", this); - } - else if( suspendInProgress ) { - auto msg = std::make_shared(commandsList, mode, sgui::DrawMessage::DrawCommand::SUSPEND ); - sys::Bus::SendUnicast(msg, "ServiceGUI", this); - } - else { - auto msg = std::make_shared(commandsList, mode, sgui::DrawMessage::DrawCommand::NORMAL ); - sys::Bus::SendUnicast(msg, "ServiceGUI", this); - } - } - - if( suspendInProgress ) - suspendInProgress = false; -} -void Application::blockEvents(bool isBlocked ) { - acceptInput = isBlocked; -} -int Application::switchWindow( const std::string& windowName, gui::ShowMode cmd, std::unique_ptr data ) { - - std::string window; -#if DEBUG_APPLICATION_MANAGEMENT == 1 - LOG_INFO("switching [%s] to window: %s data description: %s", GetName().c_str(), - windowName.length() ? windowName.c_str() : gui::name::window::main_window.c_str(), data ? data->getDescription().c_str() : ""); -#endif - - //case to handle returning to previous application - if( windowName == "LastWindow" ) { - window = getCurrentWindow()->getName(); - auto msg = std::make_shared(window, getCurrentWindow()->getName(), std::move(data), cmd); - sys::Bus::SendUnicast(msg, this->GetName(), this ); - } - else { - window = windowName.empty() ? gui::name::window::main_window : windowName; - auto msg = std::make_shared(window, getCurrentWindow() ? getCurrentWindow()->getName() : "", std::move(data), cmd); - sys::Bus::SendUnicast(msg, this->GetName(), this ); - } - - return 0; -} - -// TODO: this one seems to be unused -int Application::switchBackWindow( const std::string& windowName, uint32_t cmd, std::unique_ptr data ) { - auto msg = std::make_shared( MessageType::AppSwitchWindowBack ); - sys::Bus::SendUnicast(msg, this->GetName(), this ); - - return 0; -} -int Application::refreshWindow(gui::RefreshModes mode) { - auto msg = std::make_shared( mode ); - sys::Bus::SendUnicast(msg, this->GetName(), this ); - - return 0; -} - -bool Application::signalStrengthUpdateHandler() -{ - if ((state == State::ACTIVE_FORGROUND) && getCurrentWindow()->updateSignalStrength()) - { - refreshWindow(gui::RefreshModes::GUI_REFRESH_FAST); - } - - return true; -} - -sys::Message_t Application::DataReceivedHandler(sys::DataMessage* msgl) { - - bool handled = false; - - auto msg = dynamic_cast(msgl); - if (msg != nullptr && msg->type == CellularNotificationMessage::Type::SignalStrengthUpdate) - { - handled = signalStrengthUpdateHandler(); - } - else if (msgl->messageType == MessageType::AppInputEvent) - { - AppInputEventMessage* msg = reinterpret_cast( msgl ); - if (getCurrentWindow() != nullptr) - getCurrentWindow()->onInput(msg->getEvent()); - - // LOG_INFO( "Key event :%s", msg->getEvent().to_string().c_str()); - handled = true; - } - else if (msgl->messageType == MessageType::KBDKeyEvent) - { - if (this->getState() != app::Application::State::ACTIVE_FORGROUND) - { - LOG_FATAL("!!! Terrible terrible damage! application with no focus grabbed key!"); - } - sevm::KbdMessage *msg = static_cast(msgl); - gui::InputEvent iev = keyTranslator->translate(msg->key); - if(iev.keyCode != gui::KeyCode::KEY_UNDEFINED ) { - messageInputEventApplication( this, this->GetName(), iev ); - } - handled = true; - } - else if (msgl->messageType == MessageType::EVMBatteryLevel) - { - sevm::BatteryLevelMessage* msg = static_cast(msgl); - LOG_INFO("Application battery level: %d", msg->levelPercents ); - - if (getCurrentWindow()->updateBatteryLevel(msg->levelPercents)) - { - refreshWindow(gui::RefreshModes::GUI_REFRESH_FAST); - } - - handled = true; - } - else if (msgl->messageType == MessageType::EVMChargerPlugged) - { - sevm::BatteryPlugMessage* msg = static_cast(msgl); - if(msg->plugged == true) { - LOG_INFO("Application charger connected" ); - getCurrentWindow()->batteryCharging(true); - refreshWindow(gui::RefreshModes::GUI_REFRESH_FAST); - } - else { - //hide plug icon - LOG_INFO("Application charger disconnected" ); - getCurrentWindow()->batteryCharging(false); - refreshWindow(gui::RefreshModes::GUI_REFRESH_FAST); - } - - refreshWindow( gui::RefreshModes::GUI_REFRESH_FAST ); - handled = true; - } - else if (msgl->messageType == MessageType::EVMMinuteUpdated) - { - sevm::RtcMinuteAlarmMessage* msg = static_cast(msgl); - LOG_INFO("Application time updated"); - - getCurrentWindow()->updateTime(msg->timestamp, !settings.timeFormat12); - - if( state == State::ACTIVE_FORGROUND ) - refreshWindow( gui::RefreshModes::GUI_REFRESH_FAST ); - - handled = true; - } - - else if (msgl->messageType == MessageType::AppSwitch) - { - LOG_DEBUG("AppSwitch"); - AppSwitchMessage *msg = reinterpret_cast(msgl); - // Application is starting or it is in the background. Upon switch command if name if correct it goes foreground - if ((state == State::ACTIVATING) || (state == State::INITIALIZING) || (state == State::ACTIVE_BACKGROUND)) - { - - if( msg->getTargetApplicationName() == this->GetName()) { - setState(State::ACTIVE_FORGROUND); - if( sapm::ApplicationManager::messageConfirmSwitch(this) ) { - LOG_INFO("%s : %s", msg->getTargetWindowName().c_str(), msg->getData() ? msg->getData()->getDescription().c_str() : ""); - switchWindow( msg->getTargetWindowName(), std::move( msg->getData())); - handled = true; - } - else { - //TODO send to itself message to close - LOG_ERROR("Failed to communicate "); - } - } - else { - LOG_ERROR("Received switch message outside of activation flow"); - } - } - else if( state == State::ACTIVE_FORGROUND ) { - if( msg->getTargetApplicationName() == this->GetName()) { - //if window name and data are null pointers this is a message informing - //that application should go to background mode - if( (msg->getTargetWindowName() == "") && (msg->getData() == nullptr ) ) { - setState(State::ACTIVE_BACKGROUND); - if( sapm::ApplicationManager::messageConfirmSwitch(this) ) { - handled = true; - } - else { - //TODO send to itself message to close - LOG_ERROR("Failed to communicate "); - } - } - //if application is in front and receives message with defined window it should - //change to that window. - else { - switchWindow( msg->getTargetWindowName(), std::move( msg->getData())); - handled = true; - } - } - else { - LOG_ERROR("Received switch message outside of activation flow"); - } - } - else { - LOG_ERROR("Wrong internal application %s switch to ACTIVE state form %s", msg->getTargetApplicationName().c_str(), stateStr(state)); + else { + LOG_ERROR("Requested timer doesn't exist here (ID: %s)\n", + std::to_string(id).c_str()); // either timer was deleted or this id should not arrive. } } - else if (msgl->messageType == MessageType::AppSwitchWindow) + + void Application::DeleteTimer(AppTimer &timer) { - AppSwitchWindowMessage* msg = reinterpret_cast( msgl ); - //check if specified window is in the application - auto it = windows.find( msg->getWindowName() ); - if( it != windows.end() ) { + Service::DeleteTimer(timer.getID()); // remove the real FreeRTOS timer + auto timerOnTheList = std::find(appTimers.begin(), appTimers.end(), timer); + if (timerOnTheList != appTimers.end()) { + appTimers.erase(timerOnTheList); + } + } - setActiveWindow( msg->getWindowName() ); + [[deprecated("only for compatibility")]] void Application::DeleteTimer(uint32_t id) + { + auto found = std::find(appTimers.begin(), appTimers.end(), id); + if (found != appTimers.end()) { + DeleteTimer(*found); + } + } - getCurrentWindow()->handleSwitchData(msg->getData().get()); + void Application::longPressTimerCallback() + { + // TODO if(check widget type long press trigger) + uint32_t time = xTaskGetTickCount(); + if (keyTranslator->timeout(time)) { + // previous key press was over standard keypress timeout - send long press + gui::InputEvent iev = keyTranslator->translate(time); + messageInputEventApplication(this, this->GetName(), iev); + // clean previous key + keyTranslator->prev_key_press = {}; + } + } - //check if this is case where application is returning to the last visible window. - if ((msg->getData() != nullptr) && (msg->LastSeenWindow)) {} + void Application::render(gui::RefreshModes mode) + { + if (getCurrentWindow() == nullptr) { + LOG_ERROR("Current window is not defined"); + return; + } + + // send drawing commands only when if application is in active and visible. + if (state == State::ACTIVE_FORGROUND) { + auto currwin = getCurrentWindow(); + if (Store::Battery::get().state == Store::Battery::State::Charging) { + currwin->batteryCharging(true); + } else { - getCurrentWindow()->onBeforeShow(msg->getCommand(), msg->getData().get()); - auto ret = dynamic_cast(msg->getData().get()); - if (ret != nullptr && msg->getData() != nullptr) - { - auto text = dynamic_cast(getCurrentWindow()->getFocusItem()); - if (text) - { - if (text->handleChar(ret->getDescription()[0])) - { - text->updateCursor(); + currwin->updateBatteryLevel(Store::Battery::get().level); + } + currwin->setSIM(); + currwin->updateSignalStrength(); + + std::list commandsList = currwin->buildDrawList(); + + if (shutdownInProgress) { + auto msg = + std::make_shared(commandsList, mode, sgui::DrawMessage::DrawCommand::SHUTDOWN); + sys::Bus::SendUnicast(msg, "ServiceGUI", this); + } + else if (suspendInProgress) { + auto msg = + std::make_shared(commandsList, mode, sgui::DrawMessage::DrawCommand::SUSPEND); + sys::Bus::SendUnicast(msg, "ServiceGUI", this); + } + else { + auto msg = + std::make_shared(commandsList, mode, sgui::DrawMessage::DrawCommand::NORMAL); + sys::Bus::SendUnicast(msg, "ServiceGUI", this); + } + } + + if (suspendInProgress) + suspendInProgress = false; + } + void Application::blockEvents(bool isBlocked) + { + acceptInput = isBlocked; + } + int Application::switchWindow(const std::string &windowName, + gui::ShowMode cmd, + std::unique_ptr data) + { + + std::string window; +#if DEBUG_APPLICATION_MANAGEMENT == 1 + LOG_INFO("switching [%s] to window: %s data description: %s", + GetName().c_str(), + windowName.length() ? windowName.c_str() : gui::name::window::main_window.c_str(), + data ? data->getDescription().c_str() : ""); +#endif + + // case to handle returning to previous application + if (windowName == "LastWindow") { + window = getCurrentWindow()->getName(); + auto msg = + std::make_shared(window, getCurrentWindow()->getName(), std::move(data), cmd); + sys::Bus::SendUnicast(msg, this->GetName(), this); + } + else { + window = windowName.empty() ? gui::name::window::main_window : windowName; + auto msg = std::make_shared( + window, getCurrentWindow() ? getCurrentWindow()->getName() : "", std::move(data), cmd); + sys::Bus::SendUnicast(msg, this->GetName(), this); + } + + return 0; + } + + // TODO: this one seems to be unused + int Application::switchBackWindow(const std::string &windowName, + uint32_t cmd, + std::unique_ptr data) + { + auto msg = std::make_shared(MessageType::AppSwitchWindowBack); + sys::Bus::SendUnicast(msg, this->GetName(), this); + + return 0; + } + int Application::refreshWindow(gui::RefreshModes mode) + { + auto msg = std::make_shared(mode); + sys::Bus::SendUnicast(msg, this->GetName(), this); + + return 0; + } + + bool Application::signalStrengthUpdateHandler() + { + if ((state == State::ACTIVE_FORGROUND) && getCurrentWindow()->updateSignalStrength()) { + refreshWindow(gui::RefreshModes::GUI_REFRESH_FAST); + } + + return true; + } + + sys::Message_t Application::DataReceivedHandler(sys::DataMessage *msgl) + { + + bool handled = false; + + auto msg = dynamic_cast(msgl); + if (msg != nullptr && msg->type == CellularNotificationMessage::Type::SignalStrengthUpdate) { + handled = signalStrengthUpdateHandler(); + } + else if (msgl->messageType == MessageType::AppInputEvent) { + AppInputEventMessage *msg = reinterpret_cast(msgl); + if (getCurrentWindow() != nullptr) + getCurrentWindow()->onInput(msg->getEvent()); + + // LOG_INFO( "Key event :%s", msg->getEvent().to_string().c_str()); + handled = true; + } + else if (msgl->messageType == MessageType::KBDKeyEvent) { + if (this->getState() != app::Application::State::ACTIVE_FORGROUND) { + LOG_FATAL("!!! Terrible terrible damage! application with no focus grabbed key!"); + } + sevm::KbdMessage *msg = static_cast(msgl); + gui::InputEvent iev = keyTranslator->translate(msg->key); + if (iev.keyCode != gui::KeyCode::KEY_UNDEFINED) { + messageInputEventApplication(this, this->GetName(), iev); + } + handled = true; + } + else if (msgl->messageType == MessageType::EVMBatteryLevel) { + sevm::BatteryLevelMessage *msg = static_cast(msgl); + LOG_INFO("Application battery level: %d", msg->levelPercents); + + if (getCurrentWindow()->updateBatteryLevel(msg->levelPercents)) { + refreshWindow(gui::RefreshModes::GUI_REFRESH_FAST); + } + + handled = true; + } + else if (msgl->messageType == MessageType::EVMChargerPlugged) { + sevm::BatteryPlugMessage *msg = static_cast(msgl); + if (msg->plugged == true) { + LOG_INFO("Application charger connected"); + getCurrentWindow()->batteryCharging(true); + refreshWindow(gui::RefreshModes::GUI_REFRESH_FAST); + } + else { + // hide plug icon + LOG_INFO("Application charger disconnected"); + getCurrentWindow()->batteryCharging(false); + refreshWindow(gui::RefreshModes::GUI_REFRESH_FAST); + } + + refreshWindow(gui::RefreshModes::GUI_REFRESH_FAST); + handled = true; + } + else if (msgl->messageType == MessageType::EVMMinuteUpdated) { + sevm::RtcMinuteAlarmMessage *msg = static_cast(msgl); + LOG_INFO("Application time updated"); + + getCurrentWindow()->updateTime(msg->timestamp, !settings.timeFormat12); + + if (state == State::ACTIVE_FORGROUND) + refreshWindow(gui::RefreshModes::GUI_REFRESH_FAST); + + handled = true; + } + + else if (msgl->messageType == MessageType::AppSwitch) { + LOG_DEBUG("AppSwitch"); + AppSwitchMessage *msg = reinterpret_cast(msgl); + // Application is starting or it is in the background. Upon switch command if name if correct it goes + // foreground + if ((state == State::ACTIVATING) || (state == State::INITIALIZING) || (state == State::ACTIVE_BACKGROUND)) { + + if (msg->getTargetApplicationName() == this->GetName()) { + setState(State::ACTIVE_FORGROUND); + if (sapm::ApplicationManager::messageConfirmSwitch(this)) { + LOG_INFO("%s : %s", + msg->getTargetWindowName().c_str(), + msg->getData() ? msg->getData()->getDescription().c_str() : ""); + switchWindow(msg->getTargetWindowName(), std::move(msg->getData())); + handled = true; + } + else { + // TODO send to itself message to close + LOG_ERROR("Failed to communicate "); + } + } + else { + LOG_ERROR("Received switch message outside of activation flow"); + } + } + else if (state == State::ACTIVE_FORGROUND) { + if (msg->getTargetApplicationName() == this->GetName()) { + // if window name and data are null pointers this is a message informing + // that application should go to background mode + if ((msg->getTargetWindowName() == "") && (msg->getData() == nullptr)) { + setState(State::ACTIVE_BACKGROUND); + if (sapm::ApplicationManager::messageConfirmSwitch(this)) { + handled = true; + } + else { + // TODO send to itself message to close + LOG_ERROR("Failed to communicate "); + } + } + // if application is in front and receives message with defined window it should + // change to that window. + else { + switchWindow(msg->getTargetWindowName(), std::move(msg->getData())); + handled = true; + } + } + else { + LOG_ERROR("Received switch message outside of activation flow"); + } + } + else { + LOG_ERROR("Wrong internal application %s switch to ACTIVE state form %s", + msg->getTargetApplicationName().c_str(), + stateStr(state)); + } + } + else if (msgl->messageType == MessageType::AppSwitchWindow) { + AppSwitchWindowMessage *msg = reinterpret_cast(msgl); + // check if specified window is in the application + auto it = windows.find(msg->getWindowName()); + if (it != windows.end()) { + + setActiveWindow(msg->getWindowName()); + + getCurrentWindow()->handleSwitchData(msg->getData().get()); + + // check if this is case where application is returning to the last visible window. + if ((msg->getData() != nullptr) && (msg->LastSeenWindow)) {} + else { + getCurrentWindow()->onBeforeShow(msg->getCommand(), msg->getData().get()); + auto ret = dynamic_cast(msg->getData().get()); + if (ret != nullptr && msg->getData() != nullptr) { + auto text = dynamic_cast(getCurrentWindow()->getFocusItem()); + if (text) { + if (text->handleChar(ret->getDescription()[0])) { + text->updateCursor(); + } } } } - } - refreshWindow( gui::RefreshModes::GUI_REFRESH_DEEP ); - } - else - { - LOG_ERROR("No such window: %s", msg->getWindowName().c_str()); - } - handled = true; - } - - else if (msgl->messageType == MessageType::AppClose) - { - setState(State::DEACTIVATING); - sapm::ApplicationManager::messageConfirmClose(this); - //here should go all the cleaning - handled = true; - } - else if (msgl->messageType == MessageType::AppRebuild) - { - - LOG_INFO("Application %s rebuilding gui", GetName().c_str() ); - //for all windows call rebuild method - for (auto it = windows.begin(); it != windows.end(); it++) - { - LOG_DEBUG("Rebuild: %s", it->first.c_str()); - if (!it->second) - { - LOG_ERROR("NO SUCH WINDOW"); + refreshWindow(gui::RefreshModes::GUI_REFRESH_DEEP); } - else - { - it->second->rebuild(); + else { + LOG_ERROR("No such window: %s", msg->getWindowName().c_str()); } + handled = true; } - //if application has focus call deep refresh - LOG_INFO("Refresh app with focus!"); - if (state == State::ACTIVE_FORGROUND) - { + + else if (msgl->messageType == MessageType::AppClose) { + setState(State::DEACTIVATING); + sapm::ApplicationManager::messageConfirmClose(this); + // here should go all the cleaning + handled = true; + } + else if (msgl->messageType == MessageType::AppRebuild) { + + LOG_INFO("Application %s rebuilding gui", GetName().c_str()); + // for all windows call rebuild method + for (auto it = windows.begin(); it != windows.end(); it++) { + LOG_DEBUG("Rebuild: %s", it->first.c_str()); + if (!it->second) { + LOG_ERROR("NO SUCH WINDOW"); + } + else { + it->second->rebuild(); + } + } + // if application has focus call deep refresh + LOG_INFO("Refresh app with focus!"); + if (state == State::ACTIVE_FORGROUND) { + refreshWindow(gui::RefreshModes::GUI_REFRESH_DEEP); + } + handled = true; + LOG_INFO("App rebuild done"); + } + else if (msgl->messageType == MessageType::AppRefresh) { + AppRefreshMessage *msg = reinterpret_cast(msgl); + // getCurrentWindow()->onBeforeShow( gui::ShowMode::GUI_SHOW_RETURN, 0, nullptr ); + render(msg->getMode()); + handled = true; + } + else if (dynamic_cast(msgl) != nullptr) { + getCurrentWindow()->setSIM(); refreshWindow(gui::RefreshModes::GUI_REFRESH_DEEP); } - handled = true; - LOG_INFO("App rebuild done"); - } - else if (msgl->messageType == MessageType::AppRefresh) - { - AppRefreshMessage* msg = reinterpret_cast( msgl ); - // getCurrentWindow()->onBeforeShow( gui::ShowMode::GUI_SHOW_RETURN, 0, nullptr ); - render( msg->getMode() ); - handled = true; - } - else if (dynamic_cast(msgl) != nullptr) - { - getCurrentWindow()->setSIM(); - refreshWindow(gui::RefreshModes::GUI_REFRESH_DEEP); + + if (handled) + return std::make_shared(); + else + return std::make_shared(sys::ReturnCodes::Unresolved); } - if (handled) - return std::make_shared(); - else - return std::make_shared(sys::ReturnCodes::Unresolved); -} - -sys::ReturnCodes Application::InitHandler() { - bool initState= true; - setState(State::INITIALIZING); -// uint32_t start = xTaskGetTickCount(); - settings = DBServiceAPI::SettingsGet(this); -// uint32_t stop = xTaskGetTickCount(); -// LOG_INFO("DBServiceAPI::SettingsGet %d", stop-start); - initState = (settings.dbID == 1); - - //send response to application manager true if successful, false otherwise. - sapm::ApplicationManager::messageRegisterApplication( this, initState, startBackground ); - sys::ReturnCodes retCode = (initState?sys::ReturnCodes::Success:sys::ReturnCodes::Failure); - return retCode; -} - -void Application::setActiveWindow(const std::string &windowName) -{ - pushWindow(windowName); - acceptInput = true; -} - -bool Application::messageSwitchApplication( sys::Service* sender, std::string application, std::string window, std::unique_ptr data ) { - auto msg = std::make_shared( application, window, std::move(data) ); - sys::Bus::SendUnicast(msg, application, sender ); - return true; -} - -bool Application::messageRefreshApplication( sys::Service* sender, std::string application, std::string window, gui::SwitchData* data ) { - auto msg = std::make_shared( MessageType::AppRefresh ); - sys::Bus::SendUnicast(msg, application, sender ); - return true; -} - -bool Application::messageCloseApplication( sys::Service* sender, std::string application ) { - - auto msg = std::make_shared( MessageType::AppClose ); - sys::Bus::SendUnicast(msg, application, sender ); - return true; -} - -bool Application::messageRebuildApplication( sys::Service* sender, std::string application ) { - auto msg = std::make_shared(); - sys::Bus::SendUnicast(msg, application, sender ); - return true; -} - -bool Application::messageInputEventApplication( sys::Service* sender, std::string application , const gui::InputEvent& event ) { - auto msg = std::make_shared( event ); - sys::Bus::SendUnicast(msg, application, sender ); - return true; -} - -bool Application::popToWindow(const std::string &window) -{ - auto ret = std::find(windowStack.begin(), windowStack.end(), window); - if (ret != windowStack.end()) + sys::ReturnCodes Application::InitHandler() { - LOG_INFO("Pop last window(s) : %d! %s", std::distance(ret, windowStack.end()), ret->c_str()); - windowStack.erase(std::next(ret), windowStack.end()); + bool initState = true; + setState(State::INITIALIZING); + // uint32_t start = xTaskGetTickCount(); + settings = DBServiceAPI::SettingsGet(this); + // uint32_t stop = xTaskGetTickCount(); + // LOG_INFO("DBServiceAPI::SettingsGet %d", stop-start); + initState = (settings.dbID == 1); + + // send response to application manager true if successful, false otherwise. + sapm::ApplicationManager::messageRegisterApplication(this, initState, startBackground); + sys::ReturnCodes retCode = (initState ? sys::ReturnCodes::Success : sys::ReturnCodes::Failure); + return retCode; + } + + void Application::setActiveWindow(const std::string &windowName) + { + pushWindow(windowName); + acceptInput = true; + } + + bool Application::messageSwitchApplication(sys::Service *sender, + std::string application, + std::string window, + std::unique_ptr data) + { + auto msg = std::make_shared(application, window, std::move(data)); + sys::Bus::SendUnicast(msg, application, sender); return true; } - return false; -} -void Application::pushWindow(const std::string &newWindow) -{ - // handle if window was already on - if (popToWindow(newWindow)) + bool Application::messageRefreshApplication(sys::Service *sender, + std::string application, + std::string window, + gui::SwitchData *data) { - return; + auto msg = std::make_shared(MessageType::AppRefresh); + sys::Bus::SendUnicast(msg, application, sender); + return true; } - else + + bool Application::messageCloseApplication(sys::Service *sender, std::string application) { - windowStack.push_back(newWindow); + + auto msg = std::make_shared(MessageType::AppClose); + sys::Bus::SendUnicast(msg, application, sender); + return true; } + + bool Application::messageRebuildApplication(sys::Service *sender, std::string application) + { + auto msg = std::make_shared(); + sys::Bus::SendUnicast(msg, application, sender); + return true; + } + + bool Application::messageInputEventApplication(sys::Service *sender, + std::string application, + const gui::InputEvent &event) + { + auto msg = std::make_shared(event); + sys::Bus::SendUnicast(msg, application, sender); + return true; + } + + bool Application::popToWindow(const std::string &window) + { + auto ret = std::find(windowStack.begin(), windowStack.end(), window); + if (ret != windowStack.end()) { + LOG_INFO("Pop last window(s) : %d! %s", std::distance(ret, windowStack.end()), ret->c_str()); + windowStack.erase(std::next(ret), windowStack.end()); + return true; + } + return false; + } + + void Application::pushWindow(const std::string &newWindow) + { + // handle if window was already on + if (popToWindow(newWindow)) { + return; + } + else { + windowStack.push_back(newWindow); + } #if DEBUG_APPLICATION_MANAGEMENT == 1 - LOG_DEBUG("[%d] newWindow: %s", windowStack.size(), newWindow.c_str()); - for (auto &el : windowStack) - { - LOG_DEBUG("-> %s", el.c_str()); - } - LOG_INFO("\n\n"); + LOG_DEBUG("[%d] newWindow: %s", windowStack.size(), newWindow.c_str()); + for (auto &el : windowStack) { + LOG_DEBUG("-> %s", el.c_str()); + } + LOG_INFO("\n\n"); #endif -}; + }; -const std::string Application::getPrevWindow() const -{ - if (this->windowStack.size() <= 1) + const std::string Application::getPrevWindow() const { - return gui::name::window::no_window; - } - return *std::prev(windowStack.end(), 2); -} - -void Application::Application::cleanPrevWindw() -{ - this->windowStack.clear(); -} - -gui::AppWindow *Application::getWindow(const std::string &window) -{ - auto it = windows.find(window); - if (it != windows.end()) - { - return it->second; - } - return nullptr; -} - -gui::AppWindow *Application::getCurrentWindow() -{ - std::string window = ""; - if (windowStack.size() == 0) - { - window = gui::name::window::main_window; - } - else - { - window = windowStack.back(); + if (this->windowStack.size() <= 1) { + return gui::name::window::no_window; + } + return *std::prev(windowStack.end(), 2); } - return getWindow(window); -} - - -AppTimer Application::CreateAppTimer(TickType_t interval, bool isPeriodic, std::function callback, const std::string &name) -{ - auto id = CreateTimer(interval, isPeriodic, name); - auto timer = AppTimer(this, id, callback, name); - appTimers.push_back(timer); - return timer; // return ptr to the timer on the list -} - -AppTimer::AppTimer(Application * parent, uint32_t id, std::function callback, const std::string &name) : parent(parent) -{ - this->id = id; - registerCallback(callback); -} -AppTimer::AppTimer() = default; - -AppTimer::~AppTimer() -{ - callback = nullptr; -} - -void AppTimer::registerCallback(std::function callback) -{ - this->callback = callback; -} -void AppTimer::runCallback() -{ - callback(); -} -uint32_t AppTimer::getID() -{ - return id; -} -void AppTimer::stop() -{ - if (parent) + void Application::Application::cleanPrevWindw() { - parent->stopTimer(getID()); + this->windowStack.clear(); } -} -void AppTimer::restart() -{ - if (parent) + + gui::AppWindow *Application::getWindow(const std::string &window) { - parent->ReloadTimer(getID()); + auto it = windows.find(window); + if (it != windows.end()) { + return it->second; + } + return nullptr; + } + + gui::AppWindow *Application::getCurrentWindow() + { + std::string window = ""; + if (windowStack.size() == 0) { + window = gui::name::window::main_window; + } + else { + window = windowStack.back(); + } + + return getWindow(window); + } + + AppTimer Application::CreateAppTimer(TickType_t interval, + bool isPeriodic, + std::function callback, + const std::string &name) + { + auto id = CreateTimer(interval, isPeriodic, name); + auto timer = AppTimer(this, id, callback, name); + appTimers.push_back(timer); + return timer; // return ptr to the timer on the list + } + + AppTimer::AppTimer(Application *parent, uint32_t id, std::function callback, const std::string &name) + : parent(parent) + { + this->id = id; + registerCallback(callback); + } + AppTimer::AppTimer() = default; + + AppTimer::~AppTimer() + { + callback = nullptr; + } + + void AppTimer::registerCallback(std::function callback) + { + this->callback = callback; + } + void AppTimer::runCallback() + { + callback(); + } + uint32_t AppTimer::getID() + { + return id; + } + void AppTimer::stop() + { + if (parent) { + parent->stopTimer(getID()); + } + } + void AppTimer::restart() + { + if (parent) { + parent->ReloadTimer(getID()); + } + } + bool AppTimer::operator==(const AppTimer &rhs) const + { + return this->id == rhs.id; + } + bool AppTimer::operator==(const uint32_t &rhs) const + { + return this->id == rhs; } -} -bool AppTimer::operator==(const AppTimer &rhs) const -{ - return this->id == rhs.id; -} -bool AppTimer::operator==(const uint32_t &rhs) const -{ - return this->id == rhs; -} } /* namespace app */ diff --git a/module-apps/Application.hpp b/module-apps/Application.hpp index 3fb180098..a575110d8 100644 --- a/module-apps/Application.hpp +++ b/module-apps/Application.hpp @@ -10,309 +10,348 @@ #define MODULE_APPS_APPLICATION_HPP_ #include -//module-gui +// module-gui #include "gui/Common.hpp" //#include "gui/widgets/Window.hpp" #include "gui/input/Translator.hpp" -//module-sys +// module-sys #include "Service/Service.hpp" #include "Service/Message.hpp" #include "Service/Common.hpp" #include "SystemManager/SystemManager.hpp" -//module-db +// module-db #include "Interface/SettingsRecord.hpp" #include "SwitchData.hpp" #include "service-cellular/api/CellularServiceAPI.hpp" #include "windows/AppWindow.hpp" -namespace gui { - class AppWindow; -}; - -namespace app { - -class Application; - -class AppTimer // this should inherit from ServiceTimer, but *bodge* +namespace gui { - private: - uint32_t id = 0; // let's say 0 indicates not initalized timer - std::function callback = nullptr; - Application *parent = nullptr; - - void registerCallback( std::function ); - AppTimer(); - - public: - AppTimer(Application * parent, uint32_t id, std::function callback, const std::string &name); - ~AppTimer(); - void runCallback(); - uint32_t getID(); - static uint32_t getNextUniqueID(); - // timer controls: - void restart(); - void stop(); - bool operator==(const AppTimer &rhs) const; - bool operator==(const uint32_t &rhs) const; + class AppWindow; }; -/// This is template for creating new applications. Main difference between Application and service is that: -/// 1. Application has access to GUI and Input -/// 2. Application lifetime is managed with sapm::ApplicationManager -class Application: public sys::Service { - public: - /// state in which application is right now - /// @note do not mistake with application manager state - enum class State +namespace app +{ + + class Application; + + class AppTimer // this should inherit from ServiceTimer, but *bodge* { - /// Application doesn't exist - NONE, - /// Application: Object has been created and underlying service is waiting to execute init handler method. - /// Application Manager: Launcher for the application has been provided. Application can be started using provided launcher. The other possibility - /// is that Appication Manager received CLOSING_FINISHED message. - DEACTIVATED, - /// Application: Set after entering the init handler of the application. In this state application will request - /// in a blocking way the db configuration of the phone. Before exiting the init handler application must send APP_REGISTER message to - /// Application Manager. - /// Application Manager: Initialization is triggered by the switch message sent by other application to the application manager. - /// Launcher for the application has been executed upon receiving switch command. Optional switch data has been - /// saved and it will be provided when application manager receives registration message. - INITIALIZING, - /// Application manager sent variant of switch command to the selected application and it's now waiting for confirmation - /// from the application - ACTIVATING, - /// Application is working and has focus and can render - ACTIVE_FORGROUND, - /// Applicatino lost focus but it is still working - ACTIVE_BACKGROUND, - /// Application: Close request message has been received. As a response application must send close request acknowledge message. - /// Application must start closing all workers and releasing resources. After all workers are closed and resources released application - /// sends to application manager CLOSING_FINISHED message - /// Application Manager sent signal to application that it should be closed. Application must perform all necessary cleanup - /// and request System Manager to close it. - DEACTIVATING - }; - /// c_str() function for Application::State - static const char *stateStr(State st); + private: + uint32_t id = 0; // let's say 0 indicates not initalized timer + std::function callback = nullptr; + Application *parent = nullptr; - private: - State state = State::DEACTIVATED; + void registerCallback(std::function); + AppTimer(); - bool signalStrengthUpdateHandler(); - - public: - std::list timerIDs; - std::list appTimers; // @TODO decide on type - AppTimer longPressTimer; - Application(std::string name, std::string parent="", bool startBackground = false, uint32_t stackDepth=4096, - sys::ServicePriority priority=sys::ServicePriority::Idle); - virtual ~Application(); - - Application::State getState(); - void setState(State st); - - /// @defgroup AppTimers Application timers - /// @note Please mind that timers are from Service and implementation in service should be revritten to send notify instead of calling callback - /// Right now timers can create races. - /// @{ - /// Method to register callback function to be run on timer. - AppTimer CreateAppTimer(TickType_t interval, bool isPeriodic, std::function callback, const std::string &name = ""); - /// Remove previousy registered AppTimer by object - void DeleteTimer(AppTimer &timer); - /// Remove previousy registered AppTimer by id - void DeleteTimer(uint32_t id); - /// @} - - /// Method responsible for rendering currently active window. - /// 1. queries for static data for all windows form Store (i.e. battery level, sim card level) - /// 2. loads rendering commands and send them to GUI renderer (sgui::ServiceGUI) - void render(gui::RefreshModes mode); - - /// Method responsible for setting application to the state where incoming user input is blocked - void blockEvents(bool isBlocked); - - /// Method sending switch command for another window. It will switch window within active application. - /// to switch windows between applications use sapm::ApplicationManager::messageSwitchApplication - /// it will effectivelly trigger setActiveWindow and change on windows stack - int switchWindow(const std::string &windowName, gui::ShowMode cmd = gui::ShowMode::GUI_SHOW_INIT, std::unique_ptr data = nullptr); - - /// Same as switchWindow above - inline auto switchWindow(const std::string &windowName, std::unique_ptr data) - { - return switchWindow( windowName, gui::ShowMode::GUI_SHOW_INIT, std::move(data)); + public: + AppTimer(Application *parent, uint32_t id, std::function callback, const std::string &name); + ~AppTimer(); + void runCallback(); + uint32_t getID(); + static uint32_t getNextUniqueID(); + // timer controls: + void restart(); + void stop(); + bool operator==(const AppTimer &rhs) const; + bool operator==(const uint32_t &rhs) const; }; - /// Metod sendind switch command for previous window on windows stack. - int switchBackWindow(const std::string &windowName, uint32_t cmd, std::unique_ptr data); - - /// Method refreshing active window - int refreshWindow(gui::RefreshModes mode); - - /// Mehtod to handle bus messages, all message types are defined in Message.hpp - /// Message types are in MessageType - sys::Message_t DataReceivedHandler(sys::DataMessage *msgl); - - /// initialization function - /// 1. it has to be called for each and every application instance, it registeres application in ApplicationManager - /// and notify ApplicationManager that it's in Initialization state - /// 2. It gets settings from database - sys::ReturnCodes InitHandler() override; - - /// function to set active window for application - /// if none window is selected main window is used - /// if window name is "LastWindow" then previous window is selected - /// it modifies windows stack - void setActiveWindow(const std::string &windowName); - - /// getter for settings record - SettingsRecord &getSettings() + /// This is template for creating new applications. Main difference between Application and service is that: + /// 1. Application has access to GUI and Input + /// 2. Application lifetime is managed with sapm::ApplicationManager + class Application : public sys::Service { - return settings; + public: + /// state in which application is right now + /// @note do not mistake with application manager state + enum class State + { + /// Application doesn't exist + NONE, + /// Application: Object has been created and underlying service is waiting to execute init handler method. + /// Application Manager: Launcher for the application has been provided. Application can be started using + /// provided launcher. The other possibility is that Appication Manager received CLOSING_FINISHED message. + DEACTIVATED, + /// Application: Set after entering the init handler of the application. In this state application will + /// request in a blocking way the db configuration of the phone. Before exiting the init handler application + /// must send APP_REGISTER message to Application Manager. Application Manager: Initialization is triggered + /// by the switch message sent by other application to the application manager. Launcher for the application + /// has been executed upon receiving switch command. Optional switch data has been saved and it will be + /// provided when application manager receives registration message. + INITIALIZING, + /// Application manager sent variant of switch command to the selected application and it's now waiting for + /// confirmation from the application + ACTIVATING, + /// Application is working and has focus and can render + ACTIVE_FORGROUND, + /// Applicatino lost focus but it is still working + ACTIVE_BACKGROUND, + /// Application: Close request message has been received. As a response application must send close request + /// acknowledge message. Application must start closing all workers and releasing resources. After all + /// workers are closed and resources released application sends to application manager CLOSING_FINISHED + /// message Application Manager sent signal to application that it should be closed. Application must + /// perform all necessary cleanup and request System Manager to close it. + DEACTIVATING + }; + /// c_str() function for Application::State + static const char *stateStr(State st); + + private: + State state = State::DEACTIVATED; + + bool signalStrengthUpdateHandler(); + + public: + std::list timerIDs; + std::list appTimers; // @TODO decide on type + AppTimer longPressTimer; + Application(std::string name, + std::string parent = "", + bool startBackground = false, + uint32_t stackDepth = 4096, + sys::ServicePriority priority = sys::ServicePriority::Idle); + virtual ~Application(); + + Application::State getState(); + void setState(State st); + + /// @defgroup AppTimers Application timers + /// @note Please mind that timers are from Service and implementation in service should be revritten to send + /// notify instead of calling callback + /// Right now timers can create races. + /// @{ + /// Method to register callback function to be run on timer. + AppTimer CreateAppTimer(TickType_t interval, + bool isPeriodic, + std::function callback, + const std::string &name = ""); + /// Remove previousy registered AppTimer by object + void DeleteTimer(AppTimer &timer); + /// Remove previousy registered AppTimer by id + void DeleteTimer(uint32_t id); + /// @} + + /// Method responsible for rendering currently active window. + /// 1. queries for static data for all windows form Store (i.e. battery level, sim card level) + /// 2. loads rendering commands and send them to GUI renderer (sgui::ServiceGUI) + void render(gui::RefreshModes mode); + + /// Method responsible for setting application to the state where incoming user input is blocked + void blockEvents(bool isBlocked); + + /// Method sending switch command for another window. It will switch window within active application. + /// to switch windows between applications use sapm::ApplicationManager::messageSwitchApplication + /// it will effectivelly trigger setActiveWindow and change on windows stack + int switchWindow(const std::string &windowName, + gui::ShowMode cmd = gui::ShowMode::GUI_SHOW_INIT, + std::unique_ptr data = nullptr); + + /// Same as switchWindow above + inline auto switchWindow(const std::string &windowName, std::unique_ptr data) + { + return switchWindow(windowName, gui::ShowMode::GUI_SHOW_INIT, std::move(data)); + }; + + /// Metod sendind switch command for previous window on windows stack. + int switchBackWindow(const std::string &windowName, uint32_t cmd, std::unique_ptr data); + + /// Method refreshing active window + int refreshWindow(gui::RefreshModes mode); + + /// Mehtod to handle bus messages, all message types are defined in Message.hpp + /// Message types are in MessageType + sys::Message_t DataReceivedHandler(sys::DataMessage *msgl); + + /// initialization function + /// 1. it has to be called for each and every application instance, it registeres application in + /// ApplicationManager + /// and notify ApplicationManager that it's in Initialization state + /// 2. It gets settings from database + sys::ReturnCodes InitHandler() override; + + /// function to set active window for application + /// if none window is selected main window is used + /// if window name is "LastWindow" then previous window is selected + /// it modifies windows stack + void setActiveWindow(const std::string &windowName); + + /// getter for settings record + SettingsRecord &getSettings() + { + return settings; + } + + /// see suspendInProgress documentation + virtual void setSuspendFlag(bool val) + { + suspendInProgress = val; + }; + /// see shutdownInProgress documentation + virtual void setShutdownFlag() + { + shutdownInProgress = true; + }; + + /// @defgroup Application Application static functions + /// All this functions are meant to be used in ApplicationManager only + /// @note consider moving these as private elements of ApplicationManager i.e. under names + /// message::switchApplication etc. + /// @{ + static bool messageSwitchApplication(sys::Service *sender, + std::string application, + std::string window, + std::unique_ptr data); + static bool messageRefreshApplication(sys::Service *sender, + std::string application, + std::string window, + gui::SwitchData *data = nullptr); + static bool messageCloseApplication(sys::Service *sender, std::string application); + static bool messageRebuildApplication(sys::Service *sender, std::string application); + /// @} + + protected: + /// application's settings taken from database + SettingsRecord settings; + + void longPressTimerCallback(); + /// function executing functions registered by CreateAppTimer + /// @param id - timer identification number + virtual void TickHandler(uint32_t id) override final; + /// Method used to register all windows and widgets in application + virtual void createUserInterface() = 0; + /// Method closing application's windows. + virtual void destroyUserInterface() = 0; + /// Map containing application's windows + /// Right now all application windows are being created on application start in createUserInterface + /// then all windows are removed at the end of application + /// @note right now there is no mechanism to postphone window creation + std::map windows; + + /// stack of visited windows in application + /// @ingrup AppWindowStack + std::vector windowStack; + + public: + /// @ingrup AppWindowStack + /// get to the first time we entered this &window + bool popToWindow(const std::string &window); + /// push window to the top of windows stack + /// @ingrup AppWindowStack + void pushWindow(const std::string &newWindow); + /// getter for previous window name + /// @ingrup AppWindowStack + const std::string getPrevWindow() const; + /// clears windows stack + /// @ingrup AppWindowStack + void cleanPrevWindw(); + /// getter to get window by name + /// @note could be possibly used to implement building window on request + /// @ingrup AppWindowStack + gui::AppWindow *getWindow(const std::string &window); + /// getter for current wisible window in application + /// @ingrup AppWindowStack + gui::AppWindow *getCurrentWindow(); + + protected: + /// Flag defines whether keyboard input should be processed + bool acceptInput = false; + + /// key translator to handle + /// 1. long press transformation (right now we support long press only via top application keyTralator handling) + /// 2. simple translation of keys 1 to 1 with keyboard + std::unique_ptr keyTranslator; + /// Flag defines how application will behave after registration. It can go forground or background + bool startBackground = false; + /// Flag which defines whether application initialized suspend mode, this will influence how render message will + /// sent to gui service. If suspend is true, application manager will receive information from both eink and gui + /// services if last rendering mesage will be processed. + bool suspendInProgress = false; + /// Flag defines case when display needs to be refreshed before closing the system. If flag is set to true next + /// set of rendering commands will carry information to GUI service that system needs to be closed. After + /// displaying the screen GUI will notify application manager to request system shutdown. + bool shutdownInProgress = false; + + /// informs self that there was key press + /// used to provide a way for long press/multipress handling in application + static bool messageInputEventApplication(sys::Service *sender, + std::string application, + const gui::InputEvent &event); + }; + + /// used in ApplicationManager to start applications + class ApplicationLauncher + { + protected: + /// name of the application to run + std::string name = ""; + /// name of the application's owner + std::string parent = ""; + /// defines whether application can be closed when it looses focus + bool closeable = true; + /// defines whether application should be run without gaining focus, it will remian in the BACKGROUND state + bool startBackground = false; + /// flag defines whether this application can prevent power manager from changing + bool preventBlocking = false; + + public: + ApplicationLauncher(std::string name, bool isCloseable, bool preventBlocking = false) + : name{name}, closeable{isCloseable}, preventBlocking{preventBlocking} {}; + virtual ~ApplicationLauncher(){}; + std::string getName() + { + return name; + }; + bool isCloseable() + { + return closeable; + }; + bool isBlocking() + { + return preventBlocking; + }; + + // virtual method to run the application + virtual bool run(sys::Service *caller = nullptr) + { + return true; + }; + virtual bool runBackground(sys::Service *caller = nullptr) + { + return true; + }; + std::shared_ptr handle = nullptr; + }; + + /// application launcher boilerplate + template class ApplicationLauncherT : public ApplicationLauncher + { + public: + ApplicationLauncherT(std::string name, bool isCloseable = true) : ApplicationLauncher(name, isCloseable) + {} + virtual bool run(sys::Service *caller) override + { + parent = (caller == nullptr ? "" : caller->GetName()); + handle = std::make_shared(name, parent); + return sys::SystemManager::CreateService(handle, caller); + }; + bool runBackground(sys::Service *caller) override + { + parent = (caller == nullptr ? "" : caller->GetName()); + handle = std::make_shared(name, parent, true); + return sys::SystemManager::CreateService(handle, caller); + }; + }; + + /// creates application launcher per class provided + template + std::unique_ptr> CreateLauncher(std::string name, bool isCloseable = true) + { + return std::move(std::unique_ptr>(new ApplicationLauncherT(name, isCloseable))); } - /// see suspendInProgress documentation - virtual void setSuspendFlag(bool val) - { - suspendInProgress = val; - }; - /// see shutdownInProgress documentation - virtual void setShutdownFlag() - { - shutdownInProgress = true; - }; - - /// @defgroup Application Application static functions - /// All this functions are meant to be used in ApplicationManager only - /// @note consider moving these as private elements of ApplicationManager i.e. under names message::switchApplication etc. - /// @{ - static bool messageSwitchApplication(sys::Service *sender, std::string application, std::string window, std::unique_ptr data); - static bool messageRefreshApplication( sys::Service* sender, std::string application, std::string window, gui::SwitchData* data=nullptr ); - static bool messageCloseApplication( sys::Service* sender, std::string application ); - static bool messageRebuildApplication( sys::Service* sender, std::string application ); - /// @} - - protected: - /// application's settings taken from database - SettingsRecord settings; - - void longPressTimerCallback(); - /// function executing functions registered by CreateAppTimer - /// @param id - timer identification number - virtual void TickHandler(uint32_t id) override final; - /// Method used to register all windows and widgets in application - virtual void createUserInterface() = 0; - /// Method closing application's windows. - virtual void destroyUserInterface() = 0; - /// Map containing application's windows - /// Right now all application windows are being created on application start in createUserInterface - /// then all windows are removed at the end of application - /// @note right now there is no mechanism to postphone window creation - std::map windows; - - /// stack of visited windows in application - /// @ingrup AppWindowStack - std::vector windowStack; - - public: - /// @ingrup AppWindowStack - /// get to the first time we entered this &window - bool popToWindow(const std::string &window); - /// push window to the top of windows stack - /// @ingrup AppWindowStack - void pushWindow(const std::string &newWindow); - /// getter for previous window name - /// @ingrup AppWindowStack - const std::string getPrevWindow() const; - /// clears windows stack - /// @ingrup AppWindowStack - void cleanPrevWindw(); - /// getter to get window by name - /// @note could be possibly used to implement building window on request - /// @ingrup AppWindowStack - gui::AppWindow *getWindow(const std::string &window); - /// getter for current wisible window in application - /// @ingrup AppWindowStack - gui::AppWindow *getCurrentWindow(); - - protected: - /// Flag defines whether keyboard input should be processed - bool acceptInput = false; - - /// key translator to handle - /// 1. long press transformation (right now we support long press only via top application keyTralator handling) - /// 2. simple translation of keys 1 to 1 with keyboard - std::unique_ptr keyTranslator; - /// Flag defines how application will behave after registration. It can go forground or background - bool startBackground = false; - /// Flag which defines whether application initialized suspend mode, this will influence how render message will sent to gui service. - /// If suspend is true, application manager will receive information from both eink and gui services if last rendering mesage will - /// be processed. - bool suspendInProgress = false; - /// Flag defines case when display needs to be refreshed before closing the system. If flag is set to true next set of rendering commands will - /// carry information to GUI service that system needs to be closed. After displaying the screen GUI will notify application manager to request system - /// shutdown. - bool shutdownInProgress = false; - - /// informs self that there was key press - /// used to provide a way for long press/multipress handling in application - static bool messageInputEventApplication(sys::Service *sender, std::string application, const gui::InputEvent &event); -}; - -/// used in ApplicationManager to start applications -class ApplicationLauncher { -protected: - /// name of the application to run - std::string name = ""; - /// name of the application's owner - std::string parent = ""; - /// defines whether application can be closed when it looses focus - bool closeable = true; - /// defines whether application should be run without gaining focus, it will remian in the BACKGROUND state - bool startBackground = false; - /// flag defines whether this application can prevent power manager from changing - bool preventBlocking = false; - -public: - ApplicationLauncher( std::string name, bool isCloseable, bool preventBlocking = false ) : - name{name}, - closeable{isCloseable}, - preventBlocking{preventBlocking} {}; - virtual ~ApplicationLauncher() {}; - std::string getName() { return name;}; - bool isCloseable() { return closeable; }; - bool isBlocking() { return preventBlocking; }; - - //virtual method to run the application - virtual bool run(sys::Service* caller = nullptr ) {return true;}; - virtual bool runBackground(sys::Service* caller = nullptr ) {return true;}; - std::shared_ptr handle = nullptr; -}; - -/// application launcher boilerplate -template -class ApplicationLauncherT : public ApplicationLauncher -{ - public: - ApplicationLauncherT(std::string name, bool isCloseable=true) : ApplicationLauncher(name, isCloseable) {} - virtual bool run(sys::Service* caller) override { - parent = (caller == nullptr ? "" : caller->GetName()); - handle = std::make_shared(name, parent); - return sys::SystemManager::CreateService(handle, caller); - }; - bool runBackground(sys::Service *caller) override { - parent = (caller == nullptr ? "" : caller->GetName()); - handle = std::make_shared(name, parent, true); - return sys::SystemManager::CreateService(handle, caller); - }; -}; - -/// creates application launcher per class provided -template -std::unique_ptr> CreateLauncher(std::string name, bool isCloseable=true) { - return std::move(std::unique_ptr>(new ApplicationLauncherT(name, isCloseable))); -} - } /* namespace app */ #endif /* MODULE_APPS_APPLICATION_HPP_ */ diff --git a/module-apps/DatabaseModel.hpp b/module-apps/DatabaseModel.hpp index cbed7b9b7..66d38afa1 100644 --- a/module-apps/DatabaseModel.hpp +++ b/module-apps/DatabaseModel.hpp @@ -17,242 +17,259 @@ #include "Application.hpp" -namespace app { +namespace app +{ -/* - * - */ -template class DatabaseModel { -protected: - /** - * Number of elements requested from database in single message - */ - int pageSize = 1; - /** - * Pointer to application that owns the model - */ - Application* application; - /** - * Total number of records in database - */ - int recordsCount; - /** - * Index of first element in current page - */ - int firstIndex; - //vector that holds records received from database - first last records, than previous records and finally next records - std::vector> records; -public: + /* + * + */ + template class DatabaseModel + { + protected: + /** + * Number of elements requested from database in single message + */ + int pageSize = 1; + /** + * Pointer to application that owns the model + */ + Application *application; + /** + * Total number of records in database + */ + int recordsCount; + /** + * Index of first element in current page + */ + int firstIndex; + // vector that holds records received from database - first last records, than previous records and finally next + // records + std::vector> records; - virtual void requestRecordsCount() { - } + public: + virtual void requestRecordsCount() + {} - virtual bool updateRecords( std::unique_ptr> records, const uint32_t offset, const uint32_t limit, uint32_t count ) { - //calculate for which page is received data using offset value + virtual bool updateRecords(std::unique_ptr> records, + const uint32_t offset, + const uint32_t limit, + uint32_t count) + { + // calculate for which page is received data using offset value - int page = getPage(offset); - int currentPage = firstIndex / pageSize; + int page = getPage(offset); + int currentPage = firstIndex / pageSize; - if( (page >= currentPage - 1) && ( page <= currentPage + 1)){ + if ((page >= currentPage - 1) && (page <= currentPage + 1)) { - //store new records - for( unsigned int i=0; irecords[ii] = nullptr; - this->records[i+(pageSize*(page-currentPage) + pageSize)+offset% pageSize] = std::make_shared( records.get()->operator [](i) ); - //this->records[i+(pageSize*(page-currentPage) + pageSize)+offset% limit] = std::shared_ptr( new T(records.get()->operator [](i)) ); - } + // store new records + for (unsigned int i = 0; i < count; i++) { + auto ii = i + (pageSize * (page - currentPage) + pageSize) + offset % pageSize; + this->records[ii] = nullptr; + this->records[i + (pageSize * (page - currentPage) + pageSize) + offset % pageSize] = + std::make_shared(records.get()->operator[](i)); + // this->records[i+(pageSize*(page-currentPage) + pageSize)+offset% limit] = std::shared_ptr( new + // T(records.get()->operator [](i)) ); + } - //return true (for refreshing window) only if current page was modified. - if( page == currentPage ) - return true; - return false; - } - else { - //alarms are out of current scope - LOG_ERROR("Received records out of scope"); - return false; - } - return false; - } + // return true (for refreshing window) only if current page was modified. + if (page == currentPage) + return true; + return false; + } + else { + // alarms are out of current scope + LOG_ERROR("Received records out of scope"); + return false; + } + return false; + } - virtual void movePrevWindow() { + virtual void movePrevWindow() + { - uint32_t currentPage = firstIndex / pageSize; - //check if it is possible to move to previous window - if( currentPage <= 0 ) - return; + uint32_t currentPage = firstIndex / pageSize; + // check if it is possible to move to previous window + if (currentPage <= 0) + return; - //erase records from next window - for( int i=0; i=pageSize; --i ) - records[i] = records[i-pageSize]; + // moves current records to next records and prev records to current records + for (int i = 3 * pageSize - 1; i >= pageSize; --i) + records[i] = records[i - pageSize]; - //clear first window to nullptr - for( int i = 0; iblockEvents(true); + // lock the application for keyboard input + application->blockEvents(true); - //request records for next window - int prevPage = currentPage - 2; - if( prevPage >= 0) { - requestRecords(pageSize*prevPage, pageSize ); - } - firstIndex -= pageSize; - if( firstIndex < 0 ) - firstIndex = 0; - } + // request records for next window + int prevPage = currentPage - 2; + if (prevPage >= 0) { + requestRecords(pageSize * prevPage, pageSize); + } + firstIndex -= pageSize; + if (firstIndex < 0) + firstIndex = 0; + } - virtual void moveNextWindow() { + virtual void moveNextWindow() + { - uint32_t currentPage = firstIndex / pageSize; - uint32_t pageCount = (recordsCount % pageSize == 0) ? recordsCount/pageSize : (recordsCount/pageSize) + 1; - //check if it is possible to move to next window - if( currentPage >= pageCount ) - return; + uint32_t currentPage = firstIndex / pageSize; + uint32_t pageCount = + (recordsCount % pageSize == 0) ? recordsCount / pageSize : (recordsCount / pageSize) + 1; + // check if it is possible to move to next window + if (currentPage >= pageCount) + return; - //erase firswt window with indicies from 0 up to pageSize -1 - for( int i=0; iblockEvents(true); + // lock the application for keyboard input + application->blockEvents(true); - //request records for next window - uint32_t nextPage = currentPage + 2; - if( nextPage < pageCount ) - requestRecords(pageSize*nextPage, pageSize ); - firstIndex += pageSize; - if( firstIndex > recordsCount ) - firstIndex = recordsCount/pageCount; - } + // request records for next window + uint32_t nextPage = currentPage + 2; + if (nextPage < pageCount) + requestRecords(pageSize * nextPage, pageSize); + firstIndex += pageSize; + if (firstIndex > recordsCount) + firstIndex = recordsCount / pageCount; + } - virtual void requestRecords( const uint32_t offset, const uint32_t limit ) = 0; + virtual void requestRecords(const uint32_t offset, const uint32_t limit) = 0; - bool setRecordsCount( int count ) { + bool setRecordsCount(int count) + { - clear(); - recordsCount = count; + clear(); + recordsCount = count; - //if there are any records request blocks of data from database using recordsLocalCount and requestSize. - if( recordsCount ) { + // if there are any records request blocks of data from database using recordsLocalCount and requestSize. + if (recordsCount) { - //TODO handle validation for firstIndex when number of records has decreased. - requestRecords(firstIndex, pageSize ); - if( firstIndex + pageSize < recordsCount ) - requestRecords(firstIndex+pageSize, pageSize ); - return true; - } - return false; - } + // TODO handle validation for firstIndex when number of records has decreased. + requestRecords(firstIndex, pageSize); + if (firstIndex + pageSize < recordsCount) + requestRecords(firstIndex + pageSize, pageSize); + return true; + } + return false; + } - void setPageSize( int size ) { - clear(); - pageSize = size; - firstIndex = 0; + void setPageSize(int size) + { + clear(); + pageSize = size; + firstIndex = 0; - records.resize(3*pageSize); - std::fill( records.begin(), records.end(), nullptr ); - } + records.resize(3 * pageSize); + std::fill(records.begin(), records.end(), nullptr); + } - DatabaseModel( Application* app, int pageSize ) : - pageSize{pageSize}, - application{app}, - recordsCount{ -1 }, - firstIndex{ 0 } { + DatabaseModel(Application *app, int pageSize) + : pageSize{pageSize}, application{app}, recordsCount{-1}, firstIndex{0} + { - records.resize( pageSize*3 ); - std::fill( records.begin(), records.end(), nullptr ); - } + records.resize(pageSize * 3); + std::fill(records.begin(), records.end(), nullptr); + } - virtual ~DatabaseModel() { - clear(); - } + virtual ~DatabaseModel() + { + clear(); + } - virtual void clear() { + virtual void clear() + { - for( int i=0; i< pageSize*3; i++ ) - records[i] = nullptr; - records.clear(); - firstIndex = 0; - recordsCount = -1; - } + for (int i = 0; i < pageSize * 3; i++) + records[i] = nullptr; + records.clear(); + firstIndex = 0; + recordsCount = -1; + } - int getRecordsCount() { - return recordsCount; - } + int getRecordsCount() + { + return recordsCount; + } - int getPage( uint32_t index ) { - return (index % pageSize == 0) ? index/pageSize : (index/pageSize); - } + int getPage(uint32_t index) + { + return (index % pageSize == 0) ? index / pageSize : (index / pageSize); + } - /** - * @brief Returns database object under specified index. Performs forward and backward buffering. - * @index Index of the database element. Starts from 0 ( database objects have lowest ID equal to 1. ) - * @download Flag that controls whether model should download objects from database when requested object is - * outside visible window. - */ - std::shared_ptr getRecord( int index, bool download = true ) { + /** + * @brief Returns database object under specified index. Performs forward and backward buffering. + * @index Index of the database element. Starts from 0 ( database objects have lowest ID equal to 1. ) + * @download Flag that controls whether model should download objects from database when requested object is + * outside visible window. + */ + std::shared_ptr getRecord(int index, bool download = true) + { - //if index is greater than number of records or smaller than 0 - if( (index<0) || (index>recordsCount-1)){ - return nullptr; - } - //if index is in current window - if( (index >= firstIndex) && ( index < firstIndex + pageSize)) { - return records[pageSize + index-firstIndex]; - } - //if download is false check if requested element is in any of the windows - if( (download == false ) && (index >= firstIndex - pageSize ) && ( index < firstIndex + 2*pageSize)) { - return records[pageSize + index-firstIndex]; - } - //if index is in next window - if( download && (index >= firstIndex + pageSize) && ( index < firstIndex+2*pageSize) ) { - std::shared_ptr record = records[pageSize + index - firstIndex]; - moveNextWindow(); - return record; - } - //if index is in previous window - if( download && (index >= firstIndex - pageSize) && ( index < firstIndex) ) { - std::shared_ptr record = records[index+ pageSize-firstIndex]; - movePrevWindow(); - return record; - } - //if index is not in prev, current or next window - else if( (index < firstIndex - pageSize) || (index>firstIndex + 2*pageSize) ){ - int newCurrentPage = index/pageSize; - clear(); - firstIndex = pageSize * newCurrentPage; - //request current page - requestRecords(firstIndex, pageSize ); - //if possible request previous page; - if( firstIndex - 1 > 0 ) - requestRecords(firstIndex - pageSize, pageSize); - //if possible request next window - if( firstIndex*(pageSize + 1) <= recordsCount - 1 ) - requestRecords(firstIndex+pageSize, pageSize); + // if index is greater than number of records or smaller than 0 + if ((index < 0) || (index > recordsCount - 1)) { + return nullptr; + } + // if index is in current window + if ((index >= firstIndex) && (index < firstIndex + pageSize)) { + return records[pageSize + index - firstIndex]; + } + // if download is false check if requested element is in any of the windows + if ((download == false) && (index >= firstIndex - pageSize) && (index < firstIndex + 2 * pageSize)) { + return records[pageSize + index - firstIndex]; + } + // if index is in next window + if (download && (index >= firstIndex + pageSize) && (index < firstIndex + 2 * pageSize)) { + std::shared_ptr record = records[pageSize + index - firstIndex]; + moveNextWindow(); + return record; + } + // if index is in previous window + if (download && (index >= firstIndex - pageSize) && (index < firstIndex)) { + std::shared_ptr record = records[index + pageSize - firstIndex]; + movePrevWindow(); + return record; + } + // if index is not in prev, current or next window + else if ((index < firstIndex - pageSize) || (index > firstIndex + 2 * pageSize)) { + int newCurrentPage = index / pageSize; + clear(); + firstIndex = pageSize * newCurrentPage; + // request current page + requestRecords(firstIndex, pageSize); + // if possible request previous page; + if (firstIndex - 1 > 0) + requestRecords(firstIndex - pageSize, pageSize); + // if possible request next window + if (firstIndex * (pageSize + 1) <= recordsCount - 1) + requestRecords(firstIndex + pageSize, pageSize); - return nullptr; - } - return nullptr; - } -}; + return nullptr; + } + return nullptr; + } + }; } /* namespace app */ diff --git a/module-apps/UiCommonActions.cpp b/module-apps/UiCommonActions.cpp index aeb77d5ca..aaa46ccf7 100644 --- a/module-apps/UiCommonActions.cpp +++ b/module-apps/UiCommonActions.cpp @@ -20,12 +20,10 @@ namespace app { assert(app != nullptr); - if (contact.numbers.size() != 0) - { + if (contact.numbers.size() != 0) { return call(app, callOperation, contact.numbers[0].numberE164); } - else - { + else { LOG_ERROR("No contact numbers!"); return false; } @@ -38,16 +36,13 @@ namespace app std::unique_ptr data; - switch (callOperation) - { + switch (callOperation) { case CallOperation::ExecuteCall: { data = std::make_unique(e164number.c_str()); - } - break; + } break; case CallOperation::PrepareCall: { data = std::make_unique(e164number.c_str()); - } - break; + } break; default: { LOG_ERROR("callOperation not supported %d", static_cast(callOperation)); return false; @@ -68,11 +63,10 @@ namespace app assert(app != nullptr); // TODO return to current application doesn't change application window >_> auto param = std::shared_ptr(new ContactRecord(contact)); - switch (smsOperation) - { + switch (smsOperation) { case SmsOperation::Add: { - return sapm::ApplicationManager::messageSwitchApplication(app, name_messages, gui::name::window::thread_view, - std::make_unique(param)); + return sapm::ApplicationManager::messageSwitchApplication( + app, name_messages, gui::name::window::thread_view, std::make_unique(param)); } default: { LOG_ERROR("SmsOperation not supported %d", static_cast(smsOperation)); @@ -92,26 +86,28 @@ namespace app bool contact(Application *app, ContactOperation contactOperation, const ContactRecord &contact) { assert(app != nullptr); - switch (contactOperation) - { + switch (contactOperation) { case ContactOperation::Add: { return sapm::ApplicationManager::messageSwitchApplication( - app, name_phonebook, gui::window::name::newContact, + app, + name_phonebook, + gui::window::name::newContact, std::make_unique(std::shared_ptr(new ContactRecord(contact)))); - } - break; + } break; case ContactOperation::Details: { return sapm::ApplicationManager::messageSwitchApplication( - app, name_phonebook, gui::window::name::contact, + app, + name_phonebook, + gui::window::name::contact, std::make_unique(std::shared_ptr(new ContactRecord(contact)))); - } - break; + } break; case ContactOperation::Edit: { return sapm::ApplicationManager::messageSwitchApplication( - app, name_phonebook, gui::window::name::newContact, // TODO: need to be fixed when contact edition is working + app, + name_phonebook, + gui::window::name::newContact, // TODO: need to be fixed when contact edition is working std::make_unique(std::shared_ptr(new ContactRecord(contact)))); - } - break; + } break; default: { LOG_ERROR("ContactOperation not supported %d", static_cast(contactOperation)); return false; @@ -125,31 +121,32 @@ namespace app auto searchResults = DBServiceAPI::ContactSearch(app, "", "", number); ContactRecord contactRec; - if (searchResults.get()->size() == 1) - { + if (searchResults.get()->size() == 1) { contactRec = searchResults->front(); - LOG_INFO("Found contact matching search num %s : contact ID %u - %s %s", number.c_str(), contactRec.dbID, contactRec.primaryName.c_str(), + LOG_INFO("Found contact matching search num %s : contact ID %u - %s %s", + number.c_str(), + contactRec.dbID, + contactRec.primaryName.c_str(), contactRec.alternativeName.c_str()); - if (contactOperation == ContactOperation::Add) - { + if (contactOperation == ContactOperation::Add) { // trying to add new contact for number already assigned to existing contact, display warning return sapm::ApplicationManager::messageSwitchApplication( - app, name_phonebook, gui::window::name::duplicatedContact, - std::make_unique(std::shared_ptr(new ContactRecord(contactRec)), number)); + app, + name_phonebook, + gui::window::name::duplicatedContact, + std::make_unique(std::shared_ptr(new ContactRecord(contactRec)), + number)); } } - else if (searchResults.get()->size() > 1) - { + else if (searchResults.get()->size() > 1) { LOG_FATAL("Found more than one contact for numer %s", number.c_str()); - for (auto i : *searchResults) - { + for (auto i : *searchResults) { LOG_FATAL("ContactID = %u", i.dbID); } return false; } - else if (contactOperation != ContactOperation::Add) - { + else if (contactOperation != ContactOperation::Add) { LOG_ERROR("Invalid operation for not existing contact for numer %s", number.c_str()); return false; } @@ -163,8 +160,7 @@ namespace app assert(contactOperation != ContactOperation::Add); auto searchResults = DBServiceAPI::ContactGetByID(app, contactId); - if (searchResults.get()->size() == 1) - { + if (searchResults.get()->size() == 1) { ContactRecord contactRec = searchResults->front(); return contact(app, contactOperation, contactRec); } diff --git a/module-apps/application-antenna/ApplicationAntenna.cpp b/module-apps/application-antenna/ApplicationAntenna.cpp index c0e285402..47fcfee75 100644 --- a/module-apps/application-antenna/ApplicationAntenna.cpp +++ b/module-apps/application-antenna/ApplicationAntenna.cpp @@ -15,48 +15,42 @@ namespace app void ApplicationAntenna::timerHandler(void) { - if (!scanInProgress) - { + if (!scanInProgress) { LOG_INFO("Get Network info"); CellularServiceAPI::GetNetworkInfo(this); } } ApplicationAntenna::ApplicationAntenna(std::string name, std::string parent, bool startBackgound) - : Application(name, parent, startBackgound, 4096 * 2), appTimer(CreateAppTimer(2000, true, [=]() { timerHandler(); })) + : Application(name, parent, startBackgound, 4096 * 2), + appTimer(CreateAppTimer(2000, true, [=]() { timerHandler(); })) { appTimer.restart(); } ApplicationAntenna::~ApplicationAntenna() - { - } + {} // Invoked upon receiving data message sys::Message_t ApplicationAntenna::DataReceivedHandler(sys::DataMessage *msgl, sys::ResponseMessage *resp) { auto retMsg = Application::DataReceivedHandler(msgl); // if message was handled by application's template there is no need to process further. - if ((reinterpret_cast(retMsg.get())->retCode == sys::ReturnCodes::Success)) - { + if ((reinterpret_cast(retMsg.get())->retCode == sys::ReturnCodes::Success)) { return retMsg; } // this variable defines whether message was processed. bool handled = false; - if (msgl->messageType == MessageType::CellularOperatorsScanResult) - { + if (msgl->messageType == MessageType::CellularOperatorsScanResult) { auto msg = dynamic_cast(msgl); - if (msg != nullptr) - { + if (msg != nullptr) { auto win = getCurrentWindow(); - if (win->getName() == "MainWindow") - { + if (win->getName() == "MainWindow") { auto window = dynamic_cast(win); - if (window != nullptr) - { + if (window != nullptr) { window->updateOperatorsScan(msg->data); } @@ -65,18 +59,14 @@ namespace app } handled = true; } - if (msgl->messageType == MessageType::CellularNetworkInfoResult) - { + if (msgl->messageType == MessageType::CellularNetworkInfoResult) { auto msg = dynamic_cast(msgl); - if (msg != nullptr) - { + if (msg != nullptr) { auto win = getCurrentWindow(); - if (win->getName() == "MainWindow") - { + if (win->getName() == "MainWindow") { auto window = dynamic_cast(win); - if (window != nullptr) - { + if (window != nullptr) { window->updateDebugInfo(msg->data); } @@ -121,7 +111,6 @@ namespace app } void ApplicationAntenna::destroyUserInterface() - { - } + {} } /* namespace app */ diff --git a/module-apps/application-antenna/windows/AntennaMainWindow.cpp b/module-apps/application-antenna/windows/AntennaMainWindow.cpp index 1140f4d8e..656a1a6a4 100644 --- a/module-apps/application-antenna/windows/AntennaMainWindow.cpp +++ b/module-apps/application-antenna/windows/AntennaMainWindow.cpp @@ -16,7 +16,6 @@ #include "../ApplicationAntenna.hpp" #include "service-cellular/api/CellularServiceAPI.hpp" - namespace gui { @@ -47,15 +46,13 @@ namespace gui setTitle(utils::localize.get("app_desktop_tools_antenna")); - for (auto title : titlesText) - { + for (auto title : titlesText) { titles.push_back(addLabel(title, [=](gui::Item &item) { return true; })); } titles[3]->setPenWidth(0); uint32_t posY = 110; - for (uint32_t i = 0; i < titles.size(); i++) - { + for (uint32_t i = 0; i < titles.size(); i++) { titles[i]->setPosition(40, posY); posY += 33 + 5; } @@ -78,18 +75,17 @@ namespace gui CellularServiceAPI::StartOperatorsScan(this->application); this->application->refreshWindow(gui::RefreshModes::GUI_REFRESH_FAST); auto app = dynamic_cast(this->application); - if (app != nullptr) - { + if (app != nullptr) { app->setScanInProgress(true); } return true; })); uint32_t posX = 40; - for (uint32_t i = 0; i < buttons.size(); i++) - { + for (uint32_t i = 0; i < buttons.size(); i++) { buttons[i]->setFont(style::window::font::medium); buttons[i]->setPosition(posX, 500); - buttons[i]->setAlignement(gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_CENTER, gui::Alignment::ALIGN_VERTICAL_CENTER)); + buttons[i]->setAlignement( + gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_CENTER, gui::Alignment::ALIGN_VERTICAL_CENTER)); posX += 240; } @@ -135,36 +131,35 @@ namespace gui } void AntennaMainWindow::onBeforeShow(ShowMode mode, SwitchData *data) - { - } + {} bool AntennaMainWindow::onInput(const InputEvent &inputEvent) { bool ret = AppWindow::onInput(inputEvent); - if (ret) - { + if (ret) { application->render(RefreshModes::GUI_REFRESH_FAST); return true; } return false; } - gui::Label *AntennaMainWindow::addLabel(const UTF8 &text, std::function activatedCallback, bool visibleBorder) + gui::Label *AntennaMainWindow::addLabel(const UTF8 &text, + std::function activatedCallback, + bool visibleBorder) { gui::Label *label = new gui::Label(this, 40, 500, 400, 33, text); label->setMargins(gui::Margins(16, 0, 0, 0)); label->setFilled(false); label->setPenFocusWidth(3); - if (visibleBorder) - { + if (visibleBorder) { label->setPenWidth(1); } - else - { + else { label->setPenWidth(0); } label->setFont(style::window::font::verysmall); - label->setAlignement(gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_LEFT, gui::Alignment::ALIGN_VERTICAL_CENTER)); + label->setAlignement( + gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_LEFT, gui::Alignment::ALIGN_VERTICAL_CENTER)); label->setRadius(11); label->activatedCallback = activatedCallback; @@ -174,11 +169,13 @@ namespace gui void AntennaMainWindow::updateDebugInfo(std::vector &data) { LOG_INFO("AntennaMainWindow::updateDebugInfo vector size %d", data.size()); - if (data.size() == 3) - { - titles[static_cast(labelDescripion::csq)]->setText(titlesText[static_cast(labelDescripion::csq)] + data[0]); - titles[static_cast(labelDescripion::status)]->setText(titlesText[static_cast(labelDescripion::status)] + data[1]); - titles[static_cast(labelDescripion::band)]->setText(titlesText[static_cast(labelDescripion::band)] + data[2]); + if (data.size() == 3) { + titles[static_cast(labelDescripion::csq)]->setText( + titlesText[static_cast(labelDescripion::csq)] + data[0]); + titles[static_cast(labelDescripion::status)]->setText( + titlesText[static_cast(labelDescripion::status)] + data[1]); + titles[static_cast(labelDescripion::band)]->setText( + titlesText[static_cast(labelDescripion::band)] + data[2]); application->refreshWindow(RefreshModes::GUI_REFRESH_FAST); } } @@ -186,8 +183,7 @@ namespace gui { buttons[2]->setText("Start operators scan"); std::string formattedString; - for (auto element : data) - { + for (auto element : data) { formattedString += element + "\n"; } std::replace(formattedString.begin(), formattedString.end(), '\"', ' '); diff --git a/module-apps/application-antenna/windows/AntennaMainWindow.hpp b/module-apps/application-antenna/windows/AntennaMainWindow.hpp index cb1a79b29..60274b843 100644 --- a/module-apps/application-antenna/windows/AntennaMainWindow.hpp +++ b/module-apps/application-antenna/windows/AntennaMainWindow.hpp @@ -23,13 +23,15 @@ namespace gui std::vector buttons; gui::Text *operators; - gui::Label *addLabel(const UTF8 &title, std::function activatedCallback, bool visibleBorder = true); + gui::Label *addLabel(const UTF8 &title, + std::function activatedCallback, + bool visibleBorder = true); const std::string titlesText[4] = {"CSQ: ", "Status: ", "Band: ", "Operators: "}; enum class labelDescripion { - csq = 0, - status = 1, - band = 2, + csq = 0, + status = 1, + band = 2, operators = 3 }; diff --git a/module-apps/application-calendar/ApplicationCalendar.cpp b/module-apps/application-calendar/ApplicationCalendar.cpp index f62ec746e..b68b370ab 100644 --- a/module-apps/application-calendar/ApplicationCalendar.cpp +++ b/module-apps/application-calendar/ApplicationCalendar.cpp @@ -11,42 +11,49 @@ #include "windows/CalendarMainWindow.hpp" #include "ApplicationCalendar.hpp" -namespace app { +namespace app +{ -ApplicationCalendar::ApplicationCalendar(std::string name,std::string parent,uint32_t stackDepth,sys::ServicePriority priority) : - Application( name, parent, false, stackDepth, priority ) { -} + ApplicationCalendar::ApplicationCalendar(std::string name, + std::string parent, + uint32_t stackDepth, + sys::ServicePriority priority) + : Application(name, parent, false, stackDepth, priority) + {} -ApplicationCalendar::~ApplicationCalendar() { -} + ApplicationCalendar::~ApplicationCalendar() + {} -// Invoked upon receiving data message -sys::Message_t ApplicationCalendar::DataReceivedHandler(sys::DataMessage* msgl,sys::ResponseMessage* resp) { - return std::make_shared( ); -} + // Invoked upon receiving data message + sys::Message_t ApplicationCalendar::DataReceivedHandler(sys::DataMessage *msgl, sys::ResponseMessage *resp) + { + return std::make_shared(); + } -// Invoked during initialization -sys::ReturnCodes ApplicationCalendar::InitHandler() { + // Invoked during initialization + sys::ReturnCodes ApplicationCalendar::InitHandler() + { - createUserInterface(); + createUserInterface(); - setActiveWindow("Main"); + setActiveWindow("Main"); - return sys::ReturnCodes::Success; -} + return sys::ReturnCodes::Success; + } -sys::ReturnCodes ApplicationCalendar::DeinitHandler() { - return sys::ReturnCodes::Success; -} + sys::ReturnCodes ApplicationCalendar::DeinitHandler() + { + return sys::ReturnCodes::Success; + } + void ApplicationCalendar::createUserInterface() + { -void ApplicationCalendar::createUserInterface() { + gui::AppWindow *win = new CalendarMainWindow(this, "Main"); + windows.insert(std::pair(win->getName(), win)); + } - gui::AppWindow* win = new CalendarMainWindow(this, "Main"); - windows.insert( std::pair(win->getName(), win)); -} - -void ApplicationCalendar::destroyUserInterface() { -} + void ApplicationCalendar::destroyUserInterface() + {} } /* namespace app */ diff --git a/module-apps/application-calendar/ApplicationCalendar.hpp b/module-apps/application-calendar/ApplicationCalendar.hpp index 018959efd..b98cb808f 100644 --- a/module-apps/application-calendar/ApplicationCalendar.hpp +++ b/module-apps/application-calendar/ApplicationCalendar.hpp @@ -14,26 +14,33 @@ #include "SystemManager/SystemManager.hpp" #include "gui/widgets/Label.hpp" -namespace app { +namespace app +{ -/* - * @brief Class representing calendar application - */ -class ApplicationCalendar: public Application { -public: + /* + * @brief Class representing calendar application + */ + class ApplicationCalendar : public Application + { + public: + ApplicationCalendar(std::string name, + std::string parent, + uint32_t stackDepth = 4096, + sys::ServicePriority priority = sys::ServicePriority::Idle); + virtual ~ApplicationCalendar(); - ApplicationCalendar(std::string name, std::string parent, uint32_t stackDepth=4096,sys::ServicePriority priority=sys::ServicePriority::Idle); - virtual ~ApplicationCalendar(); + sys::Message_t DataReceivedHandler(sys::DataMessage *msgl, sys::ResponseMessage *resp) override; + sys::ReturnCodes InitHandler() override; + sys::ReturnCodes DeinitHandler() override; - sys::Message_t DataReceivedHandler(sys::DataMessage* msgl,sys::ResponseMessage* resp) override; - sys::ReturnCodes InitHandler() override; - sys::ReturnCodes DeinitHandler() override; + sys::ReturnCodes SwitchPowerModeHandler(const sys::ServicePowerMode mode) override final + { + return sys::ReturnCodes::Success; + } - sys::ReturnCodes SwitchPowerModeHandler(const sys::ServicePowerMode mode) override final{return sys::ReturnCodes::Success;} - - void createUserInterface() override; - void destroyUserInterface() override; -}; + void createUserInterface() override; + void destroyUserInterface() override; + }; } /* namespace app */ diff --git a/module-apps/application-calendar/windows/CalendarMainWindow.cpp b/module-apps/application-calendar/windows/CalendarMainWindow.cpp index 1964e878c..7bb2faafc 100644 --- a/module-apps/application-calendar/windows/CalendarMainWindow.cpp +++ b/module-apps/application-calendar/windows/CalendarMainWindow.cpp @@ -12,24 +12,28 @@ #include "gui/widgets/BoxLayout.hpp" #include "CalendarMainWindow.hpp" -namespace app { +namespace app +{ -CalendarMainWindow::CalendarMainWindow( app::Application* app, std::string name ) : AppWindow( app, name ) { - buildInterface(); -} + CalendarMainWindow::CalendarMainWindow(app::Application *app, std::string name) : AppWindow(app, name) + { + buildInterface(); + } -void CalendarMainWindow::rebuild() { + void CalendarMainWindow::rebuild() + {} + void CalendarMainWindow::buildInterface() + { + AppWindow::buildInterface(); + } + void CalendarMainWindow::destroyInterface() + { + AppWindow::destroyInterface(); + } -} -void CalendarMainWindow::buildInterface() { - AppWindow::buildInterface(); -} -void CalendarMainWindow::destroyInterface() { - AppWindow::destroyInterface(); -} - -CalendarMainWindow::~CalendarMainWindow() { - destroyInterface(); -} + CalendarMainWindow::~CalendarMainWindow() + { + destroyInterface(); + } } /* namespace app */ diff --git a/module-apps/application-calendar/windows/CalendarMainWindow.hpp b/module-apps/application-calendar/windows/CalendarMainWindow.hpp index 3a3984e77..1d606a836 100644 --- a/module-apps/application-calendar/windows/CalendarMainWindow.hpp +++ b/module-apps/application-calendar/windows/CalendarMainWindow.hpp @@ -12,22 +12,24 @@ #include "windows/AppWindow.hpp" #include "Application.hpp" -namespace app { +namespace app +{ -/* - * - */ -class CalendarMainWindow: public gui::AppWindow { -protected: - //labels with names of the days -// gui::Label days; -public: - CalendarMainWindow( Application* app, std::string name ); - virtual ~CalendarMainWindow(); - void rebuild() override; - void buildInterface() override; - void destroyInterface() override; -}; + /* + * + */ + class CalendarMainWindow : public gui::AppWindow + { + protected: + // labels with names of the days + // gui::Label days; + public: + CalendarMainWindow(Application *app, std::string name); + virtual ~CalendarMainWindow(); + void rebuild() override; + void buildInterface() override; + void destroyInterface() override; + }; } /* namespace app */ diff --git a/module-apps/application-call/ApplicationCall.cpp b/module-apps/application-call/ApplicationCall.cpp index a26954d0f..810f9eefe 100644 --- a/module-apps/application-call/ApplicationCall.cpp +++ b/module-apps/application-call/ApplicationCall.cpp @@ -26,12 +26,13 @@ #include "service-appmgr/ApplicationManager.hpp" #include -namespace app { +namespace app +{ ApplicationCall::ApplicationCall(std::string name, std::string parent, bool startBackgound) - : Application(name, parent, startBackgound, 4096 + 2048), timerCall(CreateAppTimer(1000, true, [=]() { timerCallCallback(); })) - { - } + : Application(name, parent, startBackgound, 4096 + 2048), + timerCall(CreateAppTimer(1000, true, [=]() { timerCallCallback(); })) + {} // number of seconds after end call to siwtch back to previous application constexpr auto delayToSwitchToPreviousApp = 3; @@ -41,218 +42,206 @@ namespace app { callDuration = utils::time::Timestamp().getTime() - callStartTime; auto it = windows.find(window::name_call); - if (getCurrentWindow() == it->second) - { + if (getCurrentWindow() == it->second) { auto callWindow = dynamic_cast(getCurrentWindow()); - if (callWindow && callWindow->getState() == gui::CallWindow::State::CALL_IN_PROGRESS) - { + if (callWindow && callWindow->getState() == gui::CallWindow::State::CALL_IN_PROGRESS) { callWindow->updateDuration(callDuration); refreshWindow(gui::RefreshModes::GUI_REFRESH_FAST); } } // delayed switch to previous application - if (callDuration >= callDelayedDuration) - { + if (callDuration >= callDelayedDuration) { stopCallTimer(); sapm::ApplicationManager::messageSwitchPreviousApplication(this); } -} - -void ApplicationCall::CallAbortHandler() -{ - gui::CallWindow *callWindow = dynamic_cast(windows.find(window::name_call)->second); - assert(callWindow != nullptr); - - LOG_INFO("---------------------------------CallAborted"); - AudioServiceAPI::Stop(this); - callDelayedDuration = callDuration + delayToSwitchToPreviousApp; - callWindow->setState(gui::CallWindow::State::CALL_ENDED); - refreshWindow(gui::RefreshModes::GUI_REFRESH_DEEP); -} - -void ApplicationCall::CallActiveHandler() -{ - gui::CallWindow *callWindow = dynamic_cast(windows.find(window::name_call)->second); - assert(callWindow != nullptr); - - runCallTimer(); - - LOG_INFO("---------------------------------CallActive"); - callWindow->setState(gui::CallWindow::State::CALL_IN_PROGRESS); - refreshWindow(gui::RefreshModes::GUI_REFRESH_DEEP); -} - -void ApplicationCall::IncomingCallHandler(const CellularNotificationMessage *const msg) -{ - gui::CallWindow *callWindow = dynamic_cast(windows.find(window::name_call)->second); - assert(callWindow != nullptr); - - LOG_INFO("---------------------------------IncomingCall"); - if (callWindow->getState() == gui::CallWindow::State::INCOMING_CALL) - { - LOG_INFO("ignoring call incoming"); } - else + + void ApplicationCall::CallAbortHandler() { + gui::CallWindow *callWindow = dynamic_cast(windows.find(window::name_call)->second); + assert(callWindow != nullptr); + + LOG_INFO("---------------------------------CallAborted"); + AudioServiceAPI::Stop(this); + callDelayedDuration = callDuration + delayToSwitchToPreviousApp; + callWindow->setState(gui::CallWindow::State::CALL_ENDED); + refreshWindow(gui::RefreshModes::GUI_REFRESH_DEEP); + } + + void ApplicationCall::CallActiveHandler() + { + gui::CallWindow *callWindow = dynamic_cast(windows.find(window::name_call)->second); + assert(callWindow != nullptr); + + runCallTimer(); + + LOG_INFO("---------------------------------CallActive"); + callWindow->setState(gui::CallWindow::State::CALL_IN_PROGRESS); + refreshWindow(gui::RefreshModes::GUI_REFRESH_DEEP); + } + + void ApplicationCall::IncomingCallHandler(const CellularNotificationMessage *const msg) + { + gui::CallWindow *callWindow = dynamic_cast(windows.find(window::name_call)->second); + assert(callWindow != nullptr); + + LOG_INFO("---------------------------------IncomingCall"); + if (callWindow->getState() == gui::CallWindow::State::INCOMING_CALL) { + LOG_INFO("ignoring call incoming"); + } + else { + AudioServiceAPI::RoutingStart(this); + runCallTimer(); + std::unique_ptr data = std::make_unique(msg->data); + // send to itself message to switch (run) call application + callWindow->setState(gui::CallWindow::State::INCOMING_CALL); + if (getState() == State::ACTIVE_FORGROUND) { + LOG_INFO("++++++++++++WINDOW SWITCH"); + switchWindow(window::name_call, std::move(data)); + } + else { + LOG_INFO("++++++++++++APP SWITCH"); + + sapm::ApplicationManager::messageSwitchApplication(this, name_call, window::name_call, std::move(data)); + } + } + } + + void ApplicationCall::RingingHandler(const CellularNotificationMessage *const msg) + { + gui::CallWindow *callWindow = dynamic_cast(windows.find(window::name_call)->second); + assert(callWindow != nullptr); + + LOG_INFO("---------------------------------Ringing"); AudioServiceAPI::RoutingStart(this); runCallTimer(); - std::unique_ptr data = std::make_unique(msg->data); - // send to itself message to switch (run) call application - callWindow->setState(gui::CallWindow::State::INCOMING_CALL); - if (getState() == State::ACTIVE_FORGROUND) - { - LOG_INFO("++++++++++++WINDOW SWITCH"); + + std::unique_ptr data = std::make_unique(msg->data); + callWindow->setState(gui::CallWindow::State::OUTGOING_CALL); + if (getState() == State::ACTIVE_FORGROUND) { switchWindow(window::name_call, std::move(data)); } - else - { - LOG_INFO("++++++++++++APP SWITCH"); - - sapm::ApplicationManager::messageSwitchApplication(this, name_call, window::name_call, std::move(data)); - } - } -} - -void ApplicationCall::RingingHandler(const CellularNotificationMessage *const msg) -{ - gui::CallWindow *callWindow = dynamic_cast(windows.find(window::name_call)->second); - assert(callWindow != nullptr); - - LOG_INFO("---------------------------------Ringing"); - AudioServiceAPI::RoutingStart(this); - runCallTimer(); - - std::unique_ptr data = std::make_unique(msg->data); - callWindow->setState(gui::CallWindow::State::OUTGOING_CALL); - if (getState() == State::ACTIVE_FORGROUND) - { - switchWindow(window::name_call, std::move(data)); - } -} - -// Invoked upon receiving data message -sys::Message_t ApplicationCall::DataReceivedHandler(sys::DataMessage* msgl,sys::ResponseMessage* resp) { - - auto retMsg = Application::DataReceivedHandler(msgl); - //if message was handled by application's template there is no need to process further. - if( (reinterpret_cast( retMsg.get() )->retCode == - sys::ReturnCodes::Success ) ){ - return retMsg; - } - - if (msgl->messageType == MessageType::CellularNotification) - { - CellularNotificationMessage *msg = dynamic_cast(msgl); - assert(msg != nullptr); - - switch (msg->type) - { - case CellularNotificationMessage::Type::CallAborted: { - CallAbortHandler(); - } - break; - case CellularNotificationMessage::Type::CallActive: { - CallActiveHandler(); - } - break; - case CellularNotificationMessage::Type::IncomingCall: { - IncomingCallHandler(msg); - } - break; - case CellularNotificationMessage::Type::Ringing: { - RingingHandler(msg); - } - break; - default: - break; - } - - return std::make_shared(); } - if (resp != nullptr) + // Invoked upon receiving data message + sys::Message_t ApplicationCall::DataReceivedHandler(sys::DataMessage *msgl, sys::ResponseMessage *resp) { - switch (resp->responseTo) - { - case MessageType::CellularHangupCall: { - if (resp->retCode == sys::ReturnCodes::Success) - { + + auto retMsg = Application::DataReceivedHandler(msgl); + // if message was handled by application's template there is no need to process further. + if ((reinterpret_cast(retMsg.get())->retCode == sys::ReturnCodes::Success)) { + return retMsg; + } + + if (msgl->messageType == MessageType::CellularNotification) { + CellularNotificationMessage *msg = dynamic_cast(msgl); + assert(msg != nullptr); + + switch (msg->type) { + case CellularNotificationMessage::Type::CallAborted: { CallAbortHandler(); + } break; + case CellularNotificationMessage::Type::CallActive: { + CallActiveHandler(); + } break; + case CellularNotificationMessage::Type::IncomingCall: { + IncomingCallHandler(msg); + } break; + case CellularNotificationMessage::Type::Ringing: { + RingingHandler(msg); + } break; + default: + break; } - break; - } - default: - break; + + return std::make_shared(); } - return std::make_shared(); + if (resp != nullptr) { + switch (resp->responseTo) { + case MessageType::CellularHangupCall: { + if (resp->retCode == sys::ReturnCodes::Success) { + CallAbortHandler(); + } + break; + } + default: + break; + } + + return std::make_shared(); + } + + return std::make_shared(sys::ReturnCodes::Unresolved); } - return std::make_shared(sys::ReturnCodes::Unresolved); -} + // Invoked during initialization + sys::ReturnCodes ApplicationCall::InitHandler() + { -// Invoked during initialization -sys::ReturnCodes ApplicationCall::InitHandler() { + auto ret = Application::InitHandler(); + if (ret != sys::ReturnCodes::Success) + return ret; - auto ret = Application::InitHandler(); - if( ret != sys::ReturnCodes::Success ) - return ret; + createUserInterface(); - createUserInterface(); + setActiveWindow("MainWindow"); - setActiveWindow("MainWindow"); + return ret; + } - return ret; -} + sys::ReturnCodes ApplicationCall::DeinitHandler() + { + return sys::ReturnCodes::Success; + } -sys::ReturnCodes ApplicationCall::DeinitHandler() { - return sys::ReturnCodes::Success; -} + void ApplicationCall::createUserInterface() + { + gui::AppWindow *window = nullptr; -void ApplicationCall::createUserInterface() { + window = new gui::CallMainWindow(this); + windows.insert(std::pair(window->getName(), window)); - gui::AppWindow* window = nullptr; + window = new gui::EnterNumberWindow(this); + windows.insert(std::pair(window->getName(), window)); - window = new gui::CallMainWindow(this); - windows.insert(std::pair(window->getName(), window)); + window = new gui::CallWindow(this); + windows.insert(std::pair(window->getName(), window)); - window = new gui::EnterNumberWindow(this); - windows.insert(std::pair(window->getName(), window)); + window = new gui::EmergencyCallWindow(this); + windows.insert(std::pair(window->getName(), window)); + } - window = new gui::CallWindow(this); - windows.insert(std::pair(window->getName(), window)); + void ApplicationCall::setDisplayedNumber(std::string num) + { + phoneNumber = num; + } - window = new gui::EmergencyCallWindow(this); - windows.insert(std::pair(window->getName(), window)); -} + const std::string &ApplicationCall::getDisplayedNumber() + { + return phoneNumber; + } -void ApplicationCall::setDisplayedNumber( std::string num ) { - phoneNumber = num; -} + void ApplicationCall::runCallTimer() + { + callStartTime = utils::time::Timestamp().getTime(); + callDuration = std::numeric_limits::min(); + callDelayedDuration = std::numeric_limits::max(); + timerCall.restart(); + } -const std::string& ApplicationCall::getDisplayedNumber() { - return phoneNumber; -} + void ApplicationCall::stopCallTimer() + { + callStartTime = std::numeric_limits::max(); + callDuration = std::numeric_limits::min(); + callDelayedDuration = std::numeric_limits::max(); + timerCall.stop(); + } -void ApplicationCall::runCallTimer() { - callStartTime = utils::time::Timestamp().getTime(); - callDuration = std::numeric_limits::min(); - callDelayedDuration = std::numeric_limits::max(); - timerCall.restart(); -} + void ApplicationCall::destroyUserInterface() + {} -void ApplicationCall::stopCallTimer() -{ - callStartTime = std::numeric_limits::max(); - callDuration = std::numeric_limits::min(); - callDelayedDuration = std::numeric_limits::max(); - timerCall.stop(); -} - -void ApplicationCall::destroyUserInterface() { -} - -} /* namespace gui */ +} // namespace app diff --git a/module-apps/application-call/ApplicationCall.hpp b/module-apps/application-call/ApplicationCall.hpp index 075312569..7ef9feeba 100644 --- a/module-apps/application-call/ApplicationCall.hpp +++ b/module-apps/application-call/ApplicationCall.hpp @@ -5,50 +5,57 @@ #include "SystemManager/SystemManager.hpp" #include -namespace app { - -inline const std::string name_call = "ApplicationCall"; -namespace window +namespace app { - inline const std::string name_call = "CallWindow"; - inline const std::string name_enterNumber = "EnterNumberWindow"; - inline const std::string name_emergencyCall = "EmergencyCallWindow"; - inline const std::string name_duplicatedContact = "DuplicatedContactWindow"; -} // namespace window -/* - * - */ -class ApplicationCall: public Application { - private: - void CallAbortHandler(); - void CallActiveHandler(); - void IncomingCallHandler(const CellularNotificationMessage *const msg); - void RingingHandler(const CellularNotificationMessage *const msg); - protected: - std::string phoneNumber; - AppTimer timerCall; - time_t callStartTime = std::numeric_limits::max(); - ; - time_t callDuration = 0; - time_t callDelayedDuration = std::numeric_limits::max(); - void timerCallCallback(); -public: - ApplicationCall( std::string name=name_call, std::string parent = "", bool startBackgound = false ); - ~ApplicationCall() override = default; - sys::Message_t DataReceivedHandler(sys::DataMessage* msgl,sys::ResponseMessage* resp) override; - sys::ReturnCodes InitHandler() override; - sys::ReturnCodes DeinitHandler() override; + inline const std::string name_call = "ApplicationCall"; + namespace window + { + inline const std::string name_call = "CallWindow"; + inline const std::string name_enterNumber = "EnterNumberWindow"; + inline const std::string name_emergencyCall = "EmergencyCallWindow"; + inline const std::string name_duplicatedContact = "DuplicatedContactWindow"; + } // namespace window + /* + * + */ + class ApplicationCall : public Application + { + private: + void CallAbortHandler(); + void CallActiveHandler(); + void IncomingCallHandler(const CellularNotificationMessage *const msg); + void RingingHandler(const CellularNotificationMessage *const msg); - sys::ReturnCodes SwitchPowerModeHandler(const sys::ServicePowerMode mode) override final{return sys::ReturnCodes::Success;} + protected: + std::string phoneNumber; + AppTimer timerCall; + time_t callStartTime = std::numeric_limits::max(); + ; + time_t callDuration = 0; + time_t callDelayedDuration = std::numeric_limits::max(); + void timerCallCallback(); - void createUserInterface() override; - void destroyUserInterface() override; - void setDisplayedNumber( std::string num ); - const std::string& getDisplayedNumber(); - //starts timer that upon triggering, if no user action was performed, will hide application to background and move to previous application - void runCallTimer(); - void stopCallTimer(); -}; + public: + ApplicationCall(std::string name = name_call, std::string parent = "", bool startBackgound = false); + ~ApplicationCall() override = default; + sys::Message_t DataReceivedHandler(sys::DataMessage *msgl, sys::ResponseMessage *resp) override; + sys::ReturnCodes InitHandler() override; + sys::ReturnCodes DeinitHandler() override; + + sys::ReturnCodes SwitchPowerModeHandler(const sys::ServicePowerMode mode) override final + { + return sys::ReturnCodes::Success; + } + + void createUserInterface() override; + void destroyUserInterface() override; + void setDisplayedNumber(std::string num); + const std::string &getDisplayedNumber(); + // starts timer that upon triggering, if no user action was performed, will hide application to background and + // move to previous application + void runCallTimer(); + void stopCallTimer(); + }; } /* namespace app */ diff --git a/module-apps/application-call/data/CallAppStyle.hpp b/module-apps/application-call/data/CallAppStyle.hpp index ddef6e203..1eda124d8 100644 --- a/module-apps/application-call/data/CallAppStyle.hpp +++ b/module-apps/application-call/data/CallAppStyle.hpp @@ -4,42 +4,42 @@ namespace callAppStyle { -// ICON -namespace icon -{ -constexpr uint32_t w = 100; -constexpr uint32_t h = 100; -namespace label -{ -constexpr uint32_t x = 9; -constexpr uint32_t y = 58; -constexpr uint32_t w = 82; -constexpr uint32_t h = 20; -} // namespace label -namespace img -{ -constexpr uint32_t x = 34; -constexpr uint32_t y = 15; -constexpr uint32_t w = 32; -constexpr uint32_t h = 32; -} // namespace img -} // namespace icon + // ICON + namespace icon + { + constexpr uint32_t w = 100; + constexpr uint32_t h = 100; + namespace label + { + constexpr uint32_t x = 9; + constexpr uint32_t y = 58; + constexpr uint32_t w = 82; + constexpr uint32_t h = 20; + } // namespace label + namespace img + { + constexpr uint32_t x = 34; + constexpr uint32_t y = 15; + constexpr uint32_t w = 32; + constexpr uint32_t h = 32; + } // namespace img + } // namespace icon -// ENTER NUMBER WINDOW -namespace enterNumberWindow -{ -namespace numberLabel -{ -constexpr uint32_t x = 60; -constexpr uint32_t y = 157; -constexpr uint32_t w = style::window_width - 2 * x; -constexpr uint32_t h = 66; -constexpr uint32_t borderW = 1; -} // namespace numberLabel -namespace newContactIcon -{ -constexpr uint32_t x = 190; -constexpr uint32_t y = 411; -} // namespace newContactIcon -} // namespace enterNumberWindow + // ENTER NUMBER WINDOW + namespace enterNumberWindow + { + namespace numberLabel + { + constexpr uint32_t x = 60; + constexpr uint32_t y = 157; + constexpr uint32_t w = style::window_width - 2 * x; + constexpr uint32_t h = 66; + constexpr uint32_t borderW = 1; + } // namespace numberLabel + namespace newContactIcon + { + constexpr uint32_t x = 190; + constexpr uint32_t y = 411; + } // namespace newContactIcon + } // namespace enterNumberWindow } // namespace callAppStyle \ No newline at end of file diff --git a/module-apps/application-call/data/CallSwitchData.cpp b/module-apps/application-call/data/CallSwitchData.cpp index ec99a76af..5cf768a5d 100644 --- a/module-apps/application-call/data/CallSwitchData.cpp +++ b/module-apps/application-call/data/CallSwitchData.cpp @@ -8,15 +8,17 @@ */ #include "CallSwitchData.hpp" -namespace app { +namespace app +{ -CallSwitchData::CallSwitchData() { - // TODO Auto-generated constructor stub + CallSwitchData::CallSwitchData() + { + // TODO Auto-generated constructor stub + } -} - -CallSwitchData::~CallSwitchData() { - // TODO Auto-generated destructor stub -} + CallSwitchData::~CallSwitchData() + { + // TODO Auto-generated destructor stub + } } /* namespace app */ diff --git a/module-apps/application-call/data/CallSwitchData.hpp b/module-apps/application-call/data/CallSwitchData.hpp index 77a8d6908..a182efb5d 100644 --- a/module-apps/application-call/data/CallSwitchData.hpp +++ b/module-apps/application-call/data/CallSwitchData.hpp @@ -12,48 +12,66 @@ #include #include "SwitchData.hpp" -namespace app { +namespace app +{ -class CallSwitchData: public gui::SwitchData { -public: - enum class Type { - UNDEFINED, - ENTER_NUMBER, - INCOMMING_CALL, - EXECUTE_CALL - }; - static const inline std::string descriptionStr = "CallSwitchData"; - static const inline std::string defaultPhoneNumber = "undefined"; -protected: - Type type = Type::UNDEFINED; - std::string phoneNumber; -public: - CallSwitchData( const std::string& number = defaultPhoneNumber, Type type = Type::UNDEFINED ) : SwitchData(descriptionStr), type{ type }, phoneNumber{ number } {}; - virtual ~CallSwitchData(){}; + class CallSwitchData : public gui::SwitchData + { + public: + enum class Type + { + UNDEFINED, + ENTER_NUMBER, + INCOMMING_CALL, + EXECUTE_CALL + }; + static const inline std::string descriptionStr = "CallSwitchData"; + static const inline std::string defaultPhoneNumber = "undefined"; - const Type& getType() const { return type; }; - const std::string& getPhoneNumber() const { return phoneNumber; }; -}; + protected: + Type type = Type::UNDEFINED; + std::string phoneNumber; -class EnterNumberData: public CallSwitchData { -public: - EnterNumberData( const std::string& number = "") : CallSwitchData( number, CallSwitchData::Type::ENTER_NUMBER ) {}; - virtual ~EnterNumberData(){}; -}; + public: + CallSwitchData(const std::string &number = defaultPhoneNumber, Type type = Type::UNDEFINED) + : SwitchData(descriptionStr), type{type}, phoneNumber{number} {}; + virtual ~CallSwitchData(){}; -class IncommingCallData: public CallSwitchData { -public: - IncommingCallData( const std::string& number = "") : CallSwitchData( number, CallSwitchData::Type::INCOMMING_CALL ) {}; - virtual ~IncommingCallData(){}; -}; + const Type &getType() const + { + return type; + }; + const std::string &getPhoneNumber() const + { + return phoneNumber; + }; + }; -class ExecuteCallData: public CallSwitchData { -protected: - std::string phoneNumber; -public: - ExecuteCallData( const std::string& number = "") : CallSwitchData( number, app::CallSwitchData::Type::EXECUTE_CALL ) {}; - virtual ~ExecuteCallData(){}; -}; + class EnterNumberData : public CallSwitchData + { + public: + EnterNumberData(const std::string &number = "") : CallSwitchData(number, CallSwitchData::Type::ENTER_NUMBER){}; + virtual ~EnterNumberData(){}; + }; + + class IncommingCallData : public CallSwitchData + { + public: + IncommingCallData(const std::string &number = "") + : CallSwitchData(number, CallSwitchData::Type::INCOMMING_CALL){}; + virtual ~IncommingCallData(){}; + }; + + class ExecuteCallData : public CallSwitchData + { + protected: + std::string phoneNumber; + + public: + ExecuteCallData(const std::string &number = "") + : CallSwitchData(number, app::CallSwitchData::Type::EXECUTE_CALL){}; + virtual ~ExecuteCallData(){}; + }; } /* namespace app */ diff --git a/module-apps/application-call/widgets/Icon.cpp b/module-apps/application-call/widgets/Icon.cpp index ef21a3c55..22a0b91a1 100644 --- a/module-apps/application-call/widgets/Icon.cpp +++ b/module-apps/application-call/widgets/Icon.cpp @@ -6,18 +6,20 @@ using namespace callAppStyle; namespace gui { -Icon::Icon(Item *parent, const uint32_t &x, const uint32_t &y, const std::string &imageName, const std::string &labelStr) - : Rect(parent, x, y, icon::w, icon::h) -{ - setEdges( RectangleEdgeFlags::GUI_RECT_EDGE_BOTTOM | RectangleEdgeFlags::GUI_RECT_EDGE_TOP ); - setPenFocusWidth(style::window::default_border_focucs_w); - setPenWidth(style::window::default_border_no_focus_w); + Icon::Icon( + Item *parent, const uint32_t &x, const uint32_t &y, const std::string &imageName, const std::string &labelStr) + : Rect(parent, x, y, icon::w, icon::h) + { + setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_BOTTOM | RectangleEdgeFlags::GUI_RECT_EDGE_TOP); + setPenFocusWidth(style::window::default_border_focucs_w); + setPenWidth(style::window::default_border_no_focus_w); - img = new gui::Image(this, icon::img::x, icon::img::y, icon::img::w, icon::img::h, imageName); - label = new gui::Label(this, icon::label::x, icon::label::y, icon::label::w, icon::label::h, labelStr); - label->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES); - label->setAlignement(gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_CENTER, gui::Alignment::ALIGN_VERTICAL_CENTER)); - label->setFont(style::window::font::verysmall); -} + img = new gui::Image(this, icon::img::x, icon::img::y, icon::img::w, icon::img::h, imageName); + label = new gui::Label(this, icon::label::x, icon::label::y, icon::label::w, icon::label::h, labelStr); + label->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES); + label->setAlignement( + gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_CENTER, gui::Alignment::ALIGN_VERTICAL_CENTER)); + label->setFont(style::window::font::verysmall); + } } // namespace gui \ No newline at end of file diff --git a/module-apps/application-call/widgets/Icon.hpp b/module-apps/application-call/widgets/Icon.hpp index dc26a02ba..b8ad35c62 100644 --- a/module-apps/application-call/widgets/Icon.hpp +++ b/module-apps/application-call/widgets/Icon.hpp @@ -6,16 +6,20 @@ namespace gui { -// Icon widget with custom image and label -class Icon : public Rect -{ - protected: - Image *img = nullptr; - Label *label = nullptr; + // Icon widget with custom image and label + class Icon : public Rect + { + protected: + Image *img = nullptr; + Label *label = nullptr; - public: - Icon() = delete; - Icon(Item *parent, const uint32_t &x, const uint32_t &y, const std::string &imageName, const std::string &labelStr); - virtual ~Icon() = default; -}; + public: + Icon() = delete; + Icon(Item *parent, + const uint32_t &x, + const uint32_t &y, + const std::string &imageName, + const std::string &labelStr); + virtual ~Icon() = default; + }; } // namespace gui \ No newline at end of file diff --git a/module-apps/application-call/windows/CallMainWindow.cpp b/module-apps/application-call/windows/CallMainWindow.cpp index 549e924dc..b98848fb9 100644 --- a/module-apps/application-call/windows/CallMainWindow.cpp +++ b/module-apps/application-call/windows/CallMainWindow.cpp @@ -11,25 +11,27 @@ #include "CallMainWindow.hpp" #include -namespace gui { +namespace gui +{ CallMainWindow::CallMainWindow(app::Application *app) : AppWindow(app, gui::name::window::main_window) { buildInterface(); } -void CallMainWindow::rebuild() { -} -void CallMainWindow::buildInterface() { - AppWindow::buildInterface(); - setTitle(getName()); -} -void CallMainWindow::destroyInterface() { - AppWindow::destroyInterface(); -} + void CallMainWindow::rebuild() + {} + void CallMainWindow::buildInterface() + { + AppWindow::buildInterface(); + setTitle(getName()); + } + void CallMainWindow::destroyInterface() + { + AppWindow::destroyInterface(); + } - -CallMainWindow::~CallMainWindow() { -} + CallMainWindow::~CallMainWindow() + {} } /* namespace gui */ diff --git a/module-apps/application-call/windows/CallMainWindow.hpp b/module-apps/application-call/windows/CallMainWindow.hpp index daaa0cf33..0ae0c114e 100644 --- a/module-apps/application-call/windows/CallMainWindow.hpp +++ b/module-apps/application-call/windows/CallMainWindow.hpp @@ -12,22 +12,24 @@ #include "AppWindow.hpp" #include "Label.hpp" -namespace gui { +namespace gui +{ -/* - * This window is defined only to keep common approach to creating application. - * This window should not be displayed. - */ -class CallMainWindow: public AppWindow { -protected: -public: - CallMainWindow( app::Application* app ); - virtual ~CallMainWindow(); + /* + * This window is defined only to keep common approach to creating application. + * This window should not be displayed. + */ + class CallMainWindow : public AppWindow + { + protected: + public: + CallMainWindow(app::Application *app); + virtual ~CallMainWindow(); - void rebuild() override; - void buildInterface() override; - void destroyInterface() override; -}; + void rebuild() override; + void buildInterface() override; + void destroyInterface() override; + }; } /* namespace gui */ diff --git a/module-apps/application-call/windows/CallWindow.cpp b/module-apps/application-call/windows/CallWindow.cpp index 09c6e6f6f..cd3f6ab08 100644 --- a/module-apps/application-call/windows/CallWindow.cpp +++ b/module-apps/application-call/windows/CallWindow.cpp @@ -27,382 +27,428 @@ #include "CallWindow.hpp" #include -namespace gui { +namespace gui +{ -CallWindow::CallWindow( app::Application* app, std::string windowName ) : AppWindow(app, windowName){ - buildInterface(); -} + CallWindow::CallWindow(app::Application *app, std::string windowName) : AppWindow(app, windowName) + { + buildInterface(); + } -void CallWindow::rebuild() { - destroyInterface(); - buildInterface(); -} -void CallWindow::buildInterface() { - AppWindow::buildInterface(); + void CallWindow::rebuild() + { + destroyInterface(); + buildInterface(); + } + void CallWindow::buildInterface() + { + AppWindow::buildInterface(); - topBar->setActive(gui::TopBar::Elements::BATTERY, true ); - topBar->setActive(gui::TopBar::Elements::SIGNAL, true ); - topBar->setActive(gui::TopBar::Elements::TIME, true ); + topBar->setActive(gui::TopBar::Elements::BATTERY, true); + topBar->setActive(gui::TopBar::Elements::SIGNAL, true); + topBar->setActive(gui::TopBar::Elements::TIME, true); - bottomBar->setActive( BottomBar::Side::CENTER, true ); - bottomBar->setActive( BottomBar::Side::RIGHT, true ); + bottomBar->setActive(BottomBar::Side::CENTER, true); + bottomBar->setActive(BottomBar::Side::RIGHT, true); - bottomBar->setText( BottomBar::Side::CENTER, utils::localize.get("common_select")); - bottomBar->setText( BottomBar::Side::RIGHT, utils::localize.get("common_back")); - bottomBar->setText( gui::BottomBar::Side::CENTER, "Message" ); + bottomBar->setText(BottomBar::Side::CENTER, utils::localize.get("common_select")); + bottomBar->setText(BottomBar::Side::RIGHT, utils::localize.get("common_back")); + bottomBar->setText(gui::BottomBar::Side::CENTER, "Message"); - //create circles to hold images inside - for( uint32_t i=0; i<2; ++i ) { - rects[i] = new gui::Rect( this, 0,0, 80, 80 ); - rects[i]->setFilled( false ); - rects[i]->setRadius(40); - rects[i]->setPenFocusWidth(3); - rects[i]->setPenWidth(1); - } + // create circles to hold images inside + for (uint32_t i = 0; i < 2; ++i) { + rects[i] = new gui::Rect(this, 0, 0, 80, 80); + rects[i]->setFilled(false); + rects[i]->setRadius(40); + rects[i]->setPenFocusWidth(3); + rects[i]->setPenWidth(1); + } - rects[static_cast(FocusRects::Speaker)]->setPosition( 150, 400 ); - rects[static_cast(FocusRects::Micrphone)]->setPosition( 250, 400 ); + rects[static_cast(FocusRects::Speaker)]->setPosition(150, 400); + rects[static_cast(FocusRects::Micrphone)]->setPosition(250, 400); - imageSpeaker[static_cast(AudioState::ON)] = new gui::Image( rects[static_cast(FocusRects::Speaker)], 20, 20, 0,0, "speaker_on" ); - imageSpeaker[static_cast(AudioState::OFF)] = new gui::Image( rects[static_cast(FocusRects::Speaker)], 20, 20, 0,0, "speaker_off" ); - imageSpeaker[static_cast(AudioState::ON)]->setVisible(false); - imageSpeaker[static_cast(AudioState::OFF)]->setVisible(false); + imageSpeaker[static_cast(AudioState::ON)] = + new gui::Image(rects[static_cast(FocusRects::Speaker)], 20, 20, 0, 0, "speaker_on"); + imageSpeaker[static_cast(AudioState::OFF)] = + new gui::Image(rects[static_cast(FocusRects::Speaker)], 20, 20, 0, 0, "speaker_off"); + imageSpeaker[static_cast(AudioState::ON)]->setVisible(false); + imageSpeaker[static_cast(AudioState::OFF)]->setVisible(false); -// imageMessage = new gui::Image( this, 200, 60-177, 0,0, "call_message" ); + // imageMessage = new gui::Image( this, 200, 60-177, 0,0, "call_message" ); - imageMicrophone[static_cast(AudioState::ON)] = new gui::Image( rects[static_cast(FocusRects::Micrphone)], 20, 20, 0,0, "microphone_on" ); - imageMicrophone[static_cast(AudioState::OFF)] = new gui::Image( rects[static_cast(FocusRects::Micrphone)], 20, 20, 0,0, "microphone_off" ); - imageMicrophone[static_cast(AudioState::ON)]->setVisible(false); - imageMicrophone[static_cast(AudioState::OFF)]->setVisible(false); + imageMicrophone[static_cast(AudioState::ON)] = + new gui::Image(rects[static_cast(FocusRects::Micrphone)], 20, 20, 0, 0, "microphone_on"); + imageMicrophone[static_cast(AudioState::OFF)] = + new gui::Image(rects[static_cast(FocusRects::Micrphone)], 20, 20, 0, 0, "microphone_off"); + imageMicrophone[static_cast(AudioState::ON)]->setVisible(false); + imageMicrophone[static_cast(AudioState::OFF)]->setVisible(false); - //top circle image - imageCircleTop = new gui::Image( this, 116, 82, 0,0, "circle_top" ); - imageCircleBottom = new gui::Image( this, 106, 266, 0,0, "circle_bottom" ); + // top circle image + imageCircleTop = new gui::Image(this, 116, 82, 0, 0, "circle_top"); + imageCircleBottom = new gui::Image(this, 106, 266, 0, 0, "circle_bottom"); - durationLabel = new gui::Label(this, 0, 220, 480, 80 ); - durationLabel->setFilled( false ); - durationLabel->setBorderColor( gui::ColorNoColor ); - durationLabel->setFont(style::window::font::verybig); - durationLabel->setAlignement( gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_CENTER, gui::Alignment::ALIGN_VERTICAL_BOTTOM)); + durationLabel = new gui::Label(this, 0, 220, 480, 80); + durationLabel->setFilled(false); + durationLabel->setBorderColor(gui::ColorNoColor); + durationLabel->setFont(style::window::font::verybig); + durationLabel->setAlignement( + gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_CENTER, gui::Alignment::ALIGN_VERTICAL_BOTTOM)); - numberLabel = new gui::Label(this, 11, 150, 480-22, 80 ); - numberLabel->setFilled( false ); - numberLabel->setBorderColor( gui::ColorNoColor ); - numberLabel->setFont(style::window::font::bigbold); - numberLabel->setAlignement( gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_CENTER, gui::Alignment::ALIGN_VERTICAL_BOTTOM)); + numberLabel = new gui::Label(this, 11, 150, 480 - 22, 80); + numberLabel->setFilled(false); + numberLabel->setBorderColor(gui::ColorNoColor); + numberLabel->setFont(style::window::font::bigbold); + numberLabel->setAlignement( + gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_CENTER, gui::Alignment::ALIGN_VERTICAL_BOTTOM)); - //define navigation between labels - rects[static_cast(FocusRects::Speaker)]->setNavigationItem( NavigationDirection::LEFT, - rects[static_cast(FocusRects::Micrphone)]); - rects[static_cast(FocusRects::Speaker)]->setNavigationItem( NavigationDirection::RIGHT, - rects[static_cast(FocusRects::Micrphone)]); + // define navigation between labels + rects[static_cast(FocusRects::Speaker)]->setNavigationItem( + NavigationDirection::LEFT, rects[static_cast(FocusRects::Micrphone)]); + rects[static_cast(FocusRects::Speaker)]->setNavigationItem( + NavigationDirection::RIGHT, rects[static_cast(FocusRects::Micrphone)]); - rects[static_cast(FocusRects::Micrphone)]->setNavigationItem( NavigationDirection::LEFT, - rects[static_cast(FocusRects::Speaker)]); - rects[static_cast(FocusRects::Micrphone)]->setNavigationItem( NavigationDirection::RIGHT, - rects[static_cast(FocusRects::Speaker)]); + rects[static_cast(FocusRects::Micrphone)]->setNavigationItem( + NavigationDirection::LEFT, rects[static_cast(FocusRects::Speaker)]); + rects[static_cast(FocusRects::Micrphone)]->setNavigationItem( + NavigationDirection::RIGHT, rects[static_cast(FocusRects::Speaker)]); - //focus callbacks - rects[static_cast(FocusRects::Speaker)]->focusChangedCallback = [=] (gui::Item& item){ - LOG_INFO("Speaker gets focus" ); - bottomBar->setText( BottomBar::Side::CENTER, utils::localize.get("common_speaker")); - return true; }; + // focus callbacks + rects[static_cast(FocusRects::Speaker)]->focusChangedCallback = [=](gui::Item &item) { + LOG_INFO("Speaker gets focus"); + bottomBar->setText(BottomBar::Side::CENTER, utils::localize.get("common_speaker")); + return true; + }; - rects[static_cast(FocusRects::Micrphone)]->focusChangedCallback = [=] (gui::Item& item){ - LOG_INFO("Mute gets focus" ); - bottomBar->setText( BottomBar::Side::CENTER, utils::localize.get("common_mute")); - return true; }; + rects[static_cast(FocusRects::Micrphone)]->focusChangedCallback = [=](gui::Item &item) { + LOG_INFO("Mute gets focus"); + bottomBar->setText(BottomBar::Side::CENTER, utils::localize.get("common_mute")); + return true; + }; - //activation callbacks - rects[static_cast(FocusRects::Speaker)]->activatedCallback = [=] (gui::Item& item){ - LOG_INFO("Speaker activated" ); - //update icon - imageSpeaker[static_cast(speakerState)]->setVisible(false); - speakerState = (speakerState == AudioState::ON)?AudioState::OFF:AudioState::ON; - imageSpeaker[static_cast(speakerState)]->setVisible(true); + // activation callbacks + rects[static_cast(FocusRects::Speaker)]->activatedCallback = [=](gui::Item &item) { + LOG_INFO("Speaker activated"); + // update icon + imageSpeaker[static_cast(speakerState)]->setVisible(false); + speakerState = (speakerState == AudioState::ON) ? AudioState::OFF : AudioState::ON; + imageSpeaker[static_cast(speakerState)]->setVisible(true); - application->refreshWindow( RefreshModes::GUI_REFRESH_FAST ); + application->refreshWindow(RefreshModes::GUI_REFRESH_FAST); - (speakerState == AudioState::ON)? - AudioServiceAPI::RoutingSpeakerPhone(this->application,true): - AudioServiceAPI::RoutingSpeakerPhone(this->application,false); + (speakerState == AudioState::ON) ? AudioServiceAPI::RoutingSpeakerPhone(this->application, true) + : AudioServiceAPI::RoutingSpeakerPhone(this->application, false); - return true; }; + return true; + }; - rects[static_cast(FocusRects::Micrphone)]->activatedCallback = [=] (gui::Item& item){ - LOG_INFO("Mute activated" ); + rects[static_cast(FocusRects::Micrphone)]->activatedCallback = [=](gui::Item &item) { + LOG_INFO("Mute activated"); - //update icon - imageMicrophone[static_cast(microphoneState)]->setVisible(false); - microphoneState = (microphoneState == AudioState::ON)?AudioState::OFF:AudioState::ON; - imageMicrophone[static_cast(microphoneState)]->setVisible(true); + // update icon + imageMicrophone[static_cast(microphoneState)]->setVisible(false); + microphoneState = (microphoneState == AudioState::ON) ? AudioState::OFF : AudioState::ON; + imageMicrophone[static_cast(microphoneState)]->setVisible(true); - application->refreshWindow( RefreshModes::GUI_REFRESH_FAST ); + application->refreshWindow(RefreshModes::GUI_REFRESH_FAST); - (microphoneState == AudioState::ON)? - AudioServiceAPI::RoutingMute(this->application,false): - AudioServiceAPI::RoutingMute(this->application,true); + (microphoneState == AudioState::ON) ? AudioServiceAPI::RoutingMute(this->application, false) + : AudioServiceAPI::RoutingMute(this->application, true); - return true; }; + return true; + }; + } -} + void CallWindow::destroyInterface() + { + AppWindow::destroyInterface(); -void CallWindow::destroyInterface() { - AppWindow::destroyInterface(); + if (numberLabel) { + removeWidget(numberLabel); + delete numberLabel; + numberLabel = nullptr; + } + if (durationLabel) { + removeWidget(durationLabel); + delete durationLabel; + durationLabel = nullptr; + } + if (rects[0]) { + removeWidget(rects[0]); + delete rects[0]; + rects[0] = nullptr; + } + if (rects[1]) { + removeWidget(rects[1]); + delete rects[1]; + rects[1] = nullptr; + } - if( numberLabel ){ removeWidget(numberLabel); delete numberLabel; numberLabel = nullptr; } - if( durationLabel ){ removeWidget(durationLabel); delete durationLabel; durationLabel = nullptr; } - if( rects[0] ){ removeWidget(rects[0]); delete rects[0]; rects[0]= nullptr; } - if( rects[1] ){ removeWidget(rects[1]); delete rects[1]; rects[1]= nullptr; } + if (imageMessage) { + removeWidget(imageMessage); + delete imageMessage; + imageMessage = nullptr; + } + if (imageCircleTop) { + removeWidget(imageCircleTop); + delete imageCircleTop; + imageCircleTop = nullptr; + } + if (imageCircleBottom) { + removeWidget(imageCircleBottom); + delete imageCircleBottom; + imageCircleBottom = nullptr; + } - if( imageMessage ){ removeWidget(imageMessage); delete imageMessage; imageMessage = nullptr; } - if( imageCircleTop ){ removeWidget(imageCircleTop); delete imageCircleTop; imageCircleTop = nullptr; } - if( imageCircleBottom ){ removeWidget(imageCircleBottom); delete imageCircleBottom; imageCircleBottom = nullptr; } + children.clear(); + } - children.clear(); -} + CallWindow::~CallWindow() + {} -CallWindow::~CallWindow() { -} + void CallWindow::setState(State state) + { + this->state = state; + setVisibleState(); + } -void CallWindow::setState( State state ) { - this->state = state; - setVisibleState(); -} + const CallWindow::State &CallWindow::getState() + { + return state; + } -const CallWindow::State& CallWindow::getState() { - return state; -} + void CallWindow::setVisibleState() + { -void CallWindow::setVisibleState() { + // imageMessage->setVisible(false); + rects[static_cast(FocusRects::Speaker)]->setVisible(false); + rects[static_cast(FocusRects::Micrphone)]->setVisible(false); + durationLabel->setVisible(false); + setFocusItem(nullptr); -// imageMessage->setVisible(false); - rects[static_cast(FocusRects::Speaker)]->setVisible(false); - rects[static_cast(FocusRects::Micrphone)]->setVisible(false); - durationLabel->setVisible(false); - setFocusItem(nullptr); + auto showIconsLambda = [=]() { + rects[static_cast(FocusRects::Speaker)]->setVisible(true); + rects[static_cast(FocusRects::Micrphone)]->setVisible(true); - auto showIconsLambda = [=]() { - rects[static_cast(FocusRects::Speaker)]->setVisible(true); - rects[static_cast(FocusRects::Micrphone)]->setVisible(true); + imageSpeaker[static_cast(speakerState)]->setVisible(true); + imageMicrophone[static_cast(microphoneState)]->setVisible(true); - imageSpeaker[static_cast(speakerState)]->setVisible(true); - imageMicrophone[static_cast(microphoneState)]->setVisible(true); + setFocusItem(rects[static_cast(FocusRects::Speaker)]); + }; - setFocusItem(rects[static_cast(FocusRects::Speaker)]); - }; - - //show state of the window - switch( state ) { - case State::INCOMING_CALL: { - bottomBar->setActive(gui::BottomBar::Side::LEFT, true ); - bottomBar->setActive(gui::BottomBar::Side::CENTER, true ); - bottomBar->setActive(gui::BottomBar::Side::RIGHT, true ); - bottomBar->setText( gui::BottomBar::Side::LEFT, utils::localize.get("app_call_answer") ); - bottomBar->setText( gui::BottomBar::Side::CENTER, utils::localize.get("app_call_message") ); - bottomBar->setText( gui::BottomBar::Side::RIGHT, utils::localize.get("app_call_reject") ); - durationLabel->setText(utils::localize.get("app_call_is_calling")); - durationLabel->setVisible(true); -// imageMessage->setVisible(true); - }break; - case State::CALL_ENDED: { - bottomBar->setActive(gui::BottomBar::Side::LEFT, false ); - bottomBar->setActive(gui::BottomBar::Side::CENTER, false ); - bottomBar->setActive(gui::BottomBar::Side::RIGHT, false ); + // show state of the window + switch (state) { + case State::INCOMING_CALL: { + bottomBar->setActive(gui::BottomBar::Side::LEFT, true); + bottomBar->setActive(gui::BottomBar::Side::CENTER, true); + bottomBar->setActive(gui::BottomBar::Side::RIGHT, true); + bottomBar->setText(gui::BottomBar::Side::LEFT, utils::localize.get("app_call_answer")); + bottomBar->setText(gui::BottomBar::Side::CENTER, utils::localize.get("app_call_message")); + bottomBar->setText(gui::BottomBar::Side::RIGHT, utils::localize.get("app_call_reject")); + durationLabel->setText(utils::localize.get("app_call_is_calling")); + durationLabel->setVisible(true); + // imageMessage->setVisible(true); + } break; + case State::CALL_ENDED: { + bottomBar->setActive(gui::BottomBar::Side::LEFT, false); + bottomBar->setActive(gui::BottomBar::Side::CENTER, false); + bottomBar->setActive(gui::BottomBar::Side::RIGHT, false); durationLabel->setVisible(true); durationLabel->setText(utils::localize.get("app_call_call_ended")); - }break; - case State::CALL_IN_PROGRESS: { -// titleLabel->setText("CALL_IN_PROGRESS"); - durationLabel->setVisible(true); + } break; + case State::CALL_IN_PROGRESS: { + // titleLabel->setText("CALL_IN_PROGRESS"); + durationLabel->setVisible(true); - bottomBar->setActive(gui::BottomBar::Side::LEFT, false ); - bottomBar->setActive(gui::BottomBar::Side::CENTER, false ); - bottomBar->setActive(gui::BottomBar::Side::RIGHT, true ); - bottomBar->setText( gui::BottomBar::Side::RIGHT, utils::localize.get("app_call_end_call") ); + bottomBar->setActive(gui::BottomBar::Side::LEFT, false); + bottomBar->setActive(gui::BottomBar::Side::CENTER, false); + bottomBar->setActive(gui::BottomBar::Side::RIGHT, true); + bottomBar->setText(gui::BottomBar::Side::RIGHT, utils::localize.get("app_call_end_call")); showIconsLambda(); - }break; - case State::IDLE: { -// titleLabel->setText("IDLE"); - }break; - case State::OUTGOING_CALL: { -// titleLabel->setText("OUTGOING_CALL"); + } break; + case State::IDLE: { + // titleLabel->setText("IDLE"); + } break; + case State::OUTGOING_CALL: { + // titleLabel->setText("OUTGOING_CALL"); - bottomBar->setActive(gui::BottomBar::Side::LEFT, false ); - bottomBar->setActive(gui::BottomBar::Side::CENTER, false ); - bottomBar->setActive(gui::BottomBar::Side::RIGHT, true ); - bottomBar->setText( gui::BottomBar::Side::RIGHT, utils::localize.get("app_call_end_call") ); + bottomBar->setActive(gui::BottomBar::Side::LEFT, false); + bottomBar->setActive(gui::BottomBar::Side::CENTER, false); + bottomBar->setActive(gui::BottomBar::Side::RIGHT, true); + bottomBar->setText(gui::BottomBar::Side::RIGHT, utils::localize.get("app_call_end_call")); - showIconsLambda(); + showIconsLambda(); durationLabel->setText(utils::localize.get("app_call_calling")); durationLabel->setVisible(true); - }break; - }; -} - -void CallWindow::setCallNumber( std::string ) { - -} - -void CallWindow::updateDuration(time_t duration) -{ - uint32_t seconds = 0; - uint32_t minutes = 0; - uint32_t hours = 0; - uint32_t days = 0; - - days = duration / 86400; duration -= days*86400; - hours = duration / 3600; duration -= hours*3600; - minutes = duration / 60; duration -= minutes*60; - seconds = duration; - - std::stringstream ss; - if( days ) ss<setText( ss.str()); -} - -bool CallWindow::handleSwitchData( SwitchData* data ) { - - if( data == nullptr ) { - LOG_ERROR("Received null pointer"); - return false; - } - - std::string phoneNumber; - if(data->getDescription() == app::CallSwitchData::descriptionStr) { - app::CallSwitchData* callData = reinterpret_cast(data); - phoneNumber = callData->getPhoneNumber(); - switch(callData->getType()) { - case app::CallSwitchData::Type::INCOMMING_CALL : { - state = State::INCOMING_CALL; - } break; - - case app::CallSwitchData::Type::EXECUTE_CALL : { - state = State::OUTGOING_CALL; - } break; - - default: - LOG_ERROR("Unhandled type"); - phoneNumber = ""; - } - } - else { - LOG_ERROR("Unrecognized SwitchData"); - return false; - } - - auto records = DBServiceAPI::ContactGetByPhoneNumber(this->application, phoneNumber); - if (records->size() == 1) - { - auto rec = records->operator[](0); - LOG_INFO("number = %s recognized as contact id = %u, name = %s", phoneNumber.c_str(), rec.dbID, rec.getFormattedName().c_str()); - phoneNumber = rec.getFormattedName(); + } break; + }; } - else if (records->size() > 1) + + void CallWindow::setCallNumber(std::string) + {} + + void CallWindow::updateDuration(time_t duration) { - LOG_ERROR("number = %s recognized as more than one contact", phoneNumber.c_str()); - for (auto i : *records) - { - LOG_ERROR("contact id = %u, name = %s", i.dbID, i.getFormattedName().c_str()); + uint32_t seconds = 0; + uint32_t minutes = 0; + uint32_t hours = 0; + uint32_t days = 0; + + days = duration / 86400; + duration -= days * 86400; + hours = duration / 3600; + duration -= hours * 3600; + minutes = duration / 60; + duration -= minutes * 60; + seconds = duration; + + std::stringstream ss; + if (days) + ss << days << ":"; + if (hours) + ss << hours << ":"; + if (hours && minutes < 10) + ss << "0"; + ss << minutes << ":"; + ss << std::setfill('0') << std::setw(2) << seconds; + + durationLabel->setText(ss.str()); + } + + bool CallWindow::handleSwitchData(SwitchData *data) + { + + if (data == nullptr) { + LOG_ERROR("Received null pointer"); + return false; + } + + std::string phoneNumber; + if (data->getDescription() == app::CallSwitchData::descriptionStr) { + app::CallSwitchData *callData = reinterpret_cast(data); + phoneNumber = callData->getPhoneNumber(); + switch (callData->getType()) { + case app::CallSwitchData::Type::INCOMMING_CALL: { + state = State::INCOMING_CALL; + } break; + + case app::CallSwitchData::Type::EXECUTE_CALL: { + state = State::OUTGOING_CALL; + } break; + + default: + LOG_ERROR("Unhandled type"); + phoneNumber = ""; + } + } + else { + LOG_ERROR("Unrecognized SwitchData"); + return false; + } + + auto records = DBServiceAPI::ContactGetByPhoneNumber(this->application, phoneNumber); + if (records->size() == 1) { + auto rec = records->operator[](0); + LOG_INFO("number = %s recognized as contact id = %u, name = %s", + phoneNumber.c_str(), + rec.dbID, + rec.getFormattedName().c_str()); + phoneNumber = rec.getFormattedName(); + } + else if (records->size() > 1) { + LOG_ERROR("number = %s recognized as more than one contact", phoneNumber.c_str()); + for (auto i : *records) { + LOG_ERROR("contact id = %u, name = %s", i.dbID, i.getFormattedName().c_str()); + } + } + else { + LOG_INFO("number = %s was not recognized as any valid contact", phoneNumber.c_str()); + } + + numberLabel->setText(phoneNumber); + + setVisibleState(); + application->refreshWindow(RefreshModes::GUI_REFRESH_FAST); + + return true; + } + + void CallWindow::onBeforeShow(ShowMode mode, SwitchData *data) + {} + + bool CallWindow::handleLeftButton() + { + if (state == State::INCOMING_CALL) { + auto ret = CellularServiceAPI::AnswerIncomingCall(application); + + LOG_INFO("AnswerIncomingCall: %s", (ret ? "OK" : "FAIL")); + return true; + } + + return false; + } + + bool CallWindow::handleCenterButton() + { + if (state == State::INCOMING_CALL) { + LOG_ERROR("TODO: Reject call and send message template"); + return true; + } + return false; + } + + bool CallWindow::handleRightButton() + { + switch (state) { + case State::INCOMING_CALL: + case State::OUTGOING_CALL: + case State::CALL_IN_PROGRESS: + CellularServiceAPI::HangupCall(application); + return true; + break; + default: + break; + } + + return false; + } + + bool CallWindow::onInput(const InputEvent &inputEvent) + { + + LOG_INFO("key code: %d, state: %d", + static_cast(inputEvent.keyCode), + static_cast(inputEvent.state)); + + bool handled = false; + + // process only if key is released + // InputEvent::State::keyReleasedLong is necessary for KeyCode::KEY_RF to properly abort the active call + if (inputEvent.state == InputEvent::State::keyReleasedShort || + inputEvent.state == InputEvent::State::keyReleasedLong) { + switch (inputEvent.keyCode) { + case KeyCode::KEY_ENTER: + handled = handleCenterButton(); + break; + case KeyCode::KEY_LF: + handled = handleLeftButton(); + break; + case KeyCode::KEY_RF: + handled = handleRightButton(); + break; + default: + break; + } + } + + if (handled) { + application->refreshWindow(RefreshModes::GUI_REFRESH_FAST); + return true; + } + else { + return AppWindow::onInput(inputEvent); } } - else - { - LOG_INFO("number = %s was not recognized as any valid contact", phoneNumber.c_str()); - } - - numberLabel->setText(phoneNumber); - - setVisibleState(); - application->refreshWindow( RefreshModes::GUI_REFRESH_FAST ); - - return true; -} - -void CallWindow::onBeforeShow( ShowMode mode, SwitchData* data ) { -} - -bool CallWindow::handleLeftButton() -{ - if (state == State::INCOMING_CALL) - { - auto ret = CellularServiceAPI::AnswerIncomingCall(application); - - LOG_INFO("AnswerIncomingCall: %s", (ret ? "OK" : "FAIL")); - return true; - } - - return false; -} - -bool CallWindow::handleCenterButton() -{ - if (state == State::INCOMING_CALL) - { - LOG_ERROR("TODO: Reject call and send message template"); - return true; - } - return false; -} - -bool CallWindow::handleRightButton() -{ - switch (state) - { - case State::INCOMING_CALL: - case State::OUTGOING_CALL: - case State::CALL_IN_PROGRESS: - CellularServiceAPI::HangupCall(application); - return true; - break; - default: - break; - } - - return false; -} - -bool CallWindow::onInput( const InputEvent& inputEvent ) { - - LOG_INFO("key code: %d, state: %d", static_cast(inputEvent.keyCode), static_cast(inputEvent.state)); - - bool handled = false; - - // process only if key is released - // InputEvent::State::keyReleasedLong is necessary for KeyCode::KEY_RF to properly abort the active call - if (inputEvent.state == InputEvent::State::keyReleasedShort || inputEvent.state == InputEvent::State::keyReleasedLong) - { - switch( inputEvent.keyCode ) { - case KeyCode::KEY_ENTER: - handled = handleCenterButton(); - break; - case KeyCode::KEY_LF: - handled = handleLeftButton(); - break; - case KeyCode::KEY_RF : - handled = handleRightButton(); - break; - default: - break; - } - } - - if( handled ) { - application->refreshWindow( RefreshModes::GUI_REFRESH_FAST); - return true; - } - else - { - return AppWindow::onInput(inputEvent); - } -} } /* namespace gui */ - diff --git a/module-apps/application-call/windows/CallWindow.hpp b/module-apps/application-call/windows/CallWindow.hpp index bf92fcd63..7cafd4932 100644 --- a/module-apps/application-call/windows/CallWindow.hpp +++ b/module-apps/application-call/windows/CallWindow.hpp @@ -13,75 +13,81 @@ #include "Rect.hpp" #include "Image.hpp" -namespace gui { +namespace gui +{ -/* - * - */ -class CallWindow: public AppWindow { -public: - enum class State { - IDLE, - INCOMING_CALL, - OUTGOING_CALL, - CALL_IN_PROGRESS, - CALL_ENDED - }; -protected: + /* + * + */ + class CallWindow : public AppWindow + { + public: + enum class State + { + IDLE, + INCOMING_CALL, + OUTGOING_CALL, + CALL_IN_PROGRESS, + CALL_ENDED + }; - enum class FocusRects { - Speaker, - Micrphone, - }; + protected: + enum class FocusRects + { + Speaker, + Micrphone, + }; - enum class AudioState { - ON, - OFF - }; -// gui::Label* titleLabel = nullptr; - //used to display both nnumber and name of contact - gui::Label* numberLabel = nullptr; - //used to inform user about call state of call and display duration of call - gui::Label* durationLabel = nullptr; + enum class AudioState + { + ON, + OFF + }; + // gui::Label* titleLabel = nullptr; + // used to display both nnumber and name of contact + gui::Label *numberLabel = nullptr; + // used to inform user about call state of call and display duration of call + gui::Label *durationLabel = nullptr; - gui::Image* imageSpeaker[2] = {nullptr,nullptr}; - gui::Image* imageMicrophone[2] = {nullptr,nullptr}; - gui::Rect* rects[2] = {nullptr}; - gui::Image* imageMessage = nullptr; - gui::Image* imageCircleTop = nullptr; - gui::Image* imageCircleBottom = nullptr; + gui::Image *imageSpeaker[2] = {nullptr, nullptr}; + gui::Image *imageMicrophone[2] = {nullptr, nullptr}; + gui::Rect *rects[2] = {nullptr}; + gui::Image *imageMessage = nullptr; + gui::Image *imageCircleTop = nullptr; + gui::Image *imageCircleBottom = nullptr; - AudioState microphoneState = AudioState::ON; - AudioState speakerState = AudioState::OFF; + AudioState microphoneState = AudioState::ON; + AudioState speakerState = AudioState::OFF; - State state = State::IDLE; - /** - * Manipulates widgets to handle currently set state of the window. - */ - void setVisibleState(); - bool handleLeftButton(); - bool handleCenterButton(); - bool handleRightButton(); -public: - CallWindow(app::Application *app, std::string windowName = app::window::name_call); - virtual ~CallWindow(); + State state = State::IDLE; + /** + * Manipulates widgets to handle currently set state of the window. + */ + void setVisibleState(); + bool handleLeftButton(); + bool handleCenterButton(); + bool handleRightButton(); - /** - * Used by application to update window's state - */ - void setState(State state); - const State &getState(); - void updateDuration(time_t duration); - void setCallNumber(std::string); + public: + CallWindow(app::Application *app, std::string windowName = app::window::name_call); + virtual ~CallWindow(); - bool onInput(const InputEvent &inputEvent) override; - void onBeforeShow(ShowMode mode, SwitchData *data) override; - bool handleSwitchData(SwitchData *data) override; + /** + * Used by application to update window's state + */ + void setState(State state); + const State &getState(); + void updateDuration(time_t duration); + void setCallNumber(std::string); - void rebuild() override; - void buildInterface() override; - void destroyInterface() override; -}; + bool onInput(const InputEvent &inputEvent) override; + void onBeforeShow(ShowMode mode, SwitchData *data) override; + bool handleSwitchData(SwitchData *data) override; + + void rebuild() override; + void buildInterface() override; + void destroyInterface() override; + }; } /* namespace gui */ diff --git a/module-apps/application-call/windows/EmergencyCallWindow.cpp b/module-apps/application-call/windows/EmergencyCallWindow.cpp index 9ace351a5..f423c9737 100644 --- a/module-apps/application-call/windows/EmergencyCallWindow.cpp +++ b/module-apps/application-call/windows/EmergencyCallWindow.cpp @@ -13,41 +13,47 @@ #include "i18/i18.hpp" #include "EmergencyCallWindow.hpp" -namespace gui { +namespace gui +{ - EmergencyCallWindow::EmergencyCallWindow(app::Application *app) : EnterNumberWindow(app, app::window::name_emergencyCall) + EmergencyCallWindow::EmergencyCallWindow(app::Application *app) + : EnterNumberWindow(app, app::window::name_emergencyCall) { numberLabel->setText(utils::localize.get("app_call_emergency")); } -void EmergencyCallWindow::rebuild() { + void EmergencyCallWindow::rebuild() + {} + void EmergencyCallWindow::buildInterface() + { + AppWindow::buildInterface(); + } + void EmergencyCallWindow::destroyInterface() + { + AppWindow::destroyInterface(); + } -} -void EmergencyCallWindow::buildInterface() { - AppWindow::buildInterface(); -} -void EmergencyCallWindow::destroyInterface() { - AppWindow::destroyInterface(); -} + EmergencyCallWindow::~EmergencyCallWindow() + { + // TODO Auto-generated destructor stub + } -EmergencyCallWindow::~EmergencyCallWindow() { - // TODO Auto-generated destructor stub -} + bool EmergencyCallWindow::onInput(const InputEvent &inputEvent) + { + bool ret = EnterNumberWindow::onInput(inputEvent); -bool EmergencyCallWindow::onInput( const InputEvent& inputEvent ) { - bool ret = EnterNumberWindow::onInput( inputEvent ); + // if( number.empty() ) { + // numberLabel->setText( utils::localize.get("app_call_emergency") ); + // } -// if( number.empty() ) { -// numberLabel->setText( utils::localize.get("app_call_emergency") ); -// } + return ret; + } + bool EmergencyCallWindow::handleSwitchData(SwitchData *data) + { + bool ret = EnterNumberWindow::handleSwitchData(data); - return ret; -} -bool EmergencyCallWindow::handleSwitchData( SwitchData* data ) { - bool ret = EnterNumberWindow::handleSwitchData( data ); - - return ret; -} + return ret; + } } /* namespace gui */ diff --git a/module-apps/application-call/windows/EmergencyCallWindow.hpp b/module-apps/application-call/windows/EmergencyCallWindow.hpp index 26ba0ee2c..0e63a671b 100644 --- a/module-apps/application-call/windows/EmergencyCallWindow.hpp +++ b/module-apps/application-call/windows/EmergencyCallWindow.hpp @@ -11,23 +11,25 @@ #include "EnterNumberWindow.hpp" -namespace gui { +namespace gui +{ -/* - * - */ -class EmergencyCallWindow: public EnterNumberWindow { -public: - EmergencyCallWindow( app::Application* app ); - virtual ~EmergencyCallWindow(); + /* + * + */ + class EmergencyCallWindow : public EnterNumberWindow + { + public: + EmergencyCallWindow(app::Application *app); + virtual ~EmergencyCallWindow(); - bool onInput( const InputEvent& inputEvent ) override; - bool handleSwitchData( SwitchData* data ) override; + bool onInput(const InputEvent &inputEvent) override; + bool handleSwitchData(SwitchData *data) override; - void rebuild() override; - void buildInterface() override; - void destroyInterface() override; -}; + void rebuild() override; + void buildInterface() override; + void destroyInterface() override; + }; } /* namespace gui */ diff --git a/module-apps/application-call/windows/EnterNumberWindow.cpp b/module-apps/application-call/windows/EnterNumberWindow.cpp index ed1e4cab6..26910947e 100644 --- a/module-apps/application-call/windows/EnterNumberWindow.cpp +++ b/module-apps/application-call/windows/EnterNumberWindow.cpp @@ -19,200 +19,205 @@ #include #include -namespace gui { - -using namespace callAppStyle::enterNumberWindow; - -EnterNumberWindow::EnterNumberWindow( app::Application* app, std::string windowName ) : AppWindow(app, windowName ) { - buildInterface(); -} - -void EnterNumberWindow::rebuild() { - -} - -void EnterNumberWindow::setNumberLabel(const std::string num) +namespace gui { - auto app = dynamic_cast(application); - if (app == nullptr) - { - LOG_ERROR("app != ApplicationCall"); - return; - } - app->setDisplayedNumber(num); - numberLabel->setText(num); + using namespace callAppStyle::enterNumberWindow; - if(numberLabel->getText().length() == 0) - { - bottomBar->setText(BottomBar::Side::RIGHT, utils::localize.get("common_back")); - return; - } - bottomBar->setText( BottomBar::Side::RIGHT, utils::localize.get("app_call_clear")); -} - -void EnterNumberWindow::buildInterface() { - - AppWindow::buildInterface(); - - bottomBar->setText( BottomBar::Side::LEFT, utils::localize.get("app_call_call")); - bottomBar->setText( BottomBar::Side::CENTER, utils::localize.get("app_call_add")); - bottomBar->setText( BottomBar::Side::RIGHT, utils::localize.get("app_call_clear")); - - topBar->setActive(TopBar::Elements::SIGNAL, true ); - topBar->setActive(TopBar::Elements::BATTERY, true ); - topBar->setActive(TopBar::Elements::TIME, true ); - - numberLabel = new gui::Label(this, numberLabel::x, numberLabel::y, numberLabel::w, numberLabel::h); - numberLabel->setPenWidth(numberLabel::borderW); - numberLabel->setFont(style::window::font::verybig); - numberLabel->setEdges( RectangleEdgeFlags::GUI_RECT_EDGE_BOTTOM ); - numberLabel->setAlignement( gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_CENTER, gui::Alignment::ALIGN_VERTICAL_TOP)); - numberLabel->setDotsMode( true, false); - - newContactIcon = new gui::Icon(this, newContactIcon::x, newContactIcon::y, "cross", utils::localize.get("app_call_contact")); - newContactIcon->activatedCallback = [=](gui::Item &item) { return addNewContact(); }; - setFocusItem(newContactIcon); -} - -bool EnterNumberWindow::addNewContact() -{ - auto app = dynamic_cast(application); - if (app != nullptr) + EnterNumberWindow::EnterNumberWindow(app::Application *app, std::string windowName) : AppWindow(app, windowName) { - auto phoneNumber = app->getDisplayedNumber(); - return app::contact(getApplication(), app::ContactOperation::Add, phoneNumber); + buildInterface(); } - return false; -} -void EnterNumberWindow::destroyInterface() { - AppWindow::destroyInterface(); - if( numberLabel ) { removeWidget(numberLabel); delete numberLabel; numberLabel= nullptr; } - if( newContactIcon ) { removeWidget(newContactIcon); delete newContactIcon; newContactIcon= nullptr; } - children.clear(); -} + void EnterNumberWindow::rebuild() + {} -EnterNumberWindow::~EnterNumberWindow() { - destroyInterface(); -} - -bool EnterNumberWindow::onInput( const InputEvent& inputEvent ) { - auto app = dynamic_cast(application); - if (app == nullptr) + void EnterNumberWindow::setNumberLabel(const std::string num) { - LOG_ERROR("app != ApplicationCall"); - return AppWindow::onInput(inputEvent); - } - auto code = translator.handle(inputEvent.key, InputMode({InputMode::phone}).get()); - if( inputEvent.state == InputEvent::State::keyReleasedShort ) { - if(inputEvent.keyCode == KeyCode::KEY_LF) { - std::string num = app->getDisplayedNumber(); - LOG_INFO("number: [%s]", num.c_str()); - auto ret = CellularServiceAPI::DialNumber(application,num.c_str()); - LOG_INFO("CALL RESULT: %s", (ret?"OK":"FAIL")); - return true; + auto app = dynamic_cast(application); + if (app == nullptr) { + LOG_ERROR("app != ApplicationCall"); + return; } - else if(inputEvent.keyCode == KeyCode::KEY_RF) { - std::string num = app->getDisplayedNumber(); - //if there isn't any char in phone number field return to previous application - if( num.empty() ) { - sapm::ApplicationManager::messageSwitchPreviousApplication( application ); - return true; - } + app->setDisplayedNumber(num); - num = num.substr(0, num.size()-1); - setNumberLabel(num); + numberLabel->setText(num); - application->refreshWindow(RefreshModes::GUI_REFRESH_FAST); - - return true; - } - else if (code != 0) - { - std::string num = app->getDisplayedNumber(); - num += code; - setNumberLabel(num); - - app->refreshWindow(RefreshModes::GUI_REFRESH_FAST); - - return true; - } - } - else if( inputEvent.state == InputEvent::State::keyReleasedLong) { - //erase all characters from phone number - if(inputEvent.keyCode == KeyCode::KEY_RF) { - std::string num = app->getDisplayedNumber(); - //if there isn't any char in phone number field return to previous application - if( num.empty() ) { - sapm::ApplicationManager::messageSwitchPreviousApplication( application ); - return true; - } - - setNumberLabel(""); - - application->refreshWindow(RefreshModes::GUI_REFRESH_FAST); - - return true; - } - // long press of '0' key is translated to '+' - else if (inputEvent.keyCode == KeyCode::KEY_0) - { - std::string num = app->getDisplayedNumber(); - num += '+'; - setNumberLabel(num); - - application->refreshWindow(RefreshModes::GUI_REFRESH_FAST); - - return true; + if (numberLabel->getText().length() == 0) { + bottomBar->setText(BottomBar::Side::RIGHT, utils::localize.get("common_back")); + return; } + bottomBar->setText(BottomBar::Side::RIGHT, utils::localize.get("app_call_clear")); } - //check if any of the lower inheritance onInput methods catch the event - return AppWindow::onInput( inputEvent ); -} - -bool EnterNumberWindow::handleSwitchData( SwitchData* data ) { - - if( data == nullptr ) - { - LOG_ERROR("Received null pointer"); - return false; - } - - app::CallSwitchData *callData = dynamic_cast(data); - if (callData != nullptr) + void EnterNumberWindow::buildInterface() { - std::string num = callData->getPhoneNumber(); - setNumberLabel(num); - application->refreshWindow(RefreshModes::GUI_REFRESH_FAST); - switch (callData->getType()) - { - case app::CallSwitchData::Type::EXECUTE_CALL: { - LOG_INFO("number: [%s]", num.c_str()); - auto ret = CellularServiceAPI::DialNumber(application, num.c_str()); - LOG_INFO("CALL RESULT: %s", (ret ? "OK" : "FAIL")); - return true; - } - case app::CallSwitchData::Type::ENTER_NUMBER: { - return true; - } - break; + AppWindow::buildInterface(); - default: { - LOG_ERROR("Unhandled callData type"); - return false; - } - } + bottomBar->setText(BottomBar::Side::LEFT, utils::localize.get("app_call_call")); + bottomBar->setText(BottomBar::Side::CENTER, utils::localize.get("app_call_add")); + bottomBar->setText(BottomBar::Side::RIGHT, utils::localize.get("app_call_clear")); + + topBar->setActive(TopBar::Elements::SIGNAL, true); + topBar->setActive(TopBar::Elements::BATTERY, true); + topBar->setActive(TopBar::Elements::TIME, true); + + numberLabel = new gui::Label(this, numberLabel::x, numberLabel::y, numberLabel::w, numberLabel::h); + numberLabel->setPenWidth(numberLabel::borderW); + numberLabel->setFont(style::window::font::verybig); + numberLabel->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_BOTTOM); + numberLabel->setAlignement( + gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_CENTER, gui::Alignment::ALIGN_VERTICAL_TOP)); + numberLabel->setDotsMode(true, false); + + newContactIcon = + new gui::Icon(this, newContactIcon::x, newContactIcon::y, "cross", utils::localize.get("app_call_contact")); + newContactIcon->activatedCallback = [=](gui::Item &item) { return addNewContact(); }; + setFocusItem(newContactIcon); } - else + + bool EnterNumberWindow::addNewContact() { - LOG_ERROR("Unrecognized SwitchData"); + auto app = dynamic_cast(application); + if (app != nullptr) { + auto phoneNumber = app->getDisplayedNumber(); + return app::contact(getApplication(), app::ContactOperation::Add, phoneNumber); + } return false; } - return false; -} + void EnterNumberWindow::destroyInterface() + { + AppWindow::destroyInterface(); + if (numberLabel) { + removeWidget(numberLabel); + delete numberLabel; + numberLabel = nullptr; + } + if (newContactIcon) { + removeWidget(newContactIcon); + delete newContactIcon; + newContactIcon = nullptr; + } + children.clear(); + } + + EnterNumberWindow::~EnterNumberWindow() + { + destroyInterface(); + } + + bool EnterNumberWindow::onInput(const InputEvent &inputEvent) + { + auto app = dynamic_cast(application); + if (app == nullptr) { + LOG_ERROR("app != ApplicationCall"); + return AppWindow::onInput(inputEvent); + } + auto code = translator.handle(inputEvent.key, InputMode({InputMode::phone}).get()); + if (inputEvent.state == InputEvent::State::keyReleasedShort) { + if (inputEvent.keyCode == KeyCode::KEY_LF) { + std::string num = app->getDisplayedNumber(); + LOG_INFO("number: [%s]", num.c_str()); + auto ret = CellularServiceAPI::DialNumber(application, num.c_str()); + LOG_INFO("CALL RESULT: %s", (ret ? "OK" : "FAIL")); + return true; + } + else if (inputEvent.keyCode == KeyCode::KEY_RF) { + std::string num = app->getDisplayedNumber(); + // if there isn't any char in phone number field return to previous application + if (num.empty()) { + sapm::ApplicationManager::messageSwitchPreviousApplication(application); + return true; + } + + num = num.substr(0, num.size() - 1); + setNumberLabel(num); + + application->refreshWindow(RefreshModes::GUI_REFRESH_FAST); + + return true; + } + else if (code != 0) { + std::string num = app->getDisplayedNumber(); + num += code; + setNumberLabel(num); + + app->refreshWindow(RefreshModes::GUI_REFRESH_FAST); + + return true; + } + } + else if (inputEvent.state == InputEvent::State::keyReleasedLong) { + // erase all characters from phone number + if (inputEvent.keyCode == KeyCode::KEY_RF) { + std::string num = app->getDisplayedNumber(); + // if there isn't any char in phone number field return to previous application + if (num.empty()) { + sapm::ApplicationManager::messageSwitchPreviousApplication(application); + return true; + } + + setNumberLabel(""); + + application->refreshWindow(RefreshModes::GUI_REFRESH_FAST); + + return true; + } + // long press of '0' key is translated to '+' + else if (inputEvent.keyCode == KeyCode::KEY_0) { + std::string num = app->getDisplayedNumber(); + num += '+'; + setNumberLabel(num); + + application->refreshWindow(RefreshModes::GUI_REFRESH_FAST); + + return true; + } + } + + // check if any of the lower inheritance onInput methods catch the event + return AppWindow::onInput(inputEvent); + } + + bool EnterNumberWindow::handleSwitchData(SwitchData *data) + { + + if (data == nullptr) { + LOG_ERROR("Received null pointer"); + return false; + } + + app::CallSwitchData *callData = dynamic_cast(data); + if (callData != nullptr) { + std::string num = callData->getPhoneNumber(); + setNumberLabel(num); + application->refreshWindow(RefreshModes::GUI_REFRESH_FAST); + switch (callData->getType()) { + case app::CallSwitchData::Type::EXECUTE_CALL: { + LOG_INFO("number: [%s]", num.c_str()); + auto ret = CellularServiceAPI::DialNumber(application, num.c_str()); + LOG_INFO("CALL RESULT: %s", (ret ? "OK" : "FAIL")); + return true; + } + + case app::CallSwitchData::Type::ENTER_NUMBER: { + return true; + } break; + + default: { + LOG_ERROR("Unhandled callData type"); + return false; + } + } + } + else { + LOG_ERROR("Unrecognized SwitchData"); + return false; + } + + return false; + } } /* namespace gui */ diff --git a/module-apps/application-call/windows/EnterNumberWindow.hpp b/module-apps/application-call/windows/EnterNumberWindow.hpp index 6c0b24600..7626d326b 100644 --- a/module-apps/application-call/windows/EnterNumberWindow.hpp +++ b/module-apps/application-call/windows/EnterNumberWindow.hpp @@ -18,35 +18,36 @@ #include "gui/widgets/Window.hpp" #include -namespace gui { +namespace gui +{ -/* - * - */ -class EnterNumberWindow: public AppWindow { -protected: - gui::Label *numberLabel = nullptr; - gui::Icon *newContactIcon = nullptr; + /* + * + */ + class EnterNumberWindow : public AppWindow + { + protected: + gui::Label *numberLabel = nullptr; + gui::Icon *newContactIcon = nullptr; - void setNumberLabel(const std::string num); + void setNumberLabel(const std::string num); -public: - EnterNumberWindow() = delete; - EnterNumberWindow(app::Application *app, std::string windowName = app::window::name_enterNumber); - virtual ~EnterNumberWindow(); + public: + EnterNumberWindow() = delete; + EnterNumberWindow(app::Application *app, std::string windowName = app::window::name_enterNumber); + virtual ~EnterNumberWindow(); - bool onInput(const InputEvent &inputEvent) override; - bool handleSwitchData(SwitchData *data) override; + bool onInput(const InputEvent &inputEvent) override; + bool handleSwitchData(SwitchData *data) override; - void rebuild() override; - void buildInterface() override; - void destroyInterface() override; + void rebuild() override; + void buildInterface() override; + void destroyInterface() override; -private: - gui::KeyInputMappedTranslation translator; + private: + gui::KeyInputMappedTranslation translator; - bool addNewContact(); -}; + bool addNewContact(); + }; } /* namespace gui */ - diff --git a/module-apps/application-calllog/ApplicationCallLog.cpp b/module-apps/application-calllog/ApplicationCallLog.cpp index f7771503f..6e3d8eeed 100644 --- a/module-apps/application-calllog/ApplicationCallLog.cpp +++ b/module-apps/application-calllog/ApplicationCallLog.cpp @@ -21,122 +21,125 @@ using namespace calllog; -namespace app { - -ApplicationCallLog::ApplicationCallLog(std::string name, std::string parent, bool startBackgound) : - Application( name, parent, startBackgound, 4096 ) { -} - -ApplicationCallLog::~ApplicationCallLog() { - LOG_INFO("ApplicationCallLog::destroy"); -} - -// Invoked upon receiving data message -sys::Message_t ApplicationCallLog::DataReceivedHandler(sys::DataMessage* msgl,sys::ResponseMessage* resp) { - - auto retMsg = Application::DataReceivedHandler(msgl); - //if message was handled by application's template there is no need to process further. - if( (reinterpret_cast( retMsg.get() )->retCode == sys::ReturnCodes::Success ) ){ - return retMsg; - } - - auto handled = false; - - //handle database response - if( resp != nullptr ) { - handled = true; - switch (resp->responseTo) - { - case MessageType::DBCalllogGetLimitOffset: { - if (getCurrentWindow()->onDatabaseMessage(resp)) - { - refreshWindow(gui::RefreshModes::GUI_REFRESH_FAST); - } - break; - } - default: - break; - } - } - - if( handled ) { - return std::make_shared(); - } - else { - return std::make_shared(sys::ReturnCodes::Unresolved); - } -} - -// Invoked during initialization -sys::ReturnCodes ApplicationCallLog::InitHandler() { - auto ret = Application::InitHandler(); - if(ret != sys::ReturnCodes::Success) return ret; - - createUserInterface(); - - setActiveWindow(calllog::settings::MainWindowStr); - - return ret; -} - -sys::ReturnCodes ApplicationCallLog::DeinitHandler() { - return sys::ReturnCodes::Success; -} - -void ApplicationCallLog::createUserInterface() { - - gui::AppWindow* window = nullptr; - - window = new gui::CallLogMainWindow(this); - windows.insert(std::pair(window->getName(), window)); - - window = new gui::CallLogDetailsWindow(this); - windows.insert(std::pair(window->getName(), window)); - - windowOptions = gui::newOptionWindow(this); - windows.insert(std::pair(windowOptions->getName(), windowOptions)); - - window = new gui::Dialog(this, calllog::settings::CallDeleteWindowStr, - { - .title = "", - .icon = "phonebook_contact_delete_trashcan", - .text = utils::localize.get("app_calllog_delete_call_confirmation"), - .action = []() -> bool { - LOG_INFO("!"); - return true; - }, - }); - windows.insert(std::pair(window->getName(), window)); -} - -void ApplicationCallLog::destroyUserInterface() { -} - -bool ApplicationCallLog::removeCalllogEntry(const CalllogRecord &record) +namespace app { - LOG_DEBUG("Removing CalllogRecord: %d", record.ID); - auto dialog = dynamic_cast(windows[calllog::settings::CallDeleteWindowStr]); - if (dialog != nullptr) + + ApplicationCallLog::ApplicationCallLog(std::string name, std::string parent, bool startBackgound) + : Application(name, parent, startBackgound, 4096) + {} + + ApplicationCallLog::~ApplicationCallLog() { - auto meta = dialog->meta; - meta.action = [=]() -> bool { - if (DBServiceAPI::CalllogRemove(this, record.ID) == false) - { - LOG_ERROR("CalllogRemove id=%u failed", record.ID); - return false; + LOG_INFO("ApplicationCallLog::destroy"); + } + + // Invoked upon receiving data message + sys::Message_t ApplicationCallLog::DataReceivedHandler(sys::DataMessage *msgl, sys::ResponseMessage *resp) + { + + auto retMsg = Application::DataReceivedHandler(msgl); + // if message was handled by application's template there is no need to process further. + if ((reinterpret_cast(retMsg.get())->retCode == sys::ReturnCodes::Success)) { + return retMsg; + } + + auto handled = false; + + // handle database response + if (resp != nullptr) { + handled = true; + switch (resp->responseTo) { + case MessageType::DBCalllogGetLimitOffset: { + if (getCurrentWindow()->onDatabaseMessage(resp)) { + refreshWindow(gui::RefreshModes::GUI_REFRESH_FAST); + } + break; } - this->switchWindow(calllog::settings::MainWindowStr); - return true; - }; - meta.title = record.name; - dialog->update(meta); - return switchWindow(calllog::settings::CallDeleteWindowStr, nullptr); + default: + break; + } + } + + if (handled) { + return std::make_shared(); + } + else { + return std::make_shared(sys::ReturnCodes::Unresolved); + } } - else + + // Invoked during initialization + sys::ReturnCodes ApplicationCallLog::InitHandler() { - LOG_ERROR("Dialog bad type!"); - return false; + auto ret = Application::InitHandler(); + if (ret != sys::ReturnCodes::Success) + return ret; + + createUserInterface(); + + setActiveWindow(calllog::settings::MainWindowStr); + + return ret; + } + + sys::ReturnCodes ApplicationCallLog::DeinitHandler() + { + return sys::ReturnCodes::Success; + } + + void ApplicationCallLog::createUserInterface() + { + + gui::AppWindow *window = nullptr; + + window = new gui::CallLogMainWindow(this); + windows.insert(std::pair(window->getName(), window)); + + window = new gui::CallLogDetailsWindow(this); + windows.insert(std::pair(window->getName(), window)); + + windowOptions = gui::newOptionWindow(this); + windows.insert(std::pair(windowOptions->getName(), windowOptions)); + + window = new gui::Dialog(this, + calllog::settings::CallDeleteWindowStr, + { + .title = "", + .icon = "phonebook_contact_delete_trashcan", + .text = utils::localize.get("app_calllog_delete_call_confirmation"), + .action = []() -> bool { + LOG_INFO("!"); + return true; + }, + }); + windows.insert(std::pair(window->getName(), window)); + } + + void ApplicationCallLog::destroyUserInterface() + {} + + bool ApplicationCallLog::removeCalllogEntry(const CalllogRecord &record) + { + LOG_DEBUG("Removing CalllogRecord: %d", record.ID); + auto dialog = dynamic_cast(windows[calllog::settings::CallDeleteWindowStr]); + if (dialog != nullptr) { + auto meta = dialog->meta; + meta.action = [=]() -> bool { + if (DBServiceAPI::CalllogRemove(this, record.ID) == false) { + LOG_ERROR("CalllogRemove id=%u failed", record.ID); + return false; + } + this->switchWindow(calllog::settings::MainWindowStr); + return true; + }; + meta.title = record.name; + dialog->update(meta); + return switchWindow(calllog::settings::CallDeleteWindowStr, nullptr); + } + else { + LOG_ERROR("Dialog bad type!"); + return false; + } } -} } /* namespace app */ diff --git a/module-apps/application-calllog/ApplicationCallLog.hpp b/module-apps/application-calllog/ApplicationCallLog.hpp index e7ed8de36..82c7fa448 100644 --- a/module-apps/application-calllog/ApplicationCallLog.hpp +++ b/module-apps/application-calllog/ApplicationCallLog.hpp @@ -12,29 +12,33 @@ #include #include -namespace app { +namespace app +{ -const inline std::string CallLogAppStr = "ApplicationCallLog"; + const inline std::string CallLogAppStr = "ApplicationCallLog"; -class ApplicationCallLog: public Application { -protected: -public: - ApplicationCallLog( std::string name=CallLogAppStr, std::string parent = "", bool startBackgound = false); - virtual ~ApplicationCallLog(); + class ApplicationCallLog : public Application + { + protected: + public: + ApplicationCallLog(std::string name = CallLogAppStr, std::string parent = "", bool startBackgound = false); + virtual ~ApplicationCallLog(); - gui::OptionWindow *windowOptions = nullptr; + gui::OptionWindow *windowOptions = nullptr; - sys::Message_t DataReceivedHandler(sys::DataMessage* msgl,sys::ResponseMessage* resp) override; - sys::ReturnCodes InitHandler() override; - sys::ReturnCodes DeinitHandler() override; + sys::Message_t DataReceivedHandler(sys::DataMessage *msgl, sys::ResponseMessage *resp) override; + sys::ReturnCodes InitHandler() override; + sys::ReturnCodes DeinitHandler() override; - sys::ReturnCodes SwitchPowerModeHandler(const sys::ServicePowerMode mode) override final {return sys::ReturnCodes::Success;} + sys::ReturnCodes SwitchPowerModeHandler(const sys::ServicePowerMode mode) override final + { + return sys::ReturnCodes::Success; + } - void createUserInterface() final; - void destroyUserInterface() final; + void createUserInterface() final; + void destroyUserInterface() final; - bool removeCalllogEntry(const CalllogRecord &record); -}; + bool removeCalllogEntry(const CalllogRecord &record); + }; } /* namespace app */ - diff --git a/module-apps/application-calllog/CalllogModel.cpp b/module-apps/application-calllog/CalllogModel.cpp index 7bd931f5a..c782d6b2a 100644 --- a/module-apps/application-calllog/CalllogModel.cpp +++ b/module-apps/application-calllog/CalllogModel.cpp @@ -16,64 +16,71 @@ using namespace calllog; #define DEBUG_CALLLOG_DB_ACCESS 0 -CalllogModel::CalllogModel( app::Application* app) : DatabaseModel( app, calllog::settings::pageSize ){ +CalllogModel::CalllogModel(app::Application *app) : DatabaseModel(app, calllog::settings::pageSize) +{} +void CalllogModel::requestRecordsCount() +{ +#if (DEBUG_CALLLOG_DB_ACCESS) + auto tstamp = xTaskGetTickCount(); +#endif + recordsCount = DBServiceAPI::CalllogGetCount(application); +#if (DEBUG_CALLLOG_DB_ACCESS) + LOG_INFO("DBServiceAPI::CalllogGetCount %d records %d ms", recordsCount, xTaskGetTickCount() - tstamp); +#endif + + // request first and second page if possible + if (recordsCount > 0) { + LOG_INFO("DBServiceAPI::CalllogGetCount CalllogGetLimitOffset"); + DBServiceAPI::CalllogGetLimitOffset(application, 0, pageSize); + if (recordsCount >= pageSize) { + DBServiceAPI::CalllogGetLimitOffset(application, pageSize, pageSize); + } + } } -void CalllogModel::requestRecordsCount() { - #if(DEBUG_CALLLOG_DB_ACCESS) - auto tstamp = xTaskGetTickCount(); - #endif - recordsCount = DBServiceAPI::CalllogGetCount(application); - #if(DEBUG_CALLLOG_DB_ACCESS) - LOG_INFO("DBServiceAPI::CalllogGetCount %d records %d ms", recordsCount, xTaskGetTickCount() - tstamp); - #endif - - //request first and second page if possible - if( recordsCount > 0 ){ - LOG_INFO("DBServiceAPI::CalllogGetCount CalllogGetLimitOffset"); - DBServiceAPI::CalllogGetLimitOffset(application, 0, pageSize ); - if( recordsCount >= pageSize ) { - DBServiceAPI::CalllogGetLimitOffset(application, pageSize, pageSize ); - } - } +void CalllogModel::requestRecords(const uint32_t offset, const uint32_t limit) +{ + DBServiceAPI::CalllogGetLimitOffset(application, offset, limit); } -void CalllogModel::requestRecords( const uint32_t offset, const uint32_t limit ) { - DBServiceAPI::CalllogGetLimitOffset(application, offset, limit ); +bool CalllogModel::updateRecords(std::unique_ptr> records, + const uint32_t offset, + const uint32_t limit, + uint32_t count) +{ + + LOG_INFO("Offset: %d, Limit: %d Count:%d", offset, limit, count); + // for( uint32_t i=0; isize(); ++i ) { + // LOG_INFO("id: %d, ", records.get()->operator [](i).ID, records.get()->operator [](i).path.c_str()); + // } + + DatabaseModel::updateRecords(std::move(records), offset, limit, count); + + return true; } -bool CalllogModel::updateRecords( std::unique_ptr> records, const uint32_t offset, const uint32_t limit, uint32_t count ) { +gui::ListItem *CalllogModel::getItem( + int index, int firstElement, int prevElement, uint32_t count, int remaining, bool topDown) +{ + std::shared_ptr call = getRecord(index); + SettingsRecord &settings = application->getSettings(); + if (call.get() == nullptr) { + // LOG_ERROR("getItem nullptr"); + return nullptr; + } + auto item = new gui::CalllogItem(this, !settings.timeFormat12); + if (item != nullptr) { + item->setCall(call); + item->setID(index); + item->activatedCallback = [=](gui::Item &item) { // TODO: alek: this is not the best place for this + LOG_INFO("activatedCallback"); + std::unique_ptr data = std::make_unique(*call); + application->switchWindow(calllog::settings::DetailsWindowStr, std::move(data)); + return true; + }; + return item; + } - LOG_INFO("Offset: %d, Limit: %d Count:%d", offset, limit, count); -// for( uint32_t i=0; isize(); ++i ) { -// LOG_INFO("id: %d, ", records.get()->operator [](i).ID, records.get()->operator [](i).path.c_str()); -// } - - DatabaseModel::updateRecords( std::move(records), offset, limit, count ); - - return true; -} - -gui::ListItem* CalllogModel::getItem( int index, int firstElement, int prevElement, uint32_t count, int remaining, bool topDown ) { - std::shared_ptr call = getRecord( index ); - SettingsRecord& settings = application->getSettings(); - if ( call.get() == nullptr ){ - //LOG_ERROR("getItem nullptr"); - return nullptr; - } - auto item = new gui::CalllogItem(this, !settings.timeFormat12 ); - if( item != nullptr ) { - item->setCall(call); - item->setID( index ); - item->activatedCallback = [=] (gui::Item& item){ // TODO: alek: this is not the best place for this - LOG_INFO("activatedCallback"); - std::unique_ptr data = std::make_unique(*call); - application->switchWindow(calllog::settings::DetailsWindowStr, std::move(data)); - return true; - }; - return item; - } - - return nullptr; + return nullptr; } diff --git a/module-apps/application-calllog/CalllogModel.hpp b/module-apps/application-calllog/CalllogModel.hpp index 5432bd552..2d602157d 100644 --- a/module-apps/application-calllog/CalllogModel.hpp +++ b/module-apps/application-calllog/CalllogModel.hpp @@ -19,18 +19,26 @@ /* * */ -class CalllogModel: public app::DatabaseModel, public gui::ListItemProvider { -public: - CalllogModel() = delete; - CalllogModel( app::Application* app ); - virtual ~CalllogModel() = default; +class CalllogModel : public app::DatabaseModel, public gui::ListItemProvider +{ + public: + CalllogModel() = delete; + CalllogModel(app::Application *app); + virtual ~CalllogModel() = default; - //virtual methods - void requestRecordsCount() override; - bool updateRecords( std::unique_ptr> records, const uint32_t offset, const uint32_t limit, uint32_t count ) override; - void requestRecords( const uint32_t offset, const uint32_t limit ) override; + // virtual methods + void requestRecordsCount() override; + bool updateRecords(std::unique_ptr> records, + const uint32_t offset, + const uint32_t limit, + uint32_t count) override; + void requestRecords(const uint32_t offset, const uint32_t limit) override; - //virtual methods for ListViewProvider - gui::ListItem* getItem( int index, int firstElement, int prevElement, uint32_t count, int remaining, bool topDown ) override; - int getItemCount() const override { return recordsCount; }; + // virtual methods for ListViewProvider + gui::ListItem *getItem( + int index, int firstElement, int prevElement, uint32_t count, int remaining, bool topDown) override; + int getItemCount() const override + { + return recordsCount; + }; }; diff --git a/module-apps/application-calllog/data/CallLogInternals.hpp b/module-apps/application-calllog/data/CallLogInternals.hpp index 50ff4f09b..bef638434 100644 --- a/module-apps/application-calllog/data/CallLogInternals.hpp +++ b/module-apps/application-calllog/data/CallLogInternals.hpp @@ -13,29 +13,36 @@ #include "CalllogRecord.hpp" #include -namespace calllog { +namespace calllog +{ - enum CallLogCallType { - IN = 0, - OUT = 1, - MISSED = 2, - NUM_OF_CALL_TYPES - }; + enum CallLogCallType + { + IN = 0, + OUT = 1, + MISSED = 2, + NUM_OF_CALL_TYPES + }; - inline CallLogCallType toCallLogCallType(const CallType type) { - switch(type) { - case CallType::CT_INCOMING: return CallLogCallType::IN; - case CallType::CT_OUTGOING: return CallLogCallType::OUT; - default: /* rest */ return CallLogCallType::MISSED; - } + inline CallLogCallType toCallLogCallType(const CallType type) + { + switch (type) { + case CallType::CT_INCOMING: + return CallLogCallType::IN; + case CallType::CT_OUTGOING: + return CallLogCallType::OUT; + default: /* rest */ + return CallLogCallType::MISSED; + } } - namespace settings { - // Windows - const inline std::string MainWindowStr = gui::name::window::main_window; - const inline std::string DetailsWindowStr = "DetailsWindow"; - const inline std::string CallDeleteWindowStr = "CallDeleteOptionsWindow"; + namespace settings + { + // Windows + const inline std::string MainWindowStr = gui::name::window::main_window; + const inline std::string DetailsWindowStr = "DetailsWindow"; + const inline std::string CallDeleteWindowStr = "CallDeleteOptionsWindow"; - constexpr auto pageSize = 7; - } + constexpr auto pageSize = 7; + } // namespace settings } // namespace calllog diff --git a/module-apps/application-calllog/data/CallLogStyle.hpp b/module-apps/application-calllog/data/CallLogStyle.hpp index 6cc04b5fb..cd78d8591 100644 --- a/module-apps/application-calllog/data/CallLogStyle.hpp +++ b/module-apps/application-calllog/data/CallLogStyle.hpp @@ -4,117 +4,118 @@ // CALL LOG STYLE namespace callLogStyle { -// DETAILS WINDOW -namespace detailsWindow -{ -constexpr uint32_t default_x = style::window::default_left_margin; -constexpr uint32_t default_w = style::window_width - style::window::default_left_margin - style::window::default_right_margin; -namespace information -{ -namespace label -{ -constexpr uint32_t x = default_x; -constexpr uint32_t y = 111; -constexpr uint32_t w = default_w; -} // namespace label -namespace number -{ -constexpr uint32_t x = default_x; -constexpr uint32_t y = 174; -constexpr uint32_t w = default_w; -} // namespace number -namespace imgs -{ - constexpr uint32_t y = 162; - constexpr uint32_t w = 55; - constexpr uint32_t h = 55; - namespace call + // DETAILS WINDOW + namespace detailsWindow { - constexpr uint32_t x = 317; - namespace icon + constexpr uint32_t default_x = style::window::default_left_margin; + constexpr uint32_t default_w = + style::window_width - style::window::default_left_margin - style::window::default_right_margin; + namespace information { - constexpr uint32_t x = 11; - constexpr uint32_t y = 12; - } // namespace icon - } // namespace call - namespace sms - { - constexpr uint32_t x = 389; - namespace icon + namespace label + { + constexpr uint32_t x = default_x; + constexpr uint32_t y = 111; + constexpr uint32_t w = default_w; + } // namespace label + namespace number + { + constexpr uint32_t x = default_x; + constexpr uint32_t y = 174; + constexpr uint32_t w = default_w; + } // namespace number + namespace imgs + { + constexpr uint32_t y = 162; + constexpr uint32_t w = 55; + constexpr uint32_t h = 55; + namespace call + { + constexpr uint32_t x = 317; + namespace icon + { + constexpr uint32_t x = 11; + constexpr uint32_t y = 12; + } // namespace icon + } // namespace call + namespace sms + { + constexpr uint32_t x = 389; + namespace icon + { + constexpr uint32_t x = 11; + constexpr uint32_t y = 12; + } // namespace icon + } // namespace sms + } // namespace imgs + } // namespace information + namespace type { - constexpr uint32_t x = 11; - constexpr uint32_t y = 12; - } // namespace icon - } // namespace sms -} // namespace imgs -} // namespace information -namespace type -{ -namespace label -{ -constexpr uint32_t x = default_x; -constexpr uint32_t y = 222; -constexpr uint32_t w = style::window_width / 2 - x; -} // namespace label -namespace img -{ -const uint32_t x = default_x; -const uint32_t y = 285; -} // namespace img -namespace data -{ -constexpr uint32_t x = 70; -constexpr uint32_t y = 285; -constexpr uint32_t w = style::window_width / 2 - x; -} // namespace data -} // namespace type -namespace duration -{ -namespace label -{ -constexpr uint32_t x = 281; -constexpr uint32_t y = 222; -constexpr uint32_t w = style::window_width - x - style::window::default_right_margin; -} // namespace label -namespace data -{ -constexpr uint32_t x = 281; -constexpr uint32_t y = 285; -constexpr uint32_t w = style::window_width / 2 - style::window::default_right_margin; -} // namespace data -} // namespace duration -namespace date -{ -namespace label -{ -constexpr uint32_t x = default_x; -constexpr uint32_t y = 333; -constexpr uint32_t w = default_w; -} // namespace label -namespace dataDay -{ -constexpr uint32_t x = default_x; -constexpr uint32_t y = 396; -constexpr uint32_t w = default_w; -} // namespace dataDay -namespace dataDate -{ -constexpr uint32_t x = default_x; -constexpr uint32_t y = dataDay::y + style::window::label::small_h; -constexpr uint32_t w = default_w; -} // namespace dataDate -} // namespace date -} // namespace detailsWindow + namespace label + { + constexpr uint32_t x = default_x; + constexpr uint32_t y = 222; + constexpr uint32_t w = style::window_width / 2 - x; + } // namespace label + namespace img + { + const uint32_t x = default_x; + const uint32_t y = 285; + } // namespace img + namespace data + { + constexpr uint32_t x = 70; + constexpr uint32_t y = 285; + constexpr uint32_t w = style::window_width / 2 - x; + } // namespace data + } // namespace type + namespace duration + { + namespace label + { + constexpr uint32_t x = 281; + constexpr uint32_t y = 222; + constexpr uint32_t w = style::window_width - x - style::window::default_right_margin; + } // namespace label + namespace data + { + constexpr uint32_t x = 281; + constexpr uint32_t y = 285; + constexpr uint32_t w = style::window_width / 2 - style::window::default_right_margin; + } // namespace data + } // namespace duration + namespace date + { + namespace label + { + constexpr uint32_t x = default_x; + constexpr uint32_t y = 333; + constexpr uint32_t w = default_w; + } // namespace label + namespace dataDay + { + constexpr uint32_t x = default_x; + constexpr uint32_t y = 396; + constexpr uint32_t w = default_w; + } // namespace dataDay + namespace dataDate + { + constexpr uint32_t x = default_x; + constexpr uint32_t y = dataDay::y + style::window::label::small_h; + constexpr uint32_t w = default_w; + } // namespace dataDate + } // namespace date + } // namespace detailsWindow -// MAIN WINDOW -namespace mainWindow -{ -constexpr uint32_t leftMargin = 19; -constexpr uint32_t rightMargin = 17; -constexpr uint32_t x = leftMargin; -constexpr uint32_t y = 111; -constexpr uint32_t w = style::window_width - leftMargin - rightMargin; -constexpr uint32_t h = style::window_height - y; -} // namespace mainWindow + // MAIN WINDOW + namespace mainWindow + { + constexpr uint32_t leftMargin = 19; + constexpr uint32_t rightMargin = 17; + constexpr uint32_t x = leftMargin; + constexpr uint32_t y = 111; + constexpr uint32_t w = style::window_width - leftMargin - rightMargin; + constexpr uint32_t h = style::window_height - y; + } // namespace mainWindow } // namespace callLogStyle \ No newline at end of file diff --git a/module-apps/application-calllog/data/CallLogSwitchData.hpp b/module-apps/application-calllog/data/CallLogSwitchData.hpp index 91f595e88..9ce24e136 100644 --- a/module-apps/application-calllog/data/CallLogSwitchData.hpp +++ b/module-apps/application-calllog/data/CallLogSwitchData.hpp @@ -11,19 +11,25 @@ #include "CalllogRecord.hpp" #include "SwitchData.hpp" -namespace calllog { +namespace calllog +{ -const inline std::string CALLLOG_SWITCH_DATA_STR = "CallLogSwitchData"; + const inline std::string CALLLOG_SWITCH_DATA_STR = "CallLogSwitchData"; -class CallLogSwitchData: public gui::SwitchData { -protected: - CalllogRecord record; -public: - CallLogSwitchData() = delete; - CallLogSwitchData( CalllogRecord record ) : SwitchData(CALLLOG_SWITCH_DATA_STR), record{ record } {}; - virtual ~CallLogSwitchData() = default; + class CallLogSwitchData : public gui::SwitchData + { + protected: + CalllogRecord record; - const CalllogRecord& getRecord() const { return record; }; -}; + public: + CallLogSwitchData() = delete; + CallLogSwitchData(CalllogRecord record) : SwitchData(CALLLOG_SWITCH_DATA_STR), record{record} {}; + virtual ~CallLogSwitchData() = default; -} // namespace calllog + const CalllogRecord &getRecord() const + { + return record; + }; + }; + +} // namespace calllog diff --git a/module-apps/application-calllog/widgets/CalllogItem.cpp b/module-apps/application-calllog/widgets/CalllogItem.cpp index 0472539d0..627d1366f 100644 --- a/module-apps/application-calllog/widgets/CalllogItem.cpp +++ b/module-apps/application-calllog/widgets/CalllogItem.cpp @@ -15,89 +15,107 @@ using namespace calllog; -namespace gui { - -namespace clItemStyle +namespace gui { -constexpr uint32_t w = 431; -constexpr uint32_t h = style::window::label::big_h; -namespace img -{ -constexpr uint32_t x = 11; // TODO: alek:: change to good values -constexpr uint32_t y = 22; -} // namespace img -namespace text -{ -constexpr uint32_t x = 37; -constexpr uint32_t w = 280; -} // namespace text -namespace timestamp -{ -constexpr uint32_t w = 115; -} -} // namespace clItemStyle -CalllogItem::CalllogItem(CalllogModel *model, bool mode24H) : model{model}, mode24H{mode24H} -{ - minWidth = clItemStyle::w; - minHeight = clItemStyle::h; - maxWidth = clItemStyle::w; - maxHeight = clItemStyle::h; + namespace clItemStyle + { + constexpr uint32_t w = 431; + constexpr uint32_t h = style::window::label::big_h; + namespace img + { + constexpr uint32_t x = 11; // TODO: alek:: change to good values + constexpr uint32_t y = 22; + } // namespace img + namespace text + { + constexpr uint32_t x = 37; + constexpr uint32_t w = 280; + } // namespace text + namespace timestamp + { + constexpr uint32_t w = 115; + } + } // namespace clItemStyle - setRadius( 0 ); - setEdges( RectangleEdgeFlags::GUI_RECT_EDGE_BOTTOM | RectangleEdgeFlags::GUI_RECT_EDGE_TOP ); + CalllogItem::CalllogItem(CalllogModel *model, bool mode24H) : model{model}, mode24H{mode24H} + { + minWidth = clItemStyle::w; + minHeight = clItemStyle::h; + maxWidth = clItemStyle::w; + maxHeight = clItemStyle::h; - setPenFocusWidth(style::window::default_border_focucs_w); - setPenWidth(style::window::default_border_no_focus_w); + setRadius(0); + setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_BOTTOM | RectangleEdgeFlags::GUI_RECT_EDGE_TOP); - timestamp = new gui::Label(this, 0,0,0,0); - style::window::decorate(timestamp); - timestamp->setFont(style::window::font::big); - timestamp->setAlignement(gui::Alignment { gui::Alignment::ALIGN_HORIZONTAL_RIGHT, gui::Alignment::ALIGN_VERTICAL_CENTER } ); + setPenFocusWidth(style::window::default_border_focucs_w); + setPenWidth(style::window::default_border_no_focus_w); - auto newImg = [=](const UTF8 imageName)->gui::Image* { - auto img = new gui::Image(this, clItemStyle::img::x, clItemStyle::img::y, 0, 0, imageName); - img->setVisible(false); - return img; - }; - imageCallType[calllog::CallLogCallType::IN] = newImg("calllog_arrow_in"); - imageCallType[calllog::CallLogCallType::OUT] = newImg("calllog_arrow_out"); - imageCallType[calllog::CallLogCallType::MISSED] = newImg("calllog_arrow_den"); + timestamp = new gui::Label(this, 0, 0, 0, 0); + style::window::decorate(timestamp); + timestamp->setFont(style::window::font::big); + timestamp->setAlignement( + gui::Alignment{gui::Alignment::ALIGN_HORIZONTAL_RIGHT, gui::Alignment::ALIGN_VERTICAL_CENTER}); - text = new gui::Label( this, 0,0,0,0); - style::window::decorate(text); - text->setFont(style::window::font::big); - text->setDotsMode( true ); -} + auto newImg = [=](const UTF8 imageName) -> gui::Image * { + auto img = new gui::Image(this, clItemStyle::img::x, clItemStyle::img::y, 0, 0, imageName); + img->setVisible(false); + return img; + }; + imageCallType[calllog::CallLogCallType::IN] = newImg("calllog_arrow_in"); + imageCallType[calllog::CallLogCallType::OUT] = newImg("calllog_arrow_out"); + imageCallType[calllog::CallLogCallType::MISSED] = newImg("calllog_arrow_den"); -CalllogItem::~CalllogItem() { - call = nullptr; - if( timestamp ) { removeWidget(timestamp); delete timestamp; timestamp = nullptr;} - for( auto& img : imageCallType ) { - if( img ) { removeWidget(img); delete img; img = nullptr; } - } - if( text ) { removeWidget(text); delete text; text = nullptr;} -} + text = new gui::Label(this, 0, 0, 0, 0); + style::window::decorate(text); + text->setFont(style::window::font::big); + text->setDotsMode(true); + } -bool CalllogItem::onDimensionChanged( const BoundingBox& oldDim, const BoundingBox& newDim) { - text->setPosition(clItemStyle::text::x, 0 ); - text->setSize(clItemStyle::text::w, newDim.h); + CalllogItem::~CalllogItem() + { + call = nullptr; + if (timestamp) { + removeWidget(timestamp); + delete timestamp; + timestamp = nullptr; + } + for (auto &img : imageCallType) { + if (img) { + removeWidget(img); + delete img; + img = nullptr; + } + } + if (text) { + removeWidget(text); + delete text; + text = nullptr; + } + } - timestamp->setPosition(newDim.w-clItemStyle::timestamp::w,0); - timestamp->setSize(clItemStyle::timestamp::w, newDim.h); - return true; -} + bool CalllogItem::onDimensionChanged(const BoundingBox &oldDim, const BoundingBox &newDim) + { + text->setPosition(clItemStyle::text::x, 0); + text->setSize(clItemStyle::text::w, newDim.h); -void CalllogItem::setCall( std::shared_ptr& call ) { - this->call = call; - text->setText( call->name ); + timestamp->setPosition(newDim.w - clItemStyle::timestamp::w, 0); + timestamp->setSize(clItemStyle::timestamp::w, newDim.h); + return true; + } - auto callType = calllog::toCallLogCallType(call->type); - if (callType == calllog::CallLogCallType::MISSED) text->setFont(style::window::font::bigbold); + void CalllogItem::setCall(std::shared_ptr &call) + { + this->call = call; + text->setText(call->name); - imageCallType[static_cast(callType)]->setVisible(true); + auto callType = calllog::toCallLogCallType(call->type); + if (callType == calllog::CallLogCallType::MISSED) + text->setFont(style::window::font::bigbold); - timestamp->setText(utils::time::DateTime(call->date, false)); // TODO: alek: check for AM/PM and 24h -} + imageCallType[static_cast(callType)]->setVisible(true); + + timestamp->setText(utils::time::DateTime(call->date, false)); // TODO: alek: check for AM/PM and 24h + } } /* namespace gui */ diff --git a/module-apps/application-calllog/widgets/CalllogItem.hpp b/module-apps/application-calllog/widgets/CalllogItem.hpp index ade415bd4..7c256a6f7 100644 --- a/module-apps/application-calllog/widgets/CalllogItem.hpp +++ b/module-apps/application-calllog/widgets/CalllogItem.hpp @@ -14,35 +14,36 @@ #include "../data/CallLogInternals.hpp" #include "../CalllogModel.hpp" -namespace gui { +namespace gui +{ -/* - * @brief Widget used to display information about calllog entry in the calllog list view. - */ -class CalllogItem: public ListItem { - CalllogModel* model = nullptr; - //pointer to the calls record - std::shared_ptr call = nullptr; - //this is timestamp in the mode defined in settings - gui::Label* timestamp = nullptr; - gui::Image* imageCallType[calllog::CallLogCallType::NUM_OF_CALL_TYPES] = {nullptr,nullptr,nullptr}; - gui::Label* text = nullptr; - //flag that defines if time should be displayed in 24h mode - bool mode24H = false; + /* + * @brief Widget used to display information about calllog entry in the calllog list view. + */ + class CalllogItem : public ListItem + { + CalllogModel *model = nullptr; + // pointer to the calls record + std::shared_ptr call = nullptr; + // this is timestamp in the mode defined in settings + gui::Label *timestamp = nullptr; + gui::Image *imageCallType[calllog::CallLogCallType::NUM_OF_CALL_TYPES] = {nullptr, nullptr, nullptr}; + gui::Label *text = nullptr; + // flag that defines if time should be displayed in 24h mode + bool mode24H = false; - public: - CalllogItem( CalllogModel* model, bool mode24H ); - virtual ~CalllogItem(); - //sets copy of alarm's - void setCall( std::shared_ptr& ); + public: + CalllogItem(CalllogModel *model, bool mode24H); + virtual ~CalllogItem(); + // sets copy of alarm's + void setCall(std::shared_ptr &); CalllogRecord getCall() const { return *call; }; // virtual methods from Item - bool onDimensionChanged( const BoundingBox& oldDim, const BoundingBox& newDim) override; -}; + bool onDimensionChanged(const BoundingBox &oldDim, const BoundingBox &newDim) override; + }; } /* namespace gui */ - diff --git a/module-apps/application-calllog/windows/CallLogDetailsWindow.cpp b/module-apps/application-calllog/windows/CallLogDetailsWindow.cpp index 38c3a3245..36f7490b8 100644 --- a/module-apps/application-calllog/windows/CallLogDetailsWindow.cpp +++ b/module-apps/application-calllog/windows/CallLogDetailsWindow.cpp @@ -34,266 +34,290 @@ using namespace calllog; using namespace callLogStyle::detailsWindow; -namespace gui { - -CallLogDetailsWindow::CallLogDetailsWindow( app::Application* app ) : - AppWindow(app, calllog::settings::DetailsWindowStr) { - - buildInterface(); -} - -void CallLogDetailsWindow::rebuild() { - destroyInterface(); - buildInterface(); -} - -Label *CallLogDetailsWindow::decorateLabel(Label *label) +namespace gui { - if (label == nullptr) + + CallLogDetailsWindow::CallLogDetailsWindow(app::Application *app) + : AppWindow(app, calllog::settings::DetailsWindowStr) { - LOG_ERROR("label is nullptr"); + + buildInterface(); + } + + void CallLogDetailsWindow::rebuild() + { + destroyInterface(); + buildInterface(); + } + + Label *CallLogDetailsWindow::decorateLabel(Label *label) + { + if (label == nullptr) { + LOG_ERROR("label is nullptr"); + return label; + } + style::window::decorate(label); + label->setFont(style::window::font::small); + label->setSize(label->widgetArea.w, style::window::label::big_h); + label->setLineMode(true); + return label; } - style::window::decorate(label); - label->setFont(style::window::font::small); - label->setSize(label->widgetArea.w, style::window::label::big_h); - label->setLineMode(true); - return label; -} - -Label * CallLogDetailsWindow::decorateData(Label* label){ - if(label == nullptr){ - LOG_ERROR("label is nullptr"); - return label; - } - style::window::decorate(label); - label->setFont(style::window::font::medium); - label->setSize(label->widgetArea.w, style::window::label::small_h); - - return label; -} - -void CallLogDetailsWindow::buildInterface() { - AppWindow::buildInterface(); - - bottomBar->setText( BottomBar::Side::LEFT, utils::localize.get("common_options")); - bottomBar->setText( BottomBar::Side::CENTER, utils::localize.get("common_call")); - bottomBar->setText( BottomBar::Side::RIGHT, utils::localize.get("common_back")); - - topBar->setActive(TopBar::Elements::TIME, true ); - - // NOTE: height of all labels is set using decorators - - // Information - informationLabel = - decorateLabel(new gui::Label(this, information::label::x, information::label::y, information::label::w, 0, utils::localize.get("common_information"))); - number = decorateData(new gui::Label(this, information::number::x, information::number::y, information::number::w, 0)); - number->setFont(style::window::font::mediumbold); - - for( uint32_t i=0; i<2; ++i ) { - rects[i] = new gui::Rect( this, 0,0, information::imgs::w, information::imgs::h ); - rects[i]->setFilled( false ); - rects[i]->setEdges( RectangleEdgeFlags::GUI_RECT_EDGE_BOTTOM | RectangleEdgeFlags::GUI_RECT_EDGE_TOP ); - rects[i]->setPenFocusWidth(style::window::default_border_focucs_w); - rects[i]->setPenWidth(style::window::default_border_no_focus_w); - } - - rects[static_cast(FocusRects::Call)]->setPosition(information::imgs::call::x, information::imgs::y); - rects[static_cast(FocusRects::Sms)]->setPosition(information::imgs::sms::x, information::imgs::y); - - // TODO: alek: phone ringing seems to be to small - callImg = new gui::Image(rects[FocusRects::Call], information::imgs::call::icon::x, information::imgs::call::icon::y, 0, 0, "phonebook_phone_ringing"); - smsImg = new gui::Image(rects[FocusRects::Sms], information::imgs::sms::icon::x, information::imgs::call::icon::y, 0, 0, "mail"); - - // define navigation between labels - rects[static_cast(FocusRects::Call)]->setNavigationItem(NavigationDirection::LEFT, rects[static_cast(FocusRects::Sms)]); - rects[static_cast(FocusRects::Call)]->setNavigationItem( NavigationDirection::RIGHT, - rects[static_cast(FocusRects::Sms)]); - - rects[static_cast(FocusRects::Sms)]->setNavigationItem( NavigationDirection::LEFT, - rects[static_cast(FocusRects::Call)]); - rects[static_cast(FocusRects::Sms)]->setNavigationItem( NavigationDirection::RIGHT, - rects[static_cast(FocusRects::Call)]); - - //focus callbacks - rects[static_cast(FocusRects::Call)]->focusChangedCallback = [=] (gui::Item& item){ - bottomBar->setText( BottomBar::Side::CENTER, utils::localize.get("common_call")); - return true; }; - - rects[static_cast(FocusRects::Sms)]->focusChangedCallback = [=] (gui::Item& item){ - bottomBar->setText( BottomBar::Side::CENTER, utils::localize.get("common_send")); - return true; }; - - // activated callbacks - rects[FocusRects::Call]->activatedCallback = [=](gui::Item &item) { - LOG_INFO("call %s", record.number.c_str()); - return app::call(application, app::CallOperation::ExecuteCall, record.number); - }; - - rects[FocusRects::Sms]->activatedCallback = [=](gui::Item &item) { - LOG_INFO("sms %s", record.number.c_str()); - return app::sms(application, app::SmsOperation::Add, record.number); - }; - - // Type - typeLabel = decorateLabel(new gui::Label(this, type::label::x, type::label::y, type::label::w, 0, utils::localize.get("app_calllog_type"))); - typeData = decorateData(new gui::Label(this, type::data::x, type::data::y, type::data::w, 0)); - - // TODO: alek: it is used in the code at least twice, possibly create one common function for this - auto newImg = [=](const UTF8 imageName)->gui::Image* { - auto img = new gui::Image(this, type::img::x, type::img::y, 0, 0, imageName); - img->setVisible(false); - return img; - }; - callTypeImg[calllog::CallLogCallType::IN] = newImg("calllog_arrow_in"); - callTypeImg[calllog::CallLogCallType::OUT] = newImg("calllog_arrow_out"); - callTypeImg[calllog::CallLogCallType::MISSED] = newImg("calllog_arrow_den"); - - // Duration - durationLabel = - decorateLabel(new gui::Label(this, duration::label::x, duration::label::y, duration::label::w, 0, utils::localize.get("app_calllog_duration"))); - durationData = decorateData(new gui::Label(this, duration::data::x, duration::data::y, duration::data::w, 0)); - - // Date - dateLabel = decorateLabel(new gui::Label(this, date::label::x, date::label::y, date::label::w, 0, utils::localize.get("app_calllog_date"))); - dateDay = decorateData(new gui::Label(this, date::dataDay::x, date::dataDay::y, date::dataDay::w, 0)); - dateDate = decorateData(new gui::Label(this, date::dataDate::x, date::dataDate::y, date::dataDate::w, 0)); -} - -void CallLogDetailsWindow::destroyInterface() -{ - AppWindow::destroyInterface(); - - removeWidget(informationLabel); - delete informationLabel; - informationLabel = nullptr; - removeWidget(number); - delete number; - number = nullptr; - rects[FocusRects::Call]->removeWidget(callImg); - delete callImg; - callImg = nullptr; - rects[FocusRects::Sms]->removeWidget(smsImg); - delete smsImg; - smsImg = nullptr; - for (auto &rect : rects) + Label *CallLogDetailsWindow::decorateData(Label *label) { - removeWidget(rect); - delete rect; - rect = nullptr; - } - removeWidget(typeLabel); - delete typeLabel; - typeLabel = nullptr; - removeWidget(durationLabel); - delete durationLabel; - durationLabel = nullptr; - for (auto &img : callTypeImg) - { - removeWidget(img); - delete img; - img = nullptr; - } - removeWidget(typeData); - delete typeData; - typeData = nullptr; - removeWidget(durationData); - delete durationData; - durationData = nullptr; - removeWidget(dateLabel); - delete dateLabel; - dateLabel = nullptr; - removeWidget(dateDay); - delete dateDay; - dateDay = nullptr; - removeWidget(dateDate); - delete dateDate; - dateDate = nullptr; - - children.clear(); -} - -CallLogDetailsWindow::~CallLogDetailsWindow() { - destroyInterface(); -} - -void CallLogDetailsWindow::onBeforeShow( ShowMode mode, SwitchData* data ) { - if(data != nullptr && data->getDescription() == calllog::CALLLOG_SWITCH_DATA_STR) { - auto switchData = reinterpret_cast(data); - record = switchData->getRecord(); - - setTitle(record.name); - - number->setText(record.number.c_str()); - - auto callType = toCallLogCallType( record.type ); - for (auto& img : callTypeImg) { - img->setVisible(false); - } - callTypeImg[callType]->setVisible(true); - - UTF8 callTypeStr; - switch (record.type) - { - case CallType::CT_INCOMING: - callTypeStr = utils::localize.get("app_calllog_incoming_call"); - break; - case CallType::CT_OUTGOING: - callTypeStr = utils::localize.get("app_calllog_outgoing_call"); - break; - case CallType::CT_MISSED: - callTypeStr = utils::localize.get("app_calllog_missed_call"); - break; - case CallType::CT_REJECTED: - callTypeStr = utils::localize.get("app_calllog_rejected_call"); - break; - default: - break; + if (label == nullptr) { + LOG_ERROR("label is nullptr"); + return label; } - typeData->setText(callTypeStr); + style::window::decorate(label); + label->setFont(style::window::font::medium); + label->setSize(label->widgetArea.w, style::window::label::small_h); - durationData->setText(utils::time::Timestamp(record.duration).str("%Mm %Ss")); // TODO: alek: add duration class + return label; + } - utils::time::Timestamp t(record.date); - dateDay->setText(t.day() + ","); - dateDate->setText(t.str(utils::localize.get("locale_date_full") + ", " + utils::localize.get("locale_12hour_min"))); // TODO: alek 12/24 h - } - - if( mode == ShowMode::GUI_SHOW_INIT) setFocusItem( rects[static_cast(FocusRects::Call)] ); -} - -bool CallLogDetailsWindow::onInput( const InputEvent& inputEvent ) { - //check if any of the lower inheritance onInput methods catch the event - if( AppWindow::onInput( inputEvent ) ) { - //refresh window only when key is other than enter - if( inputEvent.keyCode != KeyCode::KEY_ENTER ) { - application->render( RefreshModes::GUI_REFRESH_FAST ); - } - - return true; - } - - // process only if key is released - if (((inputEvent.state == InputEvent::State::keyReleasedShort) || ((inputEvent.state == InputEvent::State::keyReleasedLong))) && - (inputEvent.keyCode == KeyCode::KEY_LF)) + void CallLogDetailsWindow::buildInterface() { - auto app = dynamic_cast(application); - assert(app != nullptr); + AppWindow::buildInterface(); - if (app->windowOptions != nullptr) - { - app->windowOptions->clearOptions(); - app->windowOptions->addOptions(calllogWindowOptions(app, record)); - app->switchWindow(app->windowOptions->getName(), nullptr); + bottomBar->setText(BottomBar::Side::LEFT, utils::localize.get("common_options")); + bottomBar->setText(BottomBar::Side::CENTER, utils::localize.get("common_call")); + bottomBar->setText(BottomBar::Side::RIGHT, utils::localize.get("common_back")); + + topBar->setActive(TopBar::Elements::TIME, true); + + // NOTE: height of all labels is set using decorators + + // Information + informationLabel = decorateLabel(new gui::Label(this, + information::label::x, + information::label::y, + information::label::w, + 0, + utils::localize.get("common_information"))); + number = decorateData( + new gui::Label(this, information::number::x, information::number::y, information::number::w, 0)); + number->setFont(style::window::font::mediumbold); + + for (uint32_t i = 0; i < 2; ++i) { + rects[i] = new gui::Rect(this, 0, 0, information::imgs::w, information::imgs::h); + rects[i]->setFilled(false); + rects[i]->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_BOTTOM | RectangleEdgeFlags::GUI_RECT_EDGE_TOP); + rects[i]->setPenFocusWidth(style::window::default_border_focucs_w); + rects[i]->setPenWidth(style::window::default_border_no_focus_w); } - return true; + rects[static_cast(FocusRects::Call)]->setPosition(information::imgs::call::x, information::imgs::y); + rects[static_cast(FocusRects::Sms)]->setPosition(information::imgs::sms::x, information::imgs::y); + + // TODO: alek: phone ringing seems to be to small + callImg = new gui::Image(rects[FocusRects::Call], + information::imgs::call::icon::x, + information::imgs::call::icon::y, + 0, + 0, + "phonebook_phone_ringing"); + smsImg = new gui::Image( + rects[FocusRects::Sms], information::imgs::sms::icon::x, information::imgs::call::icon::y, 0, 0, "mail"); + + // define navigation between labels + rects[static_cast(FocusRects::Call)]->setNavigationItem( + NavigationDirection::LEFT, rects[static_cast(FocusRects::Sms)]); + rects[static_cast(FocusRects::Call)]->setNavigationItem( + NavigationDirection::RIGHT, rects[static_cast(FocusRects::Sms)]); + + rects[static_cast(FocusRects::Sms)]->setNavigationItem( + NavigationDirection::LEFT, rects[static_cast(FocusRects::Call)]); + rects[static_cast(FocusRects::Sms)]->setNavigationItem( + NavigationDirection::RIGHT, rects[static_cast(FocusRects::Call)]); + + // focus callbacks + rects[static_cast(FocusRects::Call)]->focusChangedCallback = [=](gui::Item &item) { + bottomBar->setText(BottomBar::Side::CENTER, utils::localize.get("common_call")); + return true; + }; + + rects[static_cast(FocusRects::Sms)]->focusChangedCallback = [=](gui::Item &item) { + bottomBar->setText(BottomBar::Side::CENTER, utils::localize.get("common_send")); + return true; + }; + + // activated callbacks + rects[FocusRects::Call]->activatedCallback = [=](gui::Item &item) { + LOG_INFO("call %s", record.number.c_str()); + return app::call(application, app::CallOperation::ExecuteCall, record.number); + }; + + rects[FocusRects::Sms]->activatedCallback = [=](gui::Item &item) { + LOG_INFO("sms %s", record.number.c_str()); + return app::sms(application, app::SmsOperation::Add, record.number); + }; + + // Type + typeLabel = decorateLabel(new gui::Label( + this, type::label::x, type::label::y, type::label::w, 0, utils::localize.get("app_calllog_type"))); + typeData = decorateData(new gui::Label(this, type::data::x, type::data::y, type::data::w, 0)); + + // TODO: alek: it is used in the code at least twice, possibly create one common function for this + auto newImg = [=](const UTF8 imageName) -> gui::Image * { + auto img = new gui::Image(this, type::img::x, type::img::y, 0, 0, imageName); + img->setVisible(false); + return img; + }; + callTypeImg[calllog::CallLogCallType::IN] = newImg("calllog_arrow_in"); + callTypeImg[calllog::CallLogCallType::OUT] = newImg("calllog_arrow_out"); + callTypeImg[calllog::CallLogCallType::MISSED] = newImg("calllog_arrow_den"); + + // Duration + durationLabel = decorateLabel(new gui::Label(this, + duration::label::x, + duration::label::y, + duration::label::w, + 0, + utils::localize.get("app_calllog_duration"))); + durationData = decorateData(new gui::Label(this, duration::data::x, duration::data::y, duration::data::w, 0)); + + // Date + dateLabel = decorateLabel(new gui::Label( + this, date::label::x, date::label::y, date::label::w, 0, utils::localize.get("app_calllog_date"))); + dateDay = decorateData(new gui::Label(this, date::dataDay::x, date::dataDay::y, date::dataDay::w, 0)); + dateDate = decorateData(new gui::Label(this, date::dataDate::x, date::dataDate::y, date::dataDate::w, 0)); } - return false; -} + void CallLogDetailsWindow::destroyInterface() + { + AppWindow::destroyInterface(); + + removeWidget(informationLabel); + delete informationLabel; + informationLabel = nullptr; + removeWidget(number); + delete number; + number = nullptr; + rects[FocusRects::Call]->removeWidget(callImg); + delete callImg; + callImg = nullptr; + rects[FocusRects::Sms]->removeWidget(smsImg); + delete smsImg; + smsImg = nullptr; + for (auto &rect : rects) { + removeWidget(rect); + delete rect; + rect = nullptr; + } + removeWidget(typeLabel); + delete typeLabel; + typeLabel = nullptr; + removeWidget(durationLabel); + delete durationLabel; + durationLabel = nullptr; + for (auto &img : callTypeImg) { + removeWidget(img); + delete img; + img = nullptr; + } + removeWidget(typeData); + delete typeData; + typeData = nullptr; + removeWidget(durationData); + delete durationData; + durationData = nullptr; + removeWidget(dateLabel); + delete dateLabel; + dateLabel = nullptr; + removeWidget(dateDay); + delete dateDay; + dateDay = nullptr; + removeWidget(dateDate); + delete dateDate; + dateDate = nullptr; + + children.clear(); + } + + CallLogDetailsWindow::~CallLogDetailsWindow() + { + destroyInterface(); + } + + void CallLogDetailsWindow::onBeforeShow(ShowMode mode, SwitchData *data) + { + if (data != nullptr && data->getDescription() == calllog::CALLLOG_SWITCH_DATA_STR) { + auto switchData = reinterpret_cast(data); + record = switchData->getRecord(); + + setTitle(record.name); + + number->setText(record.number.c_str()); + + auto callType = toCallLogCallType(record.type); + for (auto &img : callTypeImg) { + img->setVisible(false); + } + callTypeImg[callType]->setVisible(true); + + UTF8 callTypeStr; + switch (record.type) { + case CallType::CT_INCOMING: + callTypeStr = utils::localize.get("app_calllog_incoming_call"); + break; + case CallType::CT_OUTGOING: + callTypeStr = utils::localize.get("app_calllog_outgoing_call"); + break; + case CallType::CT_MISSED: + callTypeStr = utils::localize.get("app_calllog_missed_call"); + break; + case CallType::CT_REJECTED: + callTypeStr = utils::localize.get("app_calllog_rejected_call"); + break; + default: + break; + } + typeData->setText(callTypeStr); + + durationData->setText( + utils::time::Timestamp(record.duration).str("%Mm %Ss")); // TODO: alek: add duration class + + utils::time::Timestamp t(record.date); + dateDay->setText(t.day() + ","); + dateDate->setText(t.str(utils::localize.get("locale_date_full") + ", " + + utils::localize.get("locale_12hour_min"))); // TODO: alek 12/24 h + } + + if (mode == ShowMode::GUI_SHOW_INIT) + setFocusItem(rects[static_cast(FocusRects::Call)]); + } + + bool CallLogDetailsWindow::onInput(const InputEvent &inputEvent) + { + // check if any of the lower inheritance onInput methods catch the event + if (AppWindow::onInput(inputEvent)) { + // refresh window only when key is other than enter + if (inputEvent.keyCode != KeyCode::KEY_ENTER) { + application->render(RefreshModes::GUI_REFRESH_FAST); + } + + return true; + } + + // process only if key is released + if (((inputEvent.state == InputEvent::State::keyReleasedShort) || + ((inputEvent.state == InputEvent::State::keyReleasedLong))) && + (inputEvent.keyCode == KeyCode::KEY_LF)) { + auto app = dynamic_cast(application); + assert(app != nullptr); + + if (app->windowOptions != nullptr) { + app->windowOptions->clearOptions(); + app->windowOptions->addOptions(calllogWindowOptions(app, record)); + app->switchWindow(app->windowOptions->getName(), nullptr); + } + + return true; + } + + return false; + } } /* namespace gui */ - - diff --git a/module-apps/application-calllog/windows/CallLogDetailsWindow.hpp b/module-apps/application-calllog/windows/CallLogDetailsWindow.hpp index 2f6c965a8..f92ee3411 100644 --- a/module-apps/application-calllog/windows/CallLogDetailsWindow.hpp +++ b/module-apps/application-calllog/windows/CallLogDetailsWindow.hpp @@ -22,48 +22,50 @@ #include "../data/CallLogInternals.hpp" -namespace gui { +namespace gui +{ -class CallLogDetailsWindow: public AppWindow { - - enum FocusRects + class CallLogDetailsWindow : public AppWindow { - Call, - Sms, - NumOfRects + + enum FocusRects + { + Call, + Sms, + NumOfRects + }; + + Label *informationLabel = nullptr; + Label *number = nullptr; + gui::Rect *rects[static_cast(FocusRects::NumOfRects)] = {nullptr}; + Image *callImg = nullptr; + Image *smsImg = nullptr; + gui::Image *callTypeImg[static_cast(calllog::CallLogCallType::NUM_OF_CALL_TYPES)] = { + nullptr, nullptr, nullptr}; + Label *typeLabel = nullptr; + Label *durationLabel = nullptr; + Label *typeData = nullptr; + Label *durationData = nullptr; + Label *dateLabel = nullptr; + Label *dateDay = nullptr; + Label *dateDate = nullptr; + + CalllogRecord record; + + Label *decorateLabel(Label *); + Label *decorateData(Label *); + + public: + CallLogDetailsWindow(app::Application *app); + virtual ~CallLogDetailsWindow(); + + // virtual methods + bool onInput(const InputEvent &inputEvent) override; + void onBeforeShow(ShowMode mode, SwitchData *data) override; + + void rebuild() override; + void buildInterface() override; + void destroyInterface() override; }; - Label* informationLabel = nullptr; - Label* number = nullptr; - gui::Rect* rects[static_cast(FocusRects::NumOfRects)] = {nullptr}; - Image* callImg = nullptr; - Image* smsImg = nullptr; - gui::Image* callTypeImg[static_cast(calllog::CallLogCallType::NUM_OF_CALL_TYPES)] = {nullptr,nullptr,nullptr}; - Label* typeLabel = nullptr; - Label* durationLabel = nullptr; - Label* typeData = nullptr; - Label* durationData = nullptr; - Label* dateLabel = nullptr; - Label* dateDay = nullptr; - Label* dateDate = nullptr; - - CalllogRecord record; - - Label *decorateLabel(Label *); - Label *decorateData(Label *); - - public: - CallLogDetailsWindow( app::Application* app ); - virtual ~CallLogDetailsWindow(); - - //virtual methods - bool onInput( const InputEvent& inputEvent ) override; - void onBeforeShow( ShowMode mode, SwitchData* data ) override; - - void rebuild() override; - void buildInterface() override; - void destroyInterface() override; -}; - } /* namespace gui */ - diff --git a/module-apps/application-calllog/windows/CallLogMainWindow.cpp b/module-apps/application-calllog/windows/CallLogMainWindow.cpp index ec3d3ef72..b6b407cca 100644 --- a/module-apps/application-calllog/windows/CallLogMainWindow.cpp +++ b/module-apps/application-calllog/windows/CallLogMainWindow.cpp @@ -29,84 +29,97 @@ using namespace style; using namespace callLogStyle; -namespace gui { +namespace gui +{ -CallLogMainWindow::CallLogMainWindow( app::Application* app ) : - AppWindow( app, calllog::settings::MainWindowStr ), calllogModel{ new CalllogModel( app ) } { + CallLogMainWindow::CallLogMainWindow(app::Application *app) + : AppWindow(app, calllog::settings::MainWindowStr), calllogModel{new CalllogModel(app)} + { - buildInterface(); -} + buildInterface(); + } -void CallLogMainWindow::rebuild() { - destroyInterface(); - buildInterface(); -} -void CallLogMainWindow::buildInterface() { - AppWindow::buildInterface(); + void CallLogMainWindow::rebuild() + { + destroyInterface(); + buildInterface(); + } + void CallLogMainWindow::buildInterface() + { + AppWindow::buildInterface(); - setTitle(utils::localize.get("app_calllog_title_main")); + setTitle(utils::localize.get("app_calllog_title_main")); - bottomBar->setText( BottomBar::Side::LEFT, utils::localize.get("common_call") ); - bottomBar->setText( BottomBar::Side::CENTER, utils::localize.get("common_open") ); - bottomBar->setText( BottomBar::Side::RIGHT, utils::localize.get("common_back") ); + bottomBar->setText(BottomBar::Side::LEFT, utils::localize.get("common_call")); + bottomBar->setText(BottomBar::Side::CENTER, utils::localize.get("common_open")); + bottomBar->setText(BottomBar::Side::RIGHT, utils::localize.get("common_back")); - topBar->setActive( TopBar::Elements::TIME, true ); + topBar->setActive(TopBar::Elements::TIME, true); - list = new gui::ListView(this, mainWindow::x, mainWindow::y, mainWindow::w, mainWindow::h); - list->setMaxElements(calllog::settings::pageSize); - list->setPageSize(calllog::settings::pageSize); - list->setProvider(calllogModel); + list = new gui::ListView(this, mainWindow::x, mainWindow::y, mainWindow::w, mainWindow::h); + list->setMaxElements(calllog::settings::pageSize); + list->setPageSize(calllog::settings::pageSize); + list->setProvider(calllogModel); - setFocusItem( list ); -} -void CallLogMainWindow::destroyInterface() { - AppWindow::destroyInterface(); + setFocusItem(list); + } + void CallLogMainWindow::destroyInterface() + { + AppWindow::destroyInterface(); - if( list ) { removeWidget(list); delete list; list= nullptr; }; + if (list) { + removeWidget(list); + delete list; + list = nullptr; + }; - children.clear(); - delete calllogModel; -} + children.clear(); + delete calllogModel; + } -CallLogMainWindow::~CallLogMainWindow() { - destroyInterface(); -} + CallLogMainWindow::~CallLogMainWindow() + { + destroyInterface(); + } -void CallLogMainWindow::onBeforeShow( ShowMode mode, SwitchData* data ) { - if( mode == ShowMode::GUI_SHOW_INIT ){ - calllogModel->clear(); - calllogModel->requestRecordsCount(); - list->clear(); - list->setElementsCount( calllogModel->getItemCount() ); - } -} - -bool CallLogMainWindow::onInput( const InputEvent& inputEvent ) { - //process only if key is released - if(( inputEvent.state != InputEvent::State::keyReleasedShort ) || ( inputEvent.state != InputEvent::State::keyReleasedLong )) { - if( inputEvent.keyCode == KeyCode::KEY_LF ) { - LOG_DEBUG("calling"); - auto it = dynamic_cast(list->getSelectedItem()); - if (it == nullptr) - { - LOG_ERROR("wrong item type"); - assert(0); - return false; - } - return app::call(application, app::CallOperation::ExecuteCall, it->getCall().number); + void CallLogMainWindow::onBeforeShow(ShowMode mode, SwitchData *data) + { + if (mode == ShowMode::GUI_SHOW_INIT) { + calllogModel->clear(); + calllogModel->requestRecordsCount(); + list->clear(); + list->setElementsCount(calllogModel->getItemCount()); } - } + } - return AppWindow::onInput( inputEvent ); -} + bool CallLogMainWindow::onInput(const InputEvent &inputEvent) + { + // process only if key is released + if ((inputEvent.state != InputEvent::State::keyReleasedShort) || + (inputEvent.state != InputEvent::State::keyReleasedLong)) { + if (inputEvent.keyCode == KeyCode::KEY_LF) { + LOG_DEBUG("calling"); + auto it = dynamic_cast(list->getSelectedItem()); + if (it == nullptr) { + LOG_ERROR("wrong item type"); + assert(0); + return false; + } + return app::call(application, app::CallOperation::ExecuteCall, it->getCall().number); + } + } -bool CallLogMainWindow::onDatabaseMessage( sys::Message* msgl ) { - DBCalllogResponseMessage* msg = reinterpret_cast( msgl ); - if( calllogModel->updateRecords( std::move(msg->records), msg->offset, msg->limit, msg->count ) ) { - return true; - } + return AppWindow::onInput(inputEvent); + } - return false; -} + bool CallLogMainWindow::onDatabaseMessage(sys::Message *msgl) + { + DBCalllogResponseMessage *msg = reinterpret_cast(msgl); + if (calllogModel->updateRecords(std::move(msg->records), msg->offset, msg->limit, msg->count)) { + return true; + } + + return false; + } } /* namespace gui */ diff --git a/module-apps/application-calllog/windows/CallLogMainWindow.hpp b/module-apps/application-calllog/windows/CallLogMainWindow.hpp index 4a74ef0a0..3a9dd5f6d 100644 --- a/module-apps/application-calllog/windows/CallLogMainWindow.hpp +++ b/module-apps/application-calllog/windows/CallLogMainWindow.hpp @@ -21,23 +21,26 @@ #include "../CalllogModel.hpp" -namespace gui { +namespace gui +{ -class CallLogMainWindow: public AppWindow { - CalllogModel* calllogModel = nullptr; - gui::ListView* list = nullptr; -public: - CallLogMainWindow( app::Application* app ); - virtual ~CallLogMainWindow(); + class CallLogMainWindow : public AppWindow + { + CalllogModel *calllogModel = nullptr; + gui::ListView *list = nullptr; - //virtual methods - bool onInput( const InputEvent& inputEvent ) override; - void onBeforeShow( ShowMode mode, SwitchData* data ) override; + public: + CallLogMainWindow(app::Application *app); + virtual ~CallLogMainWindow(); - void rebuild() override; - void buildInterface() override; - void destroyInterface() override; - bool onDatabaseMessage( sys::Message* msg ) override; -}; + // virtual methods + bool onInput(const InputEvent &inputEvent) override; + void onBeforeShow(ShowMode mode, SwitchData *data) override; + + void rebuild() override; + void buildInterface() override; + void destroyInterface() override; + bool onDatabaseMessage(sys::Message *msg) override; + }; } /* namespace gui */ diff --git a/module-apps/application-calllog/windows/CallLogOptionsWindow.cpp b/module-apps/application-calllog/windows/CallLogOptionsWindow.cpp index ce1373aa3..03cd59e20 100644 --- a/module-apps/application-calllog/windows/CallLogOptionsWindow.cpp +++ b/module-apps/application-calllog/windows/CallLogOptionsWindow.cpp @@ -11,13 +11,11 @@ std::list calllogWindowOptions(app::ApplicationCallLog *app, const std::list options; - if (searchResults.get()->empty() || searchResults->front().contactType == ContactType::TEMPORARY) - { + if (searchResults.get()->empty() || searchResults->front().contactType == ContactType::TEMPORARY) { // add option - add contact options.push_back(gui::options::contact(app, app::ContactOperation::Add, searchResults->front())); } - else - { + else { // add option - contact details options.push_back(gui::options::contact(app, app::ContactOperation::Details, searchResults->front())); } diff --git a/module-apps/application-clock/ApplicationClock.cpp b/module-apps/application-clock/ApplicationClock.cpp index 6fc950f67..4fb1a3957 100644 --- a/module-apps/application-clock/ApplicationClock.cpp +++ b/module-apps/application-clock/ApplicationClock.cpp @@ -7,89 +7,97 @@ * @details */ -//module-gui +// module-gui #include "gui/widgets/Window.hpp" -//module-utils +// module-utils #include "log/log.hpp" -//module-services +// module-services #include "service-evtmgr/EventManager.hpp" #include "service-evtmgr/messages/EVMessages.hpp" #include "service-appmgr/ApplicationManager.hpp" -//MessageType +// MessageType #include "MessageType.hpp" -//this module +// this module #include "windows/ClockMainWindow.hpp" #include "ApplicationClock.hpp" -namespace app { - -ApplicationClock::ApplicationClock(std::string name,std::string parent,uint32_t stackDepth,sys::ServicePriority priority) : - Application( name, parent,false, stackDepth, priority ), - timerClock(CreateAppTimer(1000, true, [=]() {timerClockCallback(); })) +namespace app { - timerClock.restart(); -} -ApplicationClock::~ApplicationClock() { - // TODO Auto-generated destructor stub -} + ApplicationClock::ApplicationClock(std::string name, + std::string parent, + uint32_t stackDepth, + sys::ServicePriority priority) + : Application(name, parent, false, stackDepth, priority), + timerClock(CreateAppTimer(1000, true, [=]() { timerClockCallback(); })) + { + timerClock.restart(); + } -void ApplicationClock::timerClockCallback () { - auto it = windows.find("MainWindow"); - gui::ClockMainWindow *win = reinterpret_cast(it->second); - win->incrementSecond(); - win->updateLabels(); - render(gui::RefreshModes::GUI_REFRESH_FAST); -} + ApplicationClock::~ApplicationClock() + { + // TODO Auto-generated destructor stub + } -// Invoked upon receiving data message -sys::Message_t ApplicationClock::DataReceivedHandler(sys::DataMessage* msgl,sys::ResponseMessage* resp) { + void ApplicationClock::timerClockCallback() + { + auto it = windows.find("MainWindow"); + gui::ClockMainWindow *win = reinterpret_cast(it->second); + win->incrementSecond(); + win->updateLabels(); + render(gui::RefreshModes::GUI_REFRESH_FAST); + } - auto retMsg = Application::DataReceivedHandler(msgl); - //if message was handled by application's template there is no need to process further. - if( (reinterpret_cast( retMsg.get() )->retCode == - sys::ReturnCodes::Success ) ){ - return retMsg; - } + // Invoked upon receiving data message + sys::Message_t ApplicationClock::DataReceivedHandler(sys::DataMessage *msgl, sys::ResponseMessage *resp) + { - //this variable defines whether message was processed. - bool handled = false; - //if keyboard message received + auto retMsg = Application::DataReceivedHandler(msgl); + // if message was handled by application's template there is no need to process further. + if ((reinterpret_cast(retMsg.get())->retCode == sys::ReturnCodes::Success)) { + return retMsg; + } - if( handled ) - return std::make_shared(); - else - return std::make_shared(sys::ReturnCodes::Unresolved); -} + // this variable defines whether message was processed. + bool handled = false; + // if keyboard message received -// Invoked during initialization -sys::ReturnCodes ApplicationClock::InitHandler() { + if (handled) + return std::make_shared(); + else + return std::make_shared(sys::ReturnCodes::Unresolved); + } - auto ret = Application::InitHandler(); - if( ret != sys::ReturnCodes::Success ) - return ret; + // Invoked during initialization + sys::ReturnCodes ApplicationClock::InitHandler() + { - createUserInterface(); + auto ret = Application::InitHandler(); + if (ret != sys::ReturnCodes::Success) + return ret; - setActiveWindow("MainWindow"); + createUserInterface(); - return ret; -} + setActiveWindow("MainWindow"); -sys::ReturnCodes ApplicationClock::DeinitHandler() { - DeleteTimer(timerClock); - return sys::ReturnCodes::Success; -} + return ret; + } -void ApplicationClock::createUserInterface() { + sys::ReturnCodes ApplicationClock::DeinitHandler() + { + DeleteTimer(timerClock); + return sys::ReturnCodes::Success; + } - gui::ClockMainWindow* mainWindow = new gui::ClockMainWindow(this); - windows.insert(std::pair(mainWindow->getName(), mainWindow)); -} + void ApplicationClock::createUserInterface() + { + gui::ClockMainWindow *mainWindow = new gui::ClockMainWindow(this); + windows.insert(std::pair(mainWindow->getName(), mainWindow)); + } -void ApplicationClock::destroyUserInterface() { -} + void ApplicationClock::destroyUserInterface() + {} } /* namespace app */ diff --git a/module-apps/application-clock/ApplicationClock.hpp b/module-apps/application-clock/ApplicationClock.hpp index ae7a5e2fe..d9513e629 100644 --- a/module-apps/application-clock/ApplicationClock.hpp +++ b/module-apps/application-clock/ApplicationClock.hpp @@ -15,28 +15,36 @@ #include "gui/widgets/Image.hpp" #include "gui/widgets/Progress.hpp" +namespace app +{ -namespace app { + /* + * + */ + class ApplicationClock : public Application + { + AppTimer timerClock; + void timerClockCallback(); -/* - * - */ -class ApplicationClock: public Application { - AppTimer timerClock; - void timerClockCallback(); -public: - ApplicationClock(std::string name, std::string parent = "", uint32_t stackDepth=4096,sys::ServicePriority priority=sys::ServicePriority::Idle); - virtual ~ApplicationClock(); + public: + ApplicationClock(std::string name, + std::string parent = "", + uint32_t stackDepth = 4096, + sys::ServicePriority priority = sys::ServicePriority::Idle); + virtual ~ApplicationClock(); - sys::Message_t DataReceivedHandler(sys::DataMessage* msgl,sys::ResponseMessage* resp) override; - sys::ReturnCodes InitHandler() override; - sys::ReturnCodes DeinitHandler() override; + sys::Message_t DataReceivedHandler(sys::DataMessage *msgl, sys::ResponseMessage *resp) override; + sys::ReturnCodes InitHandler() override; + sys::ReturnCodes DeinitHandler() override; - sys::ReturnCodes SwitchPowerModeHandler(const sys::ServicePowerMode mode) override final{return sys::ReturnCodes::Success;} + sys::ReturnCodes SwitchPowerModeHandler(const sys::ServicePowerMode mode) override final + { + return sys::ReturnCodes::Success; + } - void createUserInterface() override; - void destroyUserInterface() override; -}; + void createUserInterface() override; + void destroyUserInterface() override; + }; } /* namespace app */ diff --git a/module-apps/application-clock/ClockData.hpp b/module-apps/application-clock/ClockData.hpp index db23f30de..df6b39cf3 100644 --- a/module-apps/application-clock/ClockData.hpp +++ b/module-apps/application-clock/ClockData.hpp @@ -12,14 +12,13 @@ #include #include "SwitchData.hpp" -class ClockData : public gui::SwitchData { -public: - uint32_t hour; - uint32_t minute; - ClockData ( uint32_t hour = 0, uint32_t minute = 0) : hour{hour}, minute{minute} {}; - virtual ~ClockData () {}; +class ClockData : public gui::SwitchData +{ + public: + uint32_t hour; + uint32_t minute; + ClockData(uint32_t hour = 0, uint32_t minute = 0) : hour{hour}, minute{minute} {}; + virtual ~ClockData(){}; }; - - #endif /* MODULE_APPS_APPLICATION_CLOCK_CLOCKDATA_HPP_ */ diff --git a/module-apps/application-clock/windows/ClockMainWindow.cpp b/module-apps/application-clock/windows/ClockMainWindow.cpp index 4c38a6a73..0fb5b4ce2 100644 --- a/module-apps/application-clock/windows/ClockMainWindow.cpp +++ b/module-apps/application-clock/windows/ClockMainWindow.cpp @@ -7,7 +7,7 @@ * @details */ -//module-gui +// module-gui #include "application-clock/windows/ClockMainWindow.hpp" #include "gui/widgets/Window.hpp" #include "gui/widgets/Item.hpp" @@ -19,97 +19,105 @@ #include "../ClockData.hpp" #include +namespace gui +{ -namespace gui { - -ClockMainWindow::ClockMainWindow( app::Application* app ) : gui::AppWindow( app, "MainWindow") { - uint32_t xOffset = 0; - uint32_t yOffset = 0; - - hourLabel = new gui::Label(this, 100+xOffset,300-160+yOffset,280,150); - hourLabel->setFilled( false ); - hourLabel->setBorderColor( gui::ColorNoColor ); - hourLabel->setFont(style::window::font::verybig); - hourLabel->setText("00"); - hourLabel->setAlignement( gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_CENTER, gui::Alignment::ALIGN_VERTICAL_CENTER)); - - minuteLabel = new gui::Label(this, 100+xOffset,310+yOffset,280,150); - minuteLabel->setFilled( false ); - minuteLabel->setBorderColor( gui::ColorFullBlack ); - minuteLabel->setFont(style::window::font::verybig); - minuteLabel->setText("00"); - minuteLabel->setRadius( 20 ); - minuteLabel->setPenWidth(1); - minuteLabel->setFillColor( gui::Color(10,0)); - minuteLabel->setAlignement( gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_CENTER, gui::Alignment::ALIGN_VERTICAL_CENTER)); - - uint32_t x= 480/2-90+xOffset, y= 300-6+yOffset, w = 180, h =12; - progressBar = new Progress(this, x, y, w, h ); - progressBar->setTotalProgress(59); - progressBar->setCurrentProgress(0); -} - -ClockMainWindow::~ClockMainWindow() { - // TODO Auto-generated destructor stub -} - -bool ClockMainWindow::handleSwitchData( SwitchData* data ) { - ClockData* clockData = reinterpret_cast( data ); - - if (clockData) + ClockMainWindow::ClockMainWindow(app::Application *app) : gui::AppWindow(app, "MainWindow") { - hour = clockData->hour % 24; - minute = clockData->minute % 60; + uint32_t xOffset = 0; + uint32_t yOffset = 0; + + hourLabel = new gui::Label(this, 100 + xOffset, 300 - 160 + yOffset, 280, 150); + hourLabel->setFilled(false); + hourLabel->setBorderColor(gui::ColorNoColor); + hourLabel->setFont(style::window::font::verybig); + hourLabel->setText("00"); + hourLabel->setAlignement( + gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_CENTER, gui::Alignment::ALIGN_VERTICAL_CENTER)); + + minuteLabel = new gui::Label(this, 100 + xOffset, 310 + yOffset, 280, 150); + minuteLabel->setFilled(false); + minuteLabel->setBorderColor(gui::ColorFullBlack); + minuteLabel->setFont(style::window::font::verybig); + minuteLabel->setText("00"); + minuteLabel->setRadius(20); + minuteLabel->setPenWidth(1); + minuteLabel->setFillColor(gui::Color(10, 0)); + minuteLabel->setAlignement( + gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_CENTER, gui::Alignment::ALIGN_VERTICAL_CENTER)); + + uint32_t x = 480 / 2 - 90 + xOffset, y = 300 - 6 + yOffset, w = 180, h = 12; + progressBar = new Progress(this, x, y, w, h); + progressBar->setTotalProgress(59); + progressBar->setCurrentProgress(0); } - return true; -} + ClockMainWindow::~ClockMainWindow() + { + // TODO Auto-generated destructor stub + } -void ClockMainWindow::updateLabels() { - std::string h; - if( hour<10 ) { - h += "0"; - } - h += std::to_string(hour); - hourLabel->setText( h ); + bool ClockMainWindow::handleSwitchData(SwitchData *data) + { + ClockData *clockData = reinterpret_cast(data); - std::string m; - if( minute < 10 ) { - m+= "0"; - } - m += std::to_string(minute); - minuteLabel->setText( m ); -} + if (clockData) { + hour = clockData->hour % 24; + minute = clockData->minute % 60; + } -bool ClockMainWindow::incrementHour() { - hour++; - if( hour > 23 ) { - hour = 0; - return true; - } - return false; -} -bool ClockMainWindow::incrementMinute() { - minute++; - if( minute > 59 ) { - incrementHour(); - minute = 0; - return true; - } - return false; -} + return true; + } -bool ClockMainWindow::incrementSecond(){ - bool ret = false; - seconds++; - if( seconds > 59 ) { - incrementMinute(); - seconds = 0; - ret = true; - } - progressBar->setCurrentProgress(seconds); + void ClockMainWindow::updateLabels() + { + std::string h; + if (hour < 10) { + h += "0"; + } + h += std::to_string(hour); + hourLabel->setText(h); - return ret; -} + std::string m; + if (minute < 10) { + m += "0"; + } + m += std::to_string(minute); + minuteLabel->setText(m); + } + + bool ClockMainWindow::incrementHour() + { + hour++; + if (hour > 23) { + hour = 0; + return true; + } + return false; + } + bool ClockMainWindow::incrementMinute() + { + minute++; + if (minute > 59) { + incrementHour(); + minute = 0; + return true; + } + return false; + } + + bool ClockMainWindow::incrementSecond() + { + bool ret = false; + seconds++; + if (seconds > 59) { + incrementMinute(); + seconds = 0; + ret = true; + } + progressBar->setCurrentProgress(seconds); + + return ret; + } } /* namespace gui */ diff --git a/module-apps/application-clock/windows/ClockMainWindow.hpp b/module-apps/application-clock/windows/ClockMainWindow.hpp index 3a803bd9b..6089ffb3d 100644 --- a/module-apps/application-clock/windows/ClockMainWindow.hpp +++ b/module-apps/application-clock/windows/ClockMainWindow.hpp @@ -9,7 +9,7 @@ #ifndef MODULE_APPS_APPLICATION_CLOCK_WINDOWS_CLOCKMAINWINDOW_HPP_ #define MODULE_APPS_APPLICATION_CLOCK_WINDOWS_CLOCKMAINWINDOW_HPP_ -//module-gui +// module-gui #include "AppWindow.hpp" #include "gui/widgets/Item.hpp" #include "gui/widgets/Image.hpp" @@ -18,49 +18,63 @@ #include "gui/widgets/BoxLayout.hpp" #include "gui/widgets/Progress.hpp" +namespace gui +{ -namespace gui { + /* + * + */ + class ClockMainWindow : public AppWindow + { + uint32_t seconds = 0; + uint32_t hour = 0; + uint32_t minute = 0; + Label *hourLabel = nullptr; + Label *minuteLabel = nullptr; + Progress *progressBar = nullptr; -/* - * - */ -class ClockMainWindow: public AppWindow { - uint32_t seconds = 0; - uint32_t hour = 0; - uint32_t minute = 0; - Label* hourLabel = nullptr; - Label* minuteLabel = nullptr; - Progress* progressBar = nullptr; -public: - ClockMainWindow( app::Application* app ); - virtual ~ClockMainWindow(); + public: + ClockMainWindow(app::Application *app); + virtual ~ClockMainWindow(); - bool handleSwitchData( SwitchData* data ) override; + bool handleSwitchData(SwitchData *data) override; - void setHour( uint32_t h ) {hour = h % 24; }; - void setMinute( uint32_t m ) {minute = m % 60; }; + void setHour(uint32_t h) + { + hour = h % 24; + }; + void setMinute(uint32_t m) + { + minute = m % 60; + }; - /** - * @brief Increments hours counter - */ - bool incrementHour(); - /** - * @brief Increments minutes counter - */ - bool incrementMinute(); - /** - * @brief Increments seconds counter - */ - bool incrementSecond(); - /** - * @brief Updates strings for hour and minutes - */ - void updateLabels(); + /** + * @brief Increments hours counter + */ + bool incrementHour(); + /** + * @brief Increments minutes counter + */ + bool incrementMinute(); + /** + * @brief Increments seconds counter + */ + bool incrementSecond(); + /** + * @brief Updates strings for hour and minutes + */ + void updateLabels(); - void rebuild() {}; - void buildInterface() { AppWindow::buildInterface(); }; - void destroyInterface() { AppWindow::destroyInterface();}; -}; + void rebuild(){}; + void buildInterface() + { + AppWindow::buildInterface(); + }; + void destroyInterface() + { + AppWindow::destroyInterface(); + }; + }; } /* namespace gui */ diff --git a/module-apps/application-desktop/ApplicationDesktop.cpp b/module-apps/application-desktop/ApplicationDesktop.cpp index 5bb5296ff..047c930df 100644 --- a/module-apps/application-desktop/ApplicationDesktop.cpp +++ b/module-apps/application-desktop/ApplicationDesktop.cpp @@ -7,8 +7,6 @@ * @details */ - - #include "Application.hpp" #include "MessageType.hpp" @@ -23,141 +21,143 @@ #include #include -namespace app { +namespace app +{ - ApplicationDesktop::ApplicationDesktop(std::string name, std::string parent, bool startBackground) : Application(name, parent) + ApplicationDesktop::ApplicationDesktop(std::string name, std::string parent, bool startBackground) + : Application(name, parent) { busChannels.push_back(sys::BusChannels::ServiceDBNotifications); } -ApplicationDesktop::~ApplicationDesktop() { - LOG_INFO("Desktop destruktor"); -} - -// Invoked upon receiving data message -sys::Message_t ApplicationDesktop::DataReceivedHandler(sys::DataMessage* msgl,sys::ResponseMessage* resp) { - - auto retMsg = Application::DataReceivedHandler(msgl); - //if message was handled by application's template there is no need to process further. - if( (reinterpret_cast( retMsg.get() )->retCode == - sys::ReturnCodes::Success ) ){ - return retMsg; - } - - bool handled = false; - if (auto msg = dynamic_cast(msgl)) + ApplicationDesktop::~ApplicationDesktop() { - handled = handle(msg); - } - else if (auto msg = dynamic_cast(msgl)) - { - handled = handle(msg); + LOG_INFO("Desktop destruktor"); } - if (handled) + // Invoked upon receiving data message + sys::Message_t ApplicationDesktop::DataReceivedHandler(sys::DataMessage *msgl, sys::ResponseMessage *resp) { - return std::make_shared(); - } - else - { - return std::make_shared(sys::ReturnCodes::Unresolved); - } -} -auto ApplicationDesktop::handle(DBNotificationMessage *msg) -> bool -{ - LOG_DEBUG("Received multicast"); - assert(msg); - if ((msg->notificationType == DB::NotificationType::Updated) || (msg->notificationType == DB::NotificationType::Added)) + auto retMsg = Application::DataReceivedHandler(msgl); + // if message was handled by application's template there is no need to process further. + if ((reinterpret_cast(retMsg.get())->retCode == sys::ReturnCodes::Success)) { + return retMsg; + } + + bool handled = false; + if (auto msg = dynamic_cast(msgl)) { + handled = handle(msg); + } + else if (auto msg = dynamic_cast(msgl)) { + handled = handle(msg); + } + + if (handled) { + return std::make_shared(); + } + else { + return std::make_shared(sys::ReturnCodes::Unresolved); + } + } + + auto ApplicationDesktop::handle(DBNotificationMessage *msg) -> bool { + LOG_DEBUG("Received multicast"); + assert(msg); + if ((msg->notificationType == DB::NotificationType::Updated) || + (msg->notificationType == DB::NotificationType::Added)) { + notifications.notSeenCalls = DBServiceAPI::CalllogGetCount(this, EntryState::UNREAD); + notifications.notSeenSMS = DBServiceAPI::SMSGetCount(this, EntryState::UNREAD); + this->windows[app::name::window::desktop_menu]->rebuild(); + this->windows[app::name::window::desktop_lockscreen]->rebuild(); + return true; + } + return false; + } + + auto ApplicationDesktop::handle(CellularNotificationMessage *msg) -> bool + { + assert(msg); + if (msg->type == CellularNotificationMessage::Type::ModemOn && + Store::GSM::get()->sim != Store::GSM::SIM::SIM1 && Store::GSM::get()->sim != Store::GSM::SIM::SIM1) { + if (screenLocked) { + need_sim_select = true; + } + else { + need_sim_select = false; + sapm::ApplicationManager::messageSwitchApplication(this, app::name_settings, app::sim_select, nullptr); + } + return true; + } + return false; + } + + // Invoked during initialization + sys::ReturnCodes ApplicationDesktop::InitHandler() + { + + auto ret = Application::InitHandler(); + if (ret != sys::ReturnCodes::Success) + return ret; + + // if value of the pin hash is different than 0 it means that home screen is pin protected + if (settings.lockPassHash) { + pinLocked = true; + } + + screenLocked = true; + notifications.notSeenCalls = DBServiceAPI::CalllogGetCount(this, EntryState::UNREAD); - notifications.notSeenSMS = DBServiceAPI::SMSGetCount(this, EntryState::UNREAD); - this->windows[app::name::window::desktop_menu]->rebuild(); - this->windows[app::name::window::desktop_lockscreen]->rebuild(); - return true; - } - return false; -} + notifications.notSeenSMS = DBServiceAPI::SMSGetCount(this, EntryState::UNREAD); -auto ApplicationDesktop::handle(CellularNotificationMessage *msg) -> bool -{ - assert(msg); - if (msg->type == CellularNotificationMessage::Type::ModemOn && Store::GSM::get()->sim != Store::GSM::SIM::SIM1 && - Store::GSM::get()->sim != Store::GSM::SIM::SIM1) + createUserInterface(); + + setActiveWindow(gui::name::window::main_window); + + return ret; + } + + sys::ReturnCodes ApplicationDesktop::DeinitHandler() { - if (screenLocked) - { - need_sim_select = true; - } - else - { - need_sim_select = false; - sapm::ApplicationManager::messageSwitchApplication(this, app::name_settings, app::sim_select, nullptr); - } - return true; + LOG_INFO("DeinitHandler"); + return sys::ReturnCodes::Success; } - return false; -} -// Invoked during initialization -sys::ReturnCodes ApplicationDesktop::InitHandler() { + void ApplicationDesktop::createUserInterface() + { - auto ret = Application::InitHandler(); - if( ret != sys::ReturnCodes::Success ) - return ret; + gui::AppWindow *window = nullptr; - //if value of the pin hash is different than 0 it means that home screen is pin protected - if( settings.lockPassHash ) { - pinLocked = true; - } + window = new gui::DesktopMainWindow(this); + windows.insert(std::pair(window->getName(), window)); - screenLocked = true; + window = new gui::PinLockWindow(this); + windows.insert(std::pair(window->getName(), window)); - notifications.notSeenCalls = DBServiceAPI::CalllogGetCount(this, EntryState::UNREAD); - notifications.notSeenSMS = DBServiceAPI::SMSGetCount(this, EntryState::UNREAD); + window = new gui::MenuWindow(this); + windows.insert(std::pair(window->getName(), window)); - createUserInterface(); + window = new gui::PowerOffWindow(this); + windows.insert(std::pair(window->getName(), window)); + } - setActiveWindow(gui::name::window::main_window); + bool ApplicationDesktop::getScreenLocked() + { + return screenLocked; + } - return ret; -} + bool ApplicationDesktop::getPinLocked() + { + return pinLocked; + } -sys::ReturnCodes ApplicationDesktop::DeinitHandler() { - LOG_INFO("DeinitHandler"); - return sys::ReturnCodes::Success; -} + void ApplicationDesktop::setScreenLocked(bool val) + { + screenLocked = val; + }; -void ApplicationDesktop::createUserInterface() { + void ApplicationDesktop::destroyUserInterface() + {} - gui::AppWindow* window = nullptr; - - window = new gui::DesktopMainWindow(this); - windows.insert(std::pair(window->getName(), window)); - - window = new gui::PinLockWindow(this); - windows.insert(std::pair( window->getName(), window)); - - window = new gui::MenuWindow(this); - windows.insert(std::pair( window->getName(), window)); - - window = new gui::PowerOffWindow(this); - windows.insert(std::pair( window->getName(), window)); -} - -bool ApplicationDesktop::getScreenLocked() { - return screenLocked; -} - -bool ApplicationDesktop::getPinLocked() { - return pinLocked; -} - -void ApplicationDesktop::setScreenLocked( bool val ) { - screenLocked = val; -}; - -void ApplicationDesktop::destroyUserInterface() { -} - -} /* namespace gui */ +} // namespace app diff --git a/module-apps/application-desktop/ApplicationDesktop.hpp b/module-apps/application-desktop/ApplicationDesktop.hpp index 416b4450c..f11b18b8c 100644 --- a/module-apps/application-desktop/ApplicationDesktop.hpp +++ b/module-apps/application-desktop/ApplicationDesktop.hpp @@ -14,49 +14,57 @@ #include "service-cellular/messages/CellularMessage.hpp" #include "service-db/messages/DBNotificationMessage.hpp" -namespace app { +namespace app +{ namespace name::window { - inline const std::string desktop_menu = "MenuWindow"; + inline const std::string desktop_menu = "MenuWindow"; inline const std::string desktop_lockscreen = gui::name::window::main_window; }; // namespace name::window -inline const std::string name_desktop = "ApplicationDesktop"; + inline const std::string name_desktop = "ApplicationDesktop"; -class ApplicationDesktop : public Application { -protected: - //determines whether screen should be protected by pin verification - bool screenLocked = true; - bool pinLocked = false; -public: - bool need_sim_select = false; - struct Notifications - { - unsigned int notSeenSMS = 0; - unsigned int notSeenCalls = 0; - } notifications; - ApplicationDesktop( std::string name=name_desktop, std::string parent = "", bool startBackground =false ); - virtual ~ApplicationDesktop(); - sys::Message_t DataReceivedHandler(sys::DataMessage* msgl,sys::ResponseMessage* resp) override; - sys::ReturnCodes InitHandler() override; - sys::ReturnCodes DeinitHandler() override; + class ApplicationDesktop : public Application + { + protected: + // determines whether screen should be protected by pin verification + bool screenLocked = true; + bool pinLocked = false; - sys::ReturnCodes SwitchPowerModeHandler(const sys::ServicePowerMode mode) override final{return sys::ReturnCodes::Success;} + public: + bool need_sim_select = false; + struct Notifications + { + unsigned int notSeenSMS = 0; + unsigned int notSeenCalls = 0; + } notifications; + ApplicationDesktop(std::string name = name_desktop, std::string parent = "", bool startBackground = false); + virtual ~ApplicationDesktop(); + sys::Message_t DataReceivedHandler(sys::DataMessage *msgl, sys::ResponseMessage *resp) override; + sys::ReturnCodes InitHandler() override; + sys::ReturnCodes DeinitHandler() override; - void createUserInterface() override; - void destroyUserInterface() override; - bool getScreenLocked(); - void setScreenLocked( bool val ); - bool getPinLocked(); - // if there is modem notification and there is no default SIM selected, then we need to select if when unlock is done - bool handle(DBNotificationMessage *msg); - bool handle(CellularNotificationMessage *); - /** - * This static method will be used to lock the phone - */ -// static bool messageLockPhone( sys::Service* sender, std::string application , const gui::InputEvent& event ); -}; + sys::ReturnCodes SwitchPowerModeHandler(const sys::ServicePowerMode mode) override final + { + return sys::ReturnCodes::Success; + } + + void createUserInterface() override; + void destroyUserInterface() override; + bool getScreenLocked(); + void setScreenLocked(bool val); + bool getPinLocked(); + // if there is modem notification and there is no default SIM selected, then we need to select if when unlock is + // done + bool handle(DBNotificationMessage *msg); + bool handle(CellularNotificationMessage *); + /** + * This static method will be used to lock the phone + */ + // static bool messageLockPhone( sys::Service* sender, std::string application , const gui::InputEvent& event + //); + }; } /* namespace app */ diff --git a/module-apps/application-desktop/data/LockPhoneData.hpp b/module-apps/application-desktop/data/LockPhoneData.hpp index bc0a36d6f..c6a665550 100644 --- a/module-apps/application-desktop/data/LockPhoneData.hpp +++ b/module-apps/application-desktop/data/LockPhoneData.hpp @@ -11,22 +11,31 @@ #include "gui/SwitchData.hpp" +namespace gui +{ -namespace gui { + // class template that stores information that was sent along with switch message + class LockPhoneData : public gui::SwitchData + { + std::string previousApplication; -//class template that stores information that was sent along with switch message -class LockPhoneData : public gui::SwitchData{ - std::string previousApplication; -public: - LockPhoneData() : SwitchData() { description = "LockPhoneData"; }; - virtual ~LockPhoneData() {}; + public: + LockPhoneData() : SwitchData() + { + description = "LockPhoneData"; + }; + virtual ~LockPhoneData(){}; - void setPrevApplication( const std::string& prevApp ) { previousApplication = prevApp; }; - const std::string& getPreviousApplication() { return previousApplication; }; -}; - - -} //namespace gui + void setPrevApplication(const std::string &prevApp) + { + previousApplication = prevApp; + }; + const std::string &getPreviousApplication() + { + return previousApplication; + }; + }; +} // namespace gui #endif /* MODULE_APPS_APPLICATION_DESKTOP_DATA_LOCKPHONEDATA_HPP_ */ diff --git a/module-apps/application-desktop/windows/Common.hpp b/module-apps/application-desktop/windows/Common.hpp index 9925995f5..e0c0017b1 100644 --- a/module-apps/application-desktop/windows/Common.hpp +++ b/module-apps/application-desktop/windows/Common.hpp @@ -6,8 +6,7 @@ inline void center(gui::Item *parent, gui::Item *child, gui::Axis axis) if (!parent || !child) return; auto center = (parent->area().size(axis) - child->area().size(axis)) / 2; - if (center > 0) - { + if (center > 0) { child->area().pos(axis) += center; } } @@ -17,8 +16,7 @@ inline void bottom(gui::Item *parent, gui::Item *child, gui::Axis axis) if (!parent || !child) return; auto bottom = (parent->area().size(axis) - child->area().size(axis)); - if (bottom > 0) - { + if (bottom > 0) { child->area().pos(axis) += bottom; } } diff --git a/module-apps/application-desktop/windows/DesktopMainWindow.cpp b/module-apps/application-desktop/windows/DesktopMainWindow.cpp index 4fe9d1195..e530748f5 100644 --- a/module-apps/application-desktop/windows/DesktopMainWindow.cpp +++ b/module-apps/application-desktop/windows/DesktopMainWindow.cpp @@ -34,16 +34,17 @@ namespace style { - const auto design_time_offset = 106; - const auto design_time_h = 96; - const auto design_day_offset = 204; - const auto design_day_h = 51; - const auto design_border_offset = 20; - const auto design_option_span = 8; + const auto design_time_offset = 106; + const auto design_time_h = 96; + const auto design_day_offset = 204; + const auto design_day_h = 51; + const auto design_border_offset = 20; + const auto design_option_span = 8; const auto design_notifications_offset = 284; }; // namespace style -namespace gui { +namespace gui +{ void DesktopMainWindow::buildInterface() { @@ -52,7 +53,8 @@ namespace gui { AppWindow::buildInterface(); bottomBar->setActive(BottomBar::Side::CENTER, true); - topBar->setActive({{TopBar::Elements::SIGNAL, true}, {TopBar::Elements::LOCK, true}, {TopBar::Elements::BATTERY, true}}); + topBar->setActive( + {{TopBar::Elements::SIGNAL, true}, {TopBar::Elements::LOCK, true}, {TopBar::Elements::BATTERY, true}}); time = new gui::Label(this, 0, style::design_time_offset, style::window_width, style::design_time_h); time->setFilled(false); @@ -69,291 +71,303 @@ namespace gui { dayText->setAlignement(Alignment::ALIGN_HORIZONTAL_CENTER); setVisibleState(); -} - -void DesktopMainWindow::destroyInterface() { - AppWindow::destroyInterface(); - delete time; - delete dayText; - focusItem = nullptr; - children.clear(); -} - -DesktopMainWindow::DesktopMainWindow(app::Application *app) : AppWindow(app, gui::name::window::main_window) -{ - buildInterface(); -} - -DesktopMainWindow::~DesktopMainWindow() { - destroyInterface(); -} - -void DesktopMainWindow::setVisibleState() { - - auto app = dynamic_cast(application); - if (!app) - { - return; } - if( app->getScreenLocked() ) { - bottomBar->setText( BottomBar::Side::CENTER, utils::localize.get("app_desktop_unlock")); - topBar->setActive( TopBar::Elements::LOCK, true ); - } - else + void DesktopMainWindow::destroyInterface() { - auto app = dynamic_cast(application); - assert(app); - bottomBar->setText(BottomBar::Side::CENTER, utils::localize.get("app_desktop_menu")); - topBar->setActive(TopBar::Elements::LOCK, false); - if (!fillNotifications(app)) - { - LOG_ERROR("Couldn't fit in all notifications"); - } - if (app->need_sim_select && Store::GSM::get()->sim == Store::GSM::SIM::SIM_UNKNOWN) - { - sapm::ApplicationManager::messageSwitchApplication(this->application, app::name_settings, app::sim_select, nullptr); - } + AppWindow::destroyInterface(); + delete time; + delete dayText; + focusItem = nullptr; + children.clear(); } -} -void DesktopMainWindow::onBeforeShow( ShowMode mode, SwitchData* data ) { + DesktopMainWindow::DesktopMainWindow(app::Application *app) : AppWindow(app, gui::name::window::main_window) + { + buildInterface(); + } - //update time - time->setText( topBar->getTimeString() ); + DesktopMainWindow::~DesktopMainWindow() + { + destroyInterface(); + } + + void DesktopMainWindow::setVisibleState() + { - //check if there was a signal to lock the pone due to inactivity. - if( (data != nullptr) && (data->getDescription() == "LockPhoneData")) { auto app = dynamic_cast(application); - if (!app) - { + if (!app) { return; } - app->setScreenLocked(true); - LockPhoneData* lockData = reinterpret_cast( data ); - lockTimeoutApplilcation = lockData->getPreviousApplication(); + if (app->getScreenLocked()) { + bottomBar->setText(BottomBar::Side::CENTER, utils::localize.get("app_desktop_unlock")); + topBar->setActive(TopBar::Elements::LOCK, true); + } + else { + auto app = dynamic_cast(application); + assert(app); + bottomBar->setText(BottomBar::Side::CENTER, utils::localize.get("app_desktop_menu")); + topBar->setActive(TopBar::Elements::LOCK, false); + if (!fillNotifications(app)) { + LOG_ERROR("Couldn't fit in all notifications"); + } + if (app->need_sim_select && Store::GSM::get()->sim == Store::GSM::SIM::SIM_UNKNOWN) { + sapm::ApplicationManager::messageSwitchApplication( + this->application, app::name_settings, app::sim_select, nullptr); + } + } + } - reinterpret_cast(application)->setSuspendFlag(true); - } - - setVisibleState(); -} - -bool DesktopMainWindow::onInput( const InputEvent& inputEvent ) { - - // do nothing - if( inputEvent.state == InputEvent::State::keyReleasedShort && inputEvent.keyCode == KeyCode::KEY_RF ) return false; - - app::ApplicationDesktop *app = dynamic_cast(application); - if (app == nullptr) + void DesktopMainWindow::onBeforeShow(ShowMode mode, SwitchData *data) { - LOG_ERROR("not ApplicationDesktop"); + + // update time + time->setText(topBar->getTimeString()); + + // check if there was a signal to lock the pone due to inactivity. + if ((data != nullptr) && (data->getDescription() == "LockPhoneData")) { + auto app = dynamic_cast(application); + if (!app) { + return; + } + app->setScreenLocked(true); + + LockPhoneData *lockData = reinterpret_cast(data); + lockTimeoutApplilcation = lockData->getPreviousApplication(); + + reinterpret_cast(application)->setSuspendFlag(true); + } + + setVisibleState(); + } + + bool DesktopMainWindow::onInput(const InputEvent &inputEvent) + { + + // do nothing + if (inputEvent.state == InputEvent::State::keyReleasedShort && inputEvent.keyCode == KeyCode::KEY_RF) + return false; + + app::ApplicationDesktop *app = dynamic_cast(application); + if (app == nullptr) { + LOG_ERROR("not ApplicationDesktop"); + return AppWindow::onInput(inputEvent); + } + + auto code = translator.handle(inputEvent.key, InputMode({InputMode::phone}).get()); + + // process shortpress + if (inputEvent.state == InputEvent::State::keyReleasedShort) { + + if (app->getScreenLocked()) { + // if enter was pressed + if (inputEvent.keyCode == KeyCode::KEY_ENTER) { + unlockStartTime = xTaskGetTickCount(); + enterPressed = true; + } + else if ((inputEvent.keyCode == KeyCode::KEY_PND) && enterPressed) { + // if interval between enter and pnd keys is less than time defined for unlocking + if (xTaskGetTickCount() - unlockStartTime < unclockTime) { + // display pin lock screen or simply refresh current window to update labels + if (app->getPinLocked()) + // if there was no application on to before closing proceed normally to pin protection + // window. + if (lockTimeoutApplilcation.empty()) { + application->switchWindow("PinLockWindow"); + } + else { + std::unique_ptr data = std::make_unique(); + data->setPrevApplication(lockTimeoutApplilcation); + lockTimeoutApplilcation = ""; + application->switchWindow("PinLockWindow", std::move(data)); + } + + else { + + // if phone was locked by user show unlocked main window + if (lockTimeoutApplilcation.empty()) { + app->setScreenLocked(false); + setVisibleState(); + application->refreshWindow(RefreshModes::GUI_REFRESH_FAST); + } + // if there was application on top when timeout occurred + else { + lockTimeoutApplilcation = ""; + sapm::ApplicationManager::messageSwitchPreviousApplication(application); + } + } + } + enterPressed = false; + } + else { + enterPressed = false; + } + } + // screen is unlocked + else { + // pressing enter moves user to menu screen + if (inputEvent.keyCode == KeyCode::KEY_ENTER) { + application->switchWindow("MenuWindow"); + } + // if numeric key was pressed record that key and send it to call application + else if (code != 0) { + return app::call(application, app::CallOperation::PrepareCall, code); + } + } + } + else if (inputEvent.state == InputEvent::State::keyReleasedLong) { + // long press of # locks screen if it was unlocked + if ((inputEvent.keyCode == KeyCode::KEY_PND) && (app->getScreenLocked() == false)) { + app->setScreenLocked(true); + setVisibleState(); + app->refreshWindow(RefreshModes::GUI_REFRESH_FAST); + app->setSuspendFlag(true); + return true; + } + // long press of right function button move user to power off window + else if (inputEvent.keyCode == KeyCode::KEY_RF) { + application->switchWindow("PowerOffWindow"); + return true; + } + // long press of '0' key is translated to '+' + else if (inputEvent.keyCode == KeyCode::KEY_0) { + return app::call(application, app::CallOperation::PrepareCall, '+'); + } + } + + // check if any of the lower inheritance onInput methods catch the event return AppWindow::onInput(inputEvent); } - auto code = translator.handle(inputEvent.key, InputMode({InputMode::phone}).get()); + void DesktopMainWindow::rebuild() + { + destroyInterface(); + buildInterface(); + } - //process shortpress - if( inputEvent.state == InputEvent::State::keyReleasedShort ) { + bool DesktopMainWindow::updateTime(const UTF8 &timeStr) + { + auto ret = AppWindow::updateTime(timeStr); + time->setText(topBar->getTimeString()); + return ret; + } + bool DesktopMainWindow::updateTime(const uint32_t ×tamp, bool mode24H) + { + auto ret = AppWindow::updateTime(timestamp, mode24H); + time->setText(topBar->getTimeString()); + return ret; + } - if( app->getScreenLocked() ) { - //if enter was pressed - if( inputEvent.keyCode == KeyCode::KEY_ENTER ) { - unlockStartTime = xTaskGetTickCount(); - enterPressed = true; - } - else if(( inputEvent.keyCode == KeyCode::KEY_PND ) && enterPressed ) { - //if interval between enter and pnd keys is less than time defined for unlocking - if( xTaskGetTickCount() - unlockStartTime < unclockTime) { - //display pin lock screen or simply refresh current window to update labels - if( app->getPinLocked()) - //if there was no application on to before closing proceed normally to pin protection window. - if( lockTimeoutApplilcation.empty()) { - application->switchWindow( "PinLockWindow" ); - } - else { - std::unique_ptr data = std::make_unique(); - data->setPrevApplication( lockTimeoutApplilcation ); - lockTimeoutApplilcation = ""; - application->switchWindow( "PinLockWindow", std::move(data) ); - } + std::list DesktopMainWindow::buildDrawList() + { + time->setText(topBar->getTimeString()); + return gui::AppWindow::buildDrawList(); + } - else { + auto add_box_icon(gui::BoxLayout *layout, UTF8 icon) + { + auto thumbnail = new gui::Image(icon); + center(layout, thumbnail, Axis::Y); + thumbnail->activeItem = false; + layout->addWidget(thumbnail); + } - //if phone was locked by user show unlocked main window - if( lockTimeoutApplilcation.empty() ) { - app->setScreenLocked(false); - setVisibleState(); - application->refreshWindow(RefreshModes::GUI_REFRESH_FAST); - } - //if there was application on top when timeout occurred - else { - lockTimeoutApplilcation = ""; - sapm::ApplicationManager::messageSwitchPreviousApplication( application ); - } - } - } - enterPressed = false; - } - else { - enterPressed = false; - } - } - //screen is unlocked - else { - //pressing enter moves user to menu screen - if( inputEvent.keyCode == KeyCode::KEY_ENTER ) { - application->switchWindow( "MenuWindow" ); - } - // if numeric key was pressed record that key and send it to call application - else if (code != 0) - { - return app::call(application, app::CallOperation::PrepareCall, code); + /// for now notifications are like that: `^[icon][dumb text] [dot image] [number of + /// notifications]$` + auto add_notification(BoxLayout *layout, UTF8 icon, UTF8 name, UTF8 indicator, std::function callback) + -> bool + { + const auto text_normal_size = 200; + const auto size_needed_for_2digits = 30; + // 1. create hbox for all elements + auto el = new gui::HBox(nullptr, 0, 0, layout->getWidth(), style::window::label::default_h); + auto text = new gui::Label(nullptr, 0, 0, text_normal_size, style::window::label::default_h, ""); + text->area(Item::Area::Max) = text->area(Item::Area::Normal); // set area from 0 to normal + text->area(Item::Area::Max).size(Axis::X) = el->area().w; // set max area for text in axis to max + text->setText(name); + text->setFont(style::window::font::medium); + text->setAlignement(Alignment::ALIGN_VERTICAL_CENTER); + text->setPenWidth(style::window::default_border_no_focus_w); + text->activeItem = false; + + auto number = new gui::Label(); + number->setText(indicator); + number->setFont(style::window::font::mediumbold); + number->setPenWidth(style::window::default_border_no_focus_w); + number->setSize(size_needed_for_2digits, el->area().h); + number->setAlignement(Alignment::ALIGN_VERTICAL_CENTER | Alignment::ALIGN_HORIZONTAL_RIGHT); + number->activeItem = false; + // 2. Add all elements to hbox layout + new gui::Span(el, Axis::X, style::design_border_offset); + add_box_icon(el, icon); + new gui::Span(el, Axis::X, style::design_border_offset); + el->addWidget(text); + add_box_icon(el, "dot_12px_soft"); + el->addWidget(number); + // box right inner margin + new gui::Span(el, Axis::X, style::design_border_offset); + // 3. Set hbox layout properties + el->setPenWidth(style::window::default_border_no_focus_w); + el->setPenFocusWidth(style::window::default_border_focucs_w); + el->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_BOTTOM | RectangleEdgeFlags::GUI_RECT_EDGE_TOP); + el->inputCallback = [callback](Item &, const InputEvent &event) { + if (event.state == InputEvent::State::keyReleasedShort && event.keyCode == KeyCode::KEY_LF) { + return callback(); } - } - } - else if( inputEvent.state == InputEvent::State::keyReleasedLong ) { - //long press of # locks screen if it was unlocked - if( (inputEvent.keyCode == KeyCode::KEY_PND) && ( app->getScreenLocked() == false ) ) { - app->setScreenLocked(true); - setVisibleState(); - app->refreshWindow(RefreshModes::GUI_REFRESH_FAST); - app->setSuspendFlag(true); - return true; + return false; + }; + layout->addWidget(el); + if (el->visible) { + // space between next notifications to show + layout->addWidget(new gui::Span(Axis::Y, style::design_option_span)); } - //long press of right function button move user to power off window - else if (inputEvent.keyCode == KeyCode::KEY_RF) { - application->switchWindow( "PowerOffWindow" ); - return true; + return el->visible; + } + + auto DesktopMainWindow::fillNotifications(app::ApplicationDesktop *app) -> bool + { + if (notifications) { + this->removeWidget(notifications); + delete notifications; } - // long press of '0' key is translated to '+' - else if (inputEvent.keyCode == KeyCode::KEY_0) - { - return app::call(application, app::CallOperation::PrepareCall, '+'); + // 1. create notifications box + notifications = new gui::VBox(nullptr, + style::window::default_left_margin, + style::design_notifications_offset, + style::window_width - 2 * style::window::default_left_margin, + bottomBar->widgetArea.pos(Axis::Y) - style::design_notifications_offset); + notifications->setPenWidth(style::window::default_border_no_focus_w); + notifications->setPenFocusWidth(style::window::default_border_no_focus_w); + this->addWidget(notifications); + if (!notifications->visible) { + LOG_ERROR("Can't fit notifications box!"); + return false; } - } - //check if any of the lower inheritance onInput methods catch the event - return AppWindow::onInput( inputEvent ); -} - -void DesktopMainWindow::rebuild() { - destroyInterface(); - buildInterface(); -} - -bool DesktopMainWindow::updateTime( const UTF8& timeStr ) { - auto ret = AppWindow::updateTime( timeStr ); - time->setText( topBar->getTimeString()); - return ret; -} -bool DesktopMainWindow::updateTime( const uint32_t& timestamp, bool mode24H ) { - auto ret = AppWindow::updateTime( timestamp, mode24H ); - time->setText( topBar->getTimeString()); - return ret; -} - -std::list DesktopMainWindow::buildDrawList() { - time->setText( topBar->getTimeString()); - return gui::AppWindow::buildDrawList(); -} - -auto add_box_icon(gui::BoxLayout *layout, UTF8 icon) -{ - auto thumbnail = new gui::Image(icon); - center(layout, thumbnail, Axis::Y); - thumbnail->activeItem = false; - layout->addWidget(thumbnail); -} - -/// for now notifications are like that: `^[icon][dumb text] [dot image] [number of notifications]$` -auto add_notification(BoxLayout *layout, UTF8 icon, UTF8 name, UTF8 indicator, std::function callback) -> bool -{ - const auto text_normal_size = 200; - const auto size_needed_for_2digits = 30; - // 1. create hbox for all elements - auto el = new gui::HBox(nullptr, 0, 0, layout->getWidth(), style::window::label::default_h); - auto text = new gui::Label(nullptr, 0, 0, text_normal_size, style::window::label::default_h, ""); - text->area(Item::Area::Max) = text->area(Item::Area::Normal); // set area from 0 to normal - text->area(Item::Area::Max).size(Axis::X) = el->area().w; // set max area for text in axis to max - text->setText(name); - text->setFont(style::window::font::medium); - text->setAlignement(Alignment::ALIGN_VERTICAL_CENTER); - text->setPenWidth(style::window::default_border_no_focus_w); - text->activeItem = false; - - auto number = new gui::Label(); - number->setText(indicator); - number->setFont(style::window::font::mediumbold); - number->setPenWidth(style::window::default_border_no_focus_w); - number->setSize(size_needed_for_2digits, el->area().h); - number->setAlignement(Alignment::ALIGN_VERTICAL_CENTER | Alignment::ALIGN_HORIZONTAL_RIGHT); - number->activeItem = false; - // 2. Add all elements to hbox layout - new gui::Span(el, Axis::X, style::design_border_offset); - add_box_icon(el, icon); - new gui::Span(el, Axis::X, style::design_border_offset); - el->addWidget(text); - add_box_icon(el, "dot_12px_soft"); - el->addWidget(number); - // box right inner margin - new gui::Span(el, Axis::X, style::design_border_offset); - // 3. Set hbox layout properties - el->setPenWidth(style::window::default_border_no_focus_w); - el->setPenFocusWidth(style::window::default_border_focucs_w); - el->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_BOTTOM | RectangleEdgeFlags::GUI_RECT_EDGE_TOP); - el->inputCallback = [callback](Item &, const InputEvent &event) { - if (event.state == InputEvent::State::keyReleasedShort && event.keyCode == KeyCode::KEY_LF) - { - return callback(); + // 2. actually fill it in + if (app->notifications.notSeenCalls) { + add_notification(notifications, + "phone", + utils::localize.get("app_desktop_missed_calls"), + std::to_string(app->notifications.notSeenCalls), + [this]() { + return sapm::ApplicationManager::messageSwitchApplication( + application, app::CallLogAppStr, gui::name::window::main_window, nullptr); + }); } - return false; - }; - layout->addWidget(el); - if (el->visible) - { - // space between next notifications to show - layout->addWidget(new gui::Span(Axis::Y, style::design_option_span)); + if (app->notifications.notSeenSMS) { + add_notification(notifications, + "mail", + utils::localize.get("app_desktop_unread_messages"), + std::to_string(app->notifications.notSeenSMS), + [this]() { + return sapm::ApplicationManager::messageSwitchApplication( + application, app::name_messages, gui::name::window::main_window, nullptr); + }); + } + setFocusItem(notifications); + return true; } - return el->visible; -} - -auto DesktopMainWindow::fillNotifications(app::ApplicationDesktop *app) -> bool -{ - if (notifications) - { - this->removeWidget(notifications); - delete notifications; - } - // 1. create notifications box - notifications = - new gui::VBox(nullptr, style::window::default_left_margin, style::design_notifications_offset, - style::window_width - 2 * style::window::default_left_margin, bottomBar->widgetArea.pos(Axis::Y) - style::design_notifications_offset); - notifications->setPenWidth(style::window::default_border_no_focus_w); - notifications->setPenFocusWidth(style::window::default_border_no_focus_w); - this->addWidget(notifications); - if (!notifications->visible) - { - LOG_ERROR("Can't fit notifications box!"); - return false; - } - - // 2. actually fill it in - if (app->notifications.notSeenCalls) - { - add_notification(notifications, "phone", utils::localize.get("app_desktop_missed_calls"), std::to_string(app->notifications.notSeenCalls), [this]() { - return sapm::ApplicationManager::messageSwitchApplication(application, app::CallLogAppStr, gui::name::window::main_window, nullptr); - }); - } - if (app->notifications.notSeenSMS) - { - add_notification(notifications, "mail", utils::localize.get("app_desktop_unread_messages"), std::to_string(app->notifications.notSeenSMS), [this]() { - return sapm::ApplicationManager::messageSwitchApplication(application, app::name_messages, gui::name::window::main_window, nullptr); - }); - } - setFocusItem(notifications); - return true; -} } /* namespace gui */ diff --git a/module-apps/application-desktop/windows/DesktopMainWindow.hpp b/module-apps/application-desktop/windows/DesktopMainWindow.hpp index 793e0d867..ec892c7c6 100644 --- a/module-apps/application-desktop/windows/DesktopMainWindow.hpp +++ b/module-apps/application-desktop/windows/DesktopMainWindow.hpp @@ -18,57 +18,59 @@ #include "gui/widgets/TopBar.hpp" #include "gui/widgets/Window.hpp" -namespace gui { +namespace gui +{ -/* - * - */ -class DesktopMainWindow: public AppWindow { -protected: - gui::Label* description = nullptr; - gui::Label* time = nullptr; - gui::Label* dayText = nullptr; - gui::Image* messagesImage = nullptr; - gui::VBox *notifications = nullptr; - /** - * Time for pressing sequence of two buttons for unlocking the device in miliseconds. - */ - uint32_t unclockTime = 3000; - /** - * value of the system time when enter key was pressed. - */ - uint32_t unlockStartTime = 0; - /** - * Flag used in detecting unlock seqience - */ - bool enterPressed = false; - /** - * Name of the appliction that was on top when lock timeout occured - */ - std::string lockTimeoutApplilcation = ""; + /* + * + */ + class DesktopMainWindow : public AppWindow + { + protected: + gui::Label *description = nullptr; + gui::Label *time = nullptr; + gui::Label *dayText = nullptr; + gui::Image *messagesImage = nullptr; + gui::VBox *notifications = nullptr; + /** + * Time for pressing sequence of two buttons for unlocking the device in miliseconds. + */ + uint32_t unclockTime = 3000; + /** + * value of the system time when enter key was pressed. + */ + uint32_t unlockStartTime = 0; + /** + * Flag used in detecting unlock seqience + */ + bool enterPressed = false; + /** + * Name of the appliction that was on top when lock timeout occured + */ + std::string lockTimeoutApplilcation = ""; - //method hides or show widgets and sets bars according to provided state - void setVisibleState(); - auto fillNotifications(app::ApplicationDesktop *app) -> bool; + // method hides or show widgets and sets bars according to provided state + void setVisibleState(); + auto fillNotifications(app::ApplicationDesktop *app) -> bool; - public: - DesktopMainWindow( app::Application* app ); - virtual ~DesktopMainWindow(); + public: + DesktopMainWindow(app::Application *app); + virtual ~DesktopMainWindow(); - //virtual methods gui::Window - bool onInput( const InputEvent& inputEvent ) override; - void onBeforeShow( ShowMode mode, SwitchData* data ) override; - //virtual methods gui::AppWindow - void rebuild() override; - void buildInterface() override; - void destroyInterface() override; - bool updateTime( const UTF8& timeStr ) override; - bool updateTime( const uint32_t& timestamp, bool mode24H ) override; - std::list buildDrawList() override; + // virtual methods gui::Window + bool onInput(const InputEvent &inputEvent) override; + void onBeforeShow(ShowMode mode, SwitchData *data) override; + // virtual methods gui::AppWindow + void rebuild() override; + void buildInterface() override; + void destroyInterface() override; + bool updateTime(const UTF8 &timeStr) override; + bool updateTime(const uint32_t ×tamp, bool mode24H) override; + std::list buildDrawList() override; - private: - gui::KeyInputMappedTranslation translator; -}; + private: + gui::KeyInputMappedTranslation translator; + }; } /* namespace gui */ diff --git a/module-apps/application-desktop/windows/MenuWindow.cpp b/module-apps/application-desktop/windows/MenuWindow.cpp index debc2fc87..cbaea8809 100644 --- a/module-apps/application-desktop/windows/MenuWindow.cpp +++ b/module-apps/application-desktop/windows/MenuWindow.cpp @@ -13,12 +13,12 @@ namespace style::design { // all these might not be final - as designs for these didn't look like that - inline const auto tile_w = 130; - inline const auto tile_h = 130; - inline const auto tile_margin = 24; - inline const auto tile_text_y = 50; + inline const auto tile_w = 130; + inline const auto tile_h = 130; + inline const auto tile_margin = 24; + inline const auto tile_text_y = 50; inline const auto notify_dot_x = 80; - inline const auto grid_offset = 20; + inline const auto grid_offset = 20; }; // namespace style::design namespace gui @@ -36,14 +36,15 @@ namespace gui center(it, img, Axis::X); it->addWidget(img); - auto *desc = new gui::Label(it, 0, it->area().h - style::design::tile_text_y, it->area().w, style::design::tile_text_y); + auto *desc = + new gui::Label(it, 0, it->area().h - style::design::tile_text_y, it->area().w, style::design::tile_text_y); desc->setPenWidth(style::window::default_border_no_focus_w); desc->setFont(style::window::font::verysmall); - desc->setAlignement(gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_CENTER, gui::Alignment::ALIGN_VERTICAL_BOTTOM)); + desc->setAlignement( + gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_CENTER, gui::Alignment::ALIGN_VERTICAL_BOTTOM)); desc->setText(utils::localize.get(title)); - if (notifications > 0) - { + if (notifications > 0) { auto thumbnail = new gui::Image("dot_12px_soft"); thumbnail->setPosition(it->area().x + style::design::notify_dot_x, this->area().y); it->addWidget(thumbnail); @@ -58,24 +59,20 @@ namespace gui MenuPage::MenuPage(gui::Item *parent, UTF8 title, std::vector tiles) : title(title) { - if (parent) - { + if (parent) { parent->addWidget(this); } grid.x = style::design::tile_w; grid.y = style::design::tile_h; - for (auto &tile : tiles) - { + for (auto &tile : tiles) { addWidget(tile); } } void MenuPage::setFirstTimeSelection() { - if (visible && first_time_selection) - { - if (children.size() > first_time_selected) - { + if (visible && first_time_selection) { + if (children.size() > first_time_selected) { setFocusItem(*std::next(children.begin(), first_time_selected)); first_time_selection = false; } @@ -108,72 +105,83 @@ namespace gui auto app = dynamic_cast(application); assert(app); - mainMenu = new MenuPage(this, utils::localize.get("app_desktop_menu_title"), - { + mainMenu = new MenuPage( + this, + utils::localize.get("app_desktop_menu_title"), + { - new gui::Tile{ - "menu_tools", - "app_desktop_menu_tools", - [=](gui::Item &item) { - { - switchMenu(toolsMenu); - return true; - } - }, - }, - new gui::Tile("menu_alarm", "app_desktop_menu_alarm", [=](gui::Item &item) { return true; }), - new gui::Tile("menu_calendar", "app_desktop_menu_calendar", [=](gui::Item &item) { return true; }), - new gui::Tile{"menu_phone", "app_desktop_menu_phone", - [=](gui::Item &item) { - LOG_INFO("Call Log"); - sapm::ApplicationManager::messageSwitchApplication(application, "ApplicationCallLog", - gui::name::window::main_window, nullptr); - return true; - }, - app->notifications.notSeenCalls}, - new gui::Tile("menu_contacts", "app_desktop_menu_contacts", - [=](gui::Item &item) { - LOG_INFO("Phonebook"); - sapm::ApplicationManager::messageSwitchApplication(application, "ApplicationPhonebook", - gui::name::window::main_window, nullptr); - return true; - }), + new gui::Tile{ + "menu_tools", + "app_desktop_menu_tools", + [=](gui::Item &item) { + { + switchMenu(toolsMenu); + return true; + } + }, + }, + new gui::Tile("menu_alarm", "app_desktop_menu_alarm", [=](gui::Item &item) { return true; }), + new gui::Tile("menu_calendar", "app_desktop_menu_calendar", [=](gui::Item &item) { return true; }), + new gui::Tile{"menu_phone", + "app_desktop_menu_phone", + [=](gui::Item &item) { + LOG_INFO("Call Log"); + sapm::ApplicationManager::messageSwitchApplication( + application, "ApplicationCallLog", gui::name::window::main_window, nullptr); + return true; + }, + app->notifications.notSeenCalls}, + new gui::Tile("menu_contacts", + "app_desktop_menu_contacts", + [=](gui::Item &item) { + LOG_INFO("Phonebook"); + sapm::ApplicationManager::messageSwitchApplication( + application, "ApplicationPhonebook", gui::name::window::main_window, nullptr); + return true; + }), - new gui::Tile{"menu_messages", "app_desktop_menu_messages", - [=](gui::Item &item) { - LOG_INFO("Messages"); - sapm::ApplicationManager::messageSwitchApplication(application, "ApplicationMessages", - gui::name::window::main_window, nullptr); - return true; - }, - app->notifications.notSeenSMS}, - new gui::Tile{"menu_music_player", "app_desktop_menu_music", [=](gui::Item &item) { return true; }}, - new gui::Tile{"menu_meditation", "app_desktop_menu_meditation", [=](gui::Item &item) { return true; }}, - new gui::Tile{"menu_settings", "app_desktop_menu_settings", - [=](gui::Item &item) { - LOG_INFO("page 1 settings"); - sapm::ApplicationManager::messageSwitchApplication(application, "ApplicationSettings", - gui::name::window::main_window, nullptr); - return true; - }}, - }); + new gui::Tile{"menu_messages", + "app_desktop_menu_messages", + [=](gui::Item &item) { + LOG_INFO("Messages"); + sapm::ApplicationManager::messageSwitchApplication( + application, "ApplicationMessages", gui::name::window::main_window, nullptr); + return true; + }, + app->notifications.notSeenSMS}, + new gui::Tile{"menu_music_player", "app_desktop_menu_music", [=](gui::Item &item) { return true; }}, + new gui::Tile{"menu_meditation", "app_desktop_menu_meditation", [=](gui::Item &item) { return true; }}, + new gui::Tile{"menu_settings", + "app_desktop_menu_settings", + [=](gui::Item &item) { + LOG_INFO("page 1 settings"); + sapm::ApplicationManager::messageSwitchApplication( + application, "ApplicationSettings", gui::name::window::main_window, nullptr); + return true; + }}, + }); - toolsMenu = new MenuPage(this, utils::localize.get("app_desktop_tools_title"), - { - new gui::Tile{"menu_tools_notes", "app_desktop_tools_notes", - [=](gui::Item &item) { - sapm::ApplicationManager::messageSwitchApplication(application, "ApplicationNotes", - gui::name::window::main_window, nullptr); - return true; - }}, - new gui::Tile{"menu_tools_calculator", "app_desktop_tools_calculator", [=](gui::Item &item) { return true; }}, - new gui::Tile{"menu_tools_recorder", "app_desktop_tools_antenna", - [=](gui::Item &item) { - sapm::ApplicationManager::messageSwitchApplication(application, "ApplicationAntenna", - gui::name::window::main_window, nullptr); - return true; - }}, - }); + toolsMenu = new MenuPage( + this, + utils::localize.get("app_desktop_tools_title"), + { + new gui::Tile{"menu_tools_notes", + "app_desktop_tools_notes", + [=](gui::Item &item) { + sapm::ApplicationManager::messageSwitchApplication( + application, "ApplicationNotes", gui::name::window::main_window, nullptr); + return true; + }}, + new gui::Tile{ + "menu_tools_calculator", "app_desktop_tools_calculator", [=](gui::Item &item) { return true; }}, + new gui::Tile{"menu_tools_recorder", + "app_desktop_tools_antenna", + [=](gui::Item &item) { + sapm::ApplicationManager::messageSwitchApplication( + application, "ApplicationAntenna", gui::name::window::main_window, nullptr); + return true; + }}, + }); using namespace style::window; mainMenu->setSize(this->area().w - default_left_margin - default_right_margin, @@ -202,13 +210,12 @@ namespace gui } void MenuWindow::onBeforeShow(ShowMode mode, SwitchData *data) - { - } + {} bool MenuWindow::onInput(const InputEvent &inputEvent) { - if ((inputEvent.state == InputEvent::State::keyReleasedShort) && (inputEvent.keyCode == KeyCode::KEY_RF) && (toolsMenu->visible)) - { + if ((inputEvent.state == InputEvent::State::keyReleasedShort) && (inputEvent.keyCode == KeyCode::KEY_RF) && + (toolsMenu->visible)) { switchMenu(mainMenu); return true; } @@ -217,12 +224,10 @@ namespace gui void MenuWindow::switchMenu(MenuPage *page) { - if (toolsMenu != page) - { + if (toolsMenu != page) { toolsMenu->setVisible(false); } - if (mainMenu != page) - { + if (mainMenu != page) { mainMenu->setVisible(false); } diff --git a/module-apps/application-desktop/windows/MenuWindow.hpp b/module-apps/application-desktop/windows/MenuWindow.hpp index d3e6c0d67..9d00a7c8c 100644 --- a/module-apps/application-desktop/windows/MenuWindow.hpp +++ b/module-apps/application-desktop/windows/MenuWindow.hpp @@ -16,7 +16,10 @@ namespace gui /// icon, description, name of application to run struct Tile : public Rect { - Tile(UTF8 icon, std::string title, std::function activatedCallback, unsigned int notifications = 0); + Tile(UTF8 icon, + std::string title, + std::function activatedCallback, + unsigned int notifications = 0); }; class MenuPage : public gui::GridLayout @@ -35,7 +38,7 @@ namespace gui { protected: // page that is currently selected by the user. - MenuPage *mainMenu = nullptr; + MenuPage *mainMenu = nullptr; MenuPage *toolsMenu = nullptr; public: diff --git a/module-apps/application-desktop/windows/PinLockWindow.cpp b/module-apps/application-desktop/windows/PinLockWindow.cpp index e2772e871..3309648fb 100644 --- a/module-apps/application-desktop/windows/PinLockWindow.cpp +++ b/module-apps/application-desktop/windows/PinLockWindow.cpp @@ -6,14 +6,14 @@ * @copyright Copyright (C) 2019 mudita.com * @details */ -//application manager +// application manager #include "service-appmgr/ApplicationManager.hpp" -//module-gui +// module-gui #include "gui/widgets/BottomBar.hpp" #include "gui/widgets/TopBar.hpp" -//module-utils +// module-utils #include "i18/i18.hpp" #include "PinLockWindow.hpp" @@ -22,257 +22,269 @@ #include "../data/LockPhoneData.hpp" #include -namespace gui { +namespace gui +{ -PinLockWindow::PinLockWindow( app::Application* app ) : AppWindow(app, "PinLockWindow"){ - buildInterface(); -} + PinLockWindow::PinLockWindow(app::Application *app) : AppWindow(app, "PinLockWindow") + { + buildInterface(); + } -void PinLockWindow::rebuild() { - //find which widget has focus - destroyInterface(); - buildInterface(); - //set state - focusItem = nullptr; - setVisibleState( state ); -} -void PinLockWindow::buildInterface() { - AppWindow::buildInterface(); - bottomBar->setActive( BottomBar::Side::LEFT, true ); - bottomBar->setActive( BottomBar::Side::CENTER, false ); - bottomBar->setActive( BottomBar::Side::RIGHT, true ); - bottomBar->setText( BottomBar::Side::LEFT, utils::localize.get("app_desktop_emergency")); - bottomBar->setText( BottomBar::Side::CENTER, utils::localize.get("common_confirm")); - bottomBar->setText( BottomBar::Side::RIGHT, utils::localize.get("common_back")); + void PinLockWindow::rebuild() + { + // find which widget has focus + destroyInterface(); + buildInterface(); + // set state + focusItem = nullptr; + setVisibleState(state); + } + void PinLockWindow::buildInterface() + { + AppWindow::buildInterface(); + bottomBar->setActive(BottomBar::Side::LEFT, true); + bottomBar->setActive(BottomBar::Side::CENTER, false); + bottomBar->setActive(BottomBar::Side::RIGHT, true); + bottomBar->setText(BottomBar::Side::LEFT, utils::localize.get("app_desktop_emergency")); + bottomBar->setText(BottomBar::Side::CENTER, utils::localize.get("common_confirm")); + bottomBar->setText(BottomBar::Side::RIGHT, utils::localize.get("common_back")); - topBar->setActive(TopBar::Elements::SIGNAL, true ); - topBar->setActive(TopBar::Elements::BATTERY, true ); - topBar->setActive(TopBar::Elements::LOCK, true ); + topBar->setActive(TopBar::Elements::SIGNAL, true); + topBar->setActive(TopBar::Elements::BATTERY, true); + topBar->setActive(TopBar::Elements::LOCK, true); - lockImage = new gui::Image( this, 177,132,0,0, "pin_lock" ); - infoImage = new gui::Image( this, 177,132,0,0, "pin_lock_info" ); - infoImage->setVisible(false); + lockImage = new gui::Image(this, 177, 132, 0, 0, "pin_lock"); + infoImage = new gui::Image(this, 177, 132, 0, 0, "pin_lock_info"); + infoImage->setVisible(false); - //title label - titleLabel = new gui::Label(this, 0, 60, 480, 40); - titleLabel->setFilled( false ); - titleLabel->setVisible(false); - titleLabel->setBorderColor( gui::ColorFullBlack ); - titleLabel->setFont(style::header::font::title); - titleLabel->setText(utils::localize.get("app_desktop_pin_info1")); - titleLabel->setEdges( RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES ); - titleLabel->setAlignement( gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_CENTER, gui::Alignment::ALIGN_VERTICAL_BOTTOM)); + // title label + titleLabel = new gui::Label(this, 0, 60, 480, 40); + titleLabel->setFilled(false); + titleLabel->setVisible(false); + titleLabel->setBorderColor(gui::ColorFullBlack); + titleLabel->setFont(style::header::font::title); + titleLabel->setText(utils::localize.get("app_desktop_pin_info1")); + titleLabel->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES); + titleLabel->setAlignement( + gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_CENTER, gui::Alignment::ALIGN_VERTICAL_BOTTOM)); - //labels with stars for displaying entered digits - uint32_t pinLabelX = 82; - for( uint32_t i=0; i<4; i++ ){ - gui::Label* label = new gui::Label(this, pinLabelX, 442-100, 63, 100); - label->setFilled( false ); - label->setBorderColor( gui::ColorFullBlack ); - label->setPenWidth(2); - label->setFont(style::window::font::verybig); - label->setText("*"); - label->setEdges( RectangleEdgeFlags::GUI_RECT_EDGE_BOTTOM ); - label->setAlignement( gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_CENTER, gui::Alignment::ALIGN_VERTICAL_BOTTOM)); - pinLabels.push_back( label ); - pinLabelX += 84; - } + // labels with stars for displaying entered digits + uint32_t pinLabelX = 82; + for (uint32_t i = 0; i < 4; i++) { + gui::Label *label = new gui::Label(this, pinLabelX, 442 - 100, 63, 100); + label->setFilled(false); + label->setBorderColor(gui::ColorFullBlack); + label->setPenWidth(2); + label->setFont(style::window::font::verybig); + label->setText("*"); + label->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_BOTTOM); + label->setAlignement( + gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_CENTER, gui::Alignment::ALIGN_VERTICAL_BOTTOM)); + pinLabels.push_back(label); + pinLabelX += 84; + } - //labels with stars for displaying entered digits - uint32_t infoLabelY = 316-22; - for( uint32_t i=0; i<2; i++ ){ - gui::Label* label = new gui::Label(this, 0, infoLabelY, 480, 30); - label->setFilled( false ); - label->setBorderColor( gui::ColorNoColor ); - label->setFont(style::window::font::medium); - label->setAlignement( gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_CENTER, gui::Alignment::ALIGN_VERTICAL_BOTTOM)); - infoLabels.push_back( label ); - infoLabelY += 40; - } + // labels with stars for displaying entered digits + uint32_t infoLabelY = 316 - 22; + for (uint32_t i = 0; i < 2; i++) { + gui::Label *label = new gui::Label(this, 0, infoLabelY, 480, 30); + label->setFilled(false); + label->setBorderColor(gui::ColorNoColor); + label->setFont(style::window::font::medium); + label->setAlignement( + gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_CENTER, gui::Alignment::ALIGN_VERTICAL_BOTTOM)); + infoLabels.push_back(label); + infoLabelY += 40; + } - infoLabels[0]->setText( utils::localize.get("app_desktop_pin_lock") ); - infoLabels[1]->setText( utils::localize.get("app_desktop_pin_info2") ); -} -void PinLockWindow::destroyInterface() { - AppWindow::destroyInterface(); - delete titleLabel; - for( uint32_t i=0; isetText(utils::localize.get("app_desktop_pin_lock")); + infoLabels[1]->setText(utils::localize.get("app_desktop_pin_info2")); + } + void PinLockWindow::destroyInterface() + { + AppWindow::destroyInterface(); + delete titleLabel; + for (uint32_t i = 0; i < infoLabels.size(); i++) + delete infoLabels[i]; + infoLabels.clear(); + for (uint32_t i = 0; i < pinLabels.size(); i++) + delete pinLabels[i]; + pinLabels.clear(); + delete lockImage; + delete infoImage; + focusItem = nullptr; + children.clear(); + } -PinLockWindow::~PinLockWindow() { - destroyInterface(); -} + PinLockWindow::~PinLockWindow() + { + destroyInterface(); + } -void PinLockWindow::setVisibleState( const State& state ) { + void PinLockWindow::setVisibleState(const State &state) + { - this->state = state; - //show pin labels for entering pin and erase their's content - if( state == State::EnteringPin ) { - charCount = 0; - for( uint32_t i=0; i<4; i++ ) { - pinLabels[i]->setVisible(true); - pinLabels[i]->setText(""); - } - //hide second info label - infoLabels[0]->setVisible(true); - infoLabels[1]->setVisible(false); - infoLabels[0]->setText(utils::localize.get("app_desktop_pin_lock")); - infoLabels[1]->setText(""); - - //show pin icon - lockImage->setVisible(true); - infoImage->setVisible(false); - - } - else if( state == State::WrongPinInfo ) { - for( uint32_t i=0; i<4; i++ ) { - pinLabels[i]->setVisible(false); - pinLabels[i]->setText(""); - } - //hide second info label - titleLabel->setVisible(true); - infoLabels[0]->setVisible(true); - infoLabels[1]->setVisible(true); - titleLabel->setText(utils::localize.get("app_desktop_pin_info1")); - infoLabels[0]->setText(utils::localize.get("app_desktop_pin_info2")); - infoLabels[1]->setText(std::to_string(remainingAttempts)); - - //show pin icon - lockImage->setVisible(false); - infoImage->setVisible(true); - } - else if( state == State::PhoneBlocked ) { - for( uint32_t i=0; i<4; i++ ) { - pinLabels[i]->setVisible(false); - pinLabels[i]->setText(""); - } - //hide second info label - titleLabel->setVisible(false); - infoLabels[0]->setVisible(true); - infoLabels[1]->setVisible(false); - infoLabels[0]->setText(utils::localize.get("app_desktop_pin_blocked1")); - infoLabels[1]->setText(""); - - //show pin icon - lockImage->setVisible(false); - infoImage->setVisible(true); - } -} - -void PinLockWindow::onBeforeShow( ShowMode mode, SwitchData* data ) { - - //check if there was a signal to lock the phone due to inactivity. - if( (data != nullptr) && (data->getDescription() == "LockPhoneData")) { - LockPhoneData* lockData = reinterpret_cast( data ); - lockTimeoutApplilcation = lockData->getPreviousApplication(); - } - //set state - setVisibleState( state ); -} - -bool PinLockWindow::onInput( const InputEvent& inputEvent ) { - if( inputEvent.state == gui::InputEvent::State::keyReleasedShort ) { - //accept only LF, enter, RF, #, and numeric values - if( state == State::EnteringPin ) { - if( inputEvent.keyCode == KeyCode::KEY_LF ) { - return true; - } - else if( inputEvent.keyCode == KeyCode::KEY_RF ) { - application->switchWindow(gui::name::window::main_window); - return true; + this->state = state; + // show pin labels for entering pin and erase their's content + if (state == State::EnteringPin) { + charCount = 0; + for (uint32_t i = 0; i < 4; i++) { + pinLabels[i]->setVisible(true); + pinLabels[i]->setText(""); } - else if( inputEvent.keyCode == KeyCode::KEY_PND ) { - if( charCount > 0 ) { - pinLabels[charCount-1]->setText(""); - charCount--; - bottomBar->setActive( BottomBar::Side::CENTER, false ); - application->refreshWindow( RefreshModes::GUI_REFRESH_FAST ); - } - return true; - } - else if( inputEvent.keyCode == KeyCode::KEY_ENTER ) { - if( (state == State::EnteringPin) && (charCount == 4)) { + // hide second info label + infoLabels[0]->setVisible(true); + infoLabels[1]->setVisible(false); + infoLabels[0]->setText(utils::localize.get("app_desktop_pin_lock")); + infoLabels[1]->setText(""); - //TODO make pin checking here, currently it always fails - if( application->getSettings().lockPassHash == (1000*charValue[0]+100*charValue[1]+10*charValue[2]+charValue[3] ) ) { - remainingAttempts = maxPasswordAttempts; - app::ApplicationDesktop* app = reinterpret_cast( application ); - app->setScreenLocked(false); + // show pin icon + lockImage->setVisible(true); + infoImage->setVisible(false); + } + else if (state == State::WrongPinInfo) { + for (uint32_t i = 0; i < 4; i++) { + pinLabels[i]->setVisible(false); + pinLabels[i]->setText(""); + } + // hide second info label + titleLabel->setVisible(true); + infoLabels[0]->setVisible(true); + infoLabels[1]->setVisible(true); + titleLabel->setText(utils::localize.get("app_desktop_pin_info1")); + infoLabels[0]->setText(utils::localize.get("app_desktop_pin_info2")); + infoLabels[1]->setText(std::to_string(remainingAttempts)); - //if there is no application to return to simply return to main window - if( lockTimeoutApplilcation.empty()) { - application->switchWindow(gui::name::window::main_window); + // show pin icon + lockImage->setVisible(false); + infoImage->setVisible(true); + } + else if (state == State::PhoneBlocked) { + for (uint32_t i = 0; i < 4; i++) { + pinLabels[i]->setVisible(false); + pinLabels[i]->setText(""); + } + // hide second info label + titleLabel->setVisible(false); + infoLabels[0]->setVisible(true); + infoLabels[1]->setVisible(false); + infoLabels[0]->setText(utils::localize.get("app_desktop_pin_blocked1")); + infoLabels[1]->setText(""); + + // show pin icon + lockImage->setVisible(false); + infoImage->setVisible(true); + } + } + + void PinLockWindow::onBeforeShow(ShowMode mode, SwitchData *data) + { + + // check if there was a signal to lock the phone due to inactivity. + if ((data != nullptr) && (data->getDescription() == "LockPhoneData")) { + LockPhoneData *lockData = reinterpret_cast(data); + lockTimeoutApplilcation = lockData->getPreviousApplication(); + } + // set state + setVisibleState(state); + } + + bool PinLockWindow::onInput(const InputEvent &inputEvent) + { + if (inputEvent.state == gui::InputEvent::State::keyReleasedShort) { + // accept only LF, enter, RF, #, and numeric values + if (state == State::EnteringPin) { + if (inputEvent.keyCode == KeyCode::KEY_LF) { + return true; + } + else if (inputEvent.keyCode == KeyCode::KEY_RF) { + application->switchWindow(gui::name::window::main_window); + return true; + } + else if (inputEvent.keyCode == KeyCode::KEY_PND) { + if (charCount > 0) { + pinLabels[charCount - 1]->setText(""); + charCount--; + bottomBar->setActive(BottomBar::Side::CENTER, false); + application->refreshWindow(RefreshModes::GUI_REFRESH_FAST); + } + return true; + } + else if (inputEvent.keyCode == KeyCode::KEY_ENTER) { + if ((state == State::EnteringPin) && (charCount == 4)) { + + // TODO make pin checking here, currently it always fails + if (application->getSettings().lockPassHash == + (1000 * charValue[0] + 100 * charValue[1] + 10 * charValue[2] + charValue[3])) { + remainingAttempts = maxPasswordAttempts; + app::ApplicationDesktop *app = reinterpret_cast(application); + app->setScreenLocked(false); + + // if there is no application to return to simply return to main window + if (lockTimeoutApplilcation.empty()) { + application->switchWindow(gui::name::window::main_window); + } + else { + lockTimeoutApplilcation = ""; + sapm::ApplicationManager::messageSwitchPreviousApplication(application); + } + return true; + } + + if (remainingAttempts == 1) { + state = State::PhoneBlocked; + bottomBar->setActive(BottomBar::Side::CENTER, false); + setVisibleState(State::PhoneBlocked); } else { - lockTimeoutApplilcation = ""; - sapm::ApplicationManager::messageSwitchPreviousApplication( application ); - } - return true; - } + remainingAttempts--; + setVisibleState(State::WrongPinInfo); + } + application->refreshWindow(RefreshModes::GUI_REFRESH_FAST); + } + else if (state == State::WrongPinInfo) { + setVisibleState(State::EnteringPin); + application->refreshWindow(RefreshModes::GUI_REFRESH_FAST); + } + return true; + } + else if (0 <= gui::toNumeric(inputEvent.keyCode) && gui::toNumeric(inputEvent.keyCode) <= 9) { + // fill next field with star and store value in array + if (charCount < 4) { + pinLabels[charCount]->setText("*"); + charValue[charCount] = gui::toNumeric(inputEvent.keyCode); + charCount++; - if( remainingAttempts == 1 ) { - state = State::PhoneBlocked; - bottomBar->setActive( BottomBar::Side::CENTER, false ); - setVisibleState( State::PhoneBlocked ); - } - else { - remainingAttempts--; - setVisibleState( State::WrongPinInfo ); - } - application->refreshWindow( RefreshModes::GUI_REFRESH_FAST ); - } - else if( state == State::WrongPinInfo ) { - setVisibleState( State::EnteringPin ); - application->refreshWindow( RefreshModes::GUI_REFRESH_FAST ); - } - return true; - } - else if( 0 <= gui::toNumeric(inputEvent.keyCode) && gui::toNumeric(inputEvent.keyCode) <= 9) { - //fill next field with star and store value in array - if( charCount < 4 ) { - pinLabels[charCount]->setText("*"); - charValue[charCount] = gui::toNumeric(inputEvent.keyCode); - charCount++; - - //if 4 char has been entered show bottom bar confirm - if( charCount == 4 ) { - bottomBar->setActive( BottomBar::Side::CENTER, true ); - } - application->refreshWindow( RefreshModes::GUI_REFRESH_FAST ); - } - return true; - } - } - else if( state == State::WrongPinInfo ) { - if( inputEvent.keyCode == KeyCode::KEY_ENTER ) { - state = State::EnteringPin; - setVisibleState( State::EnteringPin ); - application->refreshWindow( RefreshModes::GUI_REFRESH_FAST ); - } - else if( inputEvent.keyCode == KeyCode::KEY_RF ) { - state = State::EnteringPin; - application->switchWindow(gui::name::window::main_window); + // if 4 char has been entered show bottom bar confirm + if (charCount == 4) { + bottomBar->setActive(BottomBar::Side::CENTER, true); + } + application->refreshWindow(RefreshModes::GUI_REFRESH_FAST); + } + return true; + } + } + else if (state == State::WrongPinInfo) { + if (inputEvent.keyCode == KeyCode::KEY_ENTER) { + state = State::EnteringPin; + setVisibleState(State::EnteringPin); + application->refreshWindow(RefreshModes::GUI_REFRESH_FAST); + } + else if (inputEvent.keyCode == KeyCode::KEY_RF) { + state = State::EnteringPin; + application->switchWindow(gui::name::window::main_window); + } + } + else if (state == State::PhoneBlocked) { + if (inputEvent.keyCode == KeyCode::KEY_RF) { + application->switchWindow(gui::name::window::main_window); + return true; + } } } - else if( state == State::PhoneBlocked) { - if( inputEvent.keyCode == KeyCode::KEY_RF ) { - application->switchWindow(gui::name::window::main_window); - return true; - } - } - } - //check if any of the lower inheritance onInput methods catch the event - return AppWindow::onInput( inputEvent ); -} + // check if any of the lower inheritance onInput methods catch the event + return AppWindow::onInput(inputEvent); + } } /* namespace gui */ diff --git a/module-apps/application-desktop/windows/PinLockWindow.hpp b/module-apps/application-desktop/windows/PinLockWindow.hpp index 85c3effcf..74aa5bb69 100644 --- a/module-apps/application-desktop/windows/PinLockWindow.hpp +++ b/module-apps/application-desktop/windows/PinLockWindow.hpp @@ -15,43 +15,47 @@ #include "gui/widgets/BottomBar.hpp" #include "gui/widgets/TopBar.hpp" -namespace gui { +namespace gui +{ -class PinLockWindow: public AppWindow { - const uint32_t maxPasswordAttempts = 4; - enum class State { - EnteringPin, - WrongPinInfo, - PhoneBlocked - }; + class PinLockWindow : public AppWindow + { + const uint32_t maxPasswordAttempts = 4; + enum class State + { + EnteringPin, + WrongPinInfo, + PhoneBlocked + }; - gui::Label* titleLabel = nullptr; - std::vector infoLabels; - std::vector pinLabels; - gui::Image* lockImage = nullptr; - gui::Image* infoImage = nullptr; - uint32_t remainingAttempts = maxPasswordAttempts; - //code of the entered character on specified position - uint32_t charValue[4] = {0}; - //flag defines number of entered characters - uint32_t charCount = 0; - //state of the window - State state = State::EnteringPin; + gui::Label *titleLabel = nullptr; + std::vector infoLabels; + std::vector pinLabels; + gui::Image *lockImage = nullptr; + gui::Image *infoImage = nullptr; + uint32_t remainingAttempts = maxPasswordAttempts; + // code of the entered character on specified position + uint32_t charValue[4] = {0}; + // flag defines number of entered characters + uint32_t charCount = 0; + // state of the window + State state = State::EnteringPin; - std::string lockTimeoutApplilcation = ""; + std::string lockTimeoutApplilcation = ""; - //method hides or show widgets and sets bars according to provided state - void setVisibleState( const State& state ); -public: - PinLockWindow( app::Application* app ); - virtual ~PinLockWindow(); - void onBeforeShow( ShowMode mode, SwitchData* data ) override; - bool onInput( const InputEvent& inputEvent ) override; + // method hides or show widgets and sets bars according to provided state + void setVisibleState(const State &state); - void rebuild() override; - void buildInterface() override; - void destroyInterface() override; -}; + public: + PinLockWindow(app::Application *app); + virtual ~PinLockWindow(); + void onBeforeShow(ShowMode mode, SwitchData *data) override; + bool onInput(const InputEvent &inputEvent) override; + + void rebuild() override; + void buildInterface() override; + void destroyInterface() override; + }; } /* namespace gui */ diff --git a/module-apps/application-desktop/windows/PowerOffWindow.cpp b/module-apps/application-desktop/windows/PowerOffWindow.cpp index 4d87c815a..b61d66f65 100644 --- a/module-apps/application-desktop/windows/PowerOffWindow.cpp +++ b/module-apps/application-desktop/windows/PowerOffWindow.cpp @@ -10,206 +10,239 @@ #include "gui/widgets/BottomBar.hpp" #include "gui/widgets/TopBar.hpp" -//module-utils +// module-utils #include "i18/i18.hpp" #include "PowerOffWindow.hpp" #include "../ApplicationDesktop.hpp" -//services +// services #include "service-appmgr/ApplicationManager.hpp" #include "service-cellular/ServiceCellular.hpp" #include -namespace gui { +namespace gui +{ -PowerOffWindow::PowerOffWindow( app::Application* app ) : AppWindow(app, "PowerOffWindow"){ - buildInterface(); -} + PowerOffWindow::PowerOffWindow(app::Application *app) : AppWindow(app, "PowerOffWindow") + { + buildInterface(); + } -void PowerOffWindow::rebuild() { - //find which widget has focus - uint32_t index = 0; - for( uint32_t i=0; isetActive( BottomBar::Side::CENTER, true ); - bottomBar->setActive( BottomBar::Side::RIGHT, true ); - bottomBar->setText( BottomBar::Side::CENTER, utils::localize.get("common_confirm")); - bottomBar->setText( BottomBar::Side::RIGHT, utils::localize.get("common_back")); + destroyInterface(); + buildInterface(); + setFocusItem(selectionLabels[index]); + } + void PowerOffWindow::buildInterface() + { + AppWindow::buildInterface(); + bottomBar->setActive(BottomBar::Side::CENTER, true); + bottomBar->setActive(BottomBar::Side::RIGHT, true); + bottomBar->setText(BottomBar::Side::CENTER, utils::localize.get("common_confirm")); + bottomBar->setText(BottomBar::Side::RIGHT, utils::localize.get("common_back")); - powerImage = new gui::Image( this, 177,132,0,0, "pin_lock_info" ); - powerDownImage = new gui::Image( this, 0,0 ,0,0, "logo" ); - powerDownImage->setVisible(false); + powerImage = new gui::Image(this, 177, 132, 0, 0, "pin_lock_info"); + powerDownImage = new gui::Image(this, 0, 0, 0, 0, "logo"); + powerDownImage->setVisible(false); - //title label - titleLabel = new gui::Label(this, 0, 60, 480, 40); - titleLabel->setFilled( false ); - titleLabel->setBorderColor( gui::ColorFullBlack ); - titleLabel->setFont(style::header::font::title); - titleLabel->setText(utils::localize.get("app_desktop_poweroff_title")); - titleLabel->setEdges( RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES ); - titleLabel->setAlignement( gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_CENTER, gui::Alignment::ALIGN_VERTICAL_BOTTOM)); + // title label + titleLabel = new gui::Label(this, 0, 60, 480, 40); + titleLabel->setFilled(false); + titleLabel->setBorderColor(gui::ColorFullBlack); + titleLabel->setFont(style::header::font::title); + titleLabel->setText(utils::localize.get("app_desktop_poweroff_title")); + titleLabel->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES); + titleLabel->setAlignement( + gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_CENTER, gui::Alignment::ALIGN_VERTICAL_BOTTOM)); - //label with question for powering down - infoLabel = new gui::Label(this, 0, 294, 480, 30); - infoLabel->setFilled( false ); - infoLabel->setBorderColor( gui::ColorNoColor ); - infoLabel->setFont(style::window::font::medium); - infoLabel->setAlignement( gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_CENTER, gui::Alignment::ALIGN_VERTICAL_BOTTOM)); - infoLabel->setText( utils::localize.get("app_desktop_poweroff_question") ); + // label with question for powering down + infoLabel = new gui::Label(this, 0, 294, 480, 30); + infoLabel->setFilled(false); + infoLabel->setBorderColor(gui::ColorNoColor); + infoLabel->setFont(style::window::font::medium); + infoLabel->setAlignement( + gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_CENTER, gui::Alignment::ALIGN_VERTICAL_BOTTOM)); + infoLabel->setText(utils::localize.get("app_desktop_poweroff_question")); - uint32_t pinLabelX = 46; - //TODO change this to 397 after power manager is finished - uint32_t pinLabelY = 350; - for( uint32_t i=0; i<4; i++ ){ - gui::Label* label = new gui::Label(this, pinLabelX, pinLabelY, 193, 75); - label->setFilled( false ); - label->setBorderColor( gui::ColorFullBlack ); - label->setPenWidth(0); - label->setPenFocusWidth(2); - label->setRadius(5); - label->setFont(style::window::font::medium); - label->setEdges( RectangleEdgeFlags::GUI_RECT_ALL_EDGES ); - label->setAlignement( gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_CENTER, gui::Alignment::ALIGN_VERTICAL_CENTER)); - selectionLabels.push_back( label ); - pinLabelX += 193; - } - - selectionLabels[0]->setText( utils::localize.get("common_no") ); - selectionLabels[1]->setText( utils::localize.get("common_yes") ); - - pinLabelX = 46; - pinLabelY += 75; - eventMgrLabel = new gui::Label(this, pinLabelX, pinLabelY, 193*2, 75); - eventMgrLabel->setFilled( false ); - eventMgrLabel->setBorderColor( gui::ColorFullBlack ); - eventMgrLabel->setPenWidth(0); - eventMgrLabel->setPenFocusWidth(2); - eventMgrLabel->setRadius(5); - eventMgrLabel->setFont(style::window::font::bigbold); - eventMgrLabel->setText( "TURN PWR MGR OFF" ); - eventMgrLabel->setEdges( RectangleEdgeFlags::GUI_RECT_ALL_EDGES ); - eventMgrLabel->setAlignement( gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_CENTER, gui::Alignment::ALIGN_VERTICAL_CENTER)); - - //define navigation between labels - selectionLabels[0]->setNavigationItem( NavigationDirection::LEFT, selectionLabels[1] ); - selectionLabels[0]->setNavigationItem( NavigationDirection::RIGHT, selectionLabels[1] ); - selectionLabels[0]->setNavigationItem( NavigationDirection::DOWN, eventMgrLabel ); - - selectionLabels[1]->setNavigationItem( NavigationDirection::LEFT, selectionLabels[0] ); - selectionLabels[1]->setNavigationItem( NavigationDirection::RIGHT, selectionLabels[0] ); - selectionLabels[1]->setNavigationItem( NavigationDirection::DOWN, eventMgrLabel ); - - eventMgrLabel->setNavigationItem( NavigationDirection::UP, selectionLabels[0]); - - //callbacks for getting focus - selectionLabels[0]->focusChangedCallback = [=] (gui::Item& item) { - if( item.focus ) - this->state = State::Return; - return true; }; - - selectionLabels[1]->focusChangedCallback = [=] (gui::Item& item) { - if( item.focus ) - this->state = State::PowerDown; - return true; }; - - selectionLabels[1]->activatedCallback = [=] (gui::Item& item) { - LOG_INFO("Closing system"); - application->setShutdownFlag(); - - bottomBar->setVisible(false); - topBar->setVisible(false); - selectionLabels[0]->setVisible(false); - selectionLabels[1]->setVisible(false); - eventMgrLabel->setVisible(false); - powerImage->setVisible(false); - powerDownImage->setVisible(true); - titleLabel->setVisible(false); - infoLabel->setVisible(false); - - application->refreshWindow( RefreshModes::GUI_REFRESH_DEEP ); - - return true; }; - - //TODO Mati pisze tutaj. - eventMgrLabel->activatedCallback = [=] (gui::Item& item) { - static bool state = false; - if(state == false){ - //sys::SystemManager::DestroyService(ServiceCellular::serviceName,application); - sys::SystemManager::SuspendSystem(application); - LOG_INFO("SUSPEND SYSTEM"); - state = true; + uint32_t pinLabelX = 46; + // TODO change this to 397 after power manager is finished + uint32_t pinLabelY = 350; + for (uint32_t i = 0; i < 4; i++) { + gui::Label *label = new gui::Label(this, pinLabelX, pinLabelY, 193, 75); + label->setFilled(false); + label->setBorderColor(gui::ColorFullBlack); + label->setPenWidth(0); + label->setPenFocusWidth(2); + label->setRadius(5); + label->setFont(style::window::font::medium); + label->setEdges(RectangleEdgeFlags::GUI_RECT_ALL_EDGES); + label->setAlignement( + gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_CENTER, gui::Alignment::ALIGN_VERTICAL_CENTER)); + selectionLabels.push_back(label); + pinLabelX += 193; } - else{ - sys::SystemManager::ResumeSystem(application); - LOG_INFO("RESUME SYSTEM"); - state = false; + + selectionLabels[0]->setText(utils::localize.get("common_no")); + selectionLabels[1]->setText(utils::localize.get("common_yes")); + + pinLabelX = 46; + pinLabelY += 75; + eventMgrLabel = new gui::Label(this, pinLabelX, pinLabelY, 193 * 2, 75); + eventMgrLabel->setFilled(false); + eventMgrLabel->setBorderColor(gui::ColorFullBlack); + eventMgrLabel->setPenWidth(0); + eventMgrLabel->setPenFocusWidth(2); + eventMgrLabel->setRadius(5); + eventMgrLabel->setFont(style::window::font::bigbold); + eventMgrLabel->setText("TURN PWR MGR OFF"); + eventMgrLabel->setEdges(RectangleEdgeFlags::GUI_RECT_ALL_EDGES); + eventMgrLabel->setAlignement( + gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_CENTER, gui::Alignment::ALIGN_VERTICAL_CENTER)); + + // define navigation between labels + selectionLabels[0]->setNavigationItem(NavigationDirection::LEFT, selectionLabels[1]); + selectionLabels[0]->setNavigationItem(NavigationDirection::RIGHT, selectionLabels[1]); + selectionLabels[0]->setNavigationItem(NavigationDirection::DOWN, eventMgrLabel); + + selectionLabels[1]->setNavigationItem(NavigationDirection::LEFT, selectionLabels[0]); + selectionLabels[1]->setNavigationItem(NavigationDirection::RIGHT, selectionLabels[0]); + selectionLabels[1]->setNavigationItem(NavigationDirection::DOWN, eventMgrLabel); + + eventMgrLabel->setNavigationItem(NavigationDirection::UP, selectionLabels[0]); + + // callbacks for getting focus + selectionLabels[0]->focusChangedCallback = [=](gui::Item &item) { + if (item.focus) + this->state = State::Return; + return true; + }; + + selectionLabels[1]->focusChangedCallback = [=](gui::Item &item) { + if (item.focus) + this->state = State::PowerDown; + return true; + }; + + selectionLabels[1]->activatedCallback = [=](gui::Item &item) { + LOG_INFO("Closing system"); + application->setShutdownFlag(); + + bottomBar->setVisible(false); + topBar->setVisible(false); + selectionLabels[0]->setVisible(false); + selectionLabels[1]->setVisible(false); + eventMgrLabel->setVisible(false); + powerImage->setVisible(false); + powerDownImage->setVisible(true); + titleLabel->setVisible(false); + infoLabel->setVisible(false); + + application->refreshWindow(RefreshModes::GUI_REFRESH_DEEP); + + return true; + }; + + // TODO Mati pisze tutaj. + eventMgrLabel->activatedCallback = [=](gui::Item &item) { + static bool state = false; + if (state == false) { + // sys::SystemManager::DestroyService(ServiceCellular::serviceName,application); + sys::SystemManager::SuspendSystem(application); + LOG_INFO("SUSPEND SYSTEM"); + state = true; + } + else { + sys::SystemManager::ResumeSystem(application); + LOG_INFO("RESUME SYSTEM"); + state = false; + } + return true; + }; + } + void PowerOffWindow::destroyInterface() + { + AppWindow::destroyInterface(); + if (titleLabel) { + removeWidget(titleLabel); + delete titleLabel; + titleLabel = nullptr; + }; + if (infoLabel) { + removeWidget(infoLabel); + delete infoLabel; + infoLabel = nullptr; + }; + + for (uint32_t i = 0; i < selectionLabels.size(); i++) { + if (selectionLabels[i]) { + removeWidget(selectionLabels[i]); + delete selectionLabels[i]; + selectionLabels[i] = nullptr; + }; } - return true; - }; -} -void PowerOffWindow::destroyInterface() { - AppWindow::destroyInterface(); - if( titleLabel ) { removeWidget(titleLabel); delete titleLabel; titleLabel = nullptr; }; - if( infoLabel ) { removeWidget(infoLabel); delete infoLabel; infoLabel = nullptr; }; + selectionLabels.clear(); - for( uint32_t i=0; iswitchWindow("MainWindow"); + } + } - //process only short press, consume rest - if( inputEvent.state != gui::InputEvent::State::keyReleasedShort ) - return true; - - - //if enter was pressed check state and power down or return to main desktop's window - if (inputEvent.keyCode == KeyCode::KEY_ENTER) { - if( state == State::PowerDown ){ - //TODO start powering down procedure - } - else { - application->switchWindow( "MainWindow" ); - } - } - - return false; -} + return false; + } } /* namespace gui */ diff --git a/module-apps/application-desktop/windows/PowerOffWindow.hpp b/module-apps/application-desktop/windows/PowerOffWindow.hpp index a13da8373..6f15025f5 100644 --- a/module-apps/application-desktop/windows/PowerOffWindow.hpp +++ b/module-apps/application-desktop/windows/PowerOffWindow.hpp @@ -15,39 +15,41 @@ #include "gui/widgets/Image.hpp" #include "gui/widgets/BottomBar.hpp" -namespace gui { +namespace gui +{ -/* - * Class that defines look and functions for power down window. - */ -class PowerOffWindow: public AppWindow { + /* + * Class that defines look and functions for power down window. + */ + class PowerOffWindow : public AppWindow + { -enum class State { - PowerDown, - Return, - }; + enum class State + { + PowerDown, + Return, + }; - gui::Label* titleLabel = nullptr; - gui::Label* infoLabel = nullptr; + gui::Label *titleLabel = nullptr; + gui::Label *infoLabel = nullptr; - std::vector selectionLabels; - //TODO remove this label after power manager is finished. - gui::Label* eventMgrLabel = nullptr; - gui::Image* powerImage = nullptr; - gui::Image* powerDownImage = nullptr; - State state = State::Return; + std::vector selectionLabels; + // TODO remove this label after power manager is finished. + gui::Label *eventMgrLabel = nullptr; + gui::Image *powerImage = nullptr; + gui::Image *powerDownImage = nullptr; + State state = State::Return; -public: - PowerOffWindow( app::Application* app ); - virtual ~PowerOffWindow(); - void onBeforeShow( ShowMode mode, SwitchData* data ) override; - bool onInput( const InputEvent& inputEvent ) override; + public: + PowerOffWindow(app::Application *app); + virtual ~PowerOffWindow(); + void onBeforeShow(ShowMode mode, SwitchData *data) override; + bool onInput(const InputEvent &inputEvent) override; - void rebuild() override; - void buildInterface() override; - void destroyInterface() override; - -}; + void rebuild() override; + void buildInterface() override; + void destroyInterface() override; + }; } /* namespace gui */ diff --git a/module-apps/application-messages/ApplicationMessages.cpp b/module-apps/application-messages/ApplicationMessages.cpp index a5ce47076..9bb226bd0 100644 --- a/module-apps/application-messages/ApplicationMessages.cpp +++ b/module-apps/application-messages/ApplicationMessages.cpp @@ -21,132 +21,128 @@ #include <../module-services/service-db/messages/DBNotificationMessage.hpp> #include -namespace app { +namespace app +{ - ApplicationMessages::ApplicationMessages(std::string name, std::string parent, bool startBackgound) : Application(name, parent, startBackgound, 4096 * 2) + ApplicationMessages::ApplicationMessages(std::string name, std::string parent, bool startBackgound) + : Application(name, parent, startBackgound, 4096 * 2) { busChannels.push_back(sys::BusChannels::ServiceDBNotifications); } -ApplicationMessages::~ApplicationMessages() { -} + ApplicationMessages::~ApplicationMessages() + {} -// Invoked upon receiving data message -sys::Message_t ApplicationMessages::DataReceivedHandler(sys::DataMessage *msgl, - sys::ResponseMessage *resp) { - auto retMsg = Application::DataReceivedHandler(msgl); - // if message was handled by application's template there is no need to process further. - if (reinterpret_cast(retMsg.get())->retCode - == sys::ReturnCodes::Success) { - return retMsg; - } - - if (msgl->messageType == MessageType::DBServiceNotification) + // Invoked upon receiving data message + sys::Message_t ApplicationMessages::DataReceivedHandler(sys::DataMessage *msgl, sys::ResponseMessage *resp) { - DBNotificationMessage *msg = dynamic_cast(msgl); - LOG_DEBUG("Received multicast"); - if ((msg != nullptr) && (msg->baseType == DB::BaseType::SmsDB) && - ((msg->notificationType == DB::NotificationType::Updated) || (msg->notificationType == DB::NotificationType::Added))) - { - if (this->getCurrentWindow() == this->windows[gui::name::window::thread_view]) - { - LOG_DEBUG("TODO"); - this->getCurrentWindow()->rebuild(); - } - return std::make_shared(); + auto retMsg = Application::DataReceivedHandler(msgl); + // if message was handled by application's template there is no need to process further. + if (reinterpret_cast(retMsg.get())->retCode == sys::ReturnCodes::Success) { + return retMsg; } - } - // this variable defines whether message was processed. - bool handled = false; - //handle database response - if (resp != nullptr) { - handled = true; - switch (resp->responseTo) - { - case MessageType::DBThreadGetLimitOffset: { - if (getCurrentWindow()->onDatabaseMessage(resp)) - refreshWindow(gui::RefreshModes::GUI_REFRESH_FAST); + if (msgl->messageType == MessageType::DBServiceNotification) { + DBNotificationMessage *msg = dynamic_cast(msgl); + LOG_DEBUG("Received multicast"); + if ((msg != nullptr) && (msg->baseType == DB::BaseType::SmsDB) && + ((msg->notificationType == DB::NotificationType::Updated) || + (msg->notificationType == DB::NotificationType::Added))) { + if (this->getCurrentWindow() == this->windows[gui::name::window::thread_view]) { + LOG_DEBUG("TODO"); + this->getCurrentWindow()->rebuild(); + } + return std::make_shared(); + } } - break; + // this variable defines whether message was processed. + bool handled = false; + + // handle database response + if (resp != nullptr) { + handled = true; + switch (resp->responseTo) { + case MessageType::DBThreadGetLimitOffset: { + if (getCurrentWindow()->onDatabaseMessage(resp)) + refreshWindow(gui::RefreshModes::GUI_REFRESH_FAST); + } break; default: break; } - } - - if (handled) - return std::make_shared(); - else - return std::make_shared( - sys::ReturnCodes::Unresolved); -} - -// Invoked during initialization -sys::ReturnCodes ApplicationMessages::InitHandler() { - - auto ret = Application::InitHandler(); - if (ret != sys::ReturnCodes::Success) - return ret; - - createUserInterface(); - - setActiveWindow(gui::name::window::main_window); - - return ret; -} - -sys::ReturnCodes ApplicationMessages::DeinitHandler() { - return sys::ReturnCodes::Success; -} - -void ApplicationMessages::createUserInterface() -{ - windowOptions = gui::newOptionWindow(this); - - windows.insert({gui::name::window::main_window, new gui::MessagesMainWindow(this)}); - windows.insert({gui::name::window::thread_view, new gui::ThreadViewWindow(this)}); - windows.insert({gui::name::window::new_sms, new gui::NewSMS_Window(this)}); - windows.insert({windowOptions->getName(), windowOptions}); - windows.insert({gui::name::window::thread_rm_confirm, new gui::Dialog(this, gui::name::window::thread_rm_confirm, - { - .title = "", - .icon = "phonebook_contact_delete_trashcan", - .text = "", - .action = []() -> bool { - LOG_INFO("!"); - return true; - }, - })}); -} - -void ApplicationMessages::destroyUserInterface() { -} - -bool ApplicationMessages::removeSMS_thread(const ThreadRecord *record) -{ - if (record == nullptr) - { - LOG_ERROR("removing null SMS thread!"); - return false; - } - else - { - LOG_DEBUG("Removing thread: %d", record->dbID); - auto dialog = dynamic_cast(windows[gui::name::window::thread_rm_confirm]); - if (dialog != nullptr) - { - auto meta = dialog->meta; - meta.action = [=]() -> bool { return DBServiceAPI::ThreadRemove(this, record->dbID); }; - meta.text = "Remove thread: " + std::to_string(record->dbID) + " ?"; - dialog->update(meta); - return switchWindow(gui::name::window::thread_rm_confirm, nullptr); } + + if (handled) + return std::make_shared(); else - { - LOG_ERROR("Dialog bad type!"); + return std::make_shared(sys::ReturnCodes::Unresolved); + } + + // Invoked during initialization + sys::ReturnCodes ApplicationMessages::InitHandler() + { + + auto ret = Application::InitHandler(); + if (ret != sys::ReturnCodes::Success) + return ret; + + createUserInterface(); + + setActiveWindow(gui::name::window::main_window); + + return ret; + } + + sys::ReturnCodes ApplicationMessages::DeinitHandler() + { + return sys::ReturnCodes::Success; + } + + void ApplicationMessages::createUserInterface() + { + windowOptions = gui::newOptionWindow(this); + + windows.insert({gui::name::window::main_window, new gui::MessagesMainWindow(this)}); + windows.insert({gui::name::window::thread_view, new gui::ThreadViewWindow(this)}); + windows.insert({gui::name::window::new_sms, new gui::NewSMS_Window(this)}); + windows.insert({windowOptions->getName(), windowOptions}); + windows.insert({gui::name::window::thread_rm_confirm, + new gui::Dialog(this, + gui::name::window::thread_rm_confirm, + { + .title = "", + .icon = "phonebook_contact_delete_trashcan", + .text = "", + .action = []() -> bool { + LOG_INFO("!"); + return true; + }, + })}); + } + + void ApplicationMessages::destroyUserInterface() + {} + + bool ApplicationMessages::removeSMS_thread(const ThreadRecord *record) + { + if (record == nullptr) { + LOG_ERROR("removing null SMS thread!"); return false; } + else { + LOG_DEBUG("Removing thread: %d", record->dbID); + auto dialog = dynamic_cast(windows[gui::name::window::thread_rm_confirm]); + if (dialog != nullptr) { + auto meta = dialog->meta; + meta.action = [=]() -> bool { return DBServiceAPI::ThreadRemove(this, record->dbID); }; + meta.text = "Remove thread: " + std::to_string(record->dbID) + " ?"; + dialog->update(meta); + return switchWindow(gui::name::window::thread_rm_confirm, nullptr); + } + else { + LOG_ERROR("Dialog bad type!"); + return false; + } + } } -} } /* namespace app */ diff --git a/module-apps/application-messages/ApplicationMessages.hpp b/module-apps/application-messages/ApplicationMessages.hpp index c8a3e12d1..1906501a8 100644 --- a/module-apps/application-messages/ApplicationMessages.hpp +++ b/module-apps/application-messages/ApplicationMessages.hpp @@ -24,33 +24,33 @@ namespace gui }; // namespace name }; // namespace gui -namespace app { +namespace app +{ -inline const std::string name_messages = "ApplicationMessages"; + inline const std::string name_messages = "ApplicationMessages"; -class ApplicationMessages: public app::Application { -public: - ApplicationMessages(std::string name = name_messages, - std::string parent = "", bool startBackgound = false); - virtual ~ApplicationMessages(); + class ApplicationMessages : public app::Application + { + public: + ApplicationMessages(std::string name = name_messages, std::string parent = "", bool startBackgound = false); + virtual ~ApplicationMessages(); - gui::OptionWindow *windowOptions = nullptr; + gui::OptionWindow *windowOptions = nullptr; - sys::Message_t DataReceivedHandler(sys::DataMessage *msgl, - sys::ResponseMessage *resp) override; - sys::ReturnCodes InitHandler() override; - sys::ReturnCodes DeinitHandler() override; + sys::Message_t DataReceivedHandler(sys::DataMessage *msgl, sys::ResponseMessage *resp) override; + sys::ReturnCodes InitHandler() override; + sys::ReturnCodes DeinitHandler() override; - sys::ReturnCodes SwitchPowerModeHandler(const sys::ServicePowerMode mode) - override final { - return sys::ReturnCodes::Success; - } + sys::ReturnCodes SwitchPowerModeHandler(const sys::ServicePowerMode mode) override final + { + return sys::ReturnCodes::Success; + } - void createUserInterface() override; - void destroyUserInterface() override; + void createUserInterface() override; + void destroyUserInterface() override; - bool removeSMS_thread(const ThreadRecord *record); -}; + bool removeSMS_thread(const ThreadRecord *record); + }; } /* namespace app */ #endif /* MODULE_APPS_APPLICATION_MESSAGES_APPLICATIONMESSAGES_HPP_ */ diff --git a/module-apps/application-messages/MessagesStyle.hpp b/module-apps/application-messages/MessagesStyle.hpp index 18eddfb31..45627faeb 100644 --- a/module-apps/application-messages/MessagesStyle.hpp +++ b/module-apps/application-messages/MessagesStyle.hpp @@ -7,26 +7,28 @@ #pragma once -namespace messages { -namespace threads { -constexpr auto pageSize = 4; +namespace messages +{ + namespace threads + { + constexpr auto pageSize = 4; -constexpr auto listHeight = 445; -constexpr auto listWidth = 458; -constexpr auto listPositionX = 11; -constexpr auto ListPositionY = 105; // @TODO M.G. tweak it to design. Spacers between entries, top margin -} //namespace threads + constexpr auto listHeight = 445; + constexpr auto listWidth = 458; + constexpr auto listPositionX = 11; + constexpr auto ListPositionY = 105; // @TODO M.G. tweak it to design. Spacers between entries, top margin + } // namespace threads -namespace threadItem { + namespace threadItem + { -constexpr auto contactPositionX = 14; -constexpr auto contactPositionY = 10; -constexpr auto cotactWidthOffset = 133; + constexpr auto contactPositionX = 14; + constexpr auto contactPositionY = 10; + constexpr auto cotactWidthOffset = 133; -constexpr auto timestampWidth = 100; - -constexpr auto prewievPositionX = 14; -constexpr auto previewWidthOffset = 20; -} -} //namespace messages + constexpr auto timestampWidth = 100; + constexpr auto prewievPositionX = 14; + constexpr auto previewWidthOffset = 20; + } // namespace threadItem +} // namespace messages diff --git a/module-apps/application-messages/data/SMSdata.hpp b/module-apps/application-messages/data/SMSdata.hpp index 160c46da6..d2fb40c2b 100644 --- a/module-apps/application-messages/data/SMSdata.hpp +++ b/module-apps/application-messages/data/SMSdata.hpp @@ -12,8 +12,7 @@ class SMSThreadData : public gui::SwitchData public: std::shared_ptr thread = nullptr; SMSThreadData(std::shared_ptr thread) : thread(thread) - { - } + {} virtual ~SMSThreadData() = default; }; @@ -22,7 +21,6 @@ class SMSSendRequest : public gui::SwitchData public: std::shared_ptr contact = nullptr; SMSSendRequest(std::shared_ptr contact) : contact(contact) - { - } + {} virtual ~SMSSendRequest() = default; }; diff --git a/module-apps/application-messages/widgets/ThreadItem.cpp b/module-apps/application-messages/widgets/ThreadItem.cpp index a33490043..20328f7ba 100644 --- a/module-apps/application-messages/widgets/ThreadItem.cpp +++ b/module-apps/application-messages/widgets/ThreadItem.cpp @@ -12,84 +12,79 @@ #include #include "../MessagesStyle.hpp" -namespace gui { +namespace gui +{ -ThreadItem::ThreadItem(ThreadModel *threadmodel) { - using namespace style; + ThreadItem::ThreadItem(ThreadModel *threadmodel) + { + using namespace style; - model = threadmodel; - minWidth = 431; - minHeight = 100; - maxWidth = 431; - maxHeight = 100; + model = threadmodel; + minWidth = 431; + minHeight = 100; + maxWidth = 431; + maxHeight = 100; - setRadius(0); - setEdges( - RectangleEdgeFlags::GUI_RECT_EDGE_BOTTOM - | RectangleEdgeFlags::GUI_RECT_EDGE_TOP); + setRadius(0); + setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_BOTTOM | RectangleEdgeFlags::GUI_RECT_EDGE_TOP); - setPenFocusWidth(window::default_border_focucs_w); - setPenWidth(window::default_border_no_focus_w); + setPenFocusWidth(window::default_border_focucs_w); + setPenWidth(window::default_border_no_focus_w); - contact = new gui::Label(this, 0, 0, 0, 0); - contact->setPenFocusWidth(window::default_border_no_focus_w); - contact->setPenWidth(window::default_border_no_focus_w); - contact->setFont(style::window::font::big); - contact->setDotsMode(true); - contact->setAlignement(gui::Alignment { - gui::Alignment::ALIGN_HORIZONTAL_LEFT, - gui::Alignment::ALIGN_VERTICAL_CENTER }); + contact = new gui::Label(this, 0, 0, 0, 0); + contact->setPenFocusWidth(window::default_border_no_focus_w); + contact->setPenWidth(window::default_border_no_focus_w); + contact->setFont(style::window::font::big); + contact->setDotsMode(true); + contact->setAlignement( + gui::Alignment{gui::Alignment::ALIGN_HORIZONTAL_LEFT, gui::Alignment::ALIGN_VERTICAL_CENTER}); - timestamp = new gui::Label(this, 0, 0, 0, 0); - timestamp->setPenFocusWidth(window::default_border_no_focus_w); - timestamp->setPenWidth(window::default_border_no_focus_w); - timestamp->setFont(style::window::font::small); - timestamp->setDotsMode(true); - timestamp->setAlignement(gui::Alignment { - gui::Alignment::ALIGN_HORIZONTAL_RIGHT, - gui::Alignment::ALIGN_VERTICAL_CENTER }); + timestamp = new gui::Label(this, 0, 0, 0, 0); + timestamp->setPenFocusWidth(window::default_border_no_focus_w); + timestamp->setPenWidth(window::default_border_no_focus_w); + timestamp->setFont(style::window::font::small); + timestamp->setDotsMode(true); + timestamp->setAlignement( + gui::Alignment{gui::Alignment::ALIGN_HORIZONTAL_RIGHT, gui::Alignment::ALIGN_VERTICAL_CENTER}); - preview = new gui::Label(this, 0, 0, 0, 0); - preview->setPenFocusWidth(window::default_border_no_focus_w); - preview->setPenWidth(window::default_border_no_focus_w); - preview->setFont(style::window::font::small); - preview->setDotsMode(true); - preview->setAlignement(gui::Alignment { - gui::Alignment::ALIGN_HORIZONTAL_LEFT, - gui::Alignment::ALIGN_VERTICAL_CENTER }); - -} - -bool ThreadItem::onDimensionChanged(const BoundingBox &oldDim, - const BoundingBox &newDim) { - using namespace messages::threadItem; - - contact->setPosition(contactPositionX, contactPositionY); - contact->setSize(newDim.w - cotactWidthOffset, newDim.h / 2); - - timestamp->setPosition(newDim.w - timestampWidth, 0); - timestamp->setSize(timestampWidth, newDim.h / 2); - - preview->setPosition(14, newDim.h / 2); - preview->setSize(newDim.w - previewWidthOffset, newDim.h / 2); - - return true; -} - -void ThreadItem::setThreadItem(std::shared_ptr &thread) { - this->thread = thread; - - if (model != nullptr) { - auto contactRec = DBServiceAPI::ContactGetByID(model->getApplication(), - thread->contactID); - auto cont = contactRec->front(); - contact->setText(cont.getFormattedName()); + preview = new gui::Label(this, 0, 0, 0, 0); + preview->setPenFocusWidth(window::default_border_no_focus_w); + preview->setPenWidth(window::default_border_no_focus_w); + preview->setFont(style::window::font::small); + preview->setDotsMode(true); + preview->setAlignement( + gui::Alignment{gui::Alignment::ALIGN_HORIZONTAL_LEFT, gui::Alignment::ALIGN_VERTICAL_CENTER}); } - timestamp->setText(utils::time::DateTime(thread->date)); + bool ThreadItem::onDimensionChanged(const BoundingBox &oldDim, const BoundingBox &newDim) + { + using namespace messages::threadItem; - preview->setText(thread->snippet); -} + contact->setPosition(contactPositionX, contactPositionY); + contact->setSize(newDim.w - cotactWidthOffset, newDim.h / 2); + + timestamp->setPosition(newDim.w - timestampWidth, 0); + timestamp->setSize(timestampWidth, newDim.h / 2); + + preview->setPosition(14, newDim.h / 2); + preview->setSize(newDim.w - previewWidthOffset, newDim.h / 2); + + return true; + } + + void ThreadItem::setThreadItem(std::shared_ptr &thread) + { + this->thread = thread; + + if (model != nullptr) { + auto contactRec = DBServiceAPI::ContactGetByID(model->getApplication(), thread->contactID); + auto cont = contactRec->front(); + contact->setText(cont.getFormattedName()); + } + + timestamp->setText(utils::time::DateTime(thread->date)); + + preview->setText(thread->snippet); + } } /*namespace gui*/ - diff --git a/module-apps/application-messages/widgets/ThreadItem.hpp b/module-apps/application-messages/widgets/ThreadItem.hpp index 643840136..9d676d545 100644 --- a/module-apps/application-messages/widgets/ThreadItem.hpp +++ b/module-apps/application-messages/widgets/ThreadItem.hpp @@ -12,28 +12,30 @@ #include "ListItem.hpp" #include "ThreadModel.hpp" -namespace gui { +namespace gui +{ -class ThreadItem: public ListItem { - -private: - ThreadModel *model = nullptr; - - std::shared_ptr thread = nullptr; - gui::Label *contact = nullptr; - gui::Label *timestamp = nullptr; - gui::Label *preview = nullptr; - - gui::Image *dot = nullptr; -public: - ThreadItem(ThreadModel *model); - - bool onDimensionChanged(const BoundingBox &oldDim, - const BoundingBox &newDim) override; - void setThreadItem(std::shared_ptr &thread); - std::shared_ptr getThreadItem() + class ThreadItem : public ListItem { - return thread; - } -}; + + private: + ThreadModel *model = nullptr; + + std::shared_ptr thread = nullptr; + gui::Label *contact = nullptr; + gui::Label *timestamp = nullptr; + gui::Label *preview = nullptr; + + gui::Image *dot = nullptr; + + public: + ThreadItem(ThreadModel *model); + + bool onDimensionChanged(const BoundingBox &oldDim, const BoundingBox &newDim) override; + void setThreadItem(std::shared_ptr &thread); + std::shared_ptr getThreadItem() + { + return thread; + } + }; } /*namespace gui*/ diff --git a/module-apps/application-messages/widgets/ThreadModel.cpp b/module-apps/application-messages/widgets/ThreadModel.cpp index 7de46fc56..12eedf5aa 100644 --- a/module-apps/application-messages/widgets/ThreadModel.cpp +++ b/module-apps/application-messages/widgets/ThreadModel.cpp @@ -15,61 +15,60 @@ #include "../windows/ThreadViewWindow.hpp" // for name of window #include "service-db/api/DBServiceAPI.hpp" -ThreadModel::ThreadModel(app::Application *app) : - DatabaseModel(app, messages::threads::pageSize) { +ThreadModel::ThreadModel(app::Application *app) : DatabaseModel(app, messages::threads::pageSize) +{} +void ThreadModel::requestRecordsCount(void) +{ + recordsCount = DBServiceAPI::ThreadGetCount(application); + + if (recordsCount > 0) { + + DBServiceAPI::ThreadGetLimitOffset(application, 0, messages::threads::pageSize); + if (recordsCount >= messages::threads::pageSize) { + DBServiceAPI::ThreadGetLimitOffset(application, messages::threads::pageSize, messages::threads::pageSize); + } + } +} +bool ThreadModel::updateRecords(std::unique_ptr> records, + const uint32_t offset, + const uint32_t limit, + uint32_t count) +{ + DatabaseModel::updateRecords(std::move(records), offset, limit, count); + + return true; } -void ThreadModel::requestRecordsCount(void) { - recordsCount = DBServiceAPI::ThreadGetCount(application); - - if (recordsCount > 0) { - - DBServiceAPI::ThreadGetLimitOffset(application, 0, - messages::threads::pageSize); - if (recordsCount >= messages::threads::pageSize) { - DBServiceAPI::ThreadGetLimitOffset(application, - messages::threads::pageSize, messages::threads::pageSize); - } - } -} -bool ThreadModel::updateRecords( - std::unique_ptr> records, - const uint32_t offset, const uint32_t limit, uint32_t count) { - DatabaseModel::updateRecords(std::move(records), offset, limit, count); - - return true; +void ThreadModel::requestRecords(uint32_t offset, uint32_t limit) +{ + DBServiceAPI::ThreadGetLimitOffset(application, offset, limit); } -void ThreadModel::requestRecords(uint32_t offset, uint32_t limit) { - DBServiceAPI::ThreadGetLimitOffset(application, offset, limit); -} +gui::ListItem *ThreadModel::getItem( + int index, int fistElement, int prevElement, uint32_t limit, int remaining, bool topDown) +{ + std::shared_ptr thread = getRecord(index); -gui::ListItem* ThreadModel::getItem(int index, int fistElement, int prevElement, - uint32_t limit, int remaining, bool topDown) { - std::shared_ptr thread = getRecord(index); + if (thread.get() == nullptr) { + return nullptr; + } - if (thread.get() == nullptr) { - return nullptr; - } - - auto item = new gui::ThreadItem(this); - if (item != nullptr) { - item->setThreadItem(thread); - item->setID(index); + auto item = new gui::ThreadItem(this); + if (item != nullptr) { + item->setThreadItem(thread); + item->setID(index); item->activatedCallback = [=](gui::Item &item) { LOG_INFO("ThreadItem ActivatedCallback"); - if (application) - { + if (application) { application->switchWindow(gui::name::window::thread_view, std::make_unique(thread)); } - else - { + else { LOG_ERROR("No application!"); } return true; }; return item; } - return nullptr; + return nullptr; } diff --git a/module-apps/application-messages/widgets/ThreadModel.hpp b/module-apps/application-messages/widgets/ThreadModel.hpp index 4cb36f13a..fb728fc40 100644 --- a/module-apps/application-messages/widgets/ThreadModel.hpp +++ b/module-apps/application-messages/widgets/ThreadModel.hpp @@ -15,28 +15,28 @@ #include "ListItemProvider.hpp" #include "Interface/ThreadRecord.hpp" -class ThreadModel: public app::DatabaseModel, - public gui::ListItemProvider { -public: - ThreadModel() = delete; - ThreadModel(app::Application *app); - virtual ~ThreadModel() = default; +class ThreadModel : public app::DatabaseModel, public gui::ListItemProvider +{ + public: + ThreadModel() = delete; + ThreadModel(app::Application *app); + virtual ~ThreadModel() = default; - void requestRecordsCount() override; - bool updateRecords(std::unique_ptr> records, - const uint32_t offset, const uint32_t limit, uint32_t count) - override; - void requestRecords(const uint32_t offset, const uint32_t limit) override; + void requestRecordsCount() override; + bool updateRecords(std::unique_ptr> records, + const uint32_t offset, + const uint32_t limit, + uint32_t count) override; + void requestRecords(const uint32_t offset, const uint32_t limit) override; - gui::ListItem* getItem(int index, int firstElement, int prevElement, - uint32_t limit, int remaining, bool topDown) override; - int getItemCount() const override { - return recordsCount; - } - ; - app::Application* getApplication(void) { - return application; - } - ; + gui::ListItem *getItem( + int index, int firstElement, int prevElement, uint32_t limit, int remaining, bool topDown) override; + int getItemCount() const override + { + return recordsCount; + }; + app::Application *getApplication(void) + { + return application; + }; }; - diff --git a/module-apps/application-messages/windows/MessagesMainWindow.cpp b/module-apps/application-messages/windows/MessagesMainWindow.cpp index aee151daa..1c9b6b99d 100644 --- a/module-apps/application-messages/windows/MessagesMainWindow.cpp +++ b/module-apps/application-messages/windows/MessagesMainWindow.cpp @@ -35,173 +35,164 @@ #include "time/time_conversion.hpp" -namespace gui { +namespace gui +{ - MessagesMainWindow::MessagesMainWindow(app::Application *app) : AppWindow(app, gui::name::window::main_window), threadModel{new ThreadModel(app)} + MessagesMainWindow::MessagesMainWindow(app::Application *app) + : AppWindow(app, gui::name::window::main_window), threadModel{new ThreadModel(app)} { buildInterface(); } -void MessagesMainWindow::rebuild() { - destroyInterface(); - buildInterface(); -} -void MessagesMainWindow::buildInterface() { - - using namespace messages; - - AppWindow::buildInterface(); - - list = new gui::ListView(this, threads::listPositionX, - threads::ListPositionY, threads::listWidth, threads::listWidth); - list->setMaxElements(threads::pageSize); - list->setPageSize(threads::pageSize); - list->setPenFocusWidth(0); - list->setPenWidth(0); - list->setProvider(threadModel); - - bottomBar->setActive(BottomBar::Side::LEFT, true); - - bottomBar->setActive(BottomBar::Side::CENTER, true); - bottomBar->setActive(BottomBar::Side::RIGHT, true); - bottomBar->setText(BottomBar::Side::LEFT, - utils::localize.get("common_options")); - bottomBar->setText(BottomBar::Side::CENTER, - utils::localize.get("common_open")); - bottomBar->setText(BottomBar::Side::RIGHT, - utils::localize.get("common_back")); - - topBar->setActive(TopBar::Elements::TIME, true); - - setTitle(utils::localize.get("app_messages_title_main")); - - leftArrowImage = new gui::Image(this, 30, 62, 0, 0, "arrow_left"); - rightArrowImage = new gui::Image(this, 480 - 30 - 13, 62, 0, 0, - "arrow_right"); - newMessageImage = new gui::Image(this, 48, 55, 0, 0, "cross"); - searchImage = new gui::Image(this, 480 - 48 - 26, 55, 0, 0, "search"); - -// setFocusItem( list ); -} -void MessagesMainWindow::destroyInterface() { - AppWindow::destroyInterface(); - if (list) { - removeWidget(list); - delete list; - list = nullptr; - } - if (leftArrowImage) { - removeWidget(leftArrowImage); - delete leftArrowImage; - leftArrowImage = nullptr; - } - if (rightArrowImage) { - removeWidget(rightArrowImage); - delete rightArrowImage; - rightArrowImage = nullptr; - } - if (newMessageImage) { - removeWidget(newMessageImage); - delete newMessageImage; - newMessageImage = nullptr; - } - if (searchImage) { - removeWidget(searchImage); - delete searchImage; - searchImage = nullptr; - } - - children.clear(); - delete threadModel; -} - -MessagesMainWindow::~MessagesMainWindow() { - destroyInterface(); -} - -void MessagesMainWindow::onBeforeShow(ShowMode mode, SwitchData *data) { - - LOG_INFO("Data: %s", data ? data->getDescription().c_str() : ""); + void MessagesMainWindow::rebuild() { - if (auto pdata = dynamic_cast(data)) + destroyInterface(); + buildInterface(); + } + void MessagesMainWindow::buildInterface() + { + + using namespace messages; + + AppWindow::buildInterface(); + + list = new gui::ListView( + this, threads::listPositionX, threads::ListPositionY, threads::listWidth, threads::listWidth); + list->setMaxElements(threads::pageSize); + list->setPageSize(threads::pageSize); + list->setPenFocusWidth(0); + list->setPenWidth(0); + list->setProvider(threadModel); + + bottomBar->setActive(BottomBar::Side::LEFT, true); + + bottomBar->setActive(BottomBar::Side::CENTER, true); + bottomBar->setActive(BottomBar::Side::RIGHT, true); + bottomBar->setText(BottomBar::Side::LEFT, utils::localize.get("common_options")); + bottomBar->setText(BottomBar::Side::CENTER, utils::localize.get("common_open")); + bottomBar->setText(BottomBar::Side::RIGHT, utils::localize.get("common_back")); + + topBar->setActive(TopBar::Elements::TIME, true); + + setTitle(utils::localize.get("app_messages_title_main")); + + leftArrowImage = new gui::Image(this, 30, 62, 0, 0, "arrow_left"); + rightArrowImage = new gui::Image(this, 480 - 30 - 13, 62, 0, 0, "arrow_right"); + newMessageImage = new gui::Image(this, 48, 55, 0, 0, "cross"); + searchImage = new gui::Image(this, 480 - 48 - 26, 55, 0, 0, "search"); + + // setFocusItem( list ); + } + void MessagesMainWindow::destroyInterface() + { + AppWindow::destroyInterface(); + if (list) { + removeWidget(list); + delete list; + list = nullptr; + } + if (leftArrowImage) { + removeWidget(leftArrowImage); + delete leftArrowImage; + leftArrowImage = nullptr; + } + if (rightArrowImage) { + removeWidget(rightArrowImage); + delete rightArrowImage; + rightArrowImage = nullptr; + } + if (newMessageImage) { + removeWidget(newMessageImage); + delete newMessageImage; + newMessageImage = nullptr; + } + if (searchImage) { + removeWidget(searchImage); + delete searchImage; + searchImage = nullptr; + } + + children.clear(); + delete threadModel; + } + + MessagesMainWindow::~MessagesMainWindow() + { + destroyInterface(); + } + + void MessagesMainWindow::onBeforeShow(ShowMode mode, SwitchData *data) + { + + LOG_INFO("Data: %s", data ? data->getDescription().c_str() : ""); { - auto thread = DBServiceAPI::ThreadGetByContact(application, pdata->result->dbID); - if (thread) - { - application->switchWindow(gui::name::window::thread_view, std::make_unique(std::move(thread))); - } - else - { - LOG_FATAL("No thread and thread not created!"); + if (auto pdata = dynamic_cast(data)) { + auto thread = DBServiceAPI::ThreadGetByContact(application, pdata->result->dbID); + if (thread) { + application->switchWindow(gui::name::window::thread_view, + std::make_unique(std::move(thread))); + } + else { + LOG_FATAL("No thread and thread not created!"); + } } } - } - if (mode == ShowMode::GUI_SHOW_INIT || data == nullptr) - { - threadModel->clear(); - threadModel->requestRecordsCount(); - list->clear(); - list->setElementsCount(threadModel->getItemCount()); + if (mode == ShowMode::GUI_SHOW_INIT || data == nullptr) { + threadModel->clear(); + threadModel->requestRecordsCount(); + list->clear(); + list->setElementsCount(threadModel->getItemCount()); - setFocusItem(list); - } -} - -bool MessagesMainWindow::onInput(const InputEvent &inputEvent) -{ - // check if any of the lower inheritance onInput methods catch the event - if (AppWindow::onInput(inputEvent)) - { - return true; - } - else - { - if (inputEvent.state == InputEvent::State::keyReleasedShort) - { - switch (inputEvent.keyCode) - { - case gui::KeyCode::KEY_LEFT: - application->switchWindow(gui::name::window::new_sms, nullptr); - return true; - case gui::KeyCode::KEY_LF: { - auto app = dynamic_cast(application); - if (app == nullptr) - { - LOG_ERROR("Something went horribly wrong"); - return false; - } - if (app->windowOptions != nullptr) - { - app->windowOptions->clearOptions(); - auto it = dynamic_cast(list->getSelectedItem()); - if (it) - { - app->windowOptions->addOptions(threadWindowOptions(app, it->getThreadItem().get())); - app->switchWindow(app->windowOptions->getName(), nullptr); - } - else - { - LOG_ERROR("Can't switch to options -wrong input type"); - } - } - return true; - } - default: - LOG_DEBUG("SMS main window not handled key: %d", inputEvent.keyCode); - } + setFocusItem(list); } } - return false; -} -bool MessagesMainWindow::onDatabaseMessage(sys::Message *msgl) { - DBThreadResponseMessage *msg = - reinterpret_cast(msgl); - if (threadModel->updateRecords(std::move(msg->records), msg->offset, - msg->limit, msg->count)) - return true; + bool MessagesMainWindow::onInput(const InputEvent &inputEvent) + { + // check if any of the lower inheritance onInput methods catch the event + if (AppWindow::onInput(inputEvent)) { + return true; + } + else { + if (inputEvent.state == InputEvent::State::keyReleasedShort) { + switch (inputEvent.keyCode) { + case gui::KeyCode::KEY_LEFT: + application->switchWindow(gui::name::window::new_sms, nullptr); + return true; + case gui::KeyCode::KEY_LF: { + auto app = dynamic_cast(application); + if (app == nullptr) { + LOG_ERROR("Something went horribly wrong"); + return false; + } + if (app->windowOptions != nullptr) { + app->windowOptions->clearOptions(); + auto it = dynamic_cast(list->getSelectedItem()); + if (it) { + app->windowOptions->addOptions(threadWindowOptions(app, it->getThreadItem().get())); + app->switchWindow(app->windowOptions->getName(), nullptr); + } + else { + LOG_ERROR("Can't switch to options -wrong input type"); + } + } + return true; + } + default: + LOG_DEBUG("SMS main window not handled key: %d", inputEvent.keyCode); + } + } + } + return false; + } - return false; -} + bool MessagesMainWindow::onDatabaseMessage(sys::Message *msgl) + { + DBThreadResponseMessage *msg = reinterpret_cast(msgl); + if (threadModel->updateRecords(std::move(msg->records), msg->offset, msg->limit, msg->count)) + return true; + + return false; + } } /* namespace gui */ diff --git a/module-apps/application-messages/windows/MessagesMainWindow.hpp b/module-apps/application-messages/windows/MessagesMainWindow.hpp index e030caf83..1441d39ba 100644 --- a/module-apps/application-messages/windows/MessagesMainWindow.hpp +++ b/module-apps/application-messages/windows/MessagesMainWindow.hpp @@ -19,35 +19,37 @@ #include "ListView.hpp" #include "../widgets/ThreadModel.hpp" -namespace gui { +namespace gui +{ -class MessagesMainWindow: public AppWindow { -protected: -// PhonebookListView* list; -// PhonebookModel* phonebookModel = nullptr; + class MessagesMainWindow : public AppWindow + { + protected: + // PhonebookListView* list; + // PhonebookModel* phonebookModel = nullptr; - Image *leftArrowImage = nullptr; - Image *rightArrowImage = nullptr; - Image *newMessageImage = nullptr; - Image *searchImage = nullptr; + Image *leftArrowImage = nullptr; + Image *rightArrowImage = nullptr; + Image *newMessageImage = nullptr; + Image *searchImage = nullptr; - ThreadModel *threadModel = nullptr; - gui::ListView *list = nullptr; + ThreadModel *threadModel = nullptr; + gui::ListView *list = nullptr; -public: - MessagesMainWindow(app::Application *app); - virtual ~MessagesMainWindow(); + public: + MessagesMainWindow(app::Application *app); + virtual ~MessagesMainWindow(); - // virtual methods - bool onInput(const InputEvent &inputEvent) override; - void onBeforeShow(ShowMode mode, SwitchData *data) override; + // virtual methods + bool onInput(const InputEvent &inputEvent) override; + void onBeforeShow(ShowMode mode, SwitchData *data) override; - bool onDatabaseMessage(sys::Message *msgl); + bool onDatabaseMessage(sys::Message *msgl); - void rebuild() override; - void buildInterface() override; - void destroyInterface() override; -}; + void rebuild() override; + void buildInterface() override; + void destroyInterface() override; + }; } /* namespace gui */ diff --git a/module-apps/application-messages/windows/NewMessage.cpp b/module-apps/application-messages/windows/NewMessage.cpp index 325681cb5..60966a897 100644 --- a/module-apps/application-messages/windows/NewMessage.cpp +++ b/module-apps/application-messages/windows/NewMessage.cpp @@ -23,7 +23,7 @@ namespace gui uint32_t w = this->getWidth() - style::window::default_left_margin * 2; uint32_t h = this->getHeight() - title->offset_h() - bottomBar->getHeight(); - auto body = new gui::VBox(this, style::window::default_left_margin, (uint32_t)title->offset_h(), w, h); + auto body = new gui::VBox(this, style::window::default_left_margin, (uint32_t)title->offset_h(), w, h); auto label = new Label(body, 0, 0, body->getWidth(), 40); label->setText(utils::localize.get("sms_add_rec_num")); @@ -38,10 +38,11 @@ namespace gui std::shared_ptr> searchResults = DBServiceAPI::ContactSearch(application, text->getText(), text->getText(), text->getText()); LOG_INFO("Get contact from another app, contacts matching num: %d", searchResults.get()->size()); - if (searchResults.get()->size() > 0) - { - std::unique_ptr data = std::make_unique(text->getText(), searchResults); - return sapm::ApplicationManager::messageSwitchApplication(application, app::name_phonebook, name::window::search_results, std::move(data)); + if (searchResults.get()->size() > 0) { + std::unique_ptr data = + std::make_unique(text->getText(), searchResults); + return sapm::ApplicationManager::messageSwitchApplication( + application, app::name_phonebook, name::window::search_results, std::move(data)); } return true; }; @@ -60,22 +61,18 @@ namespace gui void NewSMS_Window::onBeforeShow(ShowMode mode, SwitchData *data) { - if (dynamic_cast(data)) - { + if (dynamic_cast(data)) { LOG_INFO("SUCCESS!"); application->switchWindow(gui::name::window::thread_view, std::make_unique(*data)); } } void NewSMS_Window::rebuild() - { - } + {} void NewSMS_Window::buildInterface() - { - } + {} void NewSMS_Window::destroyInterface() - { - } + {} }; // namespace gui diff --git a/module-apps/application-messages/windows/OptionsMessages.cpp b/module-apps/application-messages/windows/OptionsMessages.cpp index d7fd4975e..0bef3df86 100644 --- a/module-apps/application-messages/windows/OptionsMessages.cpp +++ b/module-apps/application-messages/windows/OptionsMessages.cpp @@ -16,7 +16,7 @@ gui::HBox *newCombo(app::ApplicationMessages *app, const ContactRecord &contact) box->setPenWidth(0); box->setPenFocusWidth(0); auto text_len = 200; // Dumb text size - this won't be needed when Text(...) widget will be refactored - auto l = new gui::Label(box, 0, 0, text_len, label::big_h); + auto l = new gui::Label(box, 0, 0, text_len, label::big_h); l->area(gui::Item::Area::Max).w = box->area().w; // let box layout resize decorate(l); l->setText(contact.primaryName); @@ -51,8 +51,12 @@ gui::HBox *newCombo(app::ApplicationMessages *app, const ContactRecord &contact) gui::Item *placeholder(const UTF8 &text) { - auto ret = new gui::Rect(nullptr, default_left_margin, 0, style::window_width - default_left_margin - default_right_margin, label::small_h); - auto t = new gui::Label(ret, 0, 0, 0, 0, text); + auto ret = new gui::Rect(nullptr, + default_left_margin, + 0, + style::window_width - default_left_margin - default_right_margin, + label::small_h); + auto t = new gui::Label(ret, 0, 0, 0, 0, text); auto width = t->getTextNeedSpace() + 20; t->setSize(width, label::small_h); @@ -73,10 +77,16 @@ std::list smsWindowOptions(app::ApplicationMessages *app, const SMS gui::newOptionLabel(gui::options::contact(app, app::ContactOperation::Details, contact)), // TODO - gui::newOptionLabel( - {UTF8(" ") + UTF8(utils::localize.get("sms_forvard_message")), [=](gui::Item &item) { return false; }, gui::Arrow::Disabled}), - gui::newOptionLabel({UTF8(" ") + UTF8(utils::localize.get("sms_copy")), [=](gui::Item &item) { return false; }, gui::Arrow::Disabled}), - gui::newOptionLabel({UTF8(" ") + UTF8(utils::localize.get("sms_delete_message")), [=](gui::Item &item) { return false; }, gui::Arrow::Disabled}), - placeholder(utils::localize.get("sms_from_this_sms")), newCombo(app, contact) // contact.numbers[0].numberE164) + gui::newOptionLabel({UTF8(" ") + UTF8(utils::localize.get("sms_forvard_message")), + [=](gui::Item &item) { return false; }, + gui::Arrow::Disabled}), + gui::newOptionLabel({UTF8(" ") + UTF8(utils::localize.get("sms_copy")), + [=](gui::Item &item) { return false; }, + gui::Arrow::Disabled}), + gui::newOptionLabel({UTF8(" ") + UTF8(utils::localize.get("sms_delete_message")), + [=](gui::Item &item) { return false; }, + gui::Arrow::Disabled}), + placeholder(utils::localize.get("sms_from_this_sms")), + newCombo(app, contact) // contact.numbers[0].numberE164) }; } diff --git a/module-apps/application-messages/windows/ThreadViewWindow.cpp b/module-apps/application-messages/windows/ThreadViewWindow.cpp index 4c77eae9f..9ee54b881 100644 --- a/module-apps/application-messages/windows/ThreadViewWindow.cpp +++ b/module-apps/application-messages/windows/ThreadViewWindow.cpp @@ -32,9 +32,7 @@ #include "service-db/api/DBServiceAPI.hpp" namespace style -{ - -}; // namespace style +{}; // namespace style namespace gui { @@ -50,24 +48,24 @@ namespace gui bottomBar->setText(BottomBar::Side::LEFT, utils::localize.get("common_options")); bottomBar->setText(BottomBar::Side::CENTER, utils::localize.get("common_send")); bottomBar->setText(BottomBar::Side::RIGHT, utils::localize.get("common_back")); - body = new gui::VBox(this, style::window::default_left_margin, title->offset_h(), elements_width, bottomBar->getY() - title->offset_h()); + body = new gui::VBox(this, + style::window::default_left_margin, + title->offset_h(), + elements_width, + bottomBar->getY() - title->offset_h()); body->setPenWidth(style::window::default_border_no_focus_w); body->setPenFocusWidth(style::window::default_border_no_focus_w); body->borderCallback = [this](const InputEvent &inputEvent) -> bool { - if (inputEvent.state != InputEvent::State::keyReleasedShort) - { + if (inputEvent.state != InputEvent::State::keyReleasedShort) { return false; } - if (inputEvent.keyCode == KeyCode::KEY_UP) - { + if (inputEvent.keyCode == KeyCode::KEY_UP) { return this->showMessages(Action::Next); } - else if (inputEvent.keyCode == KeyCode::KEY_DOWN) - { + else if (inputEvent.keyCode == KeyCode::KEY_DOWN) { return this->showMessages(Action::Previous); } - else - { + else { return false; } }; @@ -81,28 +79,29 @@ namespace gui void ThreadViewWindow::rebuildText() { - if (text) - { + if (text) { body->removeWidget(text); } - text = new gui::Text(nullptr, 0, 0, body->getWidth(), style::window::messages::sms_height, "", gui::Text::ExpandMode::EXPAND_UP); + text = new gui::Text( + nullptr, 0, 0, body->getWidth(), style::window::messages::sms_height, "", gui::Text::ExpandMode::EXPAND_UP); text->setInputMode(new InputMode( - {InputMode::ABC, InputMode::abc}, [=](const UTF8 &text) { textModeShowCB(text); }, [=]() { textSelectSpecialCB(); })); + {InputMode::ABC, InputMode::abc}, + [=](const UTF8 &text) { textModeShowCB(text); }, + [=]() { textSelectSpecialCB(); })); text->setPenFocusWidth(style::window::default_border_focucs_w); text->setPenWidth(style::window::default_border_focucs_w); text->setEdges(gui::RectangleEdgeFlags::GUI_RECT_EDGE_BOTTOM); text->activatedCallback = [&](gui::Item &item) { - if (text->getText().length() == 0) - { + if (text->getText().length() == 0) { LOG_DEBUG("No text to send in SMS"); return true; } SMSRecord record; record.number = title->getText(); - record.body = text->getText(); - record.type = SMSType::QUEUED; - auto time = utils::time::Timestamp(); - record.date = time.getTime(); + record.body = text->getText(); + record.type = SMSType::QUEUED; + auto time = utils::time::Timestamp(); + record.date = time.getTime(); DBServiceAPI::SMSAdd(this->application, record); return true; @@ -119,8 +118,7 @@ namespace gui bool ThreadViewWindow::showMessages(ThreadViewWindow::Action what) { - if (SMS.thread <= 0) - { + if (SMS.thread <= 0) { LOG_ERROR("threadID not set!"); return false; } @@ -136,39 +134,31 @@ namespace gui // 1. load elements to tmp vector SMS.dbsize = DBServiceAPI::SMSGetCount(this->application); LOG_DEBUG("start: %d end: %d db: %d", SMS.start, SMS.end, SMS.dbsize); - if (what == Action::Start) - { + if (what == Action::Start) { SMS.start = 0; - SMS.end = maxsmsinwindow; + SMS.end = maxsmsinwindow; rebuildText(); } // TODO 2. check how many of these will fit in box // update begin / end in `SMS` - if (what == Action::Next) - { - if (SMS.end != SMS.dbsize) - { + if (what == Action::Next) { + if (SMS.end != SMS.dbsize) { SMS.start = SMS.end; } - else - { + else { LOG_INFO("All sms shown"); return; } } - else if (what == Action::Previous) - { - if (SMS.start == 0) - { + else if (what == Action::Previous) { + if (SMS.start == 0) { return; } - else if (SMS.start - maxsmsinwindow < 0) - { + else if (SMS.start - maxsmsinwindow < 0) { SMS.start = 0; } - else - { + else { SMS.start -= maxsmsinwindow; } LOG_DEBUG("in progress %d", SMS.start); @@ -178,25 +168,21 @@ namespace gui // 3. add them to box this->cleanView(); // if we are going from 0 then we want to show text prompt - if (SMS.start == 0) - { + if (SMS.start == 0) { body->addWidget(text); } SMS.end = SMS.start; - for (auto &el : *SMS.sms) - { + for (auto &el : *SMS.sms) { LOG_DEBUG("..."); - if (!smsBuild(el, false)) - { + if (!smsBuild(el, false)) { break; } ++SMS.end; } body->setNavigation(); setFocusItem(body); - if (Action::Previous == what) - { + if (Action::Previous == what) { body->setVisible(true, true); } LOG_DEBUG("sms built"); @@ -211,17 +197,19 @@ namespace gui labelSpan->setSize(elements_width, smsBubble->getHeight()); labelSpan->addWidget(smsBubble); - auto timeLabel = new gui::Label(nullptr, 0, 0, 0, smsBubble->getHeight()); + auto timeLabel = new gui::Label(nullptr, 0, 0, 0, smsBubble->getHeight()); timeLabel->activeItem = false; timeLabel->setFont(style::window::font::verysmall); timeLabel->setText(utils::time::Time(timestamp)); timeLabel->setSize(timeLabel->getTextNeedSpace(), timeLabel->getHeight()); timeLabel->setPenWidth(style::window::default_border_no_focus_w); timeLabel->setVisible(false); - timeLabel->setAlignement(gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_CENTER, gui::Alignment::ALIGN_VERTICAL_CENTER)); + timeLabel->setAlignement( + gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_CENTER, gui::Alignment::ALIGN_VERTICAL_CENTER)); - uint16_t dateLabelSpacerWidth = (elements_width - smsBubble->getWidth() - timeLabel->getWidth() - smsBubble->yapSize); - auto timeLabelSpacer = new gui::Label(nullptr, 0, 0, dateLabelSpacerWidth, smsBubble->getHeight()); + uint16_t dateLabelSpacerWidth = + (elements_width - smsBubble->getWidth() - timeLabel->getWidth() - smsBubble->yapSize); + auto timeLabelSpacer = new gui::Label(nullptr, 0, 0, dateLabelSpacerWidth, smsBubble->getHeight()); timeLabelSpacer->activeItem = false; timeLabelSpacer->setPenWidth(0); @@ -235,8 +223,7 @@ namespace gui return true; }; - if (!smsBubble->visible) - { + if (!smsBubble->visible) { delete labelSpan; // total fail labelSpan = nullptr; } @@ -257,19 +244,19 @@ namespace gui label->expandMode = Text::ExpandMode::EXPAND_DOWN; label->buildDrawList(); label->setText(el.body.length() ? el.body : " "); // text doesn't really like being empty// - label->setMargins(gui::Margins(style::window::messages::sms_h_padding, style::window::messages::sms_v_padding, style::window::messages::sms_h_padding, + label->setMargins(gui::Margins(style::window::messages::sms_h_padding, + style::window::messages::sms_v_padding, + style::window::messages::sms_h_padding, style::window::messages::sms_v_padding)); label->activatedCallback = [=](Item &) { LOG_INFO("Message activated!"); auto app = dynamic_cast(application); - if (app == nullptr) - { + if (app == nullptr) { LOG_ERROR("Something went horribly wrong"); return false; } - if (app->windowOptions != nullptr) - { + if (app->windowOptions != nullptr) { app->windowOptions->clearOptions(); app->windowOptions->addOptions(smsWindowOptions(app, el)); app->switchWindow(app->windowOptions->getName(), nullptr); @@ -282,8 +269,7 @@ namespace gui // TODO dashed (dotted) outline LOG_DEBUG("ADD SMS TYPE: %d", el.type); - switch (el.type) - { + switch (el.type) { case SMSType::OUTBOX: label->setYaps(RectangleYapFlags::GUI_RECT_YAP_TOP_RIGHT); label->setX(body->getWidth() - label->getWidth()); @@ -297,12 +283,12 @@ namespace gui break; } - if (labelSpan == nullptr) - { + if (labelSpan == nullptr) { return false; } - auto verticalSpacer = new gui::Rect(nullptr, 0, 0, elements_width, style::window::messages::sms_vertical_spacer); + auto verticalSpacer = + new gui::Rect(nullptr, 0, 0, elements_width, style::window::messages::sms_vertical_spacer); verticalSpacer->activeItem = false; verticalSpacer->setPenWidth(style::window::default_border_no_focus_w); body->addWidget(verticalSpacer); @@ -318,8 +304,7 @@ namespace gui } void ThreadViewWindow::buildInterface() - { - } + {} void ThreadViewWindow::destroyInterface() { @@ -336,8 +321,7 @@ namespace gui { { auto pdata = dynamic_cast(data); - if (pdata) - { + if (pdata) { LOG_INFO("We have it! %d", pdata->thread->dbID); cleanView(); SMS.thread = pdata->thread->dbID; @@ -350,19 +334,20 @@ namespace gui } { auto pdata = dynamic_cast(data); - if (pdata) - { + if (pdata) { LOG_INFO("Phonebook sms send request!"); // TODO agree what should be used and how. Now Request have only contact, // maybe it should have additional info - which nr to use and how to show it - if (pdata->contact->numbers.size() != 0) - { - LOG_DEBUG("SEND SMS TO: %s %s %s %s %s", pdata->contact->number.c_str(), pdata->contact->numbers[0].numberE164.c_str(), - pdata->contact->numbers[0].numberUser.c_str(), pdata->contact->primaryName.c_str(), pdata->contact->alternativeName.c_str()); + if (pdata->contact->numbers.size() != 0) { + LOG_DEBUG("SEND SMS TO: %s %s %s %s %s", + pdata->contact->number.c_str(), + pdata->contact->numbers[0].numberE164.c_str(), + pdata->contact->numbers[0].numberUser.c_str(), + pdata->contact->primaryName.c_str(), + pdata->contact->alternativeName.c_str()); setTitle(pdata->contact->numbers[0].numberUser); } - else - { + else { // TODO handle error better setTitle("NO CONTACT"); } @@ -378,8 +363,8 @@ namespace gui bool ThreadViewWindow::onDatabaseMessage(sys::Message *msgl) { // DBContactResponseMessage* msg = reinterpret_cast( msgl ); - // if( phonebookModel->updateRecords( std::move(msg->records), msg->offset, msg->limit, msg->count, msg->favourite ) ) - // return true; + // if( phonebookModel->updateRecords( std::move(msg->records), msg->offset, msg->limit, msg->count, + //msg->favourite ) ) return true; return false; } diff --git a/module-apps/application-messages/windows/ThreadViewWindow.hpp b/module-apps/application-messages/windows/ThreadViewWindow.hpp index 0b5bc076e..7b99b6b82 100644 --- a/module-apps/application-messages/windows/ThreadViewWindow.hpp +++ b/module-apps/application-messages/windows/ThreadViewWindow.hpp @@ -26,7 +26,7 @@ namespace gui class ThreadViewWindow : public AppWindow { private: - gui::VBox *body = nullptr; + gui::VBox *body = nullptr; uint16_t elements_width = this->getWidth() - style::window::default_left_margin * 2; void cleanView(); enum class Action @@ -44,10 +44,10 @@ namespace gui struct { - int start = 0; // actual shown position start - int end = 7; // actual shown position end - int thread = 0; // thread we are showing - int dbsize = 0; // size of elements in db + int start = 0; // actual shown position start + int end = 7; // actual shown position end + int thread = 0; // thread we are showing + int dbsize = 0; // size of elements in db std::unique_ptr> sms = nullptr; // loaded sms from db } SMS; diff --git a/module-apps/application-notes/ApplicationNotes.cpp b/module-apps/application-notes/ApplicationNotes.cpp index 5dd391141..178e56298 100644 --- a/module-apps/application-notes/ApplicationNotes.cpp +++ b/module-apps/application-notes/ApplicationNotes.cpp @@ -13,79 +13,82 @@ #include "ApplicationNotes.hpp" -namespace app { +namespace app +{ -ApplicationNotes::ApplicationNotes(std::string name, std::string parent, bool startBackgound) : - Application( name, parent, startBackgound, 4096 ) { -} + ApplicationNotes::ApplicationNotes(std::string name, std::string parent, bool startBackgound) + : Application(name, parent, startBackgound, 4096) + {} -ApplicationNotes::~ApplicationNotes() { - LOG_INFO("deleting"); -} - -// Invoked upon receiving data message -sys::Message_t ApplicationNotes::DataReceivedHandler(sys::DataMessage* msgl,sys::ResponseMessage* resp) { - - auto retMsg = Application::DataReceivedHandler(msgl); - //if message was handled by application's template there is no need to process further. - if( (reinterpret_cast( retMsg.get() )->retCode == sys::ReturnCodes::Success ) ){ - return retMsg; - } - - - bool handled = false; - - //handle database response - if( resp != nullptr ) { - handled = true; - switch (resp->responseTo) - { - case MessageType::DBNotesGetLimitOffset: { - if (getCurrentWindow()->onDatabaseMessage(resp)) - refreshWindow(gui::RefreshModes::GUI_REFRESH_FAST); - } - break; - default: - break; - } + ApplicationNotes::~ApplicationNotes() + { + LOG_INFO("deleting"); } - if( handled ) - return std::make_shared(); - else - return std::make_shared(sys::ReturnCodes::Unresolved); -} + // Invoked upon receiving data message + sys::Message_t ApplicationNotes::DataReceivedHandler(sys::DataMessage *msgl, sys::ResponseMessage *resp) + { -// Invoked during initialization -sys::ReturnCodes ApplicationNotes::InitHandler() { + auto retMsg = Application::DataReceivedHandler(msgl); + // if message was handled by application's template there is no need to process further. + if ((reinterpret_cast(retMsg.get())->retCode == sys::ReturnCodes::Success)) { + return retMsg; + } - auto ret = Application::InitHandler(); - if( ret != sys::ReturnCodes::Success ) - return ret; + bool handled = false; - createUserInterface(); + // handle database response + if (resp != nullptr) { + handled = true; + switch (resp->responseTo) { + case MessageType::DBNotesGetLimitOffset: { + if (getCurrentWindow()->onDatabaseMessage(resp)) + refreshWindow(gui::RefreshModes::GUI_REFRESH_FAST); + } break; + default: + break; + } + } - setActiveWindow(gui::name::window::main_window); + if (handled) + return std::make_shared(); + else + return std::make_shared(sys::ReturnCodes::Unresolved); + } - return ret; -} + // Invoked during initialization + sys::ReturnCodes ApplicationNotes::InitHandler() + { -sys::ReturnCodes ApplicationNotes::DeinitHandler() { - return sys::ReturnCodes::Success; -} + auto ret = Application::InitHandler(); + if (ret != sys::ReturnCodes::Success) + return ret; -void ApplicationNotes::createUserInterface() { + createUserInterface(); - gui::AppWindow* window = nullptr; + setActiveWindow(gui::name::window::main_window); - window = new gui::NotesMainWindow(this); - windows.insert(std::pair(window->getName(), window)); + return ret; + } - window = new gui::NotesEditWindow(this); - windows.insert(std::pair(window->getName(), window)); -} + sys::ReturnCodes ApplicationNotes::DeinitHandler() + { + return sys::ReturnCodes::Success; + } -void ApplicationNotes::destroyUserInterface() { -} + void ApplicationNotes::createUserInterface() + { + + gui::AppWindow *window = nullptr; + + window = new gui::NotesMainWindow(this); + windows.insert(std::pair(window->getName(), window)); + + window = new gui::NotesEditWindow(this); + windows.insert(std::pair(window->getName(), window)); + } + + void ApplicationNotes::destroyUserInterface() + {} } /* namespace app */ diff --git a/module-apps/application-notes/ApplicationNotes.hpp b/module-apps/application-notes/ApplicationNotes.hpp index efb8e86dc..971d947cc 100644 --- a/module-apps/application-notes/ApplicationNotes.hpp +++ b/module-apps/application-notes/ApplicationNotes.hpp @@ -12,29 +12,30 @@ #include "NotesModel.hpp" #include "Application.hpp" -namespace app { +namespace app +{ -inline const std::string name_notes = "ApplicationNotes"; + inline const std::string name_notes = "ApplicationNotes"; -class ApplicationNotes: public Application { -protected: + class ApplicationNotes : public Application + { + protected: + public: + ApplicationNotes(std::string name = name_notes, std::string parent = "", bool startBackgound = false); + virtual ~ApplicationNotes(); + sys::Message_t DataReceivedHandler(sys::DataMessage *msgl, sys::ResponseMessage *resp) override; + sys::ReturnCodes InitHandler() override; + sys::ReturnCodes DeinitHandler() override; -public: - ApplicationNotes( std::string name=name_notes, std::string parent = "", bool startBackgound = false); - virtual ~ApplicationNotes(); - sys::Message_t DataReceivedHandler(sys::DataMessage* msgl,sys::ResponseMessage* resp) override; - sys::ReturnCodes InitHandler() override; - sys::ReturnCodes DeinitHandler() override; + sys::ReturnCodes SwitchPowerModeHandler(const sys::ServicePowerMode mode) override final + { + return sys::ReturnCodes::Success; + } - sys::ReturnCodes SwitchPowerModeHandler(const sys::ServicePowerMode mode) override final{return sys::ReturnCodes::Success;} - - void createUserInterface() override; - void destroyUserInterface() override; -}; + void createUserInterface() override; + void destroyUserInterface() override; + }; } /* namespace app */ - - - #endif /* MODULE_APPS_APPLICATION_NOTES_APPLICATIONNOTES_HPP_ */ diff --git a/module-apps/application-notes/NotesModel.cpp b/module-apps/application-notes/NotesModel.cpp index 25ba6c42c..c7315816d 100644 --- a/module-apps/application-notes/NotesModel.cpp +++ b/module-apps/application-notes/NotesModel.cpp @@ -11,59 +11,67 @@ #include "NotesModel.hpp" -NotesModel::NotesModel( app::Application* app) : DatabaseModel(app, 3){ +NotesModel::NotesModel(app::Application *app) : DatabaseModel(app, 3) +{} +NotesModel::~NotesModel() +{} + +void NotesModel::requestRecordsCount() +{ + uint32_t start = xTaskGetTickCount(); + recordsCount = DBServiceAPI::NotesGetCount(application); + uint32_t stop = xTaskGetTickCount(); + LOG_INFO("DBServiceAPI::NotesGetCount %d records %d ms", recordsCount, stop - start); + + // request first and second page if possible + if (recordsCount > 0) { + DBServiceAPI::NotesGetLimitOffset(application, 0, pageSize); + if (recordsCount > pageSize) { + DBServiceAPI::NotesGetLimitOffset(application, pageSize, pageSize); + } + } } -NotesModel::~NotesModel() { +void NotesModel::requestRecords(const uint32_t offset, const uint32_t limit) +{ + DBServiceAPI::NotesGetLimitOffset(application, offset, limit); } -void NotesModel::requestRecordsCount() { - uint32_t start = xTaskGetTickCount(); - recordsCount = DBServiceAPI::NotesGetCount(application); - uint32_t stop = xTaskGetTickCount(); - LOG_INFO("DBServiceAPI::NotesGetCount %d records %d ms", recordsCount, stop-start); +bool NotesModel::updateRecords(std::unique_ptr> records, + const uint32_t offset, + const uint32_t limit, + uint32_t count) +{ - //request first and second page if possible - if( recordsCount > 0 ){ - DBServiceAPI::NotesGetLimitOffset(application, 0, pageSize ); - if( recordsCount > pageSize ) { - DBServiceAPI::NotesGetLimitOffset(application, pageSize, pageSize ); - } - } + // LOG_INFO("Offset: %d, Limit: %d Count:%d", offset, limit, count); + // for( uint32_t i=0; isize(); ++i ) { + // LOG_INFO("id: %d, filename: %s", records.get()->operator [](i).ID, records.get()->operator + //[](i).path.c_str()); + // } + + DatabaseModel::updateRecords(std::move(records), offset, limit, count); + + return true; } -void NotesModel::requestRecords( const uint32_t offset, const uint32_t limit ) { - DBServiceAPI::NotesGetLimitOffset(application, offset, limit ); -} - -bool NotesModel::updateRecords( std::unique_ptr> records, const uint32_t offset, const uint32_t limit, uint32_t count ) { - -// LOG_INFO("Offset: %d, Limit: %d Count:%d", offset, limit, count); -// for( uint32_t i=0; isize(); ++i ) { -// LOG_INFO("id: %d, filename: %s", records.get()->operator [](i).ID, records.get()->operator [](i).path.c_str()); -// } - - DatabaseModel::updateRecords( std::move(records), offset, limit, count ); - - return true; -} - -gui::ListItem* NotesModel::getItem( int index, int firstElement, int prevElement, uint32_t count, int remaining, bool topDown ) { - - std::shared_ptr note = getRecord( index ); - - SettingsRecord& settings = application->getSettings(); - - if( note == nullptr ) - return nullptr; - - gui::NotesItem* item = new gui::NotesItem(this, !settings.timeFormat12 ); - if( item != nullptr ) { - item->setNote(note); - item->setID( index ); - return item; - } - - return nullptr; +gui::ListItem *NotesModel::getItem( + int index, int firstElement, int prevElement, uint32_t count, int remaining, bool topDown) +{ + + std::shared_ptr note = getRecord(index); + + SettingsRecord &settings = application->getSettings(); + + if (note == nullptr) + return nullptr; + + gui::NotesItem *item = new gui::NotesItem(this, !settings.timeFormat12); + if (item != nullptr) { + item->setNote(note); + item->setID(index); + return item; + } + + return nullptr; } diff --git a/module-apps/application-notes/NotesModel.hpp b/module-apps/application-notes/NotesModel.hpp index e22fae6b8..bf0b0d5dc 100644 --- a/module-apps/application-notes/NotesModel.hpp +++ b/module-apps/application-notes/NotesModel.hpp @@ -20,19 +20,27 @@ /* * */ -class NotesModel: public app::DatabaseModel, public gui::ListItemProvider { -public: - NotesModel( app::Application* app ); - virtual ~NotesModel(); +class NotesModel : public app::DatabaseModel, public gui::ListItemProvider +{ + public: + NotesModel(app::Application *app); + virtual ~NotesModel(); - //virtual methods - void requestRecordsCount() override; - bool updateRecords( std::unique_ptr> records, const uint32_t offset, const uint32_t limit, uint32_t count ) override; - void requestRecords( const uint32_t offset, const uint32_t limit ) override; + // virtual methods + void requestRecordsCount() override; + bool updateRecords(std::unique_ptr> records, + const uint32_t offset, + const uint32_t limit, + uint32_t count) override; + void requestRecords(const uint32_t offset, const uint32_t limit) override; - //virtual methods for ListViewProvider - gui::ListItem* getItem( int index, int firstElement, int prevElement, uint32_t count, int remaining, bool topDown ) override; - int getItemCount() const override { return recordsCount; }; + // virtual methods for ListViewProvider + gui::ListItem *getItem( + int index, int firstElement, int prevElement, uint32_t count, int remaining, bool topDown) override; + int getItemCount() const override + { + return recordsCount; + }; }; #endif /* MODULE_APPS_APPLICATION_NOTES_NOTESMODEL_HPP_ */ diff --git a/module-apps/application-notes/widgets/NotesItem.cpp b/module-apps/application-notes/widgets/NotesItem.cpp index 961815070..fa9d16084 100644 --- a/module-apps/application-notes/widgets/NotesItem.cpp +++ b/module-apps/application-notes/widgets/NotesItem.cpp @@ -9,67 +9,72 @@ #include "NotesItem.hpp" #include -namespace gui { +namespace gui +{ -NotesItem::NotesItem(NotesModel* model, bool mode24H) : model{model}, mode24H{mode24H} { - minWidth = 436; - minHeight = 146; - maxWidth = 436; - maxHeight = 146; + NotesItem::NotesItem(NotesModel *model, bool mode24H) : model{model}, mode24H{mode24H} + { + minWidth = 436; + minHeight = 146; + maxWidth = 436; + maxHeight = 146; - setRadius( 8 ); + setRadius(8); - setPenFocusWidth(3); - setPenWidth(1); + setPenFocusWidth(3); + setPenWidth(1); - hour = new gui::Label( this, 0,0,0,0); - hour->setPenFocusWidth(0); - hour->setPenWidth(0); - hour->setFont(style::window::font::medium); - hour->setAlignement(gui::Alignment { gui::Alignment::ALIGN_HORIZONTAL_RIGHT, gui::Alignment::ALIGN_VERTICAL_TOP } ); + hour = new gui::Label(this, 0, 0, 0, 0); + hour->setPenFocusWidth(0); + hour->setPenWidth(0); + hour->setFont(style::window::font::medium); + hour->setAlignement(gui::Alignment{gui::Alignment::ALIGN_HORIZONTAL_RIGHT, gui::Alignment::ALIGN_VERTICAL_TOP}); - title = new gui::Label( this, 0,0,0,0); - title->setPenFocusWidth(0); - title->setPenWidth(0); - title->setFont(style::window::font::bigbold); - title->setAlignement(gui::Alignment { gui::Alignment::ALIGN_HORIZONTAL_LEFT, gui::Alignment::ALIGN_VERTICAL_TOP } ); + title = new gui::Label(this, 0, 0, 0, 0); + title->setPenFocusWidth(0); + title->setPenWidth(0); + title->setFont(style::window::font::bigbold); + title->setAlignement(gui::Alignment{gui::Alignment::ALIGN_HORIZONTAL_LEFT, gui::Alignment::ALIGN_VERTICAL_TOP}); - snippet = new gui::Label( this, 0,0,0,0); - snippet->setPenFocusWidth(0); - snippet->setPenWidth(0); - snippet->setFont(style::window::font::small); - snippet->setAlignement(gui::Alignment { gui::Alignment::ALIGN_HORIZONTAL_LEFT, gui::Alignment::ALIGN_VERTICAL_CENTER} ); + snippet = new gui::Label(this, 0, 0, 0, 0); + snippet->setPenFocusWidth(0); + snippet->setPenWidth(0); + snippet->setFont(style::window::font::small); + snippet->setAlignement( + gui::Alignment{gui::Alignment::ALIGN_HORIZONTAL_LEFT, gui::Alignment::ALIGN_VERTICAL_CENTER}); + } -} + NotesItem::~NotesItem() + { + note = nullptr; + } -NotesItem::~NotesItem() { - note = nullptr; -} + bool NotesItem::onDimensionChanged(const BoundingBox &oldDim, const BoundingBox &newDim) + { + hour->setPosition(11, 0); + hour->setSize(newDim.w - 22, 40); -bool NotesItem::onDimensionChanged( const BoundingBox& oldDim, const BoundingBox& newDim) { - hour->setPosition(11, 0 ); - hour->setSize(newDim.w-22, 40 ); + title->setPosition(11, 0); + title->setSize(68, 40); - title->setPosition(11, 0 ); - title->setSize(68, 40 ); + snippet->setPosition(11, 40); + snippet->setSize(newDim.w - 22, newDim.h - 40); + return true; + } - snippet->setPosition(11, 40 ); - snippet->setSize(newDim.w-22, newDim.h-40 ); - return true; -} - -//sets copy of alarm's -void NotesItem::setNote( std::shared_ptr& note ) { - this->note = note; - //set values of the labels - title->setText( std::to_string( note->ID)); - snippet->setText( note->path ); -} - -bool NotesItem::onActivated( void* data ) { - LOG_INFO("ITEM WAS PRESSED"); - return true; -} + // sets copy of alarm's + void NotesItem::setNote(std::shared_ptr ¬e) + { + this->note = note; + // set values of the labels + title->setText(std::to_string(note->ID)); + snippet->setText(note->path); + } + bool NotesItem::onActivated(void *data) + { + LOG_INFO("ITEM WAS PRESSED"); + return true; + } } /* namespace gui */ diff --git a/module-apps/application-notes/widgets/NotesItem.hpp b/module-apps/application-notes/widgets/NotesItem.hpp index 1e46c45a9..657364e20 100644 --- a/module-apps/application-notes/widgets/NotesItem.hpp +++ b/module-apps/application-notes/widgets/NotesItem.hpp @@ -9,40 +9,41 @@ #ifndef MODULE_APPS_APPLICATION_NOTES_WIDGETS_NOTESITEM_HPP_ #define MODULE_APPS_APPLICATION_NOTES_WIDGETS_NOTESITEM_HPP_ - #include "Label.hpp" #include "ListItem.hpp" #include "../NotesModel.hpp" -namespace gui { +namespace gui +{ -/* - * @brief Widget used to display information about note in the notes list view. - */ -class NotesItem: public ListItem { + /* + * @brief Widget used to display information about note in the notes list view. + */ + class NotesItem : public ListItem + { - NotesModel* model = nullptr; - //pointer to the notes record - std::shared_ptr note = nullptr; - //this is hour in the mode defined in settings - gui::Label* hour = nullptr; - gui::Label* title = nullptr; - gui::Label* snippet = nullptr; - //flag that defines if time should be displayed in 24h mode - bool mode24H = false; + NotesModel *model = nullptr; + // pointer to the notes record + std::shared_ptr note = nullptr; + // this is hour in the mode defined in settings + gui::Label *hour = nullptr; + gui::Label *title = nullptr; + gui::Label *snippet = nullptr; + // flag that defines if time should be displayed in 24h mode + bool mode24H = false; - public: - NotesItem( NotesModel* model, bool mode24H ); - virtual ~NotesItem(); - //sets copy of alarm's - void setNote( std::shared_ptr& note ); + public: + NotesItem(NotesModel *model, bool mode24H); + virtual ~NotesItem(); + // sets copy of alarm's + void setNote(std::shared_ptr ¬e); - //returns alarm structure - std::shared_ptr getAlarm(); - //virtual methods from Item - bool onDimensionChanged( const BoundingBox& oldDim, const BoundingBox& newDim) override; - bool onActivated( void* data ) override; -}; + // returns alarm structure + std::shared_ptr getAlarm(); + // virtual methods from Item + bool onDimensionChanged(const BoundingBox &oldDim, const BoundingBox &newDim) override; + bool onActivated(void *data) override; + }; } /* namespace gui */ diff --git a/module-apps/application-notes/windows/NotesEditWindow.cpp b/module-apps/application-notes/windows/NotesEditWindow.cpp index 705224ee4..234068e66 100644 --- a/module-apps/application-notes/windows/NotesEditWindow.cpp +++ b/module-apps/application-notes/windows/NotesEditWindow.cpp @@ -26,68 +26,77 @@ #include UTF8 textString = "Very long test line ABCDEFGHIJKLMNOPQRST123456789\n" - "abcdefghijklmnopqrs 123456789 ABCDEFGHIJKLMONPQRSTUW 12345\n test\nnew line\n\n\n12345"; + "abcdefghijklmnopqrs 123456789 ABCDEFGHIJKLMONPQRSTUW 12345\n test\nnew line\n\n\n12345"; -namespace gui { +namespace gui +{ -NotesEditWindow::NotesEditWindow( app::Application* app ) : - AppWindow(app,"EditWindow") { - buildInterface(); -} + NotesEditWindow::NotesEditWindow(app::Application *app) : AppWindow(app, "EditWindow") + { + buildInterface(); + } -void NotesEditWindow::rebuild() { - destroyInterface(); - buildInterface(); -} -void NotesEditWindow::buildInterface() { - AppWindow::buildInterface(); + void NotesEditWindow::rebuild() + { + destroyInterface(); + buildInterface(); + } + void NotesEditWindow::buildInterface() + { + AppWindow::buildInterface(); - bottomBar->setActive( BottomBar::Side::CENTER, true ); - bottomBar->setActive( BottomBar::Side::RIGHT, true ); - bottomBar->setText( BottomBar::Side::CENTER, utils::localize.get("app_notes_save")); - bottomBar->setText( BottomBar::Side::RIGHT, utils::localize.get("app_notes_back")); + bottomBar->setActive(BottomBar::Side::CENTER, true); + bottomBar->setActive(BottomBar::Side::RIGHT, true); + bottomBar->setText(BottomBar::Side::CENTER, utils::localize.get("app_notes_save")); + bottomBar->setText(BottomBar::Side::RIGHT, utils::localize.get("app_notes_back")); - setTitle(utils::localize.get("app_notes_new_note")); + setTitle(utils::localize.get("app_notes_new_note")); - text = new gui::Text( this, 11, 105, 480-22, 600-105-50 ); - text->setFont(style::window::font::medium); - text->setRadius(5); - text->setMargins( gui::Margins(10, 5, 10, 5)); - text->activatedCallback = [=] (gui::Item& item){ - UTF8 getstr = text->getText(); - time_t timestamp; - bsp::rtc_GetCurrentTimestamp(×tamp); + text = new gui::Text(this, 11, 105, 480 - 22, 600 - 105 - 50); + text->setFont(style::window::font::medium); + text->setRadius(5); + text->setMargins(gui::Margins(10, 5, 10, 5)); + text->activatedCallback = [=](gui::Item &item) { + UTF8 getstr = text->getText(); + time_t timestamp; + bsp::rtc_GetCurrentTimestamp(×tamp); - UTF8 filename = "sys/data/applications/notes/" + std::to_string(timestamp) + ".txt"; + UTF8 filename = "sys/data/applications/notes/" + std::to_string(timestamp) + ".txt"; - auto file = vfs.fopen( filename.c_str(), "wb" ); - vfs.fwrite( getstr.c_str(), getstr.used()-1, 1, file ); - vfs.fclose( file ); - return true; }; - text->setTextType( gui::Text::TextType::MULTI_LINE ); - text->setEditMode(gui::Text::EditMode::BROWSE ); - text->setInputMode(new InputMode({InputMode::ABC, InputMode::abc})); + auto file = vfs.fopen(filename.c_str(), "wb"); + vfs.fwrite(getstr.c_str(), getstr.used() - 1, 1, file); + vfs.fclose(file); + return true; + }; + text->setTextType(gui::Text::TextType::MULTI_LINE); + text->setEditMode(gui::Text::EditMode::BROWSE); + text->setInputMode(new InputMode({InputMode::ABC, InputMode::abc})); - topBar->setActive(TopBar::Elements::TIME, true ); -} + topBar->setActive(TopBar::Elements::TIME, true); + } -void NotesEditWindow::destroyInterface() { - AppWindow::destroyInterface(); + void NotesEditWindow::destroyInterface() + { + AppWindow::destroyInterface(); - if( text ) { removeWidget(text); delete text; text = nullptr; } + if (text) { + removeWidget(text); + delete text; + text = nullptr; + } - children.clear(); -} + children.clear(); + } -NotesEditWindow::~NotesEditWindow() { - destroyInterface(); -} + NotesEditWindow::~NotesEditWindow() + { + destroyInterface(); + } -void NotesEditWindow::onBeforeShow( ShowMode mode, SwitchData* data ) { - text->setText( textString ); - setFocusItem( text ); -} + void NotesEditWindow::onBeforeShow(ShowMode mode, SwitchData *data) + { + text->setText(textString); + setFocusItem(text); + } } /* namespace gui */ - - diff --git a/module-apps/application-notes/windows/NotesEditWindow.hpp b/module-apps/application-notes/windows/NotesEditWindow.hpp index c7a062879..bcbcae010 100644 --- a/module-apps/application-notes/windows/NotesEditWindow.hpp +++ b/module-apps/application-notes/windows/NotesEditWindow.hpp @@ -21,22 +21,25 @@ #include "gui/widgets/TopBar.hpp" #include "gui/widgets/ListView.hpp" -namespace gui { +namespace gui +{ -class NotesEditWindow: public AppWindow { - Text* text = nullptr; - Label* title = nullptr; -public: - NotesEditWindow( app::Application* app ); - virtual ~NotesEditWindow(); + class NotesEditWindow : public AppWindow + { + Text *text = nullptr; + Label *title = nullptr; - //virtual methods - void onBeforeShow( ShowMode mode, SwitchData* data ) override; + public: + NotesEditWindow(app::Application *app); + virtual ~NotesEditWindow(); - void rebuild() override; - void buildInterface() override; - void destroyInterface() override; -}; + // virtual methods + void onBeforeShow(ShowMode mode, SwitchData *data) override; + + void rebuild() override; + void buildInterface() override; + void destroyInterface() override; + }; } /* namespace gui */ diff --git a/module-apps/application-notes/windows/NotesMainWindow.cpp b/module-apps/application-notes/windows/NotesMainWindow.cpp index 3f76b2c8d..c98e37fe6 100644 --- a/module-apps/application-notes/windows/NotesMainWindow.cpp +++ b/module-apps/application-notes/windows/NotesMainWindow.cpp @@ -21,78 +21,91 @@ #include "NotesMainWindow.hpp" #include -namespace gui { +namespace gui +{ - NotesMainWindow::NotesMainWindow(app::Application *app) : AppWindow(app, gui::name::window::main_window), notesModel{new NotesModel(app)} + NotesMainWindow::NotesMainWindow(app::Application *app) + : AppWindow(app, gui::name::window::main_window), notesModel{new NotesModel(app)} { buildInterface(); } -void NotesMainWindow::rebuild() { - destroyInterface(); - buildInterface(); -} -void NotesMainWindow::buildInterface() { - AppWindow::buildInterface(); + void NotesMainWindow::rebuild() + { + destroyInterface(); + buildInterface(); + } + void NotesMainWindow::buildInterface() + { + AppWindow::buildInterface(); - list = new gui::ListView(this, 16, 105, 480-32, 440 ); - list->setMaxElements(3); - list->setPageSize(3); - list->setPenFocusWidth(0); - list->setPenWidth(0); - list->setProvider( notesModel ); + list = new gui::ListView(this, 16, 105, 480 - 32, 440); + list->setMaxElements(3); + list->setPageSize(3); + list->setPenFocusWidth(0); + list->setPenWidth(0); + list->setProvider(notesModel); - setFocusItem(list); + setFocusItem(list); - setTitle(utils::localize.get("app_notes_title_main")); + setTitle(utils::localize.get("app_notes_title_main")); - bottomBar->setActive( BottomBar::Side::CENTER, true ); - bottomBar->setActive( BottomBar::Side::RIGHT, true ); - bottomBar->setText( BottomBar::Side::CENTER, utils::localize.get("common_open")); - bottomBar->setText( BottomBar::Side::RIGHT, utils::localize.get("common_back")); + bottomBar->setActive(BottomBar::Side::CENTER, true); + bottomBar->setActive(BottomBar::Side::RIGHT, true); + bottomBar->setText(BottomBar::Side::CENTER, utils::localize.get("common_open")); + bottomBar->setText(BottomBar::Side::RIGHT, utils::localize.get("common_back")); - topBar->setActive(TopBar::Elements::TIME, true ); + topBar->setActive(TopBar::Elements::TIME, true); + } + void NotesMainWindow::destroyInterface() + { + AppWindow::destroyInterface(); -} -void NotesMainWindow::destroyInterface() { - AppWindow::destroyInterface(); + if (list) { + removeWidget(list); + delete list; + list = nullptr; + }; - if( list ) { removeWidget(list); delete list; list= nullptr; }; + children.clear(); + delete notesModel; + } - children.clear(); - delete notesModel; -} + NotesMainWindow::~NotesMainWindow() + { + destroyInterface(); + } -NotesMainWindow::~NotesMainWindow() { - destroyInterface(); -} + void NotesMainWindow::onBeforeShow(ShowMode mode, SwitchData *data) + { + notesModel->clear(); + notesModel->requestRecordsCount(); + list->clear(); + list->setElementsCount(notesModel->getItemCount()); + } -void NotesMainWindow::onBeforeShow( ShowMode mode, SwitchData* data ) { - notesModel->clear(); - notesModel->requestRecordsCount(); - list->clear(); - list->setElementsCount( notesModel->getItemCount() ); -} + bool NotesMainWindow::onInput(const InputEvent &inputEvent) + { -bool NotesMainWindow::onInput( const InputEvent& inputEvent ) { + // process only if key is released + if ((inputEvent.state != InputEvent::State::keyReleasedShort) || + (inputEvent.state != InputEvent::State::keyReleasedLong)) { + if (inputEvent.keyCode == KeyCode::KEY_LEFT) { + application->switchWindow("EditWindow"); + return true; + } + } - //process only if key is released - if(( inputEvent.state != InputEvent::State::keyReleasedShort ) || ( inputEvent.state != InputEvent::State::keyReleasedLong )) { - if( inputEvent.keyCode == KeyCode::KEY_LEFT ) { - application->switchWindow( "EditWindow" ); - return true; - } - } + return AppWindow::onInput(inputEvent); + } - return AppWindow::onInput( inputEvent ); -} + bool NotesMainWindow::onDatabaseMessage(sys::Message *msgl) + { + DBNotesResponseMessage *msg = reinterpret_cast(msgl); + if (notesModel->updateRecords(std::move(msg->records), msg->offset, msg->limit, msg->count)) + return true; -bool NotesMainWindow::onDatabaseMessage( sys::Message* msgl ) { - DBNotesResponseMessage* msg = reinterpret_cast( msgl ); - if( notesModel->updateRecords( std::move(msg->records), msg->offset, msg->limit, msg->count ) ) - return true; - - return false; -} + return false; + } } /* namespace gui */ diff --git a/module-apps/application-notes/windows/NotesMainWindow.hpp b/module-apps/application-notes/windows/NotesMainWindow.hpp index 3e6a16941..fa6cfb51b 100644 --- a/module-apps/application-notes/windows/NotesMainWindow.hpp +++ b/module-apps/application-notes/windows/NotesMainWindow.hpp @@ -22,26 +22,28 @@ #include "../NotesModel.hpp" -namespace gui { +namespace gui +{ -class NotesMainWindow: public AppWindow { - NotesModel* notesModel = nullptr; - gui::ListView* list = nullptr; - Label* title = nullptr; -public: - NotesMainWindow( app::Application* app ); - virtual ~NotesMainWindow(); + class NotesMainWindow : public AppWindow + { + NotesModel *notesModel = nullptr; + gui::ListView *list = nullptr; + Label *title = nullptr; - //virtual methods - bool onInput( const InputEvent& inputEvent ) override; - void onBeforeShow( ShowMode mode, SwitchData* data ) override; + public: + NotesMainWindow(app::Application *app); + virtual ~NotesMainWindow(); + // virtual methods + bool onInput(const InputEvent &inputEvent) override; + void onBeforeShow(ShowMode mode, SwitchData *data) override; - void rebuild() override; - void buildInterface() override; - void destroyInterface() override; - bool onDatabaseMessage( sys::Message* msg ) override; -}; + void rebuild() override; + void buildInterface() override; + void destroyInterface() override; + bool onDatabaseMessage(sys::Message *msg) override; + }; } /* namespace gui */ diff --git a/module-apps/application-phonebook/ApplicationPhonebook.cpp b/module-apps/application-phonebook/ApplicationPhonebook.cpp index 32ec7bba9..5abe9ee7d 100644 --- a/module-apps/application-phonebook/ApplicationPhonebook.cpp +++ b/module-apps/application-phonebook/ApplicationPhonebook.cpp @@ -14,119 +14,112 @@ namespace app { - ApplicationPhonebook::ApplicationPhonebook(std::string name, std::string parent, bool startBackgound) : Application(name, parent, startBackgound, 8192) + ApplicationPhonebook::ApplicationPhonebook(std::string name, std::string parent, bool startBackgound) + : Application(name, parent, startBackgound, 8192) + {} + + ApplicationPhonebook::~ApplicationPhonebook() + {} + + // Invoked upon receiving data message + sys::Message_t ApplicationPhonebook::DataReceivedHandler(sys::DataMessage *msgl, sys::ResponseMessage *resp) { -} -ApplicationPhonebook::~ApplicationPhonebook() -{ -} + auto retMsg = Application::DataReceivedHandler(msgl); + // if message was handled by application's template there is no need to process further. + if (reinterpret_cast(retMsg.get())->retCode == sys::ReturnCodes::Success) { + return retMsg; + } -// Invoked upon receiving data message -sys::Message_t ApplicationPhonebook::DataReceivedHandler(sys::DataMessage *msgl, sys::ResponseMessage *resp) -{ + // this variable defines whether message was processed. + bool handled = false; - auto retMsg = Application::DataReceivedHandler(msgl); - // if message was handled by application's template there is no need to process further. - if (reinterpret_cast(retMsg.get())->retCode == sys::ReturnCodes::Success) - { - return retMsg; + // handle database response + if (resp != nullptr) { + handled = true; + switch (resp->responseTo) { + case MessageType::DBContactGetLimitOffset: { + if (getCurrentWindow()->onDatabaseMessage(resp)) + refreshWindow(gui::RefreshModes::GUI_REFRESH_FAST); + } break; + default: + break; + } + } + + if (handled) + return std::make_shared(); + else + return std::make_shared(sys::ReturnCodes::Unresolved); } - // this variable defines whether message was processed. - bool handled = false; - - // handle database response - if (resp != nullptr) + // Invoked during initialization + sys::ReturnCodes ApplicationPhonebook::InitHandler() { - handled = true; - switch (resp->responseTo) - { - case MessageType::DBContactGetLimitOffset: { - if (getCurrentWindow()->onDatabaseMessage(resp)) - refreshWindow(gui::RefreshModes::GUI_REFRESH_FAST); - } - break; - default: - break; - } - } - if (handled) - return std::make_shared(); - else - return std::make_shared(sys::ReturnCodes::Unresolved); -} + auto ret = Application::InitHandler(); + if (ret != sys::ReturnCodes::Success) + return ret; -// Invoked during initialization -sys::ReturnCodes ApplicationPhonebook::InitHandler() -{ + createUserInterface(); - auto ret = Application::InitHandler(); - if (ret != sys::ReturnCodes::Success) return ret; + } - createUserInterface(); + sys::ReturnCodes ApplicationPhonebook::DeinitHandler() + { + return sys::ReturnCodes::Success; + } + void ApplicationPhonebook::createUserInterface() + { - return ret; -} + gui::AppWindow *window = nullptr; -sys::ReturnCodes ApplicationPhonebook::DeinitHandler() -{ - return sys::ReturnCodes::Success; -} + window = new PhonebookMainWindow(this); + windows.insert(std::pair(window->getName(), window)); -void ApplicationPhonebook::createUserInterface() -{ + window = new PhonebookNewContact(this); + windows.insert(std::pair(window->getName(), window)); - gui::AppWindow *window = nullptr; + window = new PhonebookContact(this); + windows.insert(std::pair(window->getName(), window)); - window = new PhonebookMainWindow(this); - windows.insert(std::pair(window->getName(), window)); + window = new PhonebookDeleteContact(this); + windows.insert(std::pair(window->getName(), window)); - window = new PhonebookNewContact(this); - windows.insert(std::pair(window->getName(), window)); + window = new PhonebookBlockContact(this); + windows.insert(std::pair(window->getName(), window)); - window = new PhonebookContact(this); - windows.insert(std::pair(window->getName(), window)); + window = new PhonebookDuplicateSpeedDial(this); + windows.insert(std::pair(window->getName(), window)); - window = new PhonebookDeleteContact(this); - windows.insert(std::pair(window->getName(), window)); + window = new DuplicatedContactDialogWindow(this); + windows.insert(std::pair(window->getName(), window)); - window = new PhonebookBlockContact(this); - windows.insert(std::pair(window->getName(), window)); + window = new PhonebookSearch(this); + windows.insert(std::pair(window->getName(), window)); - window = new PhonebookDuplicateSpeedDial(this); - windows.insert(std::pair(window->getName(), window)); + window = new ErrorWindows::NoResults(this); + windows.insert(std::pair(window->getName(), window)); - window = new DuplicatedContactDialogWindow(this); - windows.insert(std::pair(window->getName(), window)); + window = new ErrorWindows::ContactBlocked(this); + windows.insert(std::pair(window->getName(), window)); - window = new PhonebookSearch(this); - windows.insert(std::pair(window->getName(), window)); + window = new ErrorWindows::ContactBlocked(this); + windows.insert(std::pair(window->getName(), window)); - window = new ErrorWindows::NoResults(this); - windows.insert(std::pair(window->getName(), window)); + window = new gui::PhonebookSearchResults(this); + windows.insert(std::pair(window->getName(), window)); - window = new ErrorWindows::ContactBlocked(this); - windows.insert(std::pair(window->getName(), window)); + window = new PhonebookOptions(this); + windows.insert(std::pair(window->getName(), window)); - window = new ErrorWindows::ContactBlocked(this); - windows.insert(std::pair(window->getName(), window)); + window = new PhonebookOptionsNamecard(this); + windows.insert(std::pair(window->getName(), window)); + } - window = new gui::PhonebookSearchResults(this); - windows.insert(std::pair(window->getName(), window)); - - window = new PhonebookOptions(this); - windows.insert(std::pair(window->getName(), window)); - - window = new PhonebookOptionsNamecard(this); - windows.insert(std::pair(window->getName(), window)); -} - -void ApplicationPhonebook::destroyUserInterface() -{ -} + void ApplicationPhonebook::destroyUserInterface() + {} } /* namespace app */ diff --git a/module-apps/application-phonebook/ApplicationPhonebook.hpp b/module-apps/application-phonebook/ApplicationPhonebook.hpp index a01edf8fa..e0ed004b8 100644 --- a/module-apps/application-phonebook/ApplicationPhonebook.hpp +++ b/module-apps/application-phonebook/ApplicationPhonebook.hpp @@ -1,25 +1,30 @@ #include "Application.hpp" -namespace app { +namespace app +{ -/* this is is a bad idea but no other exists as of 06.02.2020 */ -static std::string defaultCountryCode = "+48"; + /* this is is a bad idea but no other exists as of 06.02.2020 */ + static std::string defaultCountryCode = "+48"; -const inline std::string name_phonebook = "ApplicationPhonebook"; + const inline std::string name_phonebook = "ApplicationPhonebook"; -class ApplicationPhonebook: public app::Application { -public: - ApplicationPhonebook( std::string name=name_phonebook, std::string parent="", bool startBackgound = false); - virtual ~ApplicationPhonebook(); + class ApplicationPhonebook : public app::Application + { + public: + ApplicationPhonebook(std::string name = name_phonebook, std::string parent = "", bool startBackgound = false); + virtual ~ApplicationPhonebook(); - sys::Message_t DataReceivedHandler(sys::DataMessage* msgl,sys::ResponseMessage* resp) override; - sys::ReturnCodes InitHandler() override; - sys::ReturnCodes DeinitHandler() override; + sys::Message_t DataReceivedHandler(sys::DataMessage *msgl, sys::ResponseMessage *resp) override; + sys::ReturnCodes InitHandler() override; + sys::ReturnCodes DeinitHandler() override; - sys::ReturnCodes SwitchPowerModeHandler(const sys::ServicePowerMode mode) override final{return sys::ReturnCodes::Success;} + sys::ReturnCodes SwitchPowerModeHandler(const sys::ServicePowerMode mode) override final + { + return sys::ReturnCodes::Success; + } - void createUserInterface() override; - void destroyUserInterface() override; -}; + void createUserInterface() override; + void destroyUserInterface() override; + }; -} +} // namespace app diff --git a/module-apps/application-phonebook/data/PhonebookItemData.hpp b/module-apps/application-phonebook/data/PhonebookItemData.hpp index 6389a5dea..9a7a0c43f 100644 --- a/module-apps/application-phonebook/data/PhonebookItemData.hpp +++ b/module-apps/application-phonebook/data/PhonebookItemData.hpp @@ -9,7 +9,8 @@ class PhonebookItemData : public gui::SwitchData { public: - PhonebookItemData(std::shared_ptr contact, const std::string &text = "") : text(text), contact(contact){}; + PhonebookItemData(std::shared_ptr contact, const std::string &text = "") + : text(text), contact(contact){}; virtual ~PhonebookItemData(){}; std::shared_ptr getContact() { @@ -18,8 +19,7 @@ class PhonebookItemData : public gui::SwitchData public: PhonebookItemData() : contact(nullptr) - { - } + {} std::string text; std::shared_ptr contact = nullptr; }; @@ -66,11 +66,11 @@ class PhonebookSearchResultsData : public gui::SwitchData class PhonebookSearchReuqest : public gui::SwitchData { public: - std::string request = ""; + std::string request = ""; std::shared_ptr> results = nullptr; - PhonebookSearchReuqest(std::string request, std::shared_ptr> results) : request(request), results(results) - { - } - PhonebookSearchReuqest() = default; + PhonebookSearchReuqest(std::string request, std::shared_ptr> results) + : request(request), results(results) + {} + PhonebookSearchReuqest() = default; std::shared_ptr result = nullptr; }; diff --git a/module-apps/application-phonebook/data/PhonebookStyle.hpp b/module-apps/application-phonebook/data/PhonebookStyle.hpp index 9598e462c..2888de599 100644 --- a/module-apps/application-phonebook/data/PhonebookStyle.hpp +++ b/module-apps/application-phonebook/data/PhonebookStyle.hpp @@ -3,49 +3,57 @@ namespace phonebookStyle { -namespace search { - constexpr uint32_t default_x = style::window::default_left_margin; - constexpr uint32_t default_w = + namespace search + { + constexpr uint32_t default_x = style::window::default_left_margin; + constexpr uint32_t default_w = style::window_width - style::window::default_left_margin - style::window::default_right_margin; - namespace searchHeader { - constexpr uint32_t x = style::window::default_left_margin; - constexpr uint32_t y = 127; - constexpr uint32_t w = 86; - constexpr uint32_t h = 20; - } // namespace searchHeader - namespace horizontalBox { - constexpr uint32_t x = style::window::default_left_margin; - constexpr uint32_t y = 153; - constexpr uint32_t w = default_w; - constexpr uint32_t h = 33; - constexpr uint32_t penWidth = 2; - namespace searchTop { - constexpr uint32_t x = default_w; - constexpr uint32_t y = 1; - constexpr uint32_t w = 32; - constexpr uint32_t h = 32; - } // namespace searchTop - namespace inputField { - constexpr uint32_t x = 1; - constexpr uint32_t y = 1; - constexpr uint32_t w = default_w - searchTop::w; - constexpr uint32_t h = 33; - } // namespace inputField - } // namespace horizontalBox -} //namespace search -namespace searchResults { - constexpr uint32_t default_x = style::window::default_left_margin; - constexpr uint32_t default_w = + namespace searchHeader + { + constexpr uint32_t x = style::window::default_left_margin; + constexpr uint32_t y = 127; + constexpr uint32_t w = 86; + constexpr uint32_t h = 20; + } // namespace searchHeader + namespace horizontalBox + { + constexpr uint32_t x = style::window::default_left_margin; + constexpr uint32_t y = 153; + constexpr uint32_t w = default_w; + constexpr uint32_t h = 33; + constexpr uint32_t penWidth = 2; + namespace searchTop + { + constexpr uint32_t x = default_w; + constexpr uint32_t y = 1; + constexpr uint32_t w = 32; + constexpr uint32_t h = 32; + } // namespace searchTop + namespace inputField + { + constexpr uint32_t x = 1; + constexpr uint32_t y = 1; + constexpr uint32_t w = default_w - searchTop::w; + constexpr uint32_t h = 33; + } // namespace inputField + } // namespace horizontalBox + } // namespace search + namespace searchResults + { + constexpr uint32_t default_x = style::window::default_left_margin; + constexpr uint32_t default_w = style::window_width - style::window::default_left_margin - style::window::default_right_margin; - namespace searchResultList { - constexpr uint32_t x = style::window::default_left_margin; - constexpr uint32_t y = 105 + 6; - constexpr uint32_t w = style::window_width - style::window::default_left_margin - style::window::default_right_margin; - constexpr uint32_t h = style::window_height - y - 50; - constexpr uint32_t maxElements = 7; - constexpr uint32_t pageSize = 7; - constexpr uint32_t penFocusWidth = style::window::default_border_no_focus_w; - constexpr uint32_t penWidth = 0; - } // namespace searchResultList -} //namespace search -} //namespace phonebookStyle \ No newline at end of file + namespace searchResultList + { + constexpr uint32_t x = style::window::default_left_margin; + constexpr uint32_t y = 105 + 6; + constexpr uint32_t w = + style::window_width - style::window::default_left_margin - style::window::default_right_margin; + constexpr uint32_t h = style::window_height - y - 50; + constexpr uint32_t maxElements = 7; + constexpr uint32_t pageSize = 7; + constexpr uint32_t penFocusWidth = style::window::default_border_no_focus_w; + constexpr uint32_t penWidth = 0; + } // namespace searchResultList + } // namespace searchResults +} // namespace phonebookStyle \ No newline at end of file diff --git a/module-apps/application-phonebook/models/PhonebookModel.cpp b/module-apps/application-phonebook/models/PhonebookModel.cpp index 58591c7e8..80a98fde6 100644 --- a/module-apps/application-phonebook/models/PhonebookModel.cpp +++ b/module-apps/application-phonebook/models/PhonebookModel.cpp @@ -13,8 +13,7 @@ #include "service-db/api/DBServiceAPI.hpp" PhonebookModel::PhonebookModel(app::Application *app) : DatabaseModel(app, 14) -{ -} +{} void PhonebookModel::requestRecordsCount() { @@ -34,28 +33,27 @@ void PhonebookModel::requestRecordsCount() void PhonebookModel::requestRecords(const uint32_t offset, const uint32_t limit) { - if (offset < favouriteCount) - { + if (offset < favouriteCount) { // if it's needed to request only favorite - if (offset + limit < favouriteCount) - { + if (offset + limit < favouriteCount) { DBServiceAPI::ContactGetLimitOffset(application, offset, limit, true); } - else - { + else { uint32_t count = favouriteCount - offset; DBServiceAPI::ContactGetLimitOffset(application, offset, count, true); DBServiceAPI::ContactGetLimitOffset(application, 0, limit - count, false); } } // request normal contacts - else - { + else { DBServiceAPI::ContactGetLimitOffset(application, offset - favouriteCount, limit, false); } } -bool PhonebookModel::updateRecords(std::unique_ptr> records, const uint32_t offset, const uint32_t limit, uint32_t count, +bool PhonebookModel::updateRecords(std::unique_ptr> records, + const uint32_t offset, + const uint32_t limit, + uint32_t count, bool favourite) { @@ -67,9 +65,11 @@ bool PhonebookModel::updateRecords(std::unique_ptr> r return true; } -gui::ListItem *PhonebookModel::getItem(int index, int firstElement, int prevIndex, uint32_t count, int remaining, bool topDown) +gui::ListItem *PhonebookModel::getItem( + int index, int firstElement, int prevIndex, uint32_t count, int remaining, bool topDown) { - // LOG_INFO("index: %d, first:%d prev: %d, count: %d, rem: %d, topDown: %d", index, firstElement, prevIndex, count, remaining, topDown); + // LOG_INFO("index: %d, first:%d prev: %d, count: %d, rem: %d, topDown: %d", index, firstElement, prevIndex, count, + // remaining, topDown); bool download = false; if (index > firstIndex + pageSize / 2) download = true; @@ -80,106 +80,85 @@ gui::ListItem *PhonebookModel::getItem(int index, int firstElement, int prevInde if (contact == nullptr) return nullptr; - if (topDown) - { + if (topDown) { // return item from favorite part of contacts - if (static_cast(index) < favouriteCount) - { + if (static_cast(index) < favouriteCount) { gui::PhonebookItem *item = new gui::PhonebookItem(); - if ((index == firstElement) && (index != prevIndex)) - { + if ((index == firstElement) && (index != prevIndex)) { item->setValue(utils::localize.get("app_phonebook_list_favourites")); } - else - { + else { item->markFavourite(true); item->setContact(contact); item->setID(index); } return item; } - else - { + else { gui::PhonebookItem *item = new gui::PhonebookItem(); // on top the page or if element next after last favourite contact is requested - if (((index == firstElement) || (static_cast(index) == favouriteCount)) && (index != prevIndex)) - { + if (((index == firstElement) || (static_cast(index) == favouriteCount)) && (index != prevIndex)) { item->setValue(contact->primaryName.substr(0, 1)); } - else - { + else { std::shared_ptr prevContact = getRecord(prevIndex, false); - if (contact->primaryName.substr(0, 1) == prevContact->primaryName.substr(0, 1)) - { + if (contact->primaryName.substr(0, 1) == prevContact->primaryName.substr(0, 1)) { item->setContact(contact); item->setID(index); } - else - { + else { item->setValue(contact->primaryName.substr(0, 1)); } } return item; } } - else - { - if (static_cast(index) < favouriteCount - 1) - { + else { + if (static_cast(index) < favouriteCount - 1) { gui::PhonebookItem *item = new gui::PhonebookItem(); - if (remaining == 0) - { + if (remaining == 0) { item->setValue(utils::localize.get("app_phonebook_list_favourites")); } - else - { + else { item->markFavourite(true); item->setContact(contact); item->setID(index); } return item; } - else - { + else { gui::PhonebookItem *item = new gui::PhonebookItem(); // leaving normal contacts list and entering favourite area but character is already placed - if ((static_cast(index) == favouriteCount - 1) && (index == prevIndex)) - { + if ((static_cast(index) == favouriteCount - 1) && (index == prevIndex)) { item->markFavourite(true); item->setContact(contact); item->setID(index); } // leaving normal contacts list and entering favourite area - return character - if ((static_cast(index) == favouriteCount - 1) && (index != prevIndex)) - { + if ((static_cast(index) == favouriteCount - 1) && (index != prevIndex)) { item->setValue(contact->primaryName.substr(0, 1)); } - else - { + else { std::shared_ptr prevContact = getRecord(prevIndex, false); - if (remaining == 0) - { + if (remaining == 0) { // previous element has the same first character of alternative name so display first character - if (index == prevIndex) - { + if (index == prevIndex) { item->setContact(contact); item->setID(index); } - else - { + else { item->setValue(prevContact->primaryName.substr(0, 1)); } } - else if (((index == firstElement) || (index == prevIndex) || (contact->primaryName.substr(0, 1) == prevContact->primaryName.substr(0, 1)))) - { + else if (((index == firstElement) || (index == prevIndex) || + (contact->primaryName.substr(0, 1) == prevContact->primaryName.substr(0, 1)))) { item->setContact(contact); item->setID(index); } - else - { + else { item->setValue(prevContact->primaryName.substr(0, 1)); } } diff --git a/module-apps/application-phonebook/models/PhonebookModel.hpp b/module-apps/application-phonebook/models/PhonebookModel.hpp index a3c5600e7..e23bfa5c0 100644 --- a/module-apps/application-phonebook/models/PhonebookModel.hpp +++ b/module-apps/application-phonebook/models/PhonebookModel.hpp @@ -32,11 +32,16 @@ class PhonebookModel : public gui::ListItemProvider, public app::DatabaseModel> records, const uint32_t offset, const uint32_t limit, uint32_t count, bool favourite); + bool updateRecords(std::unique_ptr> records, + const uint32_t offset, + const uint32_t limit, + uint32_t count, + bool favourite); void requestRecords(const uint32_t offset, const uint32_t limit) override; // virtual methods for ListViewProvider - gui::ListItem *getItem(int index, int firstElement, int prevIndex, uint32_t count, int remaining, bool topDown) override; + gui::ListItem *getItem( + int index, int firstElement, int prevIndex, uint32_t count, int remaining, bool topDown) override; int getItemCount() const override { return recordsCount; diff --git a/module-apps/application-phonebook/models/SearchResultsModel.cpp b/module-apps/application-phonebook/models/SearchResultsModel.cpp index 94860155e..a1195b25b 100644 --- a/module-apps/application-phonebook/models/SearchResultsModel.cpp +++ b/module-apps/application-phonebook/models/SearchResultsModel.cpp @@ -5,8 +5,7 @@ #include "service-db/api/DBServiceAPI.hpp" SearchResultsModel::SearchResultsModel(app::Application *app) : DatabaseModel(app, 14) -{ -} +{} SearchResultsModel::~SearchResultsModel() { @@ -18,14 +17,16 @@ void SearchResultsModel::requestFavouritesCount() favouriteCount = DBServiceAPI::ContactGetCount(application, true); } -void SearchResultsModel::requestRecordsCount(){} -void SearchResultsModel::requestRecords(const uint32_t offset, const uint32_t limit){} +void SearchResultsModel::requestRecordsCount() +{} +void SearchResultsModel::requestRecords(const uint32_t offset, const uint32_t limit) +{} -gui::ListItem *SearchResultsModel::getItem(int index, int firstElement, int prevIndex, uint32_t count, int remaining, bool topDown) +gui::ListItem *SearchResultsModel::getItem( + int index, int firstElement, int prevIndex, uint32_t count, int remaining, bool topDown) { auto o = *results.get(); - if (index >= (int)o.size()) - { + if (index >= (int)o.size()) { LOG_ERROR("getItem error: index %d >= results size %d", index, o.size()); return nullptr; } @@ -34,109 +35,88 @@ gui::ListItem *SearchResultsModel::getItem(int index, int firstElement, int prev if (contact == nullptr) return nullptr; - if (topDown) - { + if (topDown) { // return item from favorite part of contacts - if (static_cast(index) < favouriteCount) - { + if (static_cast(index) < favouriteCount) { gui::PhonebookItem *item = new gui::PhonebookItem(); - if ((index == firstElement) && (index != prevIndex)) - { + if ((index == firstElement) && (index != prevIndex)) { item->setValue(utils::localize.get("app_phonebook_list_favourites")); } - else - { + else { item->markFavourite(true); item->setContact(contact); item->setID(index); } return item; } - else - { + else { gui::PhonebookItem *item = new gui::PhonebookItem(); // on top the page or if element next after last favourite contact is requested - if (((index == firstElement) || (static_cast(index) == favouriteCount)) && (index != prevIndex)) - { + if (((index == firstElement) || (static_cast(index) == favouriteCount)) && (index != prevIndex)) { item->setValue(contact->primaryName.substr(0, 1)); } - else - { + else { auto prevContact = std::make_shared(o[prevIndex]); - if (contact->alternativeName.substr(0, 1) == prevContact->alternativeName.substr(0, 1)) - { + if (contact->alternativeName.substr(0, 1) == prevContact->alternativeName.substr(0, 1)) { item->markFavourite(false); item->setContact(contact); item->setID(index); } - else - { + else { item->setValue(contact->primaryName.substr(0, 1)); } } return item; } } - else - { - if (static_cast(index) < favouriteCount - 1) - { + else { + if (static_cast(index) < favouriteCount - 1) { gui::PhonebookItem *item = new gui::PhonebookItem(); - if (remaining == 0) - { + if (remaining == 0) { item->setValue(utils::localize.get("app_phonebook_list_favourites")); } - else - { + else { item->markFavourite(true); item->setContact(contact); item->setID(index); } return item; } - else - { + else { gui::PhonebookItem *item = new gui::PhonebookItem(); // leaving normal contacts list and entering favourite area but character is already placed - if ((static_cast(index) == favouriteCount - 1) && (index == prevIndex)) - { + if ((static_cast(index) == favouriteCount - 1) && (index == prevIndex)) { item->markFavourite(true); item->setContact(contact); item->setID(index); } // leaving normal contacts list and entering favourite area - return character - if ((static_cast(index) == favouriteCount - 1) && (index != prevIndex)) - { + if ((static_cast(index) == favouriteCount - 1) && (index != prevIndex)) { item->setValue(contact->primaryName.substr(0, 1)); } - else - { + else { auto prevContact = std::make_shared(o[prevIndex]); - if (remaining == 0) - { + if (remaining == 0) { // previous element has the same first character of alternative name so display first character - if (index == prevIndex) - { + if (index == prevIndex) { item->markFavourite(false); item->setContact(contact); item->setID(index); } - else - { + else { item->setValue(prevContact->primaryName.substr(0, 1)); } } - else if (((index == firstElement) || (index == prevIndex) || (contact->primaryName.substr(0, 1) == prevContact->primaryName.substr(0, 1)))) - { + else if (((index == firstElement) || (index == prevIndex) || + (contact->primaryName.substr(0, 1) == prevContact->primaryName.substr(0, 1)))) { item->markFavourite(false); item->setContact(contact); item->setID(index); } - else - { + else { item->setValue(prevContact->primaryName.substr(0, 1)); } } @@ -148,12 +128,10 @@ gui::ListItem *SearchResultsModel::getItem(int index, int firstElement, int prev int SearchResultsModel::getItemCount() const { - if (results) - { + if (results) { return (results.get()->size()); } - else - { + else { return (0); } } diff --git a/module-apps/application-phonebook/models/SearchResultsModel.hpp b/module-apps/application-phonebook/models/SearchResultsModel.hpp index a9be6273c..3e9de27fc 100644 --- a/module-apps/application-phonebook/models/SearchResultsModel.hpp +++ b/module-apps/application-phonebook/models/SearchResultsModel.hpp @@ -14,7 +14,8 @@ class SearchResultsModel : public gui::ListItemProvider, public app::DatabaseMod SearchResultsModel(app::Application *app); virtual ~SearchResultsModel(); - gui::ListItem *getItem(int index, int firstElement, int prevIndex, uint32_t count, int remaining, bool topDown) override; + gui::ListItem *getItem( + int index, int firstElement, int prevIndex, uint32_t count, int remaining, bool topDown) override; int getItemCount() const override; void setResults(std::shared_ptr> _results); void requestFavouritesCount(); diff --git a/module-apps/application-phonebook/widgets/PhonebookItem.cpp b/module-apps/application-phonebook/widgets/PhonebookItem.cpp index 2267cb5cb..e5586127a 100644 --- a/module-apps/application-phonebook/widgets/PhonebookItem.cpp +++ b/module-apps/application-phonebook/widgets/PhonebookItem.cpp @@ -12,82 +12,82 @@ namespace gui { -PhonebookItem::PhonebookItem() -{ - minWidth = 436; - minHeight = style::window::label::big_h; - maxWidth = 436; - maxHeight = 200; - - setRadius(0); - setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_BOTTOM | RectangleEdgeFlags::GUI_RECT_EDGE_TOP); - - setPenFocusWidth(2); - setPenWidth(0); - - value = new gui::Label(this, 0, 0, 0, 0); - value->setPenFocusWidth(0); - value->setPenWidth(0); - value->setFont(style::window::font::small); - value->setAlignement(gui::Alignment{gui::Alignment::ALIGN_HORIZONTAL_LEFT, gui::Alignment::ALIGN_VERTICAL_CENTER}); -} - -PhonebookItem::~PhonebookItem() -{ - if (value) + PhonebookItem::PhonebookItem() { - removeWidget(value); - delete value; - value = nullptr; + minWidth = 436; + minHeight = style::window::label::big_h; + maxWidth = 436; + maxHeight = 200; + + setRadius(0); + setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_BOTTOM | RectangleEdgeFlags::GUI_RECT_EDGE_TOP); + + setPenFocusWidth(2); + setPenWidth(0); + + value = new gui::Label(this, 0, 0, 0, 0); + value->setPenFocusWidth(0); + value->setPenWidth(0); + value->setFont(style::window::font::small); + value->setAlignement( + gui::Alignment{gui::Alignment::ALIGN_HORIZONTAL_LEFT, gui::Alignment::ALIGN_VERTICAL_CENTER}); } -} -bool PhonebookItem::onDimensionChanged(const BoundingBox &oldDim, const BoundingBox &newDim) -{ - value->setPosition(10, 0); - value->setSize(newDim.w - 10, newDim.h); + PhonebookItem::~PhonebookItem() + { + if (value) { + removeWidget(value); + delete value; + value = nullptr; + } + } - return true; -} + bool PhonebookItem::onDimensionChanged(const BoundingBox &oldDim, const BoundingBox &newDim) + { + value->setPosition(10, 0); + value->setSize(newDim.w - 10, newDim.h); -// sets copy of alarm's -void PhonebookItem::setContact(std::shared_ptr contact) -{ - this->contact = contact; - /* alternativeName is used as Surname or Second name */ - value->setText(contact->getFormattedName()); -} + return true; + } -void PhonebookItem::setValue(UTF8 text) -{ - value->setText(text); - value->setLineMode(true); - setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES); -} + // sets copy of alarm's + void PhonebookItem::setContact(std::shared_ptr contact) + { + this->contact = contact; + /* alternativeName is used as Surname or Second name */ + value->setText(contact->getFormattedName()); + } -UTF8 PhonebookItem::getValue() -{ - return value->getText(); -} + void PhonebookItem::setValue(UTF8 text) + { + value->setText(text); + value->setLineMode(true); + setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES); + } -bool PhonebookItem::onActivated(void *data) -{ - LOG_INFO("ITEM WAS PRESSED"); - return true; -} + UTF8 PhonebookItem::getValue() + { + return value->getText(); + } -void PhonebookItem::markFavourite(bool val) -{ - favourite = val; - if (val) - value->setFont(style::window::font::bigbold); - else - value->setFont(style::window::font::big); -} + bool PhonebookItem::onActivated(void *data) + { + LOG_INFO("ITEM WAS PRESSED"); + return true; + } -std::shared_ptr PhonebookItem::getContact() -{ - return (contact); -} + void PhonebookItem::markFavourite(bool val) + { + favourite = val; + if (val) + value->setFont(style::window::font::bigbold); + else + value->setFont(style::window::font::big); + } + + std::shared_ptr PhonebookItem::getContact() + { + return (contact); + } } /* namespace gui */ diff --git a/module-apps/application-phonebook/widgets/PhonebookItem.hpp b/module-apps/application-phonebook/widgets/PhonebookItem.hpp index d5628670f..32924e1ac 100644 --- a/module-apps/application-phonebook/widgets/PhonebookItem.hpp +++ b/module-apps/application-phonebook/widgets/PhonebookItem.hpp @@ -16,36 +16,36 @@ namespace gui { -/* - * - */ -class PhonebookItem : public ListItem -{ - // pointer to the contact record - std::shared_ptr contact = nullptr; - // this is contact's name and surname or "favourites" or "first letter of surname - gui::Label *value = nullptr; - bool favourite = false; - - public: - PhonebookItem(); - virtual ~PhonebookItem(); - // sets copy of contact - void setContact(std::shared_ptr note); - void setValue(UTF8 text); - UTF8 getValue(); - /** - * Marks item as a favourite. This will cause to use bold font instead of normal font. + /* + * */ - void markFavourite(bool val); + class PhonebookItem : public ListItem + { + // pointer to the contact record + std::shared_ptr contact = nullptr; + // this is contact's name and surname or "favourites" or "first letter of surname + gui::Label *value = nullptr; + bool favourite = false; - // returns contact's structure - std::shared_ptr getContact(); + public: + PhonebookItem(); + virtual ~PhonebookItem(); + // sets copy of contact + void setContact(std::shared_ptr note); + void setValue(UTF8 text); + UTF8 getValue(); + /** + * Marks item as a favourite. This will cause to use bold font instead of normal font. + */ + void markFavourite(bool val); - // virtual methods from Item - bool onDimensionChanged(const BoundingBox &oldDim, const BoundingBox &newDim) override; - bool onActivated(void *data) override; -}; + // returns contact's structure + std::shared_ptr getContact(); + + // virtual methods from Item + bool onDimensionChanged(const BoundingBox &oldDim, const BoundingBox &newDim) override; + bool onActivated(void *data) override; + }; } /* namespace gui */ diff --git a/module-apps/application-phonebook/widgets/PhonebookListView.cpp b/module-apps/application-phonebook/widgets/PhonebookListView.cpp index 182a41788..d817d7265 100644 --- a/module-apps/application-phonebook/widgets/PhonebookListView.cpp +++ b/module-apps/application-phonebook/widgets/PhonebookListView.cpp @@ -18,383 +18,332 @@ namespace gui { -PhonebookListView::PhonebookListView() : ListView() -{ - orientation = ORIENTATION_TOP_DOWN; -} - -PhonebookListView::PhonebookListView(Item *parent, uint32_t x, uint32_t y, uint32_t w, uint32_t h) : ListView(parent, x, y, w, h) -{ - orientation = ORIENTATION_TOP_DOWN; -} - -PhonebookListView::~PhonebookListView() -{ -} - -void PhonebookListView::setApplication(app::Application *app) -{ - application = app; -} - -gui::PhonebookItem *PhonebookListView::getSelectedPhonebookItem() -{ - int index = selectedIndex - firstIndex; - auto it = items.begin(); - if (items.size() == 0) - return nullptr; - - int count = -1; - for (int i = 0; i < pageSize; i++) + PhonebookListView::PhonebookListView() : ListView() { - if ((*it)->getID() >= 0) - count++; - if (count == index) - break; - std::advance(it, 1); + orientation = ORIENTATION_TOP_DOWN; } - return (dynamic_cast(*it)); -} - -bool PhonebookListView::onInput(const InputEvent &inputEvent) -{ - // LOG_INFO("code:%d state:%d", inputEvent.keyCode, inputEvent.state); - if ((inputEvent.state == InputEvent::State::keyReleasedShort) && (inputEvent.keyCode == KeyCode::KEY_ENTER)) + PhonebookListView::PhonebookListView(Item *parent, uint32_t x, uint32_t y, uint32_t w, uint32_t h) + : ListView(parent, x, y, w, h) { - gui::PhonebookItem *item = getSelectedPhonebookItem(); - if (item) - { - if (cb_ENTER && cb_ENTER(item)) - { + orientation = ORIENTATION_TOP_DOWN; + } + + PhonebookListView::~PhonebookListView() + {} + + void PhonebookListView::setApplication(app::Application *app) + { + application = app; + } + + gui::PhonebookItem *PhonebookListView::getSelectedPhonebookItem() + { + int index = selectedIndex - firstIndex; + auto it = items.begin(); + if (items.size() == 0) + return nullptr; + + int count = -1; + for (int i = 0; i < pageSize; i++) { + if ((*it)->getID() >= 0) + count++; + if (count == index) + break; + std::advance(it, 1); + } + + return (dynamic_cast(*it)); + } + + bool PhonebookListView::onInput(const InputEvent &inputEvent) + { + // LOG_INFO("code:%d state:%d", inputEvent.keyCode, inputEvent.state); + if ((inputEvent.state == InputEvent::State::keyReleasedShort) && (inputEvent.keyCode == KeyCode::KEY_ENTER)) { + gui::PhonebookItem *item = getSelectedPhonebookItem(); + if (item) { + if (cb_ENTER && cb_ENTER(item)) { + return true; + } + // LOG_INFO("show info on index: %d %s", item->getID(), item->getValue().c_str()); + + std::unique_ptr data = std::make_unique(item->getContact()); + application->switchWindow(gui::window::name::contact, gui::ShowMode::GUI_SHOW_INIT, std::move(data)); + return true; } - // LOG_INFO("show info on index: %d %s", item->getID(), item->getValue().c_str()); - - std::unique_ptr data = std::make_unique(item->getContact()); - application->switchWindow(gui::window::name::contact, gui::ShowMode::GUI_SHOW_INIT, std::move(data)); - - return true; + else { + LOG_ERROR("failed to get selected item!"); + return false; + } } - else - { - LOG_ERROR("failed to get selected item!"); - return false; - } - } - if ((inputEvent.state == InputEvent::State::keyReleasedShort) && (inputEvent.keyCode == KeyCode::KEY_LF)) - { + if ((inputEvent.state == InputEvent::State::keyReleasedShort) && (inputEvent.keyCode == KeyCode::KEY_LF)) { - gui::PhonebookItem *item = getSelectedPhonebookItem(); - if (item) - { - // LOG_INFO("calling index: %d %s", item->getID(), item->getValue().c_str()); - return app::call(application, app::CallOperation::ExecuteCall, item->getContact()->numbers[0].numberE164); + gui::PhonebookItem *item = getSelectedPhonebookItem(); + if (item) { + // LOG_INFO("calling index: %d %s", item->getID(), item->getValue().c_str()); + return app::call( + application, app::CallOperation::ExecuteCall, item->getContact()->numbers[0].numberE164); + } + else { + LOG_ERROR("failed to get selected item!"); + return false; + } } - else - { - LOG_ERROR("failed to get selected item!"); - return false; - } - } - if ((inputEvent.state == InputEvent::State::keyReleasedShort) && (inputEvent.keyCode == KeyCode::KEY_UP)) - { - if (orientation == ORIENTATION_TOP_DOWN) - { - if (listMode == MODE_PAGE) - { - if (selectedIndex > firstIndex) - { - selectedIndex--; - return true; - } - if (selectedIndex == firstIndex) - { - // ignore when someone wants to go above first element - if (selectedIndex == 0) - return false; - orientation = ORIENTATION_BOTTOM_UP; - if (firstIndex > 0) - { - selectedIndex = firstIndex - 1; - lastIndex = selectedIndex; - updateScrollDimenstions(); + if ((inputEvent.state == InputEvent::State::keyReleasedShort) && (inputEvent.keyCode == KeyCode::KEY_UP)) { + if (orientation == ORIENTATION_TOP_DOWN) { + if (listMode == MODE_PAGE) { + if (selectedIndex > firstIndex) { + selectedIndex--; return true; } + if (selectedIndex == firstIndex) { + // ignore when someone wants to go above first element + if (selectedIndex == 0) + return false; + orientation = ORIENTATION_BOTTOM_UP; + if (firstIndex > 0) { + selectedIndex = firstIndex - 1; + lastIndex = selectedIndex; + updateScrollDimenstions(); + return true; + } + } + } + else { + // TODO implement continuous mode } } - else - { - // TODO implement continuous mode - } - } - else if (orientation == ORIENTATION_BOTTOM_UP) - { - if (listMode == MODE_PAGE) - { - if (selectedIndex > firstIndex) - { - selectedIndex--; - return true; - } - if (selectedIndex == firstIndex) - { - if (firstIndex > 0) - { - selectedIndex = firstIndex - 1; - lastIndex = selectedIndex; - updateScrollDimenstions(); + else if (orientation == ORIENTATION_BOTTOM_UP) { + if (listMode == MODE_PAGE) { + if (selectedIndex > firstIndex) { + selectedIndex--; return true; } + if (selectedIndex == firstIndex) { + if (firstIndex > 0) { + selectedIndex = firstIndex - 1; + lastIndex = selectedIndex; + updateScrollDimenstions(); + return true; + } + } + } + else { + // TODO implement continuous mode } - } - else - { - // TODO implement continuous mode } } - } - else if ((inputEvent.state == InputEvent::State::keyReleasedShort) && (inputEvent.keyCode == KeyCode::KEY_DOWN)) - { - if (orientation == ORIENTATION_TOP_DOWN) - { - if (listMode == MODE_PAGE) - { - if (selectedIndex < lastIndex) - { - selectedIndex++; - return true; - } - if (selectedIndex == lastIndex) - { - if (lastIndex < elementsCount - 1) - { - firstIndex = lastIndex + 1; - selectedIndex = firstIndex; - updateScrollDimenstions(); + else if ((inputEvent.state == InputEvent::State::keyReleasedShort) && + (inputEvent.keyCode == KeyCode::KEY_DOWN)) { + if (orientation == ORIENTATION_TOP_DOWN) { + if (listMode == MODE_PAGE) { + if (selectedIndex < lastIndex) { + selectedIndex++; return true; } + if (selectedIndex == lastIndex) { + if (lastIndex < elementsCount - 1) { + firstIndex = lastIndex + 1; + selectedIndex = firstIndex; + updateScrollDimenstions(); + return true; + } + } + } + else { // continuous mode } } - else - { // continuous mode - } - } - else if (orientation == ORIENTATION_BOTTOM_UP) - { - if (listMode == MODE_PAGE) - { - if (selectedIndex < lastIndex) - { - selectedIndex++; - return true; - } - if (selectedIndex == lastIndex) - { - orientation = ORIENTATION_TOP_DOWN; - if (lastIndex < elementsCount - 1) - { - firstIndex = lastIndex + 1; - selectedIndex = firstIndex; - updateScrollDimenstions(); + else if (orientation == ORIENTATION_BOTTOM_UP) { + if (listMode == MODE_PAGE) { + if (selectedIndex < lastIndex) { + selectedIndex++; return true; } - } - } - else - { // continuous mode - } - } - } - return false; -} - -void PhonebookListView::updatePageItems() -{ - - // defines how many slots in the list has been occupied - int visibleElements = 0; - - // for top down orientation - if (orientation == ORIENTATION_TOP_DOWN) - { - // index of requested item is incremented only if payload of returned item is not null - // if it's null it means that this is favourite label of label connected with showing Capital letters for surnames - int index = firstIndex, prevIndex = -1; - lastIndex = firstIndex; - for (int i = 0; i < pageSize; i++) - { - ListItem *item = provider->getItem(index, firstIndex, prevIndex, pageSize); - - if (item != nullptr) - { - addWidget(item); - items.push_back(item); - - prevIndex = index; - if (item->getID() >= 0) - { - index++; - this->lastIndex++; - } - visibleElements++; - } - } - // after the loop lastIndex is the number of elements not the index of last element that's why -- is used. - lastIndex--; - - // if last element has been displayed but there is still space for elements - if ((lastIndex == elementsCount - 1) && (visibleElements != pageSize) && (firstIndex != 0)) - { - - orientation = ORIENTATION_BOTTOM_UP; - - // clear all elements in the list. - auto it = items.begin(); - for (uint32_t i = 0; i < items.size(); i++) - { - ListItem *item = *it; - removeWidget(item); - delete item; - std::advance(it, 1); - } - items.clear(); - - lastIndex = elementsCount - 1; - firstIndex = lastIndex; - index = lastIndex; - prevIndex = -1; - for (int i = 0; i < pageSize; i++) - { - ListItem *item = provider->getItem(index, lastIndex, prevIndex, pageSize, pageSize - 1 - i, false); - - if (item != nullptr) - { - addWidget(item); - items.push_back(item); - - prevIndex = index; - if (item->getID() >= 0) - { - index--; - firstIndex--; + if (selectedIndex == lastIndex) { + orientation = ORIENTATION_TOP_DOWN; + if (lastIndex < elementsCount - 1) { + firstIndex = lastIndex + 1; + selectedIndex = firstIndex; + updateScrollDimenstions(); + return true; + } } } - } - } - } - else if (orientation == ORIENTATION_BOTTOM_UP) - { - // index of requested item is incremented only if payload of returned item is not null - // if it's null it means that this is favourite label of label connected with showing Capital letters for surnames - int index = lastIndex, prevIndex = -1; - firstIndex = lastIndex; - for (int i = 0; i < pageSize; i++) - { - ListItem *item = provider->getItem(index, lastIndex, prevIndex, pageSize, pageSize - 1 - i, false); - - if (item != nullptr) - { - addWidget(item); - items.push_back(item); - - prevIndex = index; - if (item->getID() >= 0) - { - index--; - firstIndex--; + else { // continuous mode } - visibleElements++; } } + return false; + } - firstIndex++; + void PhonebookListView::updatePageItems() + { - // if last element has been displayed but there is still space for elements - if ((lastIndex != elementsCount - 1) && (visibleElements != pageSize) && (firstIndex == 0)) - { - - orientation = ORIENTATION_TOP_DOWN; - - // clear all elements in the list. - auto it = items.begin(); - for (uint32_t i = 0; i < items.size(); i++) - { - ListItem *item = *it; - removeWidget(item); - delete item; - std::advance(it, 1); - } - items.clear(); + // defines how many slots in the list has been occupied + int visibleElements = 0; + // for top down orientation + if (orientation == ORIENTATION_TOP_DOWN) { + // index of requested item is incremented only if payload of returned item is not null + // if it's null it means that this is favourite label of label connected with showing Capital letters for + // surnames int index = firstIndex, prevIndex = -1; - this->lastIndex = firstIndex; - for (int i = 0; i < pageSize; i++) - { + lastIndex = firstIndex; + for (int i = 0; i < pageSize; i++) { ListItem *item = provider->getItem(index, firstIndex, prevIndex, pageSize); - if (item != nullptr) - { + if (item != nullptr) { addWidget(item); items.push_back(item); prevIndex = index; - if (item->getID() >= 0) - { + if (item->getID() >= 0) { index++; this->lastIndex++; } + visibleElements++; + } + } + // after the loop lastIndex is the number of elements not the index of last element that's why -- is used. + lastIndex--; + + // if last element has been displayed but there is still space for elements + if ((lastIndex == elementsCount - 1) && (visibleElements != pageSize) && (firstIndex != 0)) { + + orientation = ORIENTATION_BOTTOM_UP; + + // clear all elements in the list. + auto it = items.begin(); + for (uint32_t i = 0; i < items.size(); i++) { + ListItem *item = *it; + removeWidget(item); + delete item; + std::advance(it, 1); + } + items.clear(); + + lastIndex = elementsCount - 1; + firstIndex = lastIndex; + index = lastIndex; + prevIndex = -1; + for (int i = 0; i < pageSize; i++) { + ListItem *item = provider->getItem(index, lastIndex, prevIndex, pageSize, pageSize - 1 - i, false); + + if (item != nullptr) { + addWidget(item); + items.push_back(item); + + prevIndex = index; + if (item->getID() >= 0) { + index--; + firstIndex--; + } + } } } } - } + else if (orientation == ORIENTATION_BOTTOM_UP) { + // index of requested item is incremented only if payload of returned item is not null + // if it's null it means that this is favourite label of label connected with showing Capital letters for + // surnames + int index = lastIndex, prevIndex = -1; + firstIndex = lastIndex; + for (int i = 0; i < pageSize; i++) { + ListItem *item = provider->getItem(index, lastIndex, prevIndex, pageSize, pageSize - 1 - i, false); - if (firstIndex < 0) - firstIndex = 0; + if (item != nullptr) { + addWidget(item); + items.push_back(item); - // calculate height of the item using list's height and pageSize - uint32_t itemWidth = widgetArea.w; - if (drawVerticalScroll) - itemWidth -= 10; - - // substract pageSize for 1 pixel separators - int availableHeight = widgetArea.h - pageSize; - if (availableHeight < 0) - availableHeight = 0; - int itemHeight = availableHeight / pageSize; - - int verticalPosition = 0; - - if (orientation == ORIENTATION_BOTTOM_UP) - items.reverse(); - - auto it = items.begin(); - - for (unsigned int i = 0; i < items.size(); i++) - { - if (availableHeight > 0) - { - - itemHeight = (*it)->minHeight; - - (*it)->setPosition(0, verticalPosition); - verticalPosition += itemHeight + 1; // 1 for separator - - (*it)->setSize(itemWidth, itemHeight); - - // if list has focus and it is visible mark selected element - if (visible) - { - if ((*it)->getID() == selectedIndex) - (*it)->setFocus(true); + prevIndex = index; + if (item->getID() >= 0) { + index--; + firstIndex--; + } + visibleElements++; + } } - availableHeight -= itemHeight; + firstIndex++; + + // if last element has been displayed but there is still space for elements + if ((lastIndex != elementsCount - 1) && (visibleElements != pageSize) && (firstIndex == 0)) { + + orientation = ORIENTATION_TOP_DOWN; + + // clear all elements in the list. + auto it = items.begin(); + for (uint32_t i = 0; i < items.size(); i++) { + ListItem *item = *it; + removeWidget(item); + delete item; + std::advance(it, 1); + } + items.clear(); + + int index = firstIndex, prevIndex = -1; + this->lastIndex = firstIndex; + for (int i = 0; i < pageSize; i++) { + ListItem *item = provider->getItem(index, firstIndex, prevIndex, pageSize); + + if (item != nullptr) { + addWidget(item); + items.push_back(item); + + prevIndex = index; + if (item->getID() >= 0) { + index++; + this->lastIndex++; + } + } + } + } + } + + if (firstIndex < 0) + firstIndex = 0; + + // calculate height of the item using list's height and pageSize + uint32_t itemWidth = widgetArea.w; + if (drawVerticalScroll) + itemWidth -= 10; + + // substract pageSize for 1 pixel separators + int availableHeight = widgetArea.h - pageSize; + if (availableHeight < 0) + availableHeight = 0; + int itemHeight = availableHeight / pageSize; + + int verticalPosition = 0; + + if (orientation == ORIENTATION_BOTTOM_UP) + items.reverse(); + + auto it = items.begin(); + + for (unsigned int i = 0; i < items.size(); i++) { + if (availableHeight > 0) { + + itemHeight = (*it)->minHeight; + + (*it)->setPosition(0, verticalPosition); + verticalPosition += itemHeight + 1; // 1 for separator + + (*it)->setSize(itemWidth, itemHeight); + + // if list has focus and it is visible mark selected element + if (visible) { + if ((*it)->getID() == selectedIndex) + (*it)->setFocus(true); + } + + availableHeight -= itemHeight; + } + std::advance(it, 1); } - std::advance(it, 1); } -} } /* namespace gui */ diff --git a/module-apps/application-phonebook/widgets/PhonebookListView.hpp b/module-apps/application-phonebook/widgets/PhonebookListView.hpp index 1c0c6a95b..f6de73bca 100644 --- a/module-apps/application-phonebook/widgets/PhonebookListView.hpp +++ b/module-apps/application-phonebook/widgets/PhonebookListView.hpp @@ -15,27 +15,27 @@ namespace gui { -class PhonebookItem; -class PhonebookListView : public ListView -{ - /** - * Pointer to application that owns the model - */ - app::Application *application = nullptr; + class PhonebookItem; + class PhonebookListView : public ListView + { + /** + * Pointer to application that owns the model + */ + app::Application *application = nullptr; - public: - PhonebookListView(); - PhonebookListView(Item *parent, uint32_t x, uint32_t y, uint32_t w, uint32_t h); - virtual ~PhonebookListView(); - void setApplication(app::Application *app); - gui::PhonebookItem *getSelectedPhonebookItem(); + public: + PhonebookListView(); + PhonebookListView(Item *parent, uint32_t x, uint32_t y, uint32_t w, uint32_t h); + virtual ~PhonebookListView(); + void setApplication(app::Application *app); + gui::PhonebookItem *getSelectedPhonebookItem(); - bool onInput(const InputEvent &inputEvent) override; - void updatePageItems() override; + bool onInput(const InputEvent &inputEvent) override; + void updatePageItems() override; - // onClick callback to register - std::function cb_ENTER = nullptr; -}; + // onClick callback to register + std::function cb_ENTER = nullptr; + }; } /* namespace gui */ diff --git a/module-apps/application-phonebook/windows/PhonebookContact.cpp b/module-apps/application-phonebook/windows/PhonebookContact.cpp index fdb5ab417..2c4fc46a7 100644 --- a/module-apps/application-phonebook/windows/PhonebookContact.cpp +++ b/module-apps/application-phonebook/windows/PhonebookContact.cpp @@ -30,11 +30,17 @@ namespace gui buildInterface(); } - Label *PhonebookContact::addLabel(std::list *parentPage, int x, int y, int w, int h, const std::string text = "", - const std::string fontName = style::window::font::small, + Label *PhonebookContact::addLabel(std::list *parentPage, + int x, + int y, + int w, + int h, + const std::string text = "", + const std::string fontName = style::window::font::small, const RectangleEdgeFlags edges = RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES, - const Alignment alignment = Alignment(Alignment::ALIGN_HORIZONTAL_LEFT, Alignment::ALIGN_VERTICAL_BOTTOM), - const bool lineMode = false) + const Alignment alignment = Alignment(Alignment::ALIGN_HORIZONTAL_LEFT, + Alignment::ALIGN_VERTICAL_BOTTOM), + const bool lineMode = false) { Label *l = new Label(this, x, y, w, h); l->setFilled(false); @@ -63,35 +69,82 @@ namespace gui bottomBar->setText(BottomBar::Side::CENTER, utils::localize.get("app_phonebook_call")); bottomBar->setText(BottomBar::Side::RIGHT, utils::localize.get("app_phonebook_back")); - favouritesIcon = new Image(this, 97, 107, 32, 32, "small_heart"); - favouritesLabel = addLabel(nullptr, 65, 144, 89, 20, utils::localize.get("app_phonebook_contact_favourites_upper"), style::window::font::tinybold, - RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES, Alignment(Alignment::ALIGN_HORIZONTAL_CENTER, Alignment::ALIGN_VERTICAL_CENTER)); + favouritesIcon = new Image(this, 97, 107, 32, 32, "small_heart"); + favouritesLabel = addLabel(nullptr, + 65, + 144, + 89, + 20, + utils::localize.get("app_phonebook_contact_favourites_upper"), + style::window::font::tinybold, + RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES, + Alignment(Alignment::ALIGN_HORIZONTAL_CENTER, Alignment::ALIGN_VERTICAL_CENTER)); - speedDial = addLabel(nullptr, 225, 107, 32, 32, "", style::footer::font::bold, RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES, + speedDial = addLabel(nullptr, + 225, + 107, + 32, + 32, + "", + style::footer::font::bold, + RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES, Alignment(Alignment::ALIGN_HORIZONTAL_CENTER, Alignment::ALIGN_VERTICAL_CENTER)); - speedDialLabel = addLabel(nullptr, 196, 144, 89, 20, utils::localize.get("app_phonebook_contact_speed_dial_upper"), style::window::font::tinybold, - RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES, Alignment(Alignment::ALIGN_HORIZONTAL_CENTER, Alignment::ALIGN_VERTICAL_CENTER)); + speedDialLabel = addLabel(nullptr, + 196, + 144, + 89, + 20, + utils::localize.get("app_phonebook_contact_speed_dial_upper"), + style::window::font::tinybold, + RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES, + Alignment(Alignment::ALIGN_HORIZONTAL_CENTER, Alignment::ALIGN_VERTICAL_CENTER)); - blockedIcon = new Image(this, 351, 107, 32, 32, "small_circle"); - blockedLabel = addLabel(nullptr, 329, 144, 75, 20, utils::localize.get("app_phonebook_contact_speed_blocked_uppper"), style::window::font::tinybold, - RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES, Alignment(Alignment::ALIGN_HORIZONTAL_CENTER, Alignment::ALIGN_VERTICAL_CENTER)); + blockedIcon = new Image(this, 351, 107, 32, 32, "small_circle"); + blockedLabel = addLabel(nullptr, + 329, + 144, + 75, + 20, + utils::localize.get("app_phonebook_contact_speed_blocked_uppper"), + style::window::font::tinybold, + RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES, + Alignment(Alignment::ALIGN_HORIZONTAL_CENTER, Alignment::ALIGN_VERTICAL_CENTER)); // page1 contents - informationLabel = - addLabel(&page1, 30, 203, 413, 20, utils::localize.get("app_phonebook_contact_information"), style::window::font::small, - RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES, Alignment(Alignment::ALIGN_HORIZONTAL_LEFT, Alignment::ALIGN_VERTICAL_BOTTOM), true); + informationLabel = addLabel(&page1, + 30, + 203, + 413, + 20, + utils::localize.get("app_phonebook_contact_information"), + style::window::font::small, + RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES, + Alignment(Alignment::ALIGN_HORIZONTAL_LEFT, Alignment::ALIGN_VERTICAL_BOTTOM), + true); // first number line - numberPrimary = addLabel(&page1, 30, 249, 178, 33, "", style::window::font::bigbold, RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES, + numberPrimary = addLabel(&page1, + 30, + 249, + 178, + 33, + "", + style::window::font::bigbold, + RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES, Alignment(Alignment::ALIGN_HORIZONTAL_CENTER, Alignment::ALIGN_VERTICAL_CENTER)); - numberPrimaryLabel = - addLabel(&page1, 328, 237, 32, 53, "", style::window::font::small, RectangleEdgeFlags::GUI_RECT_EDGE_BOTTOM | RectangleEdgeFlags::GUI_RECT_EDGE_TOP, - Alignment(Alignment::ALIGN_HORIZONTAL_CENTER, Alignment::ALIGN_VERTICAL_CENTER)); + numberPrimaryLabel = addLabel(&page1, + 328, + 237, + 32, + 53, + "", + style::window::font::small, + RectangleEdgeFlags::GUI_RECT_EDGE_BOTTOM | RectangleEdgeFlags::GUI_RECT_EDGE_TOP, + Alignment(Alignment::ALIGN_HORIZONTAL_CENTER, Alignment::ALIGN_VERTICAL_CENTER)); numberPrimaryLabel->inputCallback = [=](Item &item, const InputEvent &input) { - if (input.keyCode == KeyCode::KEY_ENTER && input.state == InputEvent::State::keyReleasedShort) - { + if (input.keyCode == KeyCode::KEY_ENTER && input.state == InputEvent::State::keyReleasedShort) { return app::call(application, app::CallOperation::ExecuteCall, contact->numbers[0].numberE164); } LOG_DEBUG("numberPrimayLabel->inputCallback just return false"); @@ -105,16 +158,24 @@ namespace gui page1.push_back(numberPrimaryIcon); numberPrimaryMessageLabel = - addLabel(&page1, 401, 237, 32, 53, "", style::window::font::small, RectangleEdgeFlags::GUI_RECT_EDGE_BOTTOM | RectangleEdgeFlags::GUI_RECT_EDGE_TOP, + addLabel(&page1, + 401, + 237, + 32, + 53, + "", + style::window::font::small, + RectangleEdgeFlags::GUI_RECT_EDGE_BOTTOM | RectangleEdgeFlags::GUI_RECT_EDGE_TOP, Alignment(Alignment::ALIGN_HORIZONTAL_CENTER, Alignment::ALIGN_VERTICAL_CENTER)); numberPrimaryMessageLabel->setPenFocusWidth(3); numberPrimaryMessageLabel->setPenWidth(0); numberPrimaryMessageLabel->inputCallback = [=](Item &item, const InputEvent &input) { - if (input.keyCode == KeyCode::KEY_ENTER) - { + if (input.keyCode == KeyCode::KEY_ENTER) { LOG_DEBUG("numberPrimayLabel->inputCallback switch to sms window"); - return sapm::ApplicationManager::messageSwitchApplication(application, app::name_messages, gui::name::window::thread_view, + return sapm::ApplicationManager::messageSwitchApplication(application, + app::name_messages, + gui::name::window::thread_view, std::make_unique(contact)); } LOG_DEBUG("numberPrimaryMessageLabel->inputCallback just return false"); @@ -125,17 +186,30 @@ namespace gui page1.push_back(numberPrimaryMessage); // second number line - numberSecondary = addLabel(&page1, 30, 306, 178, 33, "", style::window::font::big, RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES, + numberSecondary = addLabel(&page1, + 30, + 306, + 178, + 33, + "", + style::window::font::big, + RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES, Alignment(Alignment::ALIGN_HORIZONTAL_CENTER, Alignment::ALIGN_VERTICAL_CENTER)); numberSecondaryLabel = - addLabel(&page1, 328, 297, 32, 53, "", style::window::font::small, RectangleEdgeFlags::GUI_RECT_EDGE_BOTTOM | RectangleEdgeFlags::GUI_RECT_EDGE_TOP, + addLabel(&page1, + 328, + 297, + 32, + 53, + "", + style::window::font::small, + RectangleEdgeFlags::GUI_RECT_EDGE_BOTTOM | RectangleEdgeFlags::GUI_RECT_EDGE_TOP, Alignment(Alignment::ALIGN_HORIZONTAL_CENTER, Alignment::ALIGN_VERTICAL_CENTER)); numberSecondaryLabel->setPenFocusWidth(3); numberSecondaryLabel->setPenWidth(0); numberSecondaryLabel->inputCallback = [=](Item &item, const InputEvent &input) { - if (input.keyCode == KeyCode::KEY_ENTER) - { + if (input.keyCode == KeyCode::KEY_ENTER) { return app::call(application, app::CallOperation::ExecuteCall, contact->numbers[1].numberE164); } return (false); @@ -145,14 +219,22 @@ namespace gui page1.push_back(numberSecondaryIcon); numberSecondaryMessageLabel = - addLabel(&page1, 401, 297, 32, 53, "", style::window::font::small, RectangleEdgeFlags::GUI_RECT_EDGE_BOTTOM | RectangleEdgeFlags::GUI_RECT_EDGE_TOP, + addLabel(&page1, + 401, + 297, + 32, + 53, + "", + style::window::font::small, + RectangleEdgeFlags::GUI_RECT_EDGE_BOTTOM | RectangleEdgeFlags::GUI_RECT_EDGE_TOP, Alignment(Alignment::ALIGN_HORIZONTAL_CENTER, Alignment::ALIGN_VERTICAL_CENTER)); numberSecondaryMessageLabel->setPenFocusWidth(3); numberSecondaryMessageLabel->setPenWidth(0); numberSecondaryMessageLabel->inputCallback = [=](Item &item, const InputEvent &input) { - if (input.keyCode == KeyCode::KEY_ENTER) - { - return sapm::ApplicationManager::messageSwitchApplication(application, app::name_messages, gui::name::window::thread_view, + if (input.keyCode == KeyCode::KEY_ENTER) { + return sapm::ApplicationManager::messageSwitchApplication(application, + app::name_messages, + gui::name::window::thread_view, std::make_unique(contact)); } return (false); @@ -160,21 +242,57 @@ namespace gui numberSecondaryMessage = new Image(this, 401, 306, 32, 32, "mail"); page1.push_back(numberSecondaryMessage); - email = addLabel(&page1, 30, 363, 413, 33, "", style::window::font::big, RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES, + email = addLabel(&page1, + 30, + 363, + 413, + 33, + "", + style::window::font::big, + RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES, Alignment(Alignment::ALIGN_HORIZONTAL_LEFT, Alignment::ALIGN_VERTICAL_CENTER)); - addressLabel = - addLabel(&page1, 30, 429, 413, 20, utils::localize.get("app_phonebook_contact_address"), style::window::font::small, - RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES, Alignment(Alignment::ALIGN_HORIZONTAL_LEFT, Alignment::ALIGN_VERTICAL_BOTTOM), true); + addressLabel = addLabel(&page1, + 30, + 429, + 413, + 20, + utils::localize.get("app_phonebook_contact_address"), + style::window::font::small, + RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES, + Alignment(Alignment::ALIGN_HORIZONTAL_LEFT, Alignment::ALIGN_VERTICAL_BOTTOM), + true); - addressLine1 = addLabel(&page1, 30, 475, 422, 33, "", style::window::font::big, RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES, + addressLine1 = addLabel(&page1, + 30, + 475, + 422, + 33, + "", + style::window::font::big, + RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES, Alignment(Alignment::ALIGN_HORIZONTAL_LEFT, Alignment::ALIGN_VERTICAL_CENTER)); - addressLine2 = addLabel(&page1, 30, 508, 422, 33, "", style::window::font::big, RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES, + addressLine2 = addLabel(&page1, + 30, + 508, + 422, + 33, + "", + style::window::font::big, + RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES, Alignment(Alignment::ALIGN_HORIZONTAL_LEFT, Alignment::ALIGN_VERTICAL_CENTER)); - noteLabel = addLabel(&page2, 30, 203, 413, 20, utils::localize.get("app_phonebook_contact_note"), style::window::font::small, - RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES, Alignment(Alignment::ALIGN_HORIZONTAL_LEFT, Alignment::ALIGN_VERTICAL_BOTTOM), true); + noteLabel = addLabel(&page2, + 30, + 203, + 413, + 20, + utils::localize.get("app_phonebook_contact_note"), + style::window::font::small, + RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES, + Alignment(Alignment::ALIGN_HORIZONTAL_LEFT, Alignment::ALIGN_VERTICAL_BOTTOM), + true); noteText = new Text(this, 30, 249, 422, 600 - 249 - bottomBar->getHeight()); noteText->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES); @@ -203,8 +321,7 @@ namespace gui void PhonebookContact::setVisible(std::list *page, bool shouldBeVisible) { - for (auto i : *page) - { + for (auto i : *page) { i->setVisible(shouldBeVisible); } } @@ -221,8 +338,7 @@ namespace gui } void PhonebookContact::onBeforeShow(ShowMode mode, SwitchData *data) - { - } + {} ContactRecord PhonebookContact::readContact() { @@ -241,34 +357,28 @@ namespace gui if (contact && contact->primaryName.length() > 0 && contact->alternativeName.length() > 0) setTitle(contact->primaryName + " " + contact->alternativeName); - if (contact->speeddial >= 0 && contact->speeddial < 10) - { + if (contact->speeddial >= 0 && contact->speeddial < 10) { speedDial->setText(std::to_string(contact->speeddial)); } - else - { + else { speedDial->setText(UTF8("-")); } - if (contact->isOnFavourites == false) - { + if (contact->isOnFavourites == false) { LOG_INFO("setContactData contact %s is not on fav list", contact->primaryName.c_str()); favouritesIcon->setVisible(false); favouritesLabel->setVisible(false); } - else - { + else { LOG_INFO("setContactData contact %s is on fav list", contact->primaryName.c_str()); } - if (contact->isOnBlacklist == false) - { + if (contact->isOnBlacklist == false) { blockedLabel->setVisible(false); blockedIcon->setVisible(false); } - if (contact->numbers.size() == 0) - { + if (contact->numbers.size() == 0) { numberPrimary->setVisible(false); numberPrimaryLabel->setVisible(false); numberPrimaryIcon->setVisible(false); @@ -287,8 +397,7 @@ namespace gui addressLine2->setY(508 - 33); } - if (contact->numbers.size() == 1) - { + if (contact->numbers.size() == 1) { numberPrimary->setText(contact->numbers[0].numberE164); numberSecondary->setVisible(false); @@ -308,8 +417,7 @@ namespace gui addressLine2->setY(508 - 33); } - if (contact->numbers.size() == 2) - { + if (contact->numbers.size() == 2) { numberPrimary->setText(contact->numbers[0].numberE164); numberSecondary->setText(contact->numbers[1].numberE164); @@ -319,41 +427,35 @@ namespace gui addressLine2->setY(508); } - if (contact->mail.length() > 0) - { + if (contact->mail.length() > 0) { email->setText(contact->mail); } - else - { + else { email->setVisible(false); } - if (contact->street.length() > 0) - { + if (contact->street.length() > 0) { addressLine1->setText(contact->street); } - if (contact->city.length() > 0) - { + if (contact->city.length() > 0) { addressLine2->setText(contact->city); } - if (contact->note.length() > 0) - { + if (contact->note.length() > 0) { noteText->setText(contact->note); } } bool PhonebookContact::handleSwitchData(SwitchData *data) { - if (data == nullptr) - { + if (data == nullptr) { LOG_ERROR("Received null pointer"); return false; } PhonebookItemData *item = dynamic_cast(data); - contact = item->getContact(); + contact = item->getContact(); setContactData(); @@ -362,9 +464,8 @@ namespace gui bool PhonebookContact::onInput(const InputEvent &inputEvent) { - if ((inputEvent.state != InputEvent::State::keyReleasedShort) && ((inputEvent.state != InputEvent::State::keyReleasedLong)) && - inputEvent.keyCode == KeyCode::KEY_LF) - { + if ((inputEvent.state != InputEvent::State::keyReleasedShort) && + ((inputEvent.state != InputEvent::State::keyReleasedLong)) && inputEvent.keyCode == KeyCode::KEY_LF) { std::unique_ptr data = std::make_unique(contact); application->switchWindow("Options", gui::ShowMode::GUI_SHOW_INIT, std::move(data)); return (true); diff --git a/module-apps/application-phonebook/windows/PhonebookContact.hpp b/module-apps/application-phonebook/windows/PhonebookContact.hpp index 1cafa95c8..f9b046554 100644 --- a/module-apps/application-phonebook/windows/PhonebookContact.hpp +++ b/module-apps/application-phonebook/windows/PhonebookContact.hpp @@ -33,8 +33,7 @@ static inline const std::string formatContactName(std::shared_ptr static inline void findAndReplaceAll(std::string &data, std::string toSearch, std::string replaceStr) { size_t pos = data.find(toSearch); - while (pos != std::string::npos) - { + while (pos != std::string::npos) { data.replace(pos, toSearch.size(), replaceStr); pos = data.find(toSearch, pos + replaceStr.size()); } @@ -65,36 +64,36 @@ namespace gui protected: /** labels */ Label *informationLabel = nullptr; - Label *ifnormation = nullptr; - Label *addressLabel = nullptr; - Label *addressLine1 = nullptr; - Label *addressLine2 = nullptr; - Label *email = nullptr; - Label *numberPrimary = nullptr; - Label *numberSecondary = nullptr; - Label *favouritesLabel = nullptr; - Label *speeddialLabel = nullptr; - Label *blockedLabel = nullptr; - Label *speedDialLabel = nullptr; - Label *speedDial = nullptr; - Label *noteLabel = nullptr; - Text *noteText = nullptr; + Label *ifnormation = nullptr; + Label *addressLabel = nullptr; + Label *addressLine1 = nullptr; + Label *addressLine2 = nullptr; + Label *email = nullptr; + Label *numberPrimary = nullptr; + Label *numberSecondary = nullptr; + Label *favouritesLabel = nullptr; + Label *speeddialLabel = nullptr; + Label *blockedLabel = nullptr; + Label *speedDialLabel = nullptr; + Label *speedDial = nullptr; + Label *noteLabel = nullptr; + Text *noteText = nullptr; /** icons */ Image *favouritesIcon = nullptr; - Image *blockedIcon = nullptr; + Image *blockedIcon = nullptr; Label *numberPrimaryLabel = nullptr; - Image *numberPrimaryIcon = nullptr; + Image *numberPrimaryIcon = nullptr; Label *numberPrimaryMessageLabel = nullptr; - Image *numberPrimaryMessage = nullptr; + Image *numberPrimaryMessage = nullptr; Label *numberSecondaryLabel = nullptr; - Image *numberSecondaryIcon = nullptr; + Image *numberSecondaryIcon = nullptr; Label *numberSecondaryMessageLabel = nullptr; - Image *numberSecondaryMessage = nullptr; + Image *numberSecondaryMessage = nullptr; ContactRecord readContact(); @@ -118,7 +117,15 @@ namespace gui void buildInterface() override; void destroyInterface() override; void setContactData(); - Label *addLabel(std::list *parentPage, int x, int y, int w, int h, const std::string text, const std::string fontName, - const RectangleEdgeFlags edges, const Alignment alignment, const bool lineMode); + Label *addLabel(std::list *parentPage, + int x, + int y, + int w, + int h, + const std::string text, + const std::string fontName, + const RectangleEdgeFlags edges, + const Alignment alignment, + const bool lineMode); }; } // namespace gui \ No newline at end of file diff --git a/module-apps/application-phonebook/windows/PhonebookDialogs.cpp b/module-apps/application-phonebook/windows/PhonebookDialogs.cpp index 1ee45cdbd..07dac6c18 100644 --- a/module-apps/application-phonebook/windows/PhonebookDialogs.cpp +++ b/module-apps/application-phonebook/windows/PhonebookDialogs.cpp @@ -77,7 +77,7 @@ bool PhonebookDialog::handleSwitchData(SwitchData *data) return false; PhonebookItemData *item = dynamic_cast(data); - contact = item->getContact(); + contact = item->getContact(); setContactData(); @@ -86,8 +86,7 @@ bool PhonebookDialog::handleSwitchData(SwitchData *data) bool PhonebookDialog::onInput(const InputEvent &inputEvent) { - if (inputEvent.keyCode == KeyCode::KEY_RF && (inputEvent.state == InputEvent::State::keyReleasedShort)) - { + if (inputEvent.keyCode == KeyCode::KEY_RF && (inputEvent.state == InputEvent::State::keyReleasedShort)) { std::unique_ptr data = std::make_unique(contact); application->switchWindow("Options", gui::ShowMode::GUI_SHOW_INIT, std::move(data)); contact = nullptr; @@ -103,9 +102,8 @@ void PhonebookDeleteContact::onBeforeShow(ShowMode mode, SwitchData *data) icon = new Image(this, 176, 135, 128, 128, "phonebook_contact_delete_trashcan"); noLabel->inputCallback = [=](gui::Item &item, const InputEvent &inputEvent) { - if ((inputEvent.keyCode == KeyCode::KEY_ENTER) && - ((inputEvent.state == InputEvent::State::keyReleasedShort) || (inputEvent.state == InputEvent::State::keyReleasedLong))) - { + if ((inputEvent.keyCode == KeyCode::KEY_ENTER) && ((inputEvent.state == InputEvent::State::keyReleasedShort) || + (inputEvent.state == InputEvent::State::keyReleasedLong))) { std::unique_ptr data = std::make_unique(contact); application->switchWindow("Options", gui::ShowMode::GUI_SHOW_INIT, std::move(data)); return (true); @@ -114,16 +112,13 @@ void PhonebookDeleteContact::onBeforeShow(ShowMode mode, SwitchData *data) }; yesLabel->inputCallback = [=](gui::Item &item, const InputEvent &inputEvent) { - if ((inputEvent.keyCode == KeyCode::KEY_ENTER) && - ((inputEvent.state == InputEvent::State::keyReleasedShort) || (inputEvent.state == InputEvent::State::keyReleasedLong))) - { + if ((inputEvent.keyCode == KeyCode::KEY_ENTER) && ((inputEvent.state == InputEvent::State::keyReleasedShort) || + (inputEvent.state == InputEvent::State::keyReleasedLong))) { - if (DBServiceAPI::ContactRemove(application, contact->dbID)) - { + if (DBServiceAPI::ContactRemove(application, contact->dbID)) { LOG_INFO("contact %d removed, switch to MainWindow", contact->dbID); } - else - { + else { LOG_ERROR("failed to delete contact with id %d", contact->dbID); } @@ -147,15 +142,12 @@ void PhonebookBlockContact::onBeforeShow(ShowMode mode, SwitchData *data) confirmationLabel->setText(utils::localize.get("app_phonebook_options_block_confirm")); noLabel->inputCallback = [=](gui::Item &item, const InputEvent &inputEvent) { - if ((inputEvent.keyCode == KeyCode::KEY_ENTER) && - ((inputEvent.state == InputEvent::State::keyReleasedShort) || (inputEvent.state == InputEvent::State::keyReleasedLong))) - { - if (DBServiceAPI::ContactBlock(application, contact->dbID, false)) - { + if ((inputEvent.keyCode == KeyCode::KEY_ENTER) && ((inputEvent.state == InputEvent::State::keyReleasedShort) || + (inputEvent.state == InputEvent::State::keyReleasedLong))) { + if (DBServiceAPI::ContactBlock(application, contact->dbID, false)) { LOG_INFO("contact %d unblocked, switch to MainWindow", contact->dbID); } - else - { + else { LOG_ERROR("failed to unblock contact with id %d", contact->dbID); } @@ -167,15 +159,12 @@ void PhonebookBlockContact::onBeforeShow(ShowMode mode, SwitchData *data) }; yesLabel->inputCallback = [=](gui::Item &item, const InputEvent &inputEvent) { - if ((inputEvent.keyCode == KeyCode::KEY_ENTER) && - ((inputEvent.state == InputEvent::State::keyReleasedShort) || (inputEvent.state == InputEvent::State::keyReleasedLong))) - { - if (DBServiceAPI::ContactBlock(application, contact->dbID, true)) - { + if ((inputEvent.keyCode == KeyCode::KEY_ENTER) && ((inputEvent.state == InputEvent::State::keyReleasedShort) || + (inputEvent.state == InputEvent::State::keyReleasedLong))) { + if (DBServiceAPI::ContactBlock(application, contact->dbID, true)) { LOG_INFO("contact %d blocked, switch to MainWindow", contact->dbID); } - else - { + else { LOG_ERROR("failed to block contact with id %d", contact->dbID); } @@ -193,38 +182,36 @@ void PhonebookBlockContact::setContactData() } DuplicatedContactDialogWindow::DuplicatedContactDialogWindow(app::Application *app) - : Dialog(app, gui::window::name::duplicatedContact, + : Dialog(app, + gui::window::name::duplicatedContact, { - .title = "", - .icon = "phonebook_info", - .text = utils::localize.get("app_phonebook_duplicate_speed_dial"), + .title = "", + .icon = "phonebook_info", + .text = utils::localize.get("app_phonebook_duplicate_speed_dial"), .action = []() -> bool { LOG_INFO("!"); return true; }, }) -{ -} +{} bool DuplicatedContactDialogWindow::handleSwitchData(SwitchData *data) { - if (data == nullptr) - { + if (data == nullptr) { return false; } PhonebookItemData *item = dynamic_cast(data); - if (item != nullptr) - { + if (item != nullptr) { auto record = item->getContact(); - auto meta = this->meta; + auto meta = this->meta; meta.action = [=]() -> bool { application->switchWindow(gui::window::name::newContact, std::make_unique(record)); return true; }; meta.title = item->text; - meta.text = updateText(meta.text, *record); + meta.text = updateText(meta.text, *record); this->update(meta); application->switchWindow(gui::window::name::duplicatedContact, nullptr); return true; @@ -256,9 +243,8 @@ void PhonebookDuplicateSpeedDial::onBeforeShow(ShowMode mode, SwitchData *data) dialValue->setAlignement(Alignment(Alignment::ALIGN_HORIZONTAL_CENTER, Alignment::ALIGN_VERTICAL_CENTER)); noLabel->inputCallback = [=](gui::Item &item, const InputEvent &inputEvent) { - if ((inputEvent.keyCode == KeyCode::KEY_ENTER) && - ((inputEvent.state == InputEvent::State::keyReleasedShort) || (inputEvent.state == InputEvent::State::keyReleasedLong))) - { + if ((inputEvent.keyCode == KeyCode::KEY_ENTER) && ((inputEvent.state == InputEvent::State::keyReleasedShort) || + (inputEvent.state == InputEvent::State::keyReleasedLong))) { std::unique_ptr data = std::make_unique(contact); application->switchWindow(gui::window::name::newContact, gui::ShowMode::GUI_SHOW_INIT, std::move(data)); } @@ -266,17 +252,13 @@ void PhonebookDuplicateSpeedDial::onBeforeShow(ShowMode mode, SwitchData *data) }; yesLabel->inputCallback = [=](gui::Item &item, const InputEvent &inputEvent) { - if ((inputEvent.keyCode == KeyCode::KEY_ENTER) && - ((inputEvent.state == InputEvent::State::keyReleasedShort) || (inputEvent.state == InputEvent::State::keyReleasedLong))) - { - if (contact != nullptr) - { - if (DBServiceAPI::ContactUpdate(application, *contact) == false) - { + if ((inputEvent.keyCode == KeyCode::KEY_ENTER) && ((inputEvent.state == InputEvent::State::keyReleasedShort) || + (inputEvent.state == InputEvent::State::keyReleasedLong))) { + if (contact != nullptr) { + if (DBServiceAPI::ContactUpdate(application, *contact) == false) { LOG_ERROR("can't update contact %s", contact->primaryName.c_str()); } - else - { + else { LOG_INFO("Contact %s updated", contact->primaryName.c_str()); } } diff --git a/module-apps/application-phonebook/windows/PhonebookDialogs.hpp b/module-apps/application-phonebook/windows/PhonebookDialogs.hpp index 3fe1b81e2..87c44809f 100644 --- a/module-apps/application-phonebook/windows/PhonebookDialogs.hpp +++ b/module-apps/application-phonebook/windows/PhonebookDialogs.hpp @@ -41,10 +41,10 @@ class PhonebookDialog : public AppWindow virtual void setContactData() = 0; protected: - Text *confirmationLabel = nullptr; - Label *noLabel = nullptr; - Label *yesLabel = nullptr; - Image *icon = nullptr; + Text *confirmationLabel = nullptr; + Label *noLabel = nullptr; + Label *yesLabel = nullptr; + Image *icon = nullptr; std::shared_ptr contact = nullptr; }; @@ -75,8 +75,7 @@ class PhonebookBlockContact : public PhonebookDialog { public: PhonebookBlockContact(app::Application *app) : PhonebookDialog(app, "Block") - { - } + {} virtual ~PhonebookBlockContact() = default; void onBeforeShow(ShowMode mode, SwitchData *data); void setContactData(); @@ -100,8 +99,7 @@ class PhonebookDuplicateSpeedDial : public PhonebookDialog public: PhonebookDuplicateSpeedDial(app::Application *app) : PhonebookDialog(app, "SpeedDialAlreadyAssigned") - { - } + {} virtual ~PhonebookDuplicateSpeedDial() = default; void onBeforeShow(ShowMode mode, SwitchData *data); void setContactData(); diff --git a/module-apps/application-phonebook/windows/PhonebookErrors.cpp b/module-apps/application-phonebook/windows/PhonebookErrors.cpp index bd5f66fcd..4ed418fb1 100644 --- a/module-apps/application-phonebook/windows/PhonebookErrors.cpp +++ b/module-apps/application-phonebook/windows/PhonebookErrors.cpp @@ -11,9 +11,17 @@ using namespace ErrorWindows; -static Label *addLabel(gui::Item *parentPage, int x, int y, int w, int h, const std::string text = "", const std::string fontName = style::window::font::small, +static Label *addLabel(gui::Item *parentPage, + int x, + int y, + int w, + int h, + const std::string text = "", + const std::string fontName = style::window::font::small, const RectangleEdgeFlags edges = RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES, - const Alignment alignment = Alignment(Alignment::ALIGN_HORIZONTAL_LEFT, Alignment::ALIGN_VERTICAL_BOTTOM), const bool lineMode = false) + const Alignment alignment = Alignment(Alignment::ALIGN_HORIZONTAL_LEFT, + Alignment::ALIGN_VERTICAL_BOTTOM), + const bool lineMode = false) { Label *l = new Label(parentPage, x, y, w, h); l->setFilled(false); @@ -32,8 +40,7 @@ NoResults::NoResults(app::Application *app) : AppWindow(app, "NoResults") } NoResults::~NoResults() -{ -} +{} void NoResults::buildInterface() { @@ -46,7 +53,8 @@ void NoResults::buildInterface() bottomBar->setText(BottomBar::Side::RIGHT, utils::localize.get("app_phonebook_back")); - topSeparatorLabel = addLabel(this, 0, 104, style::window_width, 1, "", style::window::font::small, RectangleEdgeFlags::GUI_RECT_EDGE_BOTTOM); + topSeparatorLabel = addLabel( + this, 0, 104, style::window_width, 1, "", style::window::font::small, RectangleEdgeFlags::GUI_RECT_EDGE_BOTTOM); informationLabel = new Text(this, 45, 315, 390, 90); informationLabel->setText(utils::localize.get("app_phonebook_search_no_results")); @@ -60,8 +68,7 @@ void NoResults::buildInterface() } void NoResults::rebuild() -{ -} +{} void NoResults::destroyInterface() { @@ -70,14 +77,13 @@ void NoResults::destroyInterface() bool NoResults::handleSwitchData(SwitchData *data) { - if (data == nullptr) - { + if (data == nullptr) { LOG_ERROR("Received null pointer"); return false; } PhonebookSearchQuery *item = dynamic_cast(data); - searchQuery = item->getQuery(); + searchQuery = item->getQuery(); setContactData(); @@ -86,13 +92,13 @@ bool NoResults::handleSwitchData(SwitchData *data) void NoResults::setContactData() { - setTitle(utils::localize.get("app_phonebook_search_results").c_str() + std::string(":\"") + searchQuery.c_str() + std::string("\"")); + setTitle(utils::localize.get("app_phonebook_search_results").c_str() + std::string(":\"") + searchQuery.c_str() + + std::string("\"")); } bool NoResults::onInput(const InputEvent &inputEvent) { - if (inputEvent.keyCode == KeyCode::KEY_RF && (inputEvent.state == InputEvent::State::keyReleasedShort)) - { + if (inputEvent.keyCode == KeyCode::KEY_RF && (inputEvent.state == InputEvent::State::keyReleasedShort)) { std::unique_ptr data = std::make_unique(searchQuery); application->switchWindow("Search", gui::ShowMode::GUI_SHOW_INIT, std::move(data)); return (true); @@ -110,8 +116,7 @@ ContactBlocked::ContactBlocked(app::Application *app) : AppWindow(app, "NoResult } ContactBlocked::~ContactBlocked() -{ -} +{} void ContactBlocked::buildInterface() { @@ -123,7 +128,8 @@ void ContactBlocked::buildInterface() bottomBar->setActive(BottomBar::Side::RIGHT, true); bottomBar->setText(BottomBar::Side::RIGHT, utils::localize.get("app_phonebook_back")); - topSeparatorLabel = addLabel(this, 0, 104, style::window_width, 1, "", style::window::font::small, RectangleEdgeFlags::GUI_RECT_EDGE_BOTTOM); + topSeparatorLabel = addLabel( + this, 0, 104, style::window_width, 1, "", style::window::font::small, RectangleEdgeFlags::GUI_RECT_EDGE_BOTTOM); informationLabel = new Text(this, 45, 315, 390, 90); informationLabel->setText(utils::localize.get("app_phonebook_search_no_results")); @@ -149,14 +155,13 @@ void ContactBlocked::destroyInterface() bool ContactBlocked::handleSwitchData(SwitchData *data) { - if (data == nullptr) - { + if (data == nullptr) { LOG_ERROR("Received null pointer"); return false; } PhonebookSearchQuery *item = dynamic_cast(data); - searchQuery = item->getQuery(); + searchQuery = item->getQuery(); setContactData(); @@ -165,13 +170,13 @@ bool ContactBlocked::handleSwitchData(SwitchData *data) void ContactBlocked::setContactData() { - setTitle(utils::localize.get("app_phonebook_search_results").c_str() + std::string(":\"") + searchQuery.c_str() + std::string("\"")); + setTitle(utils::localize.get("app_phonebook_search_results").c_str() + std::string(":\"") + searchQuery.c_str() + + std::string("\"")); } bool ContactBlocked::onInput(const InputEvent &inputEvent) { - if (inputEvent.keyCode == KeyCode::KEY_RF && (inputEvent.state == InputEvent::State::keyReleasedShort)) - { + if (inputEvent.keyCode == KeyCode::KEY_RF && (inputEvent.state == InputEvent::State::keyReleasedShort)) { std::unique_ptr data = std::make_unique(searchQuery); application->switchWindow("Search", gui::ShowMode::GUI_SHOW_INIT, std::move(data)); return (true); diff --git a/module-apps/application-phonebook/windows/PhonebookErrors.hpp b/module-apps/application-phonebook/windows/PhonebookErrors.hpp index 647eac313..549d0266a 100644 --- a/module-apps/application-phonebook/windows/PhonebookErrors.hpp +++ b/module-apps/application-phonebook/windows/PhonebookErrors.hpp @@ -16,47 +16,47 @@ using namespace gui; namespace ErrorWindows { -class NoResults : public AppWindow -{ - protected: - /** labels */ - Label *topSeparatorLabel = nullptr; - Text *informationLabel = nullptr; - Image *searchCenter; - std::string searchQuery; + class NoResults : public AppWindow + { + protected: + /** labels */ + Label *topSeparatorLabel = nullptr; + Text *informationLabel = nullptr; + Image *searchCenter; + std::string searchQuery; - public: - NoResults(app::Application *app); - virtual ~NoResults(); - bool onInput(const InputEvent &inputEvent) override; - bool handleSwitchData(SwitchData *data) override; - void rebuild() override; - void buildInterface() override; - void destroyInterface() override; + public: + NoResults(app::Application *app); + virtual ~NoResults(); + bool onInput(const InputEvent &inputEvent) override; + bool handleSwitchData(SwitchData *data) override; + void rebuild() override; + void buildInterface() override; + void destroyInterface() override; - private: - void setContactData(); -}; + private: + void setContactData(); + }; -class ContactBlocked : public AppWindow -{ - protected: - /** labels */ - Label *topSeparatorLabel = nullptr; - Text *informationLabel = nullptr; - Image *searchCenter; - std::string searchQuery; + class ContactBlocked : public AppWindow + { + protected: + /** labels */ + Label *topSeparatorLabel = nullptr; + Text *informationLabel = nullptr; + Image *searchCenter; + std::string searchQuery; - public: - ContactBlocked(app::Application *app); - virtual ~ContactBlocked(); - bool onInput(const InputEvent &inputEvent) override; - bool handleSwitchData(SwitchData *data) override; - void rebuild() override; - void buildInterface() override; - void destroyInterface() override; + public: + ContactBlocked(app::Application *app); + virtual ~ContactBlocked(); + bool onInput(const InputEvent &inputEvent) override; + bool handleSwitchData(SwitchData *data) override; + void rebuild() override; + void buildInterface() override; + void destroyInterface() override; - private: - void setContactData(); -}; + private: + void setContactData(); + }; }; // namespace ErrorWindows diff --git a/module-apps/application-phonebook/windows/PhonebookMainWindow.cpp b/module-apps/application-phonebook/windows/PhonebookMainWindow.cpp index 147df7bc2..568585dea 100644 --- a/module-apps/application-phonebook/windows/PhonebookMainWindow.cpp +++ b/module-apps/application-phonebook/windows/PhonebookMainWindow.cpp @@ -17,122 +17,121 @@ namespace gui { - PhonebookMainWindow::PhonebookMainWindow(app::Application *app) : AppWindow(app, gui::name::window::main_window), phonebookModel{new PhonebookModel(app)} + PhonebookMainWindow::PhonebookMainWindow(app::Application *app) + : AppWindow(app, gui::name::window::main_window), phonebookModel{new PhonebookModel(app)} { buildInterface(); -} - -void PhonebookMainWindow::rebuild() -{ - destroyInterface(); - buildInterface(); -} - -void PhonebookMainWindow::buildInterface() -{ - AppWindow::buildInterface(); - - list = new gui::PhonebookListView(this, 11, 105, 480 - 22, 600 - 105 - 50); - list->setMaxElements(7); - list->setPageSize(7); - list->setPenFocusWidth(0); - list->setPenWidth(0); - list->setProvider(phonebookModel); - list->setApplication(application); - - bottomBar->setActive(BottomBar::Side::LEFT, true); - bottomBar->setActive(BottomBar::Side::CENTER, true); - bottomBar->setActive(BottomBar::Side::RIGHT, true); - bottomBar->setText(BottomBar::Side::LEFT, utils::localize.get("app_phonebook_call")); - bottomBar->setText(BottomBar::Side::CENTER, utils::localize.get("app_phonebook_open")); - bottomBar->setText(BottomBar::Side::RIGHT, utils::localize.get("app_phonebook_back")); - - topBar->setActive(TopBar::Elements::TIME, true); - - setTitle(utils::localize.get("app_phonebook_title_main")); - - leftArrowImage = new gui::Image(this, 30, 62, 0, 0, "arrow_left"); - rightArrowImage = new gui::Image(this, 480 - 30 - 13, 62, 0, 0, "arrow_right"); - newContactImage = new gui::Image(this, 48, 55, 0, 0, "cross"); - searchImage = new gui::Image(this, 480 - 48 - 26, 55, 0, 0, "search"); -} - -void PhonebookMainWindow::destroyInterface() -{ - AppWindow::destroyInterface(); - - removeWidget(list); - delete list; - list = nullptr; - - removeWidget(leftArrowImage); - delete leftArrowImage; - leftArrowImage = nullptr; - - removeWidget(rightArrowImage); - delete rightArrowImage; - rightArrowImage = nullptr; - - removeWidget(newContactImage); - delete newContactImage; - newContactImage = nullptr; - - removeWidget(searchImage); - delete searchImage; - searchImage = nullptr; - - children.clear(); - delete phonebookModel; -} - -PhonebookMainWindow::~PhonebookMainWindow() -{ - destroyInterface(); -} - -void PhonebookMainWindow::onBeforeShow(ShowMode mode, SwitchData *data) -{ - LOG_INFO("onBeforeShow"); - setFocusItem(list); - - phonebookModel->clear(); - phonebookModel->requestRecordsCount(); - - list->clear(); - list->setElementsCount(phonebookModel->getItemCount()); -} - -bool PhonebookMainWindow::onInput(const InputEvent &inputEvent) -{ - // process only if key is released - if (inputEvent.state == InputEvent::State::keyReleasedShort) - { - switch (inputEvent.keyCode) - { - case KeyCode::KEY_LEFT: { - std::unique_ptr data = std::make_unique(); - application->switchWindow(gui::window::name::newContact, gui::ShowMode::GUI_SHOW_INIT, std::move(data)); - } - return true; - case KeyCode::KEY_RIGHT: - application->switchWindow("Search"); - return true; - default: - break; - } } - // check if any of the lower inheritance onInput methods catch the event - return AppWindow::onInput(inputEvent); -} + void PhonebookMainWindow::rebuild() + { + destroyInterface(); + buildInterface(); + } -bool PhonebookMainWindow::onDatabaseMessage(sys::Message *msgl) -{ - DBContactResponseMessage *msg = reinterpret_cast(msgl); - if (phonebookModel->updateRecords(std::move(msg->records), msg->offset, msg->limit, msg->count, msg->favourite)) - return true; + void PhonebookMainWindow::buildInterface() + { + AppWindow::buildInterface(); - return false; -} + list = new gui::PhonebookListView(this, 11, 105, 480 - 22, 600 - 105 - 50); + list->setMaxElements(7); + list->setPageSize(7); + list->setPenFocusWidth(0); + list->setPenWidth(0); + list->setProvider(phonebookModel); + list->setApplication(application); + + bottomBar->setActive(BottomBar::Side::LEFT, true); + bottomBar->setActive(BottomBar::Side::CENTER, true); + bottomBar->setActive(BottomBar::Side::RIGHT, true); + bottomBar->setText(BottomBar::Side::LEFT, utils::localize.get("app_phonebook_call")); + bottomBar->setText(BottomBar::Side::CENTER, utils::localize.get("app_phonebook_open")); + bottomBar->setText(BottomBar::Side::RIGHT, utils::localize.get("app_phonebook_back")); + + topBar->setActive(TopBar::Elements::TIME, true); + + setTitle(utils::localize.get("app_phonebook_title_main")); + + leftArrowImage = new gui::Image(this, 30, 62, 0, 0, "arrow_left"); + rightArrowImage = new gui::Image(this, 480 - 30 - 13, 62, 0, 0, "arrow_right"); + newContactImage = new gui::Image(this, 48, 55, 0, 0, "cross"); + searchImage = new gui::Image(this, 480 - 48 - 26, 55, 0, 0, "search"); + } + + void PhonebookMainWindow::destroyInterface() + { + AppWindow::destroyInterface(); + + removeWidget(list); + delete list; + list = nullptr; + + removeWidget(leftArrowImage); + delete leftArrowImage; + leftArrowImage = nullptr; + + removeWidget(rightArrowImage); + delete rightArrowImage; + rightArrowImage = nullptr; + + removeWidget(newContactImage); + delete newContactImage; + newContactImage = nullptr; + + removeWidget(searchImage); + delete searchImage; + searchImage = nullptr; + + children.clear(); + delete phonebookModel; + } + + PhonebookMainWindow::~PhonebookMainWindow() + { + destroyInterface(); + } + + void PhonebookMainWindow::onBeforeShow(ShowMode mode, SwitchData *data) + { + LOG_INFO("onBeforeShow"); + setFocusItem(list); + + phonebookModel->clear(); + phonebookModel->requestRecordsCount(); + + list->clear(); + list->setElementsCount(phonebookModel->getItemCount()); + } + + bool PhonebookMainWindow::onInput(const InputEvent &inputEvent) + { + // process only if key is released + if (inputEvent.state == InputEvent::State::keyReleasedShort) { + switch (inputEvent.keyCode) { + case KeyCode::KEY_LEFT: { + std::unique_ptr data = std::make_unique(); + application->switchWindow(gui::window::name::newContact, gui::ShowMode::GUI_SHOW_INIT, std::move(data)); + } + return true; + case KeyCode::KEY_RIGHT: + application->switchWindow("Search"); + return true; + default: + break; + } + } + + // check if any of the lower inheritance onInput methods catch the event + return AppWindow::onInput(inputEvent); + } + + bool PhonebookMainWindow::onDatabaseMessage(sys::Message *msgl) + { + DBContactResponseMessage *msg = reinterpret_cast(msgl); + if (phonebookModel->updateRecords(std::move(msg->records), msg->offset, msg->limit, msg->count, msg->favourite)) + return true; + + return false; + } } /* namespace gui */ diff --git a/module-apps/application-phonebook/windows/PhonebookMainWindow.hpp b/module-apps/application-phonebook/windows/PhonebookMainWindow.hpp index 08f03ff83..1a4148e4f 100644 --- a/module-apps/application-phonebook/windows/PhonebookMainWindow.hpp +++ b/module-apps/application-phonebook/windows/PhonebookMainWindow.hpp @@ -14,29 +14,29 @@ namespace gui { -class PhonebookMainWindow : public AppWindow -{ - protected: - PhonebookListView *list; - PhonebookModel *phonebookModel = nullptr; + class PhonebookMainWindow : public AppWindow + { + protected: + PhonebookListView *list; + PhonebookModel *phonebookModel = nullptr; - Image *leftArrowImage = nullptr; - Image *rightArrowImage = nullptr; - Image *newContactImage = nullptr; - Image *searchImage = nullptr; + Image *leftArrowImage = nullptr; + Image *rightArrowImage = nullptr; + Image *newContactImage = nullptr; + Image *searchImage = nullptr; - public: - PhonebookMainWindow(app::Application *app); - virtual ~PhonebookMainWindow(); + public: + PhonebookMainWindow(app::Application *app); + virtual ~PhonebookMainWindow(); - // virtual methods - bool onInput(const InputEvent &inputEvent) override; - void onBeforeShow(ShowMode mode, SwitchData *data) override; - bool onDatabaseMessage(sys::Message *msgl) override; + // virtual methods + bool onInput(const InputEvent &inputEvent) override; + void onBeforeShow(ShowMode mode, SwitchData *data) override; + bool onDatabaseMessage(sys::Message *msgl) override; - void rebuild() override; - void buildInterface() override; - void destroyInterface() override; -}; + void rebuild() override; + void buildInterface() override; + void destroyInterface() override; + }; } /* namespace gui */ diff --git a/module-apps/application-phonebook/windows/PhonebookNewContact.cpp b/module-apps/application-phonebook/windows/PhonebookNewContact.cpp index 64bc49e4d..8cf983efa 100644 --- a/module-apps/application-phonebook/windows/PhonebookNewContact.cpp +++ b/module-apps/application-phonebook/windows/PhonebookNewContact.cpp @@ -20,622 +20,567 @@ namespace gui PhonebookNewContact::PhonebookNewContact(app::Application *app) : AppWindow(app, window::name::newContact) { buildInterface(); -} - -void PhonebookNewContact::rebuild() -{ - destroyInterface(); - buildInterface(); -} - -void PhonebookNewContact::buildInterface() -{ - AppWindow::buildInterface(); - - bottomBar->setActive(BottomBar::Side::LEFT, false); - bottomBar->setActive(BottomBar::Side::CENTER, false); - bottomBar->setActive(BottomBar::Side::RIGHT, true); - bottomBar->setText(BottomBar::Side::CENTER, utils::localize.get("app_phonebook_save")); - bottomBar->setText(BottomBar::Side::RIGHT, utils::localize.get("app_phonebook_back")); - - topBar->setActive(TopBar::Elements::TIME, true); - - title = new gui::Label(this, 0, 50, 480, 54); - title->setFilled(false); - title->setBorderColor(gui::ColorFullBlack); - title->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_BOTTOM); - title->setMargins(Margins(0, 0, 0, 18)); - title->setFont(style::window::font::small); - if (contact) - { - title->setText(utils::localize.get("app_phonebook_contact_edit")); - } - else - { - title->setText(utils::localize.get("app_phonebook_contact_title")); - } - title->setAlignement(gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_CENTER, gui::Alignment::ALIGN_VERTICAL_BOTTOM)); - - // page 1 labels and text - for (uint32_t i = 0; i < 5; i++) - { - - page1.labels[i] = new gui::Label(this, 30, 114 + 87 * i, 450, 35); - page1.labels[i]->setFilled(false); - page1.labels[i]->setBorderColor(gui::ColorFullBlack); - page1.labels[i]->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES); - page1.labels[i]->setFont(style::window::font::small); - if (i == 0) - page1.labels[i]->setFont(style::footer::font::bold); - - page1.labels[i]->setAlignement(gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_LEFT, gui::Alignment::ALIGN_VERTICAL_BOTTOM)); - - page1.text[i] = new gui::Text(this, 30, 157 + 87 * i, 420, 42); - page1.text[i]->setFilled(false); - page1.text[i]->setPenFocusWidth(2); - page1.text[i]->setPenWidth(1); - page1.text[i]->setBorderColor(gui::ColorFullBlack); - page1.text[i]->setUnderline(true); - page1.text[i]->setTextType(Text::TextType::SINGLE_LINE); - page1.text[i]->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES); - page1.text[i]->setFont(style::window::font::small); - page1.text[i]->setInputMode(new InputMode({InputMode::ABC, InputMode::abc})); - - if ((i == 2) || (i == 3)) - { - page1.text[i]->focusChangedCallback = [=](gui::Item &item) { - if (item.focus) - { - page1.text[i]->setFont(style::window::font::bigbold); - } - else - { - page1.text[i]->setFont(style::window::font::small); - } - return true; - }; - } - else - { - page1.text[i]->focusChangedCallback = [=](gui::Item &item) { - if (item.focus) - { - page1.text[i]->setFont(style::window::font::bigbold); - } - else - { - page1.text[i]->setFont(style::window::font::small); - } - return true; - }; - - page1.text[i]->contentCallback = [=](gui::Item &item) { return true; }; - } - - page1.text[i]->setTextType(gui::Text::TextType::SINGLE_LINE); - page1.text[i]->setEditMode(gui::Text::EditMode::EDIT); } - page1.text[2]->setInputMode(new InputMode({InputMode::digit})); - page1.text[3]->setInputMode(new InputMode({InputMode::digit})); - - // set navigation for page 1 - for (uint32_t i = 0; i < 4; i++) + void PhonebookNewContact::rebuild() { - page1.text[i]->setNavigationItem(NavigationDirection::DOWN, page1.text[i + 1]); - page1.text[i + 1]->setNavigationItem(NavigationDirection::UP, page1.text[i]); + destroyInterface(); + buildInterface(); } - page1.text[4]->setNavigationItem(NavigationDirection::UP, page1.text[3]); - page1.labels[0]->setText(utils::localize.get("app_phonebook_new_contact_first_name")); - page1.labels[1]->setText(utils::localize.get("app_phonebook_new_contact_second_name")); - page1.labels[2]->setText(utils::localize.get("app_phonebook_new_contact_number_1")); - page1.labels[3]->setText(utils::localize.get("app_phonebook_new_contact_number_2")); - page1.labels[4]->setText(utils::localize.get("app_phonebook_new_contact_email")); + void PhonebookNewContact::buildInterface() + { + AppWindow::buildInterface(); - // page2 - page2.speedValue = new gui::Label(this, 30, 105, 56, 47); - page2.speedValue->setFilled(false); - page2.speedValue->setBorderColor(gui::ColorFullBlack); - page2.speedValue->setPenFocusWidth(3); - page2.speedValue->setPenWidth(1); - page2.speedValue->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_BOTTOM); - page2.speedValue->setFont(style::window::font::small); - page2.speedValue->setAlignement(gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_CENTER, gui::Alignment::ALIGN_VERTICAL_BOTTOM)); + bottomBar->setActive(BottomBar::Side::LEFT, false); + bottomBar->setActive(BottomBar::Side::CENTER, false); + bottomBar->setActive(BottomBar::Side::RIGHT, true); + bottomBar->setText(BottomBar::Side::CENTER, utils::localize.get("app_phonebook_save")); + bottomBar->setText(BottomBar::Side::RIGHT, utils::localize.get("app_phonebook_back")); - page2.speedValue->focusChangedCallback = [=](gui::Item &item) { return true; }; + topBar->setActive(TopBar::Elements::TIME, true); - page2.speedValue->inputCallback = [=](gui::Item &item, const InputEvent &inputEvent) { - int val = gui::toNumeric(inputEvent.keyCode); - if ((val >= 0) && (val < 9)) - { - page2.speedValue->setText(std::to_string(val)); - return true; + title = new gui::Label(this, 0, 50, 480, 54); + title->setFilled(false); + title->setBorderColor(gui::ColorFullBlack); + title->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_BOTTOM); + title->setMargins(Margins(0, 0, 0, 18)); + title->setFont(style::window::font::small); + if (contact) { + title->setText(utils::localize.get("app_phonebook_contact_edit")); } - return false; - }; - - page2.speedDescription = new gui::Label(this, 100, 105, 330, 47); - page2.speedDescription->setFilled(false); - page2.speedDescription->setBorderColor(gui::ColorFullBlack); - page2.speedDescription->setPenFocusWidth(0); - page2.speedDescription->setPenWidth(0); - page2.speedDescription->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES); - page2.speedDescription->setFont(style::window::font::small); - page2.speedDescription->setAlignement(gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_LEFT, gui::Alignment::ALIGN_VERTICAL_BOTTOM)); - - page2.imageSpeed = new gui::Image(this, 416, 122, 0, 0, "small_circle"); - - page2.favValue = new gui::Label(this, 30, 161, 56, 47); - page2.favValue->setFilled(false); - page2.favValue->setBorderColor(gui::ColorFullBlack); - page2.favValue->setPenFocusWidth(3); - page2.favValue->setPenWidth(1); - page2.favValue->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_BOTTOM); - page2.favValue->setFont(style::window::font::small); - page2.favValue->setAlignement(gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_LEFT, gui::Alignment::ALIGN_VERTICAL_BOTTOM)); - - page2.favValue->focusChangedCallback = [=](gui::Item &item) { - if (item.focus) - { - bottomBar->setText(BottomBar::Side::CENTER, "SELECT"); + else { + title->setText(utils::localize.get("app_phonebook_contact_title")); } - else - { - bottomBar->setText(BottomBar::Side::CENTER, utils::localize.get("app_phonebook_save")); - } - return true; - }; + title->setAlignement( + gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_CENTER, gui::Alignment::ALIGN_VERTICAL_BOTTOM)); - page2.favValue->inputCallback = [=](gui::Item &item, const InputEvent &inputEvent) { - if ((inputEvent.keyCode == KeyCode::KEY_ENTER) && - ((inputEvent.state == InputEvent::State::keyReleasedShort) || (inputEvent.state == InputEvent::State::keyReleasedLong))) - { - if (page2.favSelected) - { - page2.imageTick->setVisible(false); - page2.favSelected = false; - LOG_INFO("Removed from favourites"); + // page 1 labels and text + for (uint32_t i = 0; i < 5; i++) { + + page1.labels[i] = new gui::Label(this, 30, 114 + 87 * i, 450, 35); + page1.labels[i]->setFilled(false); + page1.labels[i]->setBorderColor(gui::ColorFullBlack); + page1.labels[i]->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES); + page1.labels[i]->setFont(style::window::font::small); + if (i == 0) + page1.labels[i]->setFont(style::footer::font::bold); + + page1.labels[i]->setAlignement( + gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_LEFT, gui::Alignment::ALIGN_VERTICAL_BOTTOM)); + + page1.text[i] = new gui::Text(this, 30, 157 + 87 * i, 420, 42); + page1.text[i]->setFilled(false); + page1.text[i]->setPenFocusWidth(2); + page1.text[i]->setPenWidth(1); + page1.text[i]->setBorderColor(gui::ColorFullBlack); + page1.text[i]->setUnderline(true); + page1.text[i]->setTextType(Text::TextType::SINGLE_LINE); + page1.text[i]->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES); + page1.text[i]->setFont(style::window::font::small); + page1.text[i]->setInputMode(new InputMode({InputMode::ABC, InputMode::abc})); + + if ((i == 2) || (i == 3)) { + page1.text[i]->focusChangedCallback = [=](gui::Item &item) { + if (item.focus) { + page1.text[i]->setFont(style::window::font::bigbold); + } + else { + page1.text[i]->setFont(style::window::font::small); + } + return true; + }; } - else - { + else { + page1.text[i]->focusChangedCallback = [=](gui::Item &item) { + if (item.focus) { + page1.text[i]->setFont(style::window::font::bigbold); + } + else { + page1.text[i]->setFont(style::window::font::small); + } + return true; + }; + + page1.text[i]->contentCallback = [=](gui::Item &item) { return true; }; + } + + page1.text[i]->setTextType(gui::Text::TextType::SINGLE_LINE); + page1.text[i]->setEditMode(gui::Text::EditMode::EDIT); + } + + page1.text[2]->setInputMode(new InputMode({InputMode::digit})); + page1.text[3]->setInputMode(new InputMode({InputMode::digit})); + + // set navigation for page 1 + for (uint32_t i = 0; i < 4; i++) { + page1.text[i]->setNavigationItem(NavigationDirection::DOWN, page1.text[i + 1]); + page1.text[i + 1]->setNavigationItem(NavigationDirection::UP, page1.text[i]); + } + page1.text[4]->setNavigationItem(NavigationDirection::UP, page1.text[3]); + + page1.labels[0]->setText(utils::localize.get("app_phonebook_new_contact_first_name")); + page1.labels[1]->setText(utils::localize.get("app_phonebook_new_contact_second_name")); + page1.labels[2]->setText(utils::localize.get("app_phonebook_new_contact_number_1")); + page1.labels[3]->setText(utils::localize.get("app_phonebook_new_contact_number_2")); + page1.labels[4]->setText(utils::localize.get("app_phonebook_new_contact_email")); + + // page2 + page2.speedValue = new gui::Label(this, 30, 105, 56, 47); + page2.speedValue->setFilled(false); + page2.speedValue->setBorderColor(gui::ColorFullBlack); + page2.speedValue->setPenFocusWidth(3); + page2.speedValue->setPenWidth(1); + page2.speedValue->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_BOTTOM); + page2.speedValue->setFont(style::window::font::small); + page2.speedValue->setAlignement( + gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_CENTER, gui::Alignment::ALIGN_VERTICAL_BOTTOM)); + + page2.speedValue->focusChangedCallback = [=](gui::Item &item) { return true; }; + + page2.speedValue->inputCallback = [=](gui::Item &item, const InputEvent &inputEvent) { + int val = gui::toNumeric(inputEvent.keyCode); + if ((val >= 0) && (val < 9)) { + page2.speedValue->setText(std::to_string(val)); + return true; + } + return false; + }; + + page2.speedDescription = new gui::Label(this, 100, 105, 330, 47); + page2.speedDescription->setFilled(false); + page2.speedDescription->setBorderColor(gui::ColorFullBlack); + page2.speedDescription->setPenFocusWidth(0); + page2.speedDescription->setPenWidth(0); + page2.speedDescription->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES); + page2.speedDescription->setFont(style::window::font::small); + page2.speedDescription->setAlignement( + gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_LEFT, gui::Alignment::ALIGN_VERTICAL_BOTTOM)); + + page2.imageSpeed = new gui::Image(this, 416, 122, 0, 0, "small_circle"); + + page2.favValue = new gui::Label(this, 30, 161, 56, 47); + page2.favValue->setFilled(false); + page2.favValue->setBorderColor(gui::ColorFullBlack); + page2.favValue->setPenFocusWidth(3); + page2.favValue->setPenWidth(1); + page2.favValue->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_BOTTOM); + page2.favValue->setFont(style::window::font::small); + page2.favValue->setAlignement( + gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_LEFT, gui::Alignment::ALIGN_VERTICAL_BOTTOM)); + + page2.favValue->focusChangedCallback = [=](gui::Item &item) { + if (item.focus) { + bottomBar->setText(BottomBar::Side::CENTER, "SELECT"); + } + else { + bottomBar->setText(BottomBar::Side::CENTER, utils::localize.get("app_phonebook_save")); + } + return true; + }; + + page2.favValue->inputCallback = [=](gui::Item &item, const InputEvent &inputEvent) { + if ((inputEvent.keyCode == KeyCode::KEY_ENTER) && + ((inputEvent.state == InputEvent::State::keyReleasedShort) || + (inputEvent.state == InputEvent::State::keyReleasedLong))) { + if (page2.favSelected) { + page2.imageTick->setVisible(false); + page2.favSelected = false; + LOG_INFO("Removed from favourites"); + } + else { + page2.imageTick->setVisible(true); + page2.favSelected = true; + LOG_INFO("Added to favourites"); + } + application->refreshWindow(RefreshModes::GUI_REFRESH_FAST); + return true; + } + return false; + }; + + page2.favDescription = new gui::Label(this, 100, 161, 330, 47); + page2.favDescription->setFilled(false); + page2.favDescription->setBorderColor(gui::ColorFullBlack); + page2.favDescription->setPenFocusWidth(0); + page2.favDescription->setPenWidth(0); + page2.favDescription->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES); + page2.favDescription->setFont(style::window::font::small); + page2.favDescription->setAlignement( + gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_LEFT, gui::Alignment::ALIGN_VERTICAL_BOTTOM)); + + page2.imageTick = new gui::Image(this, 43, 174, 0, 0, "small_tick"); + page2.imageTick->setVisible(false); + + page2.imageFav = new gui::Image(this, 416, 177, 0, 0, "small_heart"); + + page2.speedDescription->setText(utils::localize.get("app_phonebook_new_speed_dial_key")); + page2.favDescription->setText(utils::localize.get("app_phonebook_new_addto_fav")); + + page2.addressLabel = new gui::Label(this, 30, 241, 450, 35); + page2.addressLabel->setFilled(false); + page2.addressLabel->setBorderColor(gui::ColorFullBlack); + page2.addressLabel->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES); + page2.addressLabel->setFont(style::window::font::small); + page2.addressLabel->setAlignement( + gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_LEFT, gui::Alignment::ALIGN_VERTICAL_BOTTOM)); + page2.addressLabel->setText(utils::localize.get("app_phonebook_new_contact_address")); + + page2.noteLabel = new gui::Label(this, 30, 357, 450, 35); + page2.noteLabel->setFilled(false); + page2.noteLabel->setBorderColor(gui::ColorFullBlack); + page2.noteLabel->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES); + page2.noteLabel->setFont(style::window::font::small); + page2.noteLabel->setAlignement( + gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_LEFT, gui::Alignment::ALIGN_VERTICAL_BOTTOM)); + page2.noteLabel->setText(utils::localize.get("app_phonebook_new_contact_note")); + + for (uint32_t i = 0; i < 2; i++) { + page2.text[i] = new gui::Text(this, 30, 272 + 126 * i, 420, 90); + page2.text[i]->setFilled(false); + page2.text[i]->setPenFocusWidth(2); + page2.text[i]->setPenWidth(1); + page2.text[i]->setUnderline(true); + page2.text[i]->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES); + page2.text[i]->setBorderColor(gui::ColorFullBlack); + page2.text[i]->setMargins(Margins(0, 0, 0, 0)); + page2.text[i]->setFont(style::window::font::small); + page2.text[i]->setInputMode(new InputMode({InputMode::ABC, InputMode::abc})); + page2.text[i]->contentCallback = [=](gui::Item &item) { return true; }; + } + + page2.speedValue->setNavigationItem(NavigationDirection::DOWN, page2.favValue); + + page2.favValue->setNavigationItem(NavigationDirection::DOWN, page2.text[0]); + page2.favValue->setNavigationItem(NavigationDirection::UP, page2.speedValue); + + page2.text[0]->setNavigationItem(NavigationDirection::DOWN, page2.text[1]); + page2.text[0]->setNavigationItem(NavigationDirection::UP, page2.favValue); + + page2.text[1]->setNavigationItem(NavigationDirection::UP, page2.text[0]); + } + + void PhonebookNewContact::destroyInterface() + { + AppWindow::destroyInterface(); + + if (title) { + removeWidget(title); + delete title; + title = nullptr; + } + + // page 1 + for (uint32_t i = 0; i < 5; i++) { + if (page1.labels[i]) { + removeWidget(page1.labels[i]); + delete page1.labels[i]; + page1.labels[i] = nullptr; + } + if (page1.text[i]) { + removeWidget(page1.text[i]); + delete page1.text[i]; + page1.text[i] = nullptr; + } + } + + if (page2.speedValue) { + removeWidget(page2.speedValue); + delete page2.speedValue; + page2.speedValue = nullptr; + } + if (page2.speedDescription) { + removeWidget(page2.speedDescription); + delete page2.speedDescription; + page2.speedDescription = nullptr; + } + if (page2.imageSpeed) { + removeWidget(page2.imageSpeed); + delete page2.imageSpeed; + page2.imageSpeed = nullptr; + } + if (page2.favValue) { + removeWidget(page2.favValue); + delete page2.favValue; + page2.favValue = nullptr; + } + if (page2.favDescription) { + removeWidget(page2.favDescription); + delete page2.favDescription; + page2.favDescription = nullptr; + } + if (page2.imageFav) { + removeWidget(page2.imageFav); + delete page2.imageFav; + page2.imageFav = nullptr; + } + if (page2.imageTick) { + removeWidget(page2.imageTick); + delete page2.imageTick; + page2.imageTick = nullptr; + } + if (page2.addressLabel) { + removeWidget(page2.addressLabel); + delete page2.addressLabel; + page2.addressLabel = nullptr; + } + if (page2.noteLabel) { + removeWidget(page2.noteLabel); + delete page2.noteLabel; + page2.noteLabel = nullptr; + } + for (uint32_t i = 0; i < 2; i++) { + if (page2.text[i]) { + removeWidget(page2.text[i]); + delete page2.text[i]; + page2.text[i] = nullptr; + } + } + + children.clear(); + } + + PhonebookNewContact::~PhonebookNewContact() + { + destroyInterface(); + } + + void PhonebookNewContact::saveStateChanged() + { + if (isValidName(page1.text[0]->getText()) > 0 && isValidNumber(page1.text[2]->getText())) { + bottomBar->setActive(BottomBar::Side::CENTER, true); + } + else { + bottomBar->setActive(BottomBar::Side::CENTER, false); + } + } + + void PhonebookNewContact::coppyDataToContact() + { + if (contact) { + contact->primaryName = page1.text[0]->getText(); + contact->alternativeName = page1.text[1]->getText(); + + contact->numbers.clear(); + + contact->numbers.push_back(ContactRecord::Number(page1.text[2]->getText())); + contact->numbers.push_back(ContactRecord::Number(page1.text[3]->getText())); + + contact->mail = page1.text[4]->getText(); + contact->note = page2.text[1]->getText(); + contact->isOnFavourites = page2.favSelected; + contact->speeddial = atoi(page2.speedValue->getText().c_str()); + } + } + + void PhonebookNewContact::setContactData() + { + if (contact) { + page1.text[0]->setText(contact->primaryName); + page1.text[1]->setText(contact->alternativeName); + if (contact->numbers.size() > 0) { + if (contact->numbers[0].numberE164.length() == 0) { + page1.text[2]->setText(getCountryPrefix()); + } + else { + page1.text[2]->setText(contact->numbers[0].numberE164); + } + } + if (contact->numbers.size() > 1) { + if (contact->numbers[1].numberE164.length() == 0) { + page1.text[3]->setText(getCountryPrefix()); + } + else { + page1.text[3]->setText(contact->numbers[1].numberE164); + } + } + page1.text[4]->setText(contact->mail); + + page2.text[1]->setText(contact->note); + if (contact->isOnFavourites) { page2.imageTick->setVisible(true); page2.favSelected = true; - LOG_INFO("Added to favourites"); } - application->refreshWindow(RefreshModes::GUI_REFRESH_FAST); - return true; - } - return false; - }; - - page2.favDescription = new gui::Label(this, 100, 161, 330, 47); - page2.favDescription->setFilled(false); - page2.favDescription->setBorderColor(gui::ColorFullBlack); - page2.favDescription->setPenFocusWidth(0); - page2.favDescription->setPenWidth(0); - page2.favDescription->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES); - page2.favDescription->setFont(style::window::font::small); - page2.favDescription->setAlignement(gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_LEFT, gui::Alignment::ALIGN_VERTICAL_BOTTOM)); - - page2.imageTick = new gui::Image(this, 43, 174, 0, 0, "small_tick"); - page2.imageTick->setVisible(false); - - page2.imageFav = new gui::Image(this, 416, 177, 0, 0, "small_heart"); - - page2.speedDescription->setText(utils::localize.get("app_phonebook_new_speed_dial_key")); - page2.favDescription->setText(utils::localize.get("app_phonebook_new_addto_fav")); - - page2.addressLabel = new gui::Label(this, 30, 241, 450, 35); - page2.addressLabel->setFilled(false); - page2.addressLabel->setBorderColor(gui::ColorFullBlack); - page2.addressLabel->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES); - page2.addressLabel->setFont(style::window::font::small); - page2.addressLabel->setAlignement(gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_LEFT, gui::Alignment::ALIGN_VERTICAL_BOTTOM)); - page2.addressLabel->setText(utils::localize.get("app_phonebook_new_contact_address")); - - page2.noteLabel = new gui::Label(this, 30, 357, 450, 35); - page2.noteLabel->setFilled(false); - page2.noteLabel->setBorderColor(gui::ColorFullBlack); - page2.noteLabel->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES); - page2.noteLabel->setFont(style::window::font::small); - page2.noteLabel->setAlignement(gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_LEFT, gui::Alignment::ALIGN_VERTICAL_BOTTOM)); - page2.noteLabel->setText(utils::localize.get("app_phonebook_new_contact_note")); - - for (uint32_t i = 0; i < 2; i++) - { - page2.text[i] = new gui::Text(this, 30, 272 + 126 * i, 420, 90); - page2.text[i]->setFilled(false); - page2.text[i]->setPenFocusWidth(2); - page2.text[i]->setPenWidth(1); - page2.text[i]->setUnderline(true); - page2.text[i]->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES); - page2.text[i]->setBorderColor(gui::ColorFullBlack); - page2.text[i]->setMargins(Margins(0, 0, 0, 0)); - page2.text[i]->setFont(style::window::font::small); - page2.text[i]->setInputMode(new InputMode({InputMode::ABC, InputMode::abc})); - page2.text[i]->contentCallback = [=](gui::Item &item) { return true; }; - } - - page2.speedValue->setNavigationItem(NavigationDirection::DOWN, page2.favValue); - - page2.favValue->setNavigationItem(NavigationDirection::DOWN, page2.text[0]); - page2.favValue->setNavigationItem(NavigationDirection::UP, page2.speedValue); - - page2.text[0]->setNavigationItem(NavigationDirection::DOWN, page2.text[1]); - page2.text[0]->setNavigationItem(NavigationDirection::UP, page2.favValue); - - page2.text[1]->setNavigationItem(NavigationDirection::UP, page2.text[0]); -} - -void PhonebookNewContact::destroyInterface() -{ - AppWindow::destroyInterface(); - - if (title) - { - removeWidget(title); - delete title; - title = nullptr; - } - - // page 1 - for (uint32_t i = 0; i < 5; i++) - { - if (page1.labels[i]) - { - removeWidget(page1.labels[i]); - delete page1.labels[i]; - page1.labels[i] = nullptr; - } - if (page1.text[i]) - { - removeWidget(page1.text[i]); - delete page1.text[i]; - page1.text[i] = nullptr; - } - } - - if (page2.speedValue) - { - removeWidget(page2.speedValue); - delete page2.speedValue; - page2.speedValue = nullptr; - } - if (page2.speedDescription) - { - removeWidget(page2.speedDescription); - delete page2.speedDescription; - page2.speedDescription = nullptr; - } - if (page2.imageSpeed) - { - removeWidget(page2.imageSpeed); - delete page2.imageSpeed; - page2.imageSpeed = nullptr; - } - if (page2.favValue) - { - removeWidget(page2.favValue); - delete page2.favValue; - page2.favValue = nullptr; - } - if (page2.favDescription) - { - removeWidget(page2.favDescription); - delete page2.favDescription; - page2.favDescription = nullptr; - } - if (page2.imageFav) - { - removeWidget(page2.imageFav); - delete page2.imageFav; - page2.imageFav = nullptr; - } - if (page2.imageTick) - { - removeWidget(page2.imageTick); - delete page2.imageTick; - page2.imageTick = nullptr; - } - if (page2.addressLabel) - { - removeWidget(page2.addressLabel); - delete page2.addressLabel; - page2.addressLabel = nullptr; - } - if (page2.noteLabel) - { - removeWidget(page2.noteLabel); - delete page2.noteLabel; - page2.noteLabel = nullptr; - } - for (uint32_t i = 0; i < 2; i++) - { - if (page2.text[i]) - { - removeWidget(page2.text[i]); - delete page2.text[i]; - page2.text[i] = nullptr; - } - } - - children.clear(); -} - -PhonebookNewContact::~PhonebookNewContact() -{ - destroyInterface(); -} - -void PhonebookNewContact::saveStateChanged() -{ - if (isValidName(page1.text[0]->getText()) > 0 && isValidNumber(page1.text[2]->getText())) - { - bottomBar->setActive(BottomBar::Side::CENTER, true); - } - else - { - bottomBar->setActive(BottomBar::Side::CENTER, false); - } -} - -void PhonebookNewContact::coppyDataToContact() -{ - if (contact) - { - contact->primaryName = page1.text[0]->getText(); - contact->alternativeName = page1.text[1]->getText(); - - contact->numbers.clear(); - - contact->numbers.push_back(ContactRecord::Number(page1.text[2]->getText())); - contact->numbers.push_back(ContactRecord::Number(page1.text[3]->getText())); - - contact->mail = page1.text[4]->getText(); - contact->note = page2.text[1]->getText(); - contact->isOnFavourites = page2.favSelected; - contact->speeddial = atoi(page2.speedValue->getText().c_str()); - } -} - -void PhonebookNewContact::setContactData() -{ - if (contact) - { - page1.text[0]->setText(contact->primaryName); - page1.text[1]->setText(contact->alternativeName); - if (contact->numbers.size() > 0) - { - if (contact->numbers[0].numberE164.length() == 0) - { - page1.text[2]->setText(getCountryPrefix()); + else { + page2.imageTick->setVisible(false); + page2.favSelected = false; } + if (contact->speeddial >= 0 && contact->speeddial < 10) + page2.speedValue->setText(std::to_string(contact->speeddial)); else - { - page1.text[2]->setText(contact->numbers[0].numberE164); - } + page2.speedValue->setText("-"); + + saveStateChanged(); } - if (contact->numbers.size() > 1) - { - if (contact->numbers[1].numberE164.length() == 0) - { - page1.text[3]->setText(getCountryPrefix()); - } - else - { - page1.text[3]->setText(contact->numbers[1].numberE164); - } + else { + LOG_DEBUG("new contact create"); + page1.text[2]->setText(getCountryPrefix()); } - page1.text[4]->setText(contact->mail); + } - page2.text[1]->setText(contact->note); - if (contact->isOnFavourites) - { - page2.imageTick->setVisible(true); - page2.favSelected = true; + void PhonebookNewContact::switchPage(uint32_t page) + { + if (page == 0) { + page1.setVisibile(true); + page2.setVisibile(false); } - else - { - page2.imageTick->setVisible(false); - page2.favSelected = false; + else if (page == 1) { + page1.setVisibile(false); + page2.setVisibile(true); } - if (contact->speeddial >= 0 && contact->speeddial < 10) - page2.speedValue->setText(std::to_string(contact->speeddial)); - else - page2.speedValue->setText("-"); - - saveStateChanged(); - } - else - { - LOG_DEBUG("new contact create"); - page1.text[2]->setText(getCountryPrefix()); - } -} - -void PhonebookNewContact::switchPage(uint32_t page) -{ - if (page == 0) - { - page1.setVisibile(true); - page2.setVisibile(false); - } - else if (page == 1) - { - page1.setVisibile(false); - page2.setVisibile(true); - } -} - -void PhonebookNewContact::onBeforeShow(ShowMode mode, SwitchData *data) -{ - switchPage(0); - setFocusItem(page1.text[0]); - page2.favSelected = false; - page2.imageFav->setVisible(false); -} - -bool PhonebookNewContact::handleSwitchData(SwitchData *data) -{ - if (data == nullptr) - return false; - - PhonebookItemData *item = dynamic_cast(data); - if (item) - { - contact = item->getContact(); - setContactData(); } - return (true); -} - -bool PhonebookNewContact::onInput(const InputEvent &inputEvent) -{ - if (AppWindow::onInput(inputEvent)) + void PhonebookNewContact::onBeforeShow(ShowMode mode, SwitchData *data) { + switchPage(0); + setFocusItem(page1.text[0]); + page2.favSelected = false; + page2.imageFav->setVisible(false); + } + + bool PhonebookNewContact::handleSwitchData(SwitchData *data) + { + if (data == nullptr) + return false; + + PhonebookItemData *item = dynamic_cast(data); + if (item) { + contact = item->getContact(); + setContactData(); + } + return (true); } - if (inputEvent.state != InputEvent::State::keyReleasedShort) - return (false); - - saveStateChanged(); - - if (inputEvent.keyCode == KeyCode::KEY_ENTER) + bool PhonebookNewContact::onInput(const InputEvent &inputEvent) { - // if focus is on the favourite selection field do nothing - if (focusItem == page2.favValue) - { - return true; - } - - return (verifyAndSave()); - } - else if (inputEvent.keyCode == KeyCode::KEY_DOWN) - { - LOG_INFO("switching to second page"); - if (getFocusItem() == page1.text[4]) - { - switchPage(1); - setFocusItem(page2.speedValue); - } - } - else if (inputEvent.keyCode == KeyCode::KEY_UP) - { - LOG_INFO("switching to first page"); - if (getFocusItem() == page2.speedValue) - { - switchPage(0); - setFocusItem(page1.text[4]); - } - } - - return (false); -} - -bool PhonebookNewContact::verifyAndSave() -{ - ContactRecord record, errName, errPhone, errSpeed, errFav; - record.primaryName = page1.text[0]->getText(); - record.alternativeName = page1.text[1]->getText(); - record.numbers.push_back(page1.text[2]->getText()); - record.numbers.push_back(page1.text[3]->getText()); - record.mail = page1.text[4]->getText(); - record.note = page2.text[1]->getText(); - record.isOnFavourites = page2.favSelected; - record.speeddial = atoi(page2.speedValue->getText().c_str()); - - /** basic sanity checks */ - if (!isValidName(record.primaryName)) - { - LOG_ERROR("verifyAndSave name not valid"); - return (false); - } - - if (record.numbers.size() > 0 && isValidNumber(record.numbers[0].numberUser) == false) - { - LOG_ERROR("verifyAndSave primaryNumber not valid"); - return (false); - } - - if (contact == nullptr) // new contact - { - /** secondary verification against database data */ - DBServiceAPI::ContactVerificationError err = DBServiceAPI::verifyContact(application, record, errName, errPhone, errSpeed, errFav); - if (err != DBServiceAPI::noError) - { - if (err == DBServiceAPI::primaryNumberError) - { - std::unique_ptr data = std::make_unique(contact); - application->switchWindow("NumberAlreadyExists", gui::ShowMode::GUI_SHOW_INIT, std::move(data)); - } - - if (err == DBServiceAPI::speedDialError) - { - std::unique_ptr data = std::make_unique(contact); - application->switchWindow("SpeedDialAlreadyAssigned", gui::ShowMode::GUI_SHOW_INIT, std::move(data)); - } - LOG_ERROR("failed to verify contact data reason: \"%s\"", DBServiceAPI::getVerificationErrorString(err).c_str()); - return (false); - } - - if (DBServiceAPI::ContactAdd(application, record) == false) - { - LOG_ERROR("verifyAndSave failed to ADD contact"); - return (false); - } - else - { - coppyDataToContact(); - std::unique_ptr data = std::make_unique(contact); - application->switchWindow(gui::window::name::contact, gui::ShowMode::GUI_SHOW_INIT, std::move(data)); - LOG_INFO("verifyAndSave contact ADDED"); + if (AppWindow::onInput(inputEvent)) { return (true); } + + if (inputEvent.state != InputEvent::State::keyReleasedShort) + return (false); + + saveStateChanged(); + + if (inputEvent.keyCode == KeyCode::KEY_ENTER) { + // if focus is on the favourite selection field do nothing + if (focusItem == page2.favValue) { + return true; + } + + return (verifyAndSave()); + } + else if (inputEvent.keyCode == KeyCode::KEY_DOWN) { + LOG_INFO("switching to second page"); + if (getFocusItem() == page1.text[4]) { + switchPage(1); + setFocusItem(page2.speedValue); + } + } + else if (inputEvent.keyCode == KeyCode::KEY_UP) { + LOG_INFO("switching to first page"); + if (getFocusItem() == page2.speedValue) { + switchPage(0); + setFocusItem(page1.text[4]); + } + } + + return (false); } - else if (contact->dbID > 0) + + bool PhonebookNewContact::verifyAndSave() { - if (DBServiceAPI::ContactUpdate(application, record) == false) - { - LOG_ERROR("verifyAndSave failed to UPDATE contact"); + ContactRecord record, errName, errPhone, errSpeed, errFav; + record.primaryName = page1.text[0]->getText(); + record.alternativeName = page1.text[1]->getText(); + record.numbers.push_back(page1.text[2]->getText()); + record.numbers.push_back(page1.text[3]->getText()); + record.mail = page1.text[4]->getText(); + record.note = page2.text[1]->getText(); + record.isOnFavourites = page2.favSelected; + record.speeddial = atoi(page2.speedValue->getText().c_str()); + + /** basic sanity checks */ + if (!isValidName(record.primaryName)) { + LOG_ERROR("verifyAndSave name not valid"); return (false); } - else - { - coppyDataToContact(); - std::unique_ptr data = std::make_unique(contact); - application->switchWindow(gui::window::name::contact, gui::ShowMode::GUI_SHOW_INIT, std::move(data)); - LOG_INFO("verifyAndSave new contact UPDATED"); - return (true); + if (record.numbers.size() > 0 && isValidNumber(record.numbers[0].numberUser) == false) { + LOG_ERROR("verifyAndSave primaryNumber not valid"); + return (false); } - } - return (false); -} -const std::string PhonebookNewContact::getCountryPrefix() -{ - std::string imsi = CellularServiceAPI::GetIMSI(application, false); - if (imsi == "") - { - LOG_ERROR("Can't get IMSI code from cellular, fall back to Poland country code"); - return (app::defaultCountryCode); - } - LOG_DEBUG("getCountryPrefix imsi:%s", imsi.c_str()); - const uint32_t country_code = DBServiceAPI::GetCountryCodeByMCC(application, std::stoul(imsi)); - if (country_code <= 0) - { - LOG_ERROR("Can't get country code from database, fall back to Poland country code"); - return (app::defaultCountryCode); - } - LOG_DEBUG("getCountryPrefix country_code:%d", country_code); - std::string buf = "+"; - buf += std::to_string(country_code); + if (contact == nullptr) // new contact + { + /** secondary verification against database data */ + DBServiceAPI::ContactVerificationError err = + DBServiceAPI::verifyContact(application, record, errName, errPhone, errSpeed, errFav); + if (err != DBServiceAPI::noError) { + if (err == DBServiceAPI::primaryNumberError) { + std::unique_ptr data = std::make_unique(contact); + application->switchWindow("NumberAlreadyExists", gui::ShowMode::GUI_SHOW_INIT, std::move(data)); + } - LOG_DEBUG("getCountryPrefix return: \"%s\"", buf.c_str()); - return (buf); -} + if (err == DBServiceAPI::speedDialError) { + std::unique_ptr data = std::make_unique(contact); + application->switchWindow( + "SpeedDialAlreadyAssigned", gui::ShowMode::GUI_SHOW_INIT, std::move(data)); + } + LOG_ERROR("failed to verify contact data reason: \"%s\"", + DBServiceAPI::getVerificationErrorString(err).c_str()); + return (false); + } + + if (DBServiceAPI::ContactAdd(application, record) == false) { + LOG_ERROR("verifyAndSave failed to ADD contact"); + return (false); + } + else { + coppyDataToContact(); + std::unique_ptr data = std::make_unique(contact); + application->switchWindow(gui::window::name::contact, gui::ShowMode::GUI_SHOW_INIT, std::move(data)); + LOG_INFO("verifyAndSave contact ADDED"); + return (true); + } + } + else if (contact->dbID > 0) { + if (DBServiceAPI::ContactUpdate(application, record) == false) { + LOG_ERROR("verifyAndSave failed to UPDATE contact"); + return (false); + } + else { + coppyDataToContact(); + std::unique_ptr data = std::make_unique(contact); + application->switchWindow(gui::window::name::contact, gui::ShowMode::GUI_SHOW_INIT, std::move(data)); + + LOG_INFO("verifyAndSave new contact UPDATED"); + return (true); + } + } + + return (false); + } + const std::string PhonebookNewContact::getCountryPrefix() + { + std::string imsi = CellularServiceAPI::GetIMSI(application, false); + if (imsi == "") { + LOG_ERROR("Can't get IMSI code from cellular, fall back to Poland country code"); + return (app::defaultCountryCode); + } + LOG_DEBUG("getCountryPrefix imsi:%s", imsi.c_str()); + const uint32_t country_code = DBServiceAPI::GetCountryCodeByMCC(application, std::stoul(imsi)); + if (country_code <= 0) { + LOG_ERROR("Can't get country code from database, fall back to Poland country code"); + return (app::defaultCountryCode); + } + LOG_DEBUG("getCountryPrefix country_code:%d", country_code); + std::string buf = "+"; + buf += std::to_string(country_code); + + LOG_DEBUG("getCountryPrefix return: \"%s\"", buf.c_str()); + return (buf); + } } // namespace gui diff --git a/module-apps/application-phonebook/windows/PhonebookNewContact.hpp b/module-apps/application-phonebook/windows/PhonebookNewContact.hpp index 61500d742..7c3dfc6e8 100644 --- a/module-apps/application-phonebook/windows/PhonebookNewContact.hpp +++ b/module-apps/application-phonebook/windows/PhonebookNewContact.hpp @@ -21,97 +21,96 @@ namespace gui inline std::string newContact = "New"; } } // namespace window -class PhonebookNewContact : public AppWindow -{ - public: - enum class PageLabels + class PhonebookNewContact : public AppWindow { - Name, - Surname, - Number_1, - Number_2, - Email - }; - - protected: - gui::Label *title = nullptr; - - struct Page - { - virtual void setVisibile(bool visible) = 0; - }; - - struct Page1 : public Page - { - gui::Label *labels[5] = {nullptr}; - gui::Text *text[5] = {nullptr}; - void setVisibile(bool visible) + public: + enum class PageLabels { - for (uint32_t i = 0; i < 5; i++) + Name, + Surname, + Number_1, + Number_2, + Email + }; + + protected: + gui::Label *title = nullptr; + + struct Page + { + virtual void setVisibile(bool visible) = 0; + }; + + struct Page1 : public Page + { + gui::Label *labels[5] = {nullptr}; + gui::Text *text[5] = {nullptr}; + void setVisibile(bool visible) { - labels[i]->setVisible(visible); - text[i]->setVisible(visible); + for (uint32_t i = 0; i < 5; i++) { + labels[i]->setVisible(visible); + text[i]->setVisible(visible); + } } - } - }; + }; - struct Page2 : public Page - { - gui::Label *speedValue = nullptr; - gui::Label *speedDescription = nullptr; - gui::Image *imageSpeed = nullptr; - gui::Label *favValue = nullptr; - gui::Label *favDescription = nullptr; - gui::Image *imageFav = nullptr; - gui::Image *imageTick = nullptr; - - gui::Label *addressLabel = nullptr; - gui::Label *noteLabel = nullptr; - - gui::Text *text[2] = {nullptr}; - - bool favSelected = false; - - void setVisibile(bool visible) + struct Page2 : public Page { - speedValue->setVisible(visible); - speedDescription->setVisible(visible); - imageSpeed->setVisible(visible); - favValue->setVisible(visible); - favDescription->setVisible(visible); - imageFav->setVisible(visible); - imageTick->setVisible(visible); + gui::Label *speedValue = nullptr; + gui::Label *speedDescription = nullptr; + gui::Image *imageSpeed = nullptr; + gui::Label *favValue = nullptr; + gui::Label *favDescription = nullptr; + gui::Image *imageFav = nullptr; + gui::Image *imageTick = nullptr; - addressLabel->setVisible(visible); - noteLabel->setVisible(visible); - text[0]->setVisible(visible); - text[1]->setVisible(visible); - } + gui::Label *addressLabel = nullptr; + gui::Label *noteLabel = nullptr; + + gui::Text *text[2] = {nullptr}; + + bool favSelected = false; + + void setVisibile(bool visible) + { + speedValue->setVisible(visible); + speedDescription->setVisible(visible); + imageSpeed->setVisible(visible); + favValue->setVisible(visible); + favDescription->setVisible(visible); + imageFav->setVisible(visible); + imageTick->setVisible(visible); + + addressLabel->setVisible(visible); + noteLabel->setVisible(visible); + text[0]->setVisible(visible); + text[1]->setVisible(visible); + } + }; + + Page1 page1; + Page2 page2; + uint32_t page = 0; + + std::shared_ptr contact = nullptr; + + public: + PhonebookNewContact(app::Application *app); + virtual ~PhonebookNewContact(); + void switchPage(uint32_t page); + + // virtual methods + bool onInput(const InputEvent &inputEvent) override; + void onBeforeShow(ShowMode mode, SwitchData *data) override; + bool handleSwitchData(SwitchData *data) override; + void rebuild() override; + void buildInterface() override; + void destroyInterface() override; + bool verifyAndSave(); + void setContactData(); + void saveStateChanged(); + void coppyDataToContact(); + const std::string getCountryPrefix(); }; - Page1 page1; - Page2 page2; - uint32_t page = 0; - - std::shared_ptr contact = nullptr; - - public: - PhonebookNewContact(app::Application *app); - virtual ~PhonebookNewContact(); - void switchPage(uint32_t page); - - // virtual methods - bool onInput(const InputEvent &inputEvent) override; - void onBeforeShow(ShowMode mode, SwitchData *data) override; - bool handleSwitchData(SwitchData *data) override; - void rebuild() override; - void buildInterface() override; - void destroyInterface() override; - bool verifyAndSave(); - void setContactData(); - void saveStateChanged(); - void coppyDataToContact(); - const std::string getCountryPrefix(); -}; - } /* namespace gui */ diff --git a/module-apps/application-phonebook/windows/PhonebookOptions.cpp b/module-apps/application-phonebook/windows/PhonebookOptions.cpp index 15587690e..e181017d6 100644 --- a/module-apps/application-phonebook/windows/PhonebookOptions.cpp +++ b/module-apps/application-phonebook/windows/PhonebookOptions.cpp @@ -25,10 +25,11 @@ PhonebookOptions::PhonebookOptions(app::Application *app) : AppWindow(app, "Opti } PhonebookOptions::~PhonebookOptions() -{ -} +{} -gui::Item *PhonebookOptions::addOptionLabel(const std::string &text, bool hasSubOptions, std::function activatedCallback) +gui::Item *PhonebookOptions::addOptionLabel(const std::string &text, + bool hasSubOptions, + std::function activatedCallback) { gui::Label *label = new gui::Label(this, 19, 0, 480 - 21, 55, text); label->setMargins(gui::Margins(0, 0, 0, 0)); @@ -39,8 +40,7 @@ gui::Item *PhonebookOptions::addOptionLabel(const std::string &text, bool hasSub label->setAlignement(gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_LEFT, gui::Alignment::ALIGN_VERTICAL_CENTER)); label->activatedCallback = activatedCallback; label->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_BOTTOM | RectangleEdgeFlags::GUI_RECT_EDGE_TOP); - if (hasSubOptions) - { + if (hasSubOptions) { new gui::Image(label, 427, 20, 32, 32, "right_label_arrow"); } return label; @@ -69,11 +69,12 @@ void PhonebookOptions::buildInterface() return (true); })); - options.push_back(addOptionLabel(utils::localize.get("app_phonebook_options_forward_namecard"), true, [=](gui::Item &) { - std::unique_ptr data = std::make_unique(contact); - application->switchWindow("OptionsNamecard", gui::ShowMode::GUI_SHOW_INIT, std::move(data)); - return (true); - })); + options.push_back( + addOptionLabel(utils::localize.get("app_phonebook_options_forward_namecard"), true, [=](gui::Item &) { + std::unique_ptr data = std::make_unique(contact); + application->switchWindow("OptionsNamecard", gui::ShowMode::GUI_SHOW_INIT, std::move(data)); + return (true); + })); options.push_back(addOptionLabel(utils::localize.get("app_phonebook_options_block"), false, [=](gui::Item &) { std::unique_ptr data = std::make_unique(contact); @@ -90,8 +91,7 @@ void PhonebookOptions::buildInterface() // set position and navigation for labels uint32_t posY = 113; uint32_t size = options.size(); - for (uint32_t i = 0; i < options.size(); i++) - { + for (uint32_t i = 0; i < options.size(); i++) { options[i]->setPosition(17, posY); posY += 60; options[i]->setNavigationItem(NavigationDirection::DOWN, options[(i + 1) % size]); @@ -106,22 +106,20 @@ void PhonebookOptions::onBeforeShow(ShowMode mode, SwitchData *data) bool PhonebookOptions::handleSwitchData(SwitchData *data) { - if (data == nullptr) - { + if (data == nullptr) { LOG_ERROR("Received null pointer"); return false; } PhonebookItemData *item = dynamic_cast(data); - contact = item->getContact(); + contact = item->getContact(); return (true); } bool PhonebookOptions::onInput(const InputEvent &inputEvent) { LOG_INFO("PhonebookOptions::onInput state: %d keyCode: %d", inputEvent.state, inputEvent.keyCode); - if (inputEvent.keyCode == KeyCode::KEY_RF && inputEvent.state == InputEvent::State::keyReleasedShort) - { + if (inputEvent.keyCode == KeyCode::KEY_RF && inputEvent.state == InputEvent::State::keyReleasedShort) { std::unique_ptr data = std::make_unique(contact); application->switchWindow("Contact", gui::ShowMode::GUI_SHOW_INIT, std::move(data)); return (true); diff --git a/module-apps/application-phonebook/windows/PhonebookOptionsNamecard.cpp b/module-apps/application-phonebook/windows/PhonebookOptionsNamecard.cpp index 2fd703a6f..571f1520c 100644 --- a/module-apps/application-phonebook/windows/PhonebookOptionsNamecard.cpp +++ b/module-apps/application-phonebook/windows/PhonebookOptionsNamecard.cpp @@ -24,10 +24,11 @@ PhonebookOptionsNamecard::PhonebookOptionsNamecard(app::Application *app) : AppW } PhonebookOptionsNamecard::~PhonebookOptionsNamecard() -{ -} +{} -gui::Item *PhonebookOptionsNamecard::addOptionLabel(const std::string &text, bool hasSubOptions, std::function activatedCallback) +gui::Item *PhonebookOptionsNamecard::addOptionLabel(const std::string &text, + bool hasSubOptions, + std::function activatedCallback) { gui::Label *label = new gui::Label(this, 19, 0, 480 - 21, 55, text); label->setMargins(gui::Margins(0, 0, 0, 0)); @@ -38,8 +39,7 @@ gui::Item *PhonebookOptionsNamecard::addOptionLabel(const std::string &text, boo label->setAlignement(gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_LEFT, gui::Alignment::ALIGN_VERTICAL_CENTER)); label->activatedCallback = activatedCallback; label->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_BOTTOM | RectangleEdgeFlags::GUI_RECT_EDGE_TOP); - if (hasSubOptions) - { + if (hasSubOptions) { new gui::Image(label, 427, 20, 32, 32, "right_label_arrow"); } return label; @@ -72,8 +72,7 @@ void PhonebookOptionsNamecard::buildInterface() // set position and navigation for labels uint32_t posY = 113; uint32_t size = options.size(); - for (uint32_t i = 0; i < options.size(); i++) - { + for (uint32_t i = 0; i < options.size(); i++) { options[i]->setPosition(17, posY); posY += 60; options[i]->setNavigationItem(NavigationDirection::DOWN, options[(i + 1) % size]); @@ -97,21 +96,19 @@ void PhonebookOptionsNamecard::onBeforeShow(ShowMode mode, SwitchData *data) bool PhonebookOptionsNamecard::handleSwitchData(SwitchData *data) { - if (data == nullptr) - { + if (data == nullptr) { LOG_ERROR("Received null pointer"); return false; } PhonebookItemData *item = dynamic_cast(data); - contact = item->getContact(); + contact = item->getContact(); return (true); } bool PhonebookOptionsNamecard::onInput(const InputEvent &inputEvent) { - if (inputEvent.keyCode == KeyCode::KEY_RF && (inputEvent.state == InputEvent::State::keyReleasedShort)) - { + if (inputEvent.keyCode == KeyCode::KEY_RF && (inputEvent.state == InputEvent::State::keyReleasedShort)) { std::unique_ptr data = std::make_unique(contact); application->switchWindow("Options", gui::ShowMode::GUI_SHOW_INIT, std::move(data)); return true; @@ -143,8 +140,7 @@ const std::string PhonebookOptionsNamecard::formatVCARD() << "FN:" << contact->primaryName.c_str() << " " << contact->alternativeName.c_str() << "\n" << "TEL;TYPE=HOME,VOICE:" << priNumber << "\n"; - if (secNumber.length() > 0) - { + if (secNumber.length() > 0) { vcard << "TEL;TYPE=HOME,VOICE:" << secNumber << "\n"; } diff --git a/module-apps/application-phonebook/windows/PhonebookSearch.cpp b/module-apps/application-phonebook/windows/PhonebookSearch.cpp index 9782c96f7..764bdf945 100644 --- a/module-apps/application-phonebook/windows/PhonebookSearch.cpp +++ b/module-apps/application-phonebook/windows/PhonebookSearch.cpp @@ -9,158 +9,174 @@ #include "application-call/data/CallSwitchData.hpp" #include "service-db/api/DBServiceAPI.hpp" - namespace gui { -PhonebookSearch::PhonebookSearch(app::Application *app) : AppWindow(app, "Search"), phonebookModel{new PhonebookModel(app)} -{ - buildInterface(); -} - -PhonebookSearch::~PhonebookSearch() -{ -} - -Label *PhonebookSearch::addLabel(std::list *parentPage, int x, int y, int w, int h, const std::string text = "", - const std::string fontName = style::window::font::small, - const RectangleEdgeFlags edges = RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES, - const Alignment alignment = Alignment(Alignment::ALIGN_HORIZONTAL_LEFT, Alignment::ALIGN_VERTICAL_BOTTOM), - const bool lineMode = false) -{ - Label *l = new Label(this, x, y, w, h); - l->setFilled(false); - l->setBorderColor(ColorFullBlack); - l->setEdges(edges); - l->setFont(fontName); - l->setText(text); - l->setAlignement(alignment); - l->setLineMode(lineMode); - - if (parentPage) - parentPage->push_back(l); - - return (l); -} - -void PhonebookSearch::buildInterface() -{ - AppWindow::buildInterface(); - topBar->setActive(TopBar::Elements::TIME, true); - - setTitle(utils::localize.get("app_phonebook_title_main")); - - searchHeader = addLabel(nullptr, phonebookStyle::search::searchHeader::x, phonebookStyle::search::searchHeader::y, phonebookStyle::search::searchHeader::w, phonebookStyle::search::searchHeader::h, utils::localize.get("app_phonebook_search_win_search")); - searchHeader->setFont(style::window::font::small); - - inputField = new Text(nullptr, phonebookStyle::search::horizontalBox::inputField::x, phonebookStyle::search::horizontalBox::inputField::y, phonebookStyle::search::horizontalBox::inputField::w, phonebookStyle::search::horizontalBox::inputField::h); - inputField->setTextType(Text::TextType::SINGLE_LINE); - inputField->setEditMode(Text::EditMode::EDIT); - inputField->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES); - inputField->setInputMode(new InputMode({InputMode::ABC, InputMode::abc})); - inputField->setFont(style::window::font::mediumbold); - - searchTop = new Image(nullptr, phonebookStyle::search::horizontalBox::searchTop::x, phonebookStyle::search::horizontalBox::searchTop::y, phonebookStyle::search::horizontalBox::searchTop::w, phonebookStyle::search::horizontalBox::searchTop::h, "search"); - - horizontalBox = new HBox(this, phonebookStyle::search::horizontalBox::x, phonebookStyle::search::horizontalBox::y, phonebookStyle::search::horizontalBox::w, phonebookStyle::search::horizontalBox::h); - horizontalBox->addWidget(inputField); - horizontalBox->addWidget(searchTop); - horizontalBox->setPenWidth(phonebookStyle::search::horizontalBox::penWidth); - horizontalBox->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_BOTTOM); - - bottomBar->setActive(BottomBar::Side::LEFT, false); - bottomBar->setActive(BottomBar::Side::CENTER, true); - bottomBar->setActive(BottomBar::Side::RIGHT, true); - - bottomBar->setText(BottomBar::Side::CENTER, utils::localize.get("app_phonebook_search")); - bottomBar->setText(BottomBar::Side::RIGHT, utils::localize.get("app_phonebook_back")); - - setFocusItem(inputField); -} - -void PhonebookSearch::rebuild() -{ -} - -void PhonebookSearch::destroyInterface() -{ - AppWindow::destroyInterface(); -} - -void PhonebookSearch::onBeforeShow(ShowMode mode, SwitchData *data) -{ - setFocusItem(inputField); -} - -bool PhonebookSearch::handleSwitchData(SwitchData *data) -{ - if (data == nullptr) + PhonebookSearch::PhonebookSearch(app::Application *app) + : AppWindow(app, "Search"), phonebookModel{new PhonebookModel(app)} { - LOG_ERROR("Received null pointer"); - return false; + buildInterface(); } - PhonebookSearchQuery *item = dynamic_cast(data); - inputField->setText(item->getQuery()); + PhonebookSearch::~PhonebookSearch() + {} - return (true); -} - -bool PhonebookSearch::onInput(const InputEvent &inputEvent) -{ - bool ret = AppWindow::onInput(inputEvent); - if(ret) + Label *PhonebookSearch::addLabel(std::list *parentPage, + int x, + int y, + int w, + int h, + const std::string text = "", + const std::string fontName = style::window::font::small, + const RectangleEdgeFlags edges = RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES, + const Alignment alignment = Alignment(Alignment::ALIGN_HORIZONTAL_LEFT, + Alignment::ALIGN_VERTICAL_BOTTOM), + const bool lineMode = false) { - return ret; + Label *l = new Label(this, x, y, w, h); + l->setFilled(false); + l->setBorderColor(ColorFullBlack); + l->setEdges(edges); + l->setFont(fontName); + l->setText(text); + l->setAlignement(alignment); + l->setLineMode(lineMode); + + if (parentPage) + parentPage->push_back(l); + + return (l); } - if ((inputEvent.state != InputEvent::State::keyReleasedShort) && ((inputEvent.state != InputEvent::State::keyReleasedLong))) + void PhonebookSearch::buildInterface() { - return (false); + AppWindow::buildInterface(); + topBar->setActive(TopBar::Elements::TIME, true); + + setTitle(utils::localize.get("app_phonebook_title_main")); + + searchHeader = addLabel(nullptr, + phonebookStyle::search::searchHeader::x, + phonebookStyle::search::searchHeader::y, + phonebookStyle::search::searchHeader::w, + phonebookStyle::search::searchHeader::h, + utils::localize.get("app_phonebook_search_win_search")); + searchHeader->setFont(style::window::font::small); + + inputField = new Text(nullptr, + phonebookStyle::search::horizontalBox::inputField::x, + phonebookStyle::search::horizontalBox::inputField::y, + phonebookStyle::search::horizontalBox::inputField::w, + phonebookStyle::search::horizontalBox::inputField::h); + inputField->setTextType(Text::TextType::SINGLE_LINE); + inputField->setEditMode(Text::EditMode::EDIT); + inputField->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES); + inputField->setInputMode(new InputMode({InputMode::ABC, InputMode::abc})); + inputField->setFont(style::window::font::mediumbold); + + searchTop = new Image(nullptr, + phonebookStyle::search::horizontalBox::searchTop::x, + phonebookStyle::search::horizontalBox::searchTop::y, + phonebookStyle::search::horizontalBox::searchTop::w, + phonebookStyle::search::horizontalBox::searchTop::h, + "search"); + + horizontalBox = new HBox(this, + phonebookStyle::search::horizontalBox::x, + phonebookStyle::search::horizontalBox::y, + phonebookStyle::search::horizontalBox::w, + phonebookStyle::search::horizontalBox::h); + horizontalBox->addWidget(inputField); + horizontalBox->addWidget(searchTop); + horizontalBox->setPenWidth(phonebookStyle::search::horizontalBox::penWidth); + horizontalBox->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_BOTTOM); + + bottomBar->setActive(BottomBar::Side::LEFT, false); + bottomBar->setActive(BottomBar::Side::CENTER, true); + bottomBar->setActive(BottomBar::Side::RIGHT, true); + + bottomBar->setText(BottomBar::Side::CENTER, utils::localize.get("app_phonebook_search")); + bottomBar->setText(BottomBar::Side::RIGHT, utils::localize.get("app_phonebook_back")); + + setFocusItem(inputField); } - if (inputEvent.keyCode == KeyCode::KEY_ENTER) + void PhonebookSearch::rebuild() + {} + + void PhonebookSearch::destroyInterface() { - LOG_INFO("Enter pressed"); - std::string contents = utils::trim(inputField->getText()); - std::shared_ptr> searchResults; - std::string primaryName = ""; - std::string alternativeName = ""; - std::string number = ""; + AppWindow::destroyInterface(); + } - if (contents.size() > 0) - { - if (utils::is_number(contents) || contents.find('+') != std::string::npos) - { - number = contents; - } - else if (contents.find(' ') != std::string::npos) - { - std::vector result = utils::split(contents, ' '); - primaryName = result[0]; - alternativeName = result[1]; - } - else - { - primaryName = contents; - } + void PhonebookSearch::onBeforeShow(ShowMode mode, SwitchData *data) + { + setFocusItem(inputField); + } - LOG_INFO("searching for pri:%s alt:%s num:%s", primaryName.c_str(), alternativeName.c_str(), number.c_str()); - searchResults = DBServiceAPI::ContactSearch(application, primaryName, alternativeName, number); - if (searchResults.get()->size() > 0) - { - std::unique_ptr data = std::make_unique(inputField->getText()); - data->setResults(searchResults); - application->switchWindow("SearchResults", gui::ShowMode::GUI_SHOW_INIT, std::move(data)); - } - else - { - std::unique_ptr data = std::make_unique(inputField->getText()); - application->switchWindow("NoResults", gui::ShowMode::GUI_SHOW_INIT, std::move(data)); - } - return (true); + bool PhonebookSearch::handleSwitchData(SwitchData *data) + { + if (data == nullptr) { + LOG_ERROR("Received null pointer"); + return false; } + + PhonebookSearchQuery *item = dynamic_cast(data); + inputField->setText(item->getQuery()); + + return (true); } - return (ret); -} + bool PhonebookSearch::onInput(const InputEvent &inputEvent) + { + bool ret = AppWindow::onInput(inputEvent); + if (ret) { + return ret; + } + + if ((inputEvent.state != InputEvent::State::keyReleasedShort) && + ((inputEvent.state != InputEvent::State::keyReleasedLong))) { + return (false); + } + + if (inputEvent.keyCode == KeyCode::KEY_ENTER) { + LOG_INFO("Enter pressed"); + std::string contents = utils::trim(inputField->getText()); + std::shared_ptr> searchResults; + std::string primaryName = ""; + std::string alternativeName = ""; + std::string number = ""; + + if (contents.size() > 0) { + if (utils::is_number(contents) || contents.find('+') != std::string::npos) { + number = contents; + } + else if (contents.find(' ') != std::string::npos) { + std::vector result = utils::split(contents, ' '); + primaryName = result[0]; + alternativeName = result[1]; + } + else { + primaryName = contents; + } + + LOG_INFO( + "searching for pri:%s alt:%s num:%s", primaryName.c_str(), alternativeName.c_str(), number.c_str()); + searchResults = DBServiceAPI::ContactSearch(application, primaryName, alternativeName, number); + if (searchResults.get()->size() > 0) { + std::unique_ptr data = + std::make_unique(inputField->getText()); + data->setResults(searchResults); + application->switchWindow("SearchResults", gui::ShowMode::GUI_SHOW_INIT, std::move(data)); + } + else { + std::unique_ptr data = + std::make_unique(inputField->getText()); + application->switchWindow("NoResults", gui::ShowMode::GUI_SHOW_INIT, std::move(data)); + } + return (true); + } + } + + return (ret); + } } /* namespace gui */ diff --git a/module-apps/application-phonebook/windows/PhonebookSearch.hpp b/module-apps/application-phonebook/windows/PhonebookSearch.hpp index 1790946ce..6f44c34cd 100644 --- a/module-apps/application-phonebook/windows/PhonebookSearch.hpp +++ b/module-apps/application-phonebook/windows/PhonebookSearch.hpp @@ -12,37 +12,46 @@ #include #include -namespace gui { - -class PhonebookSearch : public AppWindow +namespace gui { - protected: - /** labels */ - Label *searchHeader = nullptr; - Text *inputField = nullptr; - HBox *horizontalBox = nullptr; - Image *searchTop = nullptr; - PhonebookModel *phonebookModel = nullptr; + class PhonebookSearch : public AppWindow + { + protected: + /** labels */ + Label *searchHeader = nullptr; + Text *inputField = nullptr; + HBox *horizontalBox = nullptr; + Image *searchTop = nullptr; - /** currently displayed contact */ - std::shared_ptr contact = nullptr; + PhonebookModel *phonebookModel = nullptr; - public: - PhonebookSearch(app::Application *app); - virtual ~PhonebookSearch(); + /** currently displayed contact */ + std::shared_ptr contact = nullptr; - // virtual methods - bool onInput(const InputEvent &inputEvent) override; - void onBeforeShow(ShowMode mode, SwitchData *data) override; - bool handleSwitchData(SwitchData *data) override; - void rebuild() override; - void buildInterface() override; - void destroyInterface() override; + public: + PhonebookSearch(app::Application *app); + virtual ~PhonebookSearch(); - private: - Label *addLabel(std::list *parentPage, int x, int y, int w, int h, const std::string text, const std::string fontName, - const RectangleEdgeFlags edges, const Alignment alignment, const bool lineMode); -}; + // virtual methods + bool onInput(const InputEvent &inputEvent) override; + void onBeforeShow(ShowMode mode, SwitchData *data) override; + bool handleSwitchData(SwitchData *data) override; + void rebuild() override; + void buildInterface() override; + void destroyInterface() override; + + private: + Label *addLabel(std::list *parentPage, + int x, + int y, + int w, + int h, + const std::string text, + const std::string fontName, + const RectangleEdgeFlags edges, + const Alignment alignment, + const bool lineMode); + }; } /* namespace gui */ diff --git a/module-apps/application-phonebook/windows/PhonebookSearchResults.cpp b/module-apps/application-phonebook/windows/PhonebookSearchResults.cpp index 1bee8cbac..24bddd19b 100644 --- a/module-apps/application-phonebook/windows/PhonebookSearchResults.cpp +++ b/module-apps/application-phonebook/windows/PhonebookSearchResults.cpp @@ -19,139 +19,136 @@ namespace gui : AppWindow(app, name::window::search_results), searchResultsModel{new SearchResultsModel(app)} { buildInterface(); -} - -void PhonebookSearchResults::rebuild() -{ - destroyInterface(); - buildInterface(); -} - -void PhonebookSearchResults::buildInterface() -{ - - AppWindow::buildInterface(); - - searchResultList = new gui::PhonebookListView(this, phonebookStyle::searchResults::searchResultList::x, phonebookStyle::searchResults::searchResultList::y, phonebookStyle::searchResults::searchResultList::w, phonebookStyle::searchResults::searchResultList::h); - searchResultList->setMaxElements(phonebookStyle::searchResults::searchResultList::maxElements); - searchResultList->setPageSize(phonebookStyle::searchResults::searchResultList::pageSize); - searchResultList->setPenFocusWidth(phonebookStyle::searchResults::searchResultList::penFocusWidth); - searchResultList->setPenWidth(phonebookStyle::searchResults::searchResultList::penWidth); - searchResultList->setProvider(searchResultsModel); - searchResultList->setApplication(application); - - bottomBar->setActive(BottomBar::Side::LEFT, true); - bottomBar->setActive(BottomBar::Side::CENTER, true); - bottomBar->setActive(BottomBar::Side::RIGHT, true); - bottomBar->setText(BottomBar::Side::LEFT, utils::localize.get("app_phonebook_call")); - bottomBar->setText(BottomBar::Side::CENTER, utils::localize.get("app_phonebook_open")); - bottomBar->setText(BottomBar::Side::RIGHT, utils::localize.get("app_phonebook_back")); - - topBar->setActive(TopBar::Elements::TIME, true); - - setTitle(utils::localize.get("app_phonebook_search_results_prefix")); -} - -void PhonebookSearchResults::destroyInterface() -{ - AppWindow::destroyInterface(); - if (searchResultList) - { - removeWidget(searchResultList); - delete searchResultList; - searchResultList = nullptr; - } - if (newContactImage) - { - removeWidget(newContactImage); - delete newContactImage; - newContactImage = nullptr; } - children.clear(); - delete searchResultsModel; -} - -PhonebookSearchResults::~PhonebookSearchResults() -{ - destroyInterface(); -} - -void PhonebookSearchResults::onBeforeShow(ShowMode mode, SwitchData *data) -{ - setFocusItem(searchResultList); - searchResultsModel->requestFavouritesCount(); -} - -bool PhonebookSearchResults::onInput(const InputEvent &inputEvent) -{ - bool ret = false; - if(AppWindow::onInput(inputEvent)) + void PhonebookSearchResults::rebuild() { - return true; + destroyInterface(); + buildInterface(); } - // process only if key is released - if ((inputEvent.state != InputEvent::State::keyReleasedShort) && ((inputEvent.state != InputEvent::State::keyReleasedLong))) - return false; - - if (inputEvent.state == InputEvent::State::keyReleasedShort) + void PhonebookSearchResults::buildInterface() { - switch (inputEvent.keyCode) - { - case KeyCode::KEY_LEFT: - LOG_INFO("Adding new contact"); - application->switchWindow(gui::window::name::newContact); - return true; - case KeyCode::KEY_RIGHT: - LOG_INFO("Searching contact"); - application->switchWindow("Search"); - return true; - default: - break; + + AppWindow::buildInterface(); + + searchResultList = new gui::PhonebookListView(this, + phonebookStyle::searchResults::searchResultList::x, + phonebookStyle::searchResults::searchResultList::y, + phonebookStyle::searchResults::searchResultList::w, + phonebookStyle::searchResults::searchResultList::h); + searchResultList->setMaxElements(phonebookStyle::searchResults::searchResultList::maxElements); + searchResultList->setPageSize(phonebookStyle::searchResults::searchResultList::pageSize); + searchResultList->setPenFocusWidth(phonebookStyle::searchResults::searchResultList::penFocusWidth); + searchResultList->setPenWidth(phonebookStyle::searchResults::searchResultList::penWidth); + searchResultList->setProvider(searchResultsModel); + searchResultList->setApplication(application); + + bottomBar->setActive(BottomBar::Side::LEFT, true); + bottomBar->setActive(BottomBar::Side::CENTER, true); + bottomBar->setActive(BottomBar::Side::RIGHT, true); + bottomBar->setText(BottomBar::Side::LEFT, utils::localize.get("app_phonebook_call")); + bottomBar->setText(BottomBar::Side::CENTER, utils::localize.get("app_phonebook_open")); + bottomBar->setText(BottomBar::Side::RIGHT, utils::localize.get("app_phonebook_back")); + + topBar->setActive(TopBar::Elements::TIME, true); + + setTitle(utils::localize.get("app_phonebook_search_results_prefix")); + } + + void PhonebookSearchResults::destroyInterface() + { + AppWindow::destroyInterface(); + if (searchResultList) { + removeWidget(searchResultList); + delete searchResultList; + searchResultList = nullptr; } - } - - // check if any of the lower inheritance onInput methods catch the event - return ret; -} - -bool PhonebookSearchResults::handleSwitchData(SwitchData *data) -{ - if (data == nullptr) - return false; - - auto fill_results = [=](std::shared_ptr> res, const std::string &title) { - if (res == nullptr || res->size() == 0) - { - return; + if (newContactImage) { + removeWidget(newContactImage); + delete newContactImage; + newContactImage = nullptr; } - searchResultsModel->setResults(res); - searchResultList->clear(); - searchResultList->setElementsCount(res.get()->size()); - setTitle(utils::localize.get("app_phonebook_search_results_prefix") + "\"" + title + "\""); - }; - auto searchResults = dynamic_cast(data); - if (searchResults) - { - fill_results(searchResults->getResults(), searchResults->getQuery()); - return (true); + children.clear(); + delete searchResultsModel; } - auto contactRequest = dynamic_cast(data); - if (contactRequest) + PhonebookSearchResults::~PhonebookSearchResults() { - searchResultList->cb_ENTER = [=](gui::PhonebookItem *item) { - std::unique_ptr data = std::make_unique(); - data->result = item->getContact(); - data->setDescription("PhonebookSearchRequest"); - return sapm::ApplicationManager::messageSwitchPreviousApplication( - application, std::make_unique(application->GetName(), std::move(data))); + destroyInterface(); + } + + void PhonebookSearchResults::onBeforeShow(ShowMode mode, SwitchData *data) + { + setFocusItem(searchResultList); + searchResultsModel->requestFavouritesCount(); + } + + bool PhonebookSearchResults::onInput(const InputEvent &inputEvent) + { + bool ret = false; + if (AppWindow::onInput(inputEvent)) { + return true; + } + + // process only if key is released + if ((inputEvent.state != InputEvent::State::keyReleasedShort) && + ((inputEvent.state != InputEvent::State::keyReleasedLong))) + return false; + + if (inputEvent.state == InputEvent::State::keyReleasedShort) { + switch (inputEvent.keyCode) { + case KeyCode::KEY_LEFT: + LOG_INFO("Adding new contact"); + application->switchWindow(gui::window::name::newContact); + return true; + case KeyCode::KEY_RIGHT: + LOG_INFO("Searching contact"); + application->switchWindow("Search"); + return true; + default: + break; + } + } + + // check if any of the lower inheritance onInput methods catch the event + return ret; + } + + bool PhonebookSearchResults::handleSwitchData(SwitchData *data) + { + if (data == nullptr) + return false; + + auto fill_results = [=](std::shared_ptr> res, const std::string &title) { + if (res == nullptr || res->size() == 0) { + return; + } + searchResultsModel->setResults(res); + searchResultList->clear(); + searchResultList->setElementsCount(res.get()->size()); + setTitle(utils::localize.get("app_phonebook_search_results_prefix") + "\"" + title + "\""); }; - fill_results(contactRequest->results, contactRequest->request); - } - return (false); -} + auto searchResults = dynamic_cast(data); + if (searchResults) { + fill_results(searchResults->getResults(), searchResults->getQuery()); + return (true); + } + + auto contactRequest = dynamic_cast(data); + if (contactRequest) { + searchResultList->cb_ENTER = [=](gui::PhonebookItem *item) { + std::unique_ptr data = std::make_unique(); + data->result = item->getContact(); + data->setDescription("PhonebookSearchRequest"); + return sapm::ApplicationManager::messageSwitchPreviousApplication( + application, std::make_unique(application->GetName(), std::move(data))); + }; + fill_results(contactRequest->results, contactRequest->request); + } + + return (false); + } } /* namespace gui */ diff --git a/module-apps/application-phonebook/windows/PhonebookSearchResults.hpp b/module-apps/application-phonebook/windows/PhonebookSearchResults.hpp index 42355285d..178f292cb 100644 --- a/module-apps/application-phonebook/windows/PhonebookSearchResults.hpp +++ b/module-apps/application-phonebook/windows/PhonebookSearchResults.hpp @@ -22,25 +22,25 @@ namespace gui }; }; // namespace name -class PhonebookSearchResults : public AppWindow -{ - protected: - PhonebookListView *searchResultList = nullptr; - SearchResultsModel *searchResultsModel = nullptr; + class PhonebookSearchResults : public AppWindow + { + protected: + PhonebookListView *searchResultList = nullptr; + SearchResultsModel *searchResultsModel = nullptr; - Image *newContactImage = nullptr; + Image *newContactImage = nullptr; - public: - PhonebookSearchResults(app::Application *app); - virtual ~PhonebookSearchResults(); + public: + PhonebookSearchResults(app::Application *app); + virtual ~PhonebookSearchResults(); - // virtual methods - bool onInput(const InputEvent &inputEvent) override; - void onBeforeShow(ShowMode mode, SwitchData *data) override; - bool handleSwitchData(SwitchData *data) override; - void rebuild() override; - void buildInterface() override; - void destroyInterface() override; -}; + // virtual methods + bool onInput(const InputEvent &inputEvent) override; + void onBeforeShow(ShowMode mode, SwitchData *data) override; + bool handleSwitchData(SwitchData *data) override; + void rebuild() override; + void buildInterface() override; + void destroyInterface() override; + }; } /* namespace gui */ diff --git a/module-apps/application-settings/ApplicationSettings.cpp b/module-apps/application-settings/ApplicationSettings.cpp index ded65b0ea..4729d3411 100644 --- a/module-apps/application-settings/ApplicationSettings.cpp +++ b/module-apps/application-settings/ApplicationSettings.cpp @@ -21,7 +21,6 @@ #include "windows/TestMessageWindow.hpp" - #include "ApplicationSettings.hpp" #include "service-cellular/ServiceCellular.hpp" @@ -29,80 +28,83 @@ #include "windows/SimSelectWindow.hpp" #include -namespace app { +namespace app +{ -ApplicationSettings::ApplicationSettings(std::string name, std::string parent, bool startBackgound) : - Application( name, parent, startBackgound ) { -} + ApplicationSettings::ApplicationSettings(std::string name, std::string parent, bool startBackgound) + : Application(name, parent, startBackgound) + {} -ApplicationSettings::~ApplicationSettings() { -} + ApplicationSettings::~ApplicationSettings() + {} -// Invoked upon receiving data message -sys::Message_t ApplicationSettings::DataReceivedHandler(sys::DataMessage* msgl,sys::ResponseMessage* resp) { + // Invoked upon receiving data message + sys::Message_t ApplicationSettings::DataReceivedHandler(sys::DataMessage *msgl, sys::ResponseMessage *resp) + { - auto retMsg = Application::DataReceivedHandler(msgl); - //if message was handled by application's template there is no need to process further. - if( (reinterpret_cast( retMsg.get() )->retCode == - sys::ReturnCodes::Success ) ){ - return retMsg; - } + auto retMsg = Application::DataReceivedHandler(msgl); + // if message was handled by application's template there is no need to process further. + if ((reinterpret_cast(retMsg.get())->retCode == sys::ReturnCodes::Success)) { + return retMsg; + } - //this variable defines whether message was processed. - bool handled = true; + // this variable defines whether message was processed. + bool handled = true; - if( handled ) - return std::make_shared(); - else - return std::make_shared(sys::ReturnCodes::Unresolved); -} + if (handled) + return std::make_shared(); + else + return std::make_shared(sys::ReturnCodes::Unresolved); + } -// Invoked during initialization -sys::ReturnCodes ApplicationSettings::InitHandler() { + // Invoked during initialization + sys::ReturnCodes ApplicationSettings::InitHandler() + { - auto ret = Application::InitHandler(); - if( ret != sys::ReturnCodes::Success ) - return ret; + auto ret = Application::InitHandler(); + if (ret != sys::ReturnCodes::Success) + return ret; - createUserInterface(); + createUserInterface(); - setActiveWindow(gui::name::window::main_window); + setActiveWindow(gui::name::window::main_window); - return ret; -} + return ret; + } -sys::ReturnCodes ApplicationSettings::DeinitHandler() { - return sys::ReturnCodes::Success; -} + sys::ReturnCodes ApplicationSettings::DeinitHandler() + { + return sys::ReturnCodes::Success; + } -void ApplicationSettings::createUserInterface() { + void ApplicationSettings::createUserInterface() + { - gui::AppWindow* window = nullptr; + gui::AppWindow *window = nullptr; - window = newOptionWindow(this, gui::name::window::main_window, mainWindowOptions(this)); - window->setTitle(utils::localize.get("app_settings_title_main")); - windows.insert(std::pair(window->getName(), window)); + window = newOptionWindow(this, gui::name::window::main_window, mainWindowOptions(this)); + window->setTitle(utils::localize.get("app_settings_title_main")); + windows.insert(std::pair(window->getName(), window)); - window = new gui::LanguageWindow(this); - windows.insert(std::pair(window->getName(), window)); + window = new gui::LanguageWindow(this); + windows.insert(std::pair(window->getName(), window)); - window = new gui::BtWindow(this); - windows.insert(std::pair(window->getName(), window)); + window = new gui::BtWindow(this); + windows.insert(std::pair(window->getName(), window)); - window = new gui::UiTestWindow(this); - windows.insert(std::pair(window->getName(), window)); + window = new gui::UiTestWindow(this); + windows.insert(std::pair(window->getName(), window)); - window = new gui::Info(this); - windows.insert(std::pair(window->getName(), window)); + window = new gui::Info(this); + windows.insert(std::pair(window->getName(), window)); - window = new gui::DateTimeWindow(this); - windows.insert(std::pair(window->getName(), window)); - window = newOptionWindow(this, app::sim_select, simSelectWindow(this)); - windows.insert(std::pair(window->getName(), window)); + window = new gui::DateTimeWindow(this); + windows.insert(std::pair(window->getName(), window)); + window = newOptionWindow(this, app::sim_select, simSelectWindow(this)); + windows.insert(std::pair(window->getName(), window)); + } -} - -void ApplicationSettings::destroyUserInterface() { -} + void ApplicationSettings::destroyUserInterface() + {} } /* namespace app */ diff --git a/module-apps/application-settings/ApplicationSettings.hpp b/module-apps/application-settings/ApplicationSettings.hpp index 5cf475f4a..1ff9085b5 100644 --- a/module-apps/application-settings/ApplicationSettings.hpp +++ b/module-apps/application-settings/ApplicationSettings.hpp @@ -11,24 +11,29 @@ #include "Application.hpp" -namespace app { +namespace app +{ -inline const std::string name_settings = "ApplicationSettings"; -inline const std::string sim_select = "SimSelect"; + inline const std::string name_settings = "ApplicationSettings"; + inline const std::string sim_select = "SimSelect"; -class ApplicationSettings: public app::Application { -public: - ApplicationSettings( std::string name=name_settings, std::string parent = "", bool startBackgound = false); - virtual ~ApplicationSettings(); - sys::Message_t DataReceivedHandler(sys::DataMessage* msgl,sys::ResponseMessage* resp) override; - sys::ReturnCodes InitHandler() override; - sys::ReturnCodes DeinitHandler() override; + class ApplicationSettings : public app::Application + { + public: + ApplicationSettings(std::string name = name_settings, std::string parent = "", bool startBackgound = false); + virtual ~ApplicationSettings(); + sys::Message_t DataReceivedHandler(sys::DataMessage *msgl, sys::ResponseMessage *resp) override; + sys::ReturnCodes InitHandler() override; + sys::ReturnCodes DeinitHandler() override; - sys::ReturnCodes SwitchPowerModeHandler(const sys::ServicePowerMode mode) override final{return sys::ReturnCodes::Success;} + sys::ReturnCodes SwitchPowerModeHandler(const sys::ServicePowerMode mode) override final + { + return sys::ReturnCodes::Success; + } - void createUserInterface() override; - void destroyUserInterface() override; -}; + void createUserInterface() override; + void destroyUserInterface() override; + }; } /* namespace app */ diff --git a/module-apps/application-settings/windows/BtWindow.cpp b/module-apps/application-settings/windows/BtWindow.cpp index 5c4292c4d..800fda15e 100644 --- a/module-apps/application-settings/windows/BtWindow.cpp +++ b/module-apps/application-settings/windows/BtWindow.cpp @@ -18,100 +18,105 @@ namespace gui { -BtWindow::BtWindow(app::Application *app) : AppWindow(app, "Bluetooth") { buildInterface(); } - -void BtWindow::rebuild() -{ - destroyInterface(); - buildInterface(); -} - -void add_box_label(VBox *layout, UTF8 name, std::function foo) -{ - auto el = new gui::Label(nullptr, 0, 0, layout->getWidth(), style::window::label::default_h); - style::window::decorateOption(el); - el->setText(name); - el->activatedCallback = foo; - layout->addWidget(el); -} - -sys::ReturnCodes message_bt(app::Application* app, BluetoothMessage::Request req) { - std::shared_ptr msg = std::make_shared(req); - auto ret = sys::Bus::SendUnicast(msg,"ServiceBluetooth",app,5000); - if(ret.first != sys::ReturnCodes::Success) { - LOG_ERROR("err: %d",ret.first); + BtWindow::BtWindow(app::Application *app) : AppWindow(app, "Bluetooth") + { + buildInterface(); } - return ret.first; -} -void BtWindow::buildInterface() -{ - AppWindow::buildInterface(); - bottomBar->setActive(BottomBar::Side::CENTER, true); - bottomBar->setActive(BottomBar::Side::RIGHT, true); - bottomBar->setText(BottomBar::Side::CENTER, utils::localize.get("common_select")); - bottomBar->setText(BottomBar::Side::RIGHT, utils::localize.get("common_back")); - topBar->setActive(TopBar::Elements::SIGNAL, true); - topBar->setActive(TopBar::Elements::BATTERY, true); + void BtWindow::rebuild() + { + destroyInterface(); + buildInterface(); + } - setTitle(utils::localize.get("app_settings_bt")); + void add_box_label(VBox *layout, UTF8 name, std::function foo) + { + auto el = new gui::Label(nullptr, 0, 0, layout->getWidth(), style::window::label::default_h); + style::window::decorateOption(el); + el->setText(name); + el->activatedCallback = foo; + layout->addWidget(el); + } - LOG_INFO("Create box layout"); - box = new gui::VBox(this, 0, title->offset_h(), style::window_width, 5*style::window::label::default_h); - box->setPenWidth(style::window::default_border_no_focus_w); - - // TODO WIP: it's just for usability now - // TODO scan should return async - handle that... (if in scan -> add to list and refresh if new on window) - add_box_label(box, "Bluetooth on off", [=](Item &) { - LOG_DEBUG("Callback Bluetooth on"); - message_bt(application, BluetoothMessage::Request::Start); - for (auto &el : box->children) - { - el->visible = true; + sys::ReturnCodes message_bt(app::Application *app, BluetoothMessage::Request req) + { + std::shared_ptr msg = std::make_shared(req); + auto ret = sys::Bus::SendUnicast(msg, "ServiceBluetooth", app, 5000); + if (ret.first != sys::ReturnCodes::Success) { + LOG_ERROR("err: %d", ret.first); } - box->setVisible(true); - application->render(gui::RefreshModes::GUI_REFRESH_FAST); - return true; - }); + return ret.first; + } - add_box_label(box, " -> All devices", [=](Item &) { - LOG_DEBUG("Callback all devices"); - message_bt(application, BluetoothMessage::Request::Scan); - return true; - }); + void BtWindow::buildInterface() + { + AppWindow::buildInterface(); + bottomBar->setActive(BottomBar::Side::CENTER, true); + bottomBar->setActive(BottomBar::Side::RIGHT, true); + bottomBar->setText(BottomBar::Side::CENTER, utils::localize.get("common_select")); + bottomBar->setText(BottomBar::Side::RIGHT, utils::localize.get("common_back")); + topBar->setActive(TopBar::Elements::SIGNAL, true); + topBar->setActive(TopBar::Elements::BATTERY, true); - add_box_label(box, " -> PAN", [=](Item &) { - LOG_DEBUG("Callback start PAN"); - message_bt(application, BluetoothMessage::Request::PAN); - return true; - }); + setTitle(utils::localize.get("app_settings_bt")); - add_box_label(box, " -> Visibility", [=](Item &) { - LOG_DEBUG("Callback visibility"); - message_bt(application, BluetoothMessage::Request::Visible); - return true; - }); + LOG_INFO("Create box layout"); + box = new gui::VBox(this, 0, title->offset_h(), style::window_width, 5 * style::window::label::default_h); + box->setPenWidth(style::window::default_border_no_focus_w); - // hide all elements except button for `bluetooth on off` - this would cause infinite loop - std::for_each(std::next(box->children.begin()), box->children.end(), [](auto &el) { el->visible = false; }); - setFocusItem(box); -} + // TODO WIP: it's just for usability now + // TODO scan should return async - handle that... (if in scan -> add to list and refresh if new on window) + add_box_label(box, "Bluetooth on off", [=](Item &) { + LOG_DEBUG("Callback Bluetooth on"); + message_bt(application, BluetoothMessage::Request::Start); + for (auto &el : box->children) { + el->visible = true; + } + box->setVisible(true); + application->render(gui::RefreshModes::GUI_REFRESH_FAST); + return true; + }); -bool BtWindow::onInput(const InputEvent &inputEvent) -{ - return AppWindow::onInput(inputEvent); -} + add_box_label(box, " -> All devices", [=](Item &) { + LOG_DEBUG("Callback all devices"); + message_bt(application, BluetoothMessage::Request::Scan); + return true; + }); -void BtWindow::destroyInterface() -{ - this->focusItem = nullptr; - AppWindow::destroyInterface(); -} + add_box_label(box, " -> PAN", [=](Item &) { + LOG_DEBUG("Callback start PAN"); + message_bt(application, BluetoothMessage::Request::PAN); + return true; + }); -BtWindow::~BtWindow() { - destroyInterface(); -} + add_box_label(box, " -> Visibility", [=](Item &) { + LOG_DEBUG("Callback visibility"); + message_bt(application, BluetoothMessage::Request::Visible); + return true; + }); -void BtWindow::onBeforeShow(ShowMode mode, SwitchData *data) {} + // hide all elements except button for `bluetooth on off` - this would cause infinite loop + std::for_each(std::next(box->children.begin()), box->children.end(), [](auto &el) { el->visible = false; }); + setFocusItem(box); + } + + bool BtWindow::onInput(const InputEvent &inputEvent) + { + return AppWindow::onInput(inputEvent); + } + + void BtWindow::destroyInterface() + { + this->focusItem = nullptr; + AppWindow::destroyInterface(); + } + + BtWindow::~BtWindow() + { + destroyInterface(); + } + + void BtWindow::onBeforeShow(ShowMode mode, SwitchData *data) + {} } // namespace gui diff --git a/module-apps/application-settings/windows/BtWindow.hpp b/module-apps/application-settings/windows/BtWindow.hpp index ed7765073..07d2541fa 100644 --- a/module-apps/application-settings/windows/BtWindow.hpp +++ b/module-apps/application-settings/windows/BtWindow.hpp @@ -13,24 +13,24 @@ namespace gui { -class BtWindow : public AppWindow -{ - protected: - std::vector options; - VBox* box; + class BtWindow : public AppWindow + { + protected: + std::vector options; + VBox *box; - gui::Item *addOptionLabel(const std::string &text, std::function activatedCallback); + gui::Item *addOptionLabel(const std::string &text, std::function activatedCallback); - public: - BtWindow(app::Application *app); - virtual ~BtWindow(); + public: + BtWindow(app::Application *app); + virtual ~BtWindow(); - // virtual methods - void onBeforeShow(ShowMode mode, SwitchData *data) override; - void rebuild() override; - void buildInterface() override; - bool onInput(const InputEvent &inputEvent) override; - void destroyInterface() override; - void set_navigation(); -}; + // virtual methods + void onBeforeShow(ShowMode mode, SwitchData *data) override; + void rebuild() override; + void buildInterface() override; + bool onInput(const InputEvent &inputEvent) override; + void destroyInterface() override; + void set_navigation(); + }; } // namespace gui diff --git a/module-apps/application-settings/windows/DateTimeWindow.cpp b/module-apps/application-settings/windows/DateTimeWindow.cpp index 8736c6a83..3b6fc0bf6 100644 --- a/module-apps/application-settings/windows/DateTimeWindow.cpp +++ b/module-apps/application-settings/windows/DateTimeWindow.cpp @@ -55,54 +55,53 @@ namespace gui utils::time::Timestamp time; SettingsRecord appSettings = application->getSettings(); - timeFormat12h = appSettings.timeFormat12; - timeDateFormat = appSettings.timeDateFormat; + timeFormat12h = appSettings.timeFormat12; + timeDateFormat = appSettings.timeDateFormat; // create date widgets dateBody = new gui::HBox(this, style::window::default_left_margin, (uint32_t)title->offset_h(), w, h); - auto item = addDateTimeItem(nullptr, utils::localize.get("app_settings_title_day"), time.get_date_time_substr(utils::time::GetParameters::Day)); + auto item = addDateTimeItem(nullptr, + utils::localize.get("app_settings_title_day"), + time.get_date_time_substr(utils::time::GetParameters::Day)); dateItems.insert(std::pair(DateTimeItems::Day, item)); - item = addDateTimeItem(nullptr, utils::localize.get("app_settings_title_month"), time.get_date_time_substr(utils::time::GetParameters::Month)); + item = addDateTimeItem(nullptr, + utils::localize.get("app_settings_title_month"), + time.get_date_time_substr(utils::time::GetParameters::Month)); dateItems.insert(std::pair(DateTimeItems::Month, item)); - item = addDateTimeItem(nullptr, utils::localize.get("app_settings_title_year"), time.get_date_time_substr(utils::time::GetParameters::Year)); + item = addDateTimeItem(nullptr, + utils::localize.get("app_settings_title_year"), + time.get_date_time_substr(utils::time::GetParameters::Year)); dateItems.insert(std::pair(DateTimeItems::Year, item)); - if (timeDateFormat) - { + if (timeDateFormat) { auto toAdd = dateItems.find(DateTimeItems::Day); - if (toAdd != dateItems.end()) - { + if (toAdd != dateItems.end()) { dateBody->addWidget(toAdd->second); dateBody->addWidget(addSpacer("")); } toAdd = dateItems.find(DateTimeItems::Month); - if (toAdd != dateItems.end()) - { + if (toAdd != dateItems.end()) { dateBody->addWidget(toAdd->second); } } - else - { + else { auto toAdd = dateItems.find(DateTimeItems::Month); - if (toAdd != dateItems.end()) - { + if (toAdd != dateItems.end()) { dateBody->addWidget(toAdd->second); dateBody->addWidget(addSpacer("")); } toAdd = dateItems.find(DateTimeItems::Day); - if (toAdd != dateItems.end()) - { + if (toAdd != dateItems.end()) { dateBody->addWidget(toAdd->second); } } dateBody->addWidget(addSpacer("")); auto toAdd = dateItems.find(DateTimeItems::Year); - if (toAdd != dateItems.end()) - { + if (toAdd != dateItems.end()) { dateBody->addWidget(toAdd->second); } @@ -112,17 +111,15 @@ namespace gui auto hourValue = time.get_date_time_sub_value(utils::time::GetParameters::Hour); - if (timeFormat12h) - { - if (hourValue > 12) - { + if (timeFormat12h) { + if (hourValue > 12) { hourValue -= 12; dayPeriod = true; } } timeBody = new gui::HBox(this, style::window::default_left_margin, (uint32_t)title->offset_h() * 2, w, h); - item = addDateTimeItem(nullptr, utils::localize.get("app_settings_title_time"), std::to_string(hourValue)); + item = addDateTimeItem(nullptr, utils::localize.get("app_settings_title_time"), std::to_string(hourValue)); timeItems.insert(std::pair(DateTimeItems::Hour, item)); timeBody->addWidget(item); timeBody->addWidget(addSpacer(":")); @@ -133,19 +130,15 @@ namespace gui timeBody->addWidget(addSpacer("")); item = addDateTimeItem(nullptr, (""), ("")); - if (timeFormat12h) - { - if (dayPeriod) - { + if (timeFormat12h) { + if (dayPeriod) { item->setText("PM"); } - else - { + else { item->setText("AM"); } } - else - { + else { item->setVisible(false); } timeItems.insert(std::pair(DateTimeItems::Hour, item)); @@ -168,8 +161,7 @@ namespace gui } DateTimeWindow::~DateTimeWindow() - { - } + {} void DateTimeWindow::onBeforeShow(ShowMode mode, SwitchData *data) { @@ -178,11 +170,13 @@ namespace gui gui::Label *DateTimeWindow::addSpacer(const UTF8 &text) { - auto label = new gui::Label(nullptr, 0, 0, style::settings::date::date_time_spacer_width, style::settings::date::date_time_item_height); + auto label = new gui::Label( + nullptr, 0, 0, style::settings::date::date_time_spacer_width, style::settings::date::date_time_item_height); label->setEdges(gui::RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES); label->setText(text); label->setFont(style::window::font::verybig); - label->setAlignement(gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_CENTER, gui::Alignment::ALIGN_VERTICAL_CENTER)); + label->setAlignement( + gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_CENTER, gui::Alignment::ALIGN_VERTICAL_CENTER)); label->activeItem = false; label->setVisible(true); return label; @@ -191,14 +185,18 @@ namespace gui gui::Label *DateTimeWindow::addDateTimeItem(Item *parent, const UTF8 &itemTitle, const UTF8 &value) { - gui::Label *label = new gui::Label(this, style::settings::date::date_time_x_offset, 0, style::settings::date::date_time_item_width, + gui::Label *label = new gui::Label(this, + style::settings::date::date_time_x_offset, + 0, + style::settings::date::date_time_item_width, style::settings::date::date_time_item_height); label->setMargins(gui::Margins(16, 0, 0, 0)); label->setFilled(false); label->setPenFocusWidth(3); label->setPenWidth(1); label->setFont(style::window::font::verybig); - label->setAlignement(gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_CENTER, gui::Alignment::ALIGN_VERTICAL_CENTER)); + label->setAlignement( + gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_CENTER, gui::Alignment::ALIGN_VERTICAL_CENTER)); label->setEdges(gui::RectangleEdgeFlags::GUI_RECT_EDGE_BOTTOM); label->activatedCallback = [=](gui::Item &) { this->setRTC(); @@ -207,7 +205,11 @@ namespace gui }; label->setText(value); - Label *title = new gui::Label(label, 0, 0, style::settings::date::date_time_item_width, style::settings::date::date_time_item_title_height); + Label *title = new gui::Label(label, + 0, + 0, + style::settings::date::date_time_item_width, + style::settings::date::date_time_item_title_height); title->setText(itemTitle); title->setEdges(gui::RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES); title->setFont(style::window::font::verysmall); @@ -217,41 +219,31 @@ namespace gui bool DateTimeWindow::onInput(const InputEvent &inputEvent) { bool ret = false; - if (AppWindow::onInput(inputEvent)) - { + if (AppWindow::onInput(inputEvent)) { return true; } - else - { - if (inputEvent.state == gui::InputEvent::State::keyReleasedShort) - { - auto key = std::to_string(gui::toNumeric(inputEvent.keyCode)); + else { + if (inputEvent.state == gui::InputEvent::State::keyReleasedShort) { + auto key = std::to_string(gui::toNumeric(inputEvent.keyCode)); auto value = gui::toNumeric(inputEvent.keyCode); // handle numeric keys - if (value >= 0) - { - if (focusItem == dateBody) - { + if (value >= 0) { + if (focusItem == dateBody) { setDate(value); } - else if (focusItem == timeBody) - { + else if (focusItem == timeBody) { setTime(value); } ret = true; } - else if (inputEvent.keyCode == gui::KeyCode::KEY_PND) - { - if (focusItem == dateBody || focusItem == timeBody) - { + else if (inputEvent.keyCode == gui::KeyCode::KEY_PND) { + if (focusItem == dateBody || focusItem == timeBody) { auto item = dynamic_cast(focusItem->focusItem); - if (item != nullptr) - { + if (item != nullptr) { auto itemValue = item->getText(); - auto len = itemValue.length(); - if (len > 0) - { + auto len = itemValue.length(); + if (len > 0) { itemValue.removeChar(len - 1); item->setText(itemValue); application->refreshWindow(RefreshModes::GUI_REFRESH_FAST); @@ -269,26 +261,20 @@ namespace gui std::string ret; - if (itemType == DateTimeItems::Day || itemType == DateTimeItems::Month || itemType == DateTimeItems::Year) - { + if (itemType == DateTimeItems::Day || itemType == DateTimeItems::Month || itemType == DateTimeItems::Year) { auto selected = dateItems.find(itemType); - if (selected != dateItems.end()) - { + if (selected != dateItems.end()) { auto item = dynamic_cast(selected->second); - if (item != nullptr) - { + if (item != nullptr) { ret = item->getText(); } } } - if (itemType == DateTimeItems::Hour || itemType == DateTimeItems::Minute) - { + if (itemType == DateTimeItems::Hour || itemType == DateTimeItems::Minute) { auto selected = timeItems.find(itemType); - if (selected != timeItems.end()) - { + if (selected != timeItems.end()) { auto item = dynamic_cast(selected->second); - if (item != nullptr) - { + if (item != nullptr) { ret = item->getText(); } } @@ -300,20 +286,18 @@ namespace gui { auto item = dynamic_cast(focusItem->focusItem); - if (item != nullptr) - { + if (item != nullptr) { auto itemValue = item->getText(); - auto key = std::to_string(keyValue); + auto key = std::to_string(keyValue); itemValue += key; item->setText(itemValue); - if (utils::time::validateDate(getDateTimeItemValue(DateTimeItems::Day), getDateTimeItemValue(DateTimeItems::Month), - getDateTimeItemValue(DateTimeItems::Year))) - { + if (utils::time::validateDate(getDateTimeItemValue(DateTimeItems::Day), + getDateTimeItemValue(DateTimeItems::Month), + getDateTimeItemValue(DateTimeItems::Year))) { application->refreshWindow(RefreshModes::GUI_REFRESH_FAST); } - else - { + else { item->setText(key); application->refreshWindow(RefreshModes::GUI_REFRESH_FAST); } @@ -325,26 +309,23 @@ namespace gui { auto item = dynamic_cast(focusItem->focusItem); - if (item != nullptr) - { + if (item != nullptr) { auto itemValue = item->getText(); - auto key = std::to_string(keyValue); - if (itemValue == "0") - { + auto key = std::to_string(keyValue); + if (itemValue == "0") { itemValue = key; } - else - { + else { itemValue += key; } item->setText(itemValue); - if (utils::time::validateTime(getDateTimeItemValue(DateTimeItems::Hour), getDateTimeItemValue(DateTimeItems::Minute), timeFormat12h)) - { + if (utils::time::validateTime(getDateTimeItemValue(DateTimeItems::Hour), + getDateTimeItemValue(DateTimeItems::Minute), + timeFormat12h)) { application->refreshWindow(RefreshModes::GUI_REFRESH_FAST); } - else - { + else { item->setText(key); application->refreshWindow(RefreshModes::GUI_REFRESH_FAST); } @@ -357,25 +338,21 @@ namespace gui { struct tm timeinfo = {0, 0, 0, 0, 0, 0, 0, 0, 0}; - try - { + try { timeinfo.tm_year = std::stoi(getDateTimeItemValue(DateTimeItems::Year)) - 1900; - timeinfo.tm_mon = std::stoi(getDateTimeItemValue(DateTimeItems::Month)) - 1; + timeinfo.tm_mon = std::stoi(getDateTimeItemValue(DateTimeItems::Month)) - 1; timeinfo.tm_mday = std::stoi(getDateTimeItemValue(DateTimeItems::Day)); auto hourValue = std::stoi(getDateTimeItemValue(DateTimeItems::Hour)); - if (timeFormat12h) - { - if (dayPeriod) - { + if (timeFormat12h) { + if (dayPeriod) { hourValue += 12; } } timeinfo.tm_hour = hourValue; - timeinfo.tm_min = std::stoi(getDateTimeItemValue(DateTimeItems::Minute)); + timeinfo.tm_min = std::stoi(getDateTimeItemValue(DateTimeItems::Minute)); } - catch (std::exception &e) - { + catch (std::exception &e) { LOG_ERROR("ServiceCellular::getIMSI exception: %s", e.what()); } diff --git a/module-apps/application-settings/windows/DateTimeWindow.hpp b/module-apps/application-settings/windows/DateTimeWindow.hpp index b0344fbdc..1ff09a49c 100644 --- a/module-apps/application-settings/windows/DateTimeWindow.hpp +++ b/module-apps/application-settings/windows/DateTimeWindow.hpp @@ -38,9 +38,9 @@ namespace gui gui::HBox *dateBody = nullptr; gui::HBox *timeBody = nullptr; - bool timeFormat12h = false; + bool timeFormat12h = false; bool timeDateFormat = false; // true europe format, flase american format - bool dayPeriod = false; // day period indicator false am, true pm + bool dayPeriod = false; // day period indicator false am, true pm gui::Label *addDateTimeItem(Item *parent, const UTF8 &itemTitle, const UTF8 &value); gui::Label *addSpacer(const UTF8 &text); diff --git a/module-apps/application-settings/windows/Info.cpp b/module-apps/application-settings/windows/Info.cpp index aa499a4f3..28ece121d 100644 --- a/module-apps/application-settings/windows/Info.cpp +++ b/module-apps/application-settings/windows/Info.cpp @@ -9,7 +9,6 @@ #include <../source/version.hpp> - namespace gui { @@ -65,7 +64,6 @@ namespace gui } void Info::onBeforeShow(ShowMode mode, SwitchData *data) - { - } + {} } // namespace gui diff --git a/module-apps/application-settings/windows/LanguageWindow.cpp b/module-apps/application-settings/windows/LanguageWindow.cpp index a6911b4d9..9cb1e8cac 100644 --- a/module-apps/application-settings/windows/LanguageWindow.cpp +++ b/module-apps/application-settings/windows/LanguageWindow.cpp @@ -13,7 +13,6 @@ #include "../ApplicationSettings.hpp" - #include "i18/i18.hpp" #include "Label.hpp" @@ -21,99 +20,110 @@ #include "LanguageWindow.hpp" #include -namespace gui { +namespace gui +{ -LanguageWindow::LanguageWindow( app::Application* app ) : AppWindow(app,"Languages"){ - buildInterface(); -} + LanguageWindow::LanguageWindow(app::Application *app) : AppWindow(app, "Languages") + { + buildInterface(); + } -void LanguageWindow::rebuild() { - //find which widget has focus - uint32_t index = 0; - for( uint32_t i=0; isetActive( BottomBar::Side::CENTER, true ); - bottomBar->setActive( BottomBar::Side::RIGHT, true ); - bottomBar->setText( BottomBar::Side::CENTER, utils::localize.get("common_select")); - bottomBar->setText( BottomBar::Side::RIGHT, utils::localize.get("common_back")); + destroyInterface(); + buildInterface(); + setFocusItem(options[index]); + } + void LanguageWindow::buildInterface() + { + AppWindow::buildInterface(); + bottomBar->setActive(BottomBar::Side::CENTER, true); + bottomBar->setActive(BottomBar::Side::RIGHT, true); + bottomBar->setText(BottomBar::Side::CENTER, utils::localize.get("common_select")); + bottomBar->setText(BottomBar::Side::RIGHT, utils::localize.get("common_back")); - topBar->setActive(TopBar::Elements::SIGNAL, true ); - topBar->setActive(TopBar::Elements::BATTERY, true ); + topBar->setActive(TopBar::Elements::SIGNAL, true); + topBar->setActive(TopBar::Elements::BATTERY, true); - setTitle(utils::localize.get("app_settings_title_languages")); + setTitle(utils::localize.get("app_settings_title_languages")); - //add option connectivity option - options.push_back( addOptionLabel( utils::localize.get("app_settings_language_english"), [=] (gui::Item& item){ - LOG_INFO("selected language: english" ); - sapm::ApplicationManager::messageChangeLanguage( application, utils::Lang::En ); - return true;} )); + // add option connectivity option + options.push_back(addOptionLabel(utils::localize.get("app_settings_language_english"), [=](gui::Item &item) { + LOG_INFO("selected language: english"); + sapm::ApplicationManager::messageChangeLanguage(application, utils::Lang::En); + return true; + })); - //add option date and time option - options.push_back( addOptionLabel( utils::localize.get("app_settings_language_polish"), [=](gui::Item&){ - LOG_INFO("selected language: polish" ); - sapm::ApplicationManager::messageChangeLanguage( application, utils::Lang::Pl ); - return true;} )); + // add option date and time option + options.push_back(addOptionLabel(utils::localize.get("app_settings_language_polish"), [=](gui::Item &) { + LOG_INFO("selected language: polish"); + sapm::ApplicationManager::messageChangeLanguage(application, utils::Lang::Pl); + return true; + })); - //add option display option - options.push_back( addOptionLabel( utils::localize.get("app_settings_language_german"), [=](gui::Item&){ - LOG_INFO("selected language: german" ); - sapm::ApplicationManager::messageChangeLanguage( application, utils::Lang::De ); - return true;} )); + // add option display option + options.push_back(addOptionLabel(utils::localize.get("app_settings_language_german"), [=](gui::Item &) { + LOG_INFO("selected language: german"); + sapm::ApplicationManager::messageChangeLanguage(application, utils::Lang::De); + return true; + })); - options.push_back( addOptionLabel( utils::localize.get("app_settings_language_spanish"), [=](gui::Item&){ - LOG_INFO("selected language: spanish" ); - sapm::ApplicationManager::messageChangeLanguage( application, utils::Lang::Sp ); - return true;} )); + options.push_back(addOptionLabel(utils::localize.get("app_settings_language_spanish"), [=](gui::Item &) { + LOG_INFO("selected language: spanish"); + sapm::ApplicationManager::messageChangeLanguage(application, utils::Lang::Sp); + return true; + })); - //set possition and navigation for labels - uint32_t posY = 100; - uint32_t size = options.size(); - for( uint32_t i=0; isetPosition(17,posY); - posY += 60; - options[i]->setNavigationItem( NavigationDirection::DOWN, options[(i+1)%size]); - options[i]->setNavigationItem( NavigationDirection::UP, options[(size+i-1)%size]); - } -} -void LanguageWindow::destroyInterface() { - AppWindow::destroyInterface(); - for( uint32_t i=0; ifocusItem = nullptr; - options.clear(); - children.clear(); -} + // set possition and navigation for labels + uint32_t posY = 100; + uint32_t size = options.size(); + for (uint32_t i = 0; i < options.size(); i++) { + options[i]->setPosition(17, posY); + posY += 60; + options[i]->setNavigationItem(NavigationDirection::DOWN, options[(i + 1) % size]); + options[i]->setNavigationItem(NavigationDirection::UP, options[(size + i - 1) % size]); + } + } + void LanguageWindow::destroyInterface() + { + AppWindow::destroyInterface(); + for (uint32_t i = 0; i < options.size(); i++) + delete options[i]; + this->focusItem = nullptr; + options.clear(); + children.clear(); + } -LanguageWindow::~LanguageWindow() { -} + LanguageWindow::~LanguageWindow() + {} -gui::Item* LanguageWindow::addOptionLabel( const std::string& text, std::function activatedCallback ) { - gui::Label* label = new gui::Label( this, 17,0, 480-34, 60, text ); - label->setMargins( gui::Margins(16,0,0,0) ); - label->setFilled( false ); - label->setPenFocusWidth( 3 ); - label->setPenWidth( 0 ); - label->setFont(style::window::font::medium); - label->setAlignement( gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_LEFT, gui::Alignment::ALIGN_VERTICAL_CENTER)); - label->setRadius(11); - label->activatedCallback = activatedCallback; + gui::Item *LanguageWindow::addOptionLabel(const std::string &text, std::function activatedCallback) + { + gui::Label *label = new gui::Label(this, 17, 0, 480 - 34, 60, text); + label->setMargins(gui::Margins(16, 0, 0, 0)); + label->setFilled(false); + label->setPenFocusWidth(3); + label->setPenWidth(0); + label->setFont(style::window::font::medium); + label->setAlignement( + gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_LEFT, gui::Alignment::ALIGN_VERTICAL_CENTER)); + label->setRadius(11); + label->activatedCallback = activatedCallback; - return label; -} + return label; + } - -void LanguageWindow::onBeforeShow( ShowMode mode, SwitchData* data ) { - setFocusItem( options[0] ); -} + void LanguageWindow::onBeforeShow(ShowMode mode, SwitchData *data) + { + setFocusItem(options[0]); + } } /* namespace gui */ diff --git a/module-apps/application-settings/windows/LanguageWindow.hpp b/module-apps/application-settings/windows/LanguageWindow.hpp index e74463594..25effd3cc 100644 --- a/module-apps/application-settings/windows/LanguageWindow.hpp +++ b/module-apps/application-settings/windows/LanguageWindow.hpp @@ -19,27 +19,30 @@ #include "gui/widgets/BottomBar.hpp" #include "gui/widgets/TopBar.hpp" -namespace gui { +namespace gui +{ -/* - * - */ -class LanguageWindow: public AppWindow { -protected: - std::vector options; + /* + * + */ + class LanguageWindow : public AppWindow + { + protected: + std::vector options; - gui::Item* addOptionLabel( const std::string& text, std::function activatedCallback ); -public: - LanguageWindow( app::Application* app ); - virtual ~LanguageWindow(); + gui::Item *addOptionLabel(const std::string &text, std::function activatedCallback); - //virtual methods - void onBeforeShow( ShowMode mode, SwitchData* data ) override; + public: + LanguageWindow(app::Application *app); + virtual ~LanguageWindow(); - void rebuild() override; - void buildInterface() override; - void destroyInterface() override; -}; + // virtual methods + void onBeforeShow(ShowMode mode, SwitchData *data) override; + + void rebuild() override; + void buildInterface() override; + void destroyInterface() override; + }; } /* namespace gui */ #endif /* MODULE_APPS_APPLICATION_SETTINGS_WINDOWS_LANGUAGEWINDOW_HPP_ */ diff --git a/module-apps/application-settings/windows/SettingsMainWindow.cpp b/module-apps/application-settings/windows/SettingsMainWindow.cpp index ccec7d1c0..b1e98d06d 100644 --- a/module-apps/application-settings/windows/SettingsMainWindow.cpp +++ b/module-apps/application-settings/windows/SettingsMainWindow.cpp @@ -6,57 +6,64 @@ std::list mainWindowOptions(app::Application *app) { - return {gui::Option{"Info", - [=](gui::Item &item) { - LOG_INFO("switching to TEST UI page"); - app->switchWindow(gui::window::hw_info, nullptr); - return true; - }, - gui::Arrow::Enabled}, - {"UI TEST", - [=](gui::Item &item) { - LOG_INFO("switching to TEST UI page"); - app->switchWindow("TEST_UI", nullptr); - return true; - }, - gui::Arrow::Enabled}, + return { + gui::Option{"Info", + [=](gui::Item &item) { + LOG_INFO("switching to TEST UI page"); + app->switchWindow(gui::window::hw_info, nullptr); + return true; + }, + gui::Arrow::Enabled}, + {"UI TEST", + [=](gui::Item &item) { + LOG_INFO("switching to TEST UI page"); + app->switchWindow("TEST_UI", nullptr); + return true; + }, + gui::Arrow::Enabled}, - {utils::localize.get("app_settings_bt"), - [=](gui::Item &item) { - LOG_INFO("switching to bluetooth page"); - app->switchWindow("Bluetooth", nullptr); - return true; - }, - gui::Arrow::Enabled}, + {utils::localize.get("app_settings_bt"), + [=](gui::Item &item) { + LOG_INFO("switching to bluetooth page"); + app->switchWindow("Bluetooth", nullptr); + return true; + }, + gui::Arrow::Enabled}, - {utils::localize.get("app_settings_language"), - [=](gui::Item &) { - LOG_INFO("switching to language page"); - app->switchWindow("Languages"); - return true; - }, - gui::Arrow::Enabled}, + {utils::localize.get("app_settings_language"), + [=](gui::Item &) { + LOG_INFO("switching to language page"); + app->switchWindow("Languages"); + return true; + }, + gui::Arrow::Enabled}, - {"SIM SELECT", - [=](gui::Item &) { - app->switchWindow(app::sim_select, nullptr); - return true; - }, - gui::Arrow::Enabled}, - {utils::localize.get("app_settings_date_and_time"), - [=](gui::Item &) { - LOG_INFO("switching to date and time page"); - app->switchWindow("DateTime"); - return true; - }, - gui::Arrow::Enabled}, - {"[None] " + utils::localize.get("app_settings_display"), [=](gui::Item &) { return true; }, gui::Arrow::Enabled}, - {"[None] " + utils::localize.get("app_settings_phone_modes"), [=](gui::Item &) { return true; }, gui::Arrow::Enabled}, - {"[None] " + utils::localize.get("app_settings_security"), [=](gui::Item &) { return true; }, gui::Arrow::Enabled}, - {"[None] " + utils::localize.get("app_settings_about"), [=](gui::Item &) { return true; }, gui::Arrow::Enabled}, - {"[Dummy]", [=](gui::Item &) { return true; }, gui::Arrow::Enabled}, - {"[Dummy]", [=](gui::Item &) { return true; }, gui::Arrow::Enabled}, - {"[Dummy]", [=](gui::Item &) { return true; }, gui::Arrow::Enabled}, - {"[Dummy]", [=](gui::Item &) { return true; }, gui::Arrow::Enabled}, - {"[Dummy]", [=](gui::Item &) { return true; }, gui::Arrow::Enabled}}; + {"SIM SELECT", + [=](gui::Item &) { + app->switchWindow(app::sim_select, nullptr); + return true; + }, + gui::Arrow::Enabled}, + {utils::localize.get("app_settings_date_and_time"), + [=](gui::Item &) { + LOG_INFO("switching to date and time page"); + app->switchWindow("DateTime"); + return true; + }, + gui::Arrow::Enabled}, + {"[None] " + utils::localize.get("app_settings_display"), + [=](gui::Item &) { return true; }, + gui::Arrow::Enabled}, + {"[None] " + utils::localize.get("app_settings_phone_modes"), + [=](gui::Item &) { return true; }, + gui::Arrow::Enabled}, + {"[None] " + utils::localize.get("app_settings_security"), + [=](gui::Item &) { return true; }, + gui::Arrow::Enabled}, + {"[None] " + utils::localize.get("app_settings_about"), [=](gui::Item &) { return true; }, gui::Arrow::Enabled}, + {"[Dummy]", [=](gui::Item &) { return true; }, gui::Arrow::Enabled}, + {"[Dummy]", [=](gui::Item &) { return true; }, gui::Arrow::Enabled}, + {"[Dummy]", [=](gui::Item &) { return true; }, gui::Arrow::Enabled}, + {"[Dummy]", [=](gui::Item &) { return true; }, gui::Arrow::Enabled}, + {"[Dummy]", [=](gui::Item &) { return true; }, gui::Arrow::Enabled}}; } diff --git a/module-apps/application-settings/windows/TestMessageWindow.cpp b/module-apps/application-settings/windows/TestMessageWindow.cpp index c724a0fee..c05715f47 100644 --- a/module-apps/application-settings/windows/TestMessageWindow.cpp +++ b/module-apps/application-settings/windows/TestMessageWindow.cpp @@ -21,128 +21,134 @@ #include "service-cellular/api/CellularServiceAPI.hpp" -namespace gui { - -TestMessageWindow::TestMessageWindow(app::Application *app) : - AppWindow(app, "Message") { - buildInterface(); -} - -void TestMessageWindow::rebuild() { - - - destroyInterface(); - buildInterface(); - -} - -void textSetInput(Text * text, bool numeric = true) +namespace gui { - /// tu ustawiasz że coś jest edytowalne - text->setEditMode(gui::Text::EditMode::EDIT); - text->setFont(style::window::font::bigbold); - /// tu ustawiasz tak naprawdę przez tą listę InputMode::digit etc jakie kolejne tryby wprowadzania są wybierane - if(numeric) { - text->setInputMode(new InputMode({InputMode::digit})); - } else { - text->setInputMode(new InputMode({InputMode::ABC, InputMode::abc, InputMode::digit})); + + TestMessageWindow::TestMessageWindow(app::Application *app) : AppWindow(app, "Message") + { + buildInterface(); } -} -void TestMessageWindow::buildInterface() { - AppWindow::buildInterface(); - bottomBar->setActive(BottomBar::Side::CENTER, true); - bottomBar->setActive(BottomBar::Side::RIGHT, true); - bottomBar->setText(BottomBar::Side::CENTER, - utils::localize.get("common_select")); - bottomBar->setText(BottomBar::Side::RIGHT, - utils::localize.get("common_back")); + void TestMessageWindow::rebuild() + { - topBar->setActive(TopBar::Elements::SIGNAL, true); - topBar->setActive(TopBar::Elements::BATTERY, true); + destroyInterface(); + buildInterface(); + } - receivedLabel = new gui::Label(this,10, 50, 480-20, 50, "Received SMS"); - receivedLabel->setAlignement(gui::Alignment( gui::Alignment::ALIGN_VERTICAL_CENTER, gui::Alignment::ALIGN_HORIZONTAL_CENTER)); - receivedLabel->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES); + void textSetInput(Text *text, bool numeric = true) + { + /// tu ustawiasz że coś jest edytowalne + text->setEditMode(gui::Text::EditMode::EDIT); + text->setFont(style::window::font::bigbold); + /// tu ustawiasz tak naprawdę przez tą listę InputMode::digit etc jakie kolejne tryby wprowadzania są wybierane + if (numeric) { + text->setInputMode(new InputMode({InputMode::digit})); + } + else { + text->setInputMode(new InputMode({InputMode::ABC, InputMode::abc, InputMode::digit})); + } + } - receiveNumber = new gui::Label(this,110, 190, 480-120, 50); - receiveNumber->setFont(style::window::font::small); + void TestMessageWindow::buildInterface() + { + AppWindow::buildInterface(); + bottomBar->setActive(BottomBar::Side::CENTER, true); + bottomBar->setActive(BottomBar::Side::RIGHT, true); + bottomBar->setText(BottomBar::Side::CENTER, utils::localize.get("common_select")); + bottomBar->setText(BottomBar::Side::RIGHT, utils::localize.get("common_back")); - RecNumberLabel = new gui::Label(this,10, 190, 90, 50, "Number"); - RecNumberLabel->setAlignement(gui::Alignment( gui::Alignment::ALIGN_VERTICAL_CENTER, gui::Alignment::ALIGN_HORIZONTAL_CENTER)); - RecNumberLabel->setFont(style::window::font::small); - RecNumberLabel->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES); + topBar->setActive(TopBar::Elements::SIGNAL, true); + topBar->setActive(TopBar::Elements::BATTERY, true); - receiveMessage = new gui::Text(this, 110, 120, 480-120, 50); - textSetInput(receiveMessage); - receiveMessage->setFont(style::window::font::small); + receivedLabel = new gui::Label(this, 10, 50, 480 - 20, 50, "Received SMS"); + receivedLabel->setAlignement( + gui::Alignment(gui::Alignment::ALIGN_VERTICAL_CENTER, gui::Alignment::ALIGN_HORIZONTAL_CENTER)); + receivedLabel->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES); - RecMessageLabel = new gui::Label(this, 10, 120, 90, 50, "Message"); - RecMessageLabel->setAlignement(gui::Alignment( gui::Alignment::ALIGN_VERTICAL_CENTER, gui::Alignment::ALIGN_HORIZONTAL_CENTER)); - RecMessageLabel->setFont(style::window::font::small); - RecMessageLabel->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES); + receiveNumber = new gui::Label(this, 110, 190, 480 - 120, 50); + receiveNumber->setFont(style::window::font::small); + RecNumberLabel = new gui::Label(this, 10, 190, 90, 50, "Number"); + RecNumberLabel->setAlignement( + gui::Alignment(gui::Alignment::ALIGN_VERTICAL_CENTER, gui::Alignment::ALIGN_HORIZONTAL_CENTER)); + RecNumberLabel->setFont(style::window::font::small); + RecNumberLabel->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES); - sendLabel = new gui::Label(this,10, 290, 480-20, 50, "New SMS"); - sendLabel->setAlignement(gui::Alignment( gui::Alignment::ALIGN_VERTICAL_CENTER, gui::Alignment::ALIGN_HORIZONTAL_CENTER)); - sendLabel->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES); + receiveMessage = new gui::Text(this, 110, 120, 480 - 120, 50); + textSetInput(receiveMessage); + receiveMessage->setFont(style::window::font::small); - sendMessage = new gui::Text(this,110, 360, 480-120, 50); - textSetInput(sendMessage,false); - sendMessage->setText("Siema tu PurePhone :)"); - sendMessage->setFont(style::window::font::small); + RecMessageLabel = new gui::Label(this, 10, 120, 90, 50, "Message"); + RecMessageLabel->setAlignement( + gui::Alignment(gui::Alignment::ALIGN_VERTICAL_CENTER, gui::Alignment::ALIGN_HORIZONTAL_CENTER)); + RecMessageLabel->setFont(style::window::font::small); + RecMessageLabel->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES); - sendNumber = new gui::Text(this,110, 430, 480-120, 50); - textSetInput(sendNumber); - sendNumber->setFont(style::window::font::small); + sendLabel = new gui::Label(this, 10, 290, 480 - 20, 50, "New SMS"); + sendLabel->setAlignement( + gui::Alignment(gui::Alignment::ALIGN_VERTICAL_CENTER, gui::Alignment::ALIGN_HORIZONTAL_CENTER)); + sendLabel->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES); - SendNumberLabel = new gui::Label(this, 10, 430, 90, 50, "Number"); - SendNumberLabel->setAlignement(gui::Alignment( gui::Alignment::ALIGN_VERTICAL_CENTER, gui::Alignment::ALIGN_HORIZONTAL_CENTER)); - SendNumberLabel->setFont(style::window::font::small); - SendNumberLabel->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES); + sendMessage = new gui::Text(this, 110, 360, 480 - 120, 50); + textSetInput(sendMessage, false); + sendMessage->setText("Siema tu PurePhone :)"); + sendMessage->setFont(style::window::font::small); - SendMessageLabel = new gui::Label(this, 10, 360, 90, 50, "Message"); - SendMessageLabel->setAlignement(gui::Alignment( gui::Alignment::ALIGN_VERTICAL_CENTER, gui::Alignment::ALIGN_HORIZONTAL_CENTER)); - SendMessageLabel->setFont(style::window::font::small); - SendMessageLabel->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES); + sendNumber = new gui::Text(this, 110, 430, 480 - 120, 50); + textSetInput(sendNumber); + sendNumber->setFont(style::window::font::small); - sendButton = new gui::Label(this,10, 500, 480-20, 50, "Send SMS"); - sendButton->setAlignement(gui::Alignment( gui::Alignment::ALIGN_VERTICAL_CENTER, gui::Alignment::ALIGN_HORIZONTAL_CENTER)); - sendButton->setPenWidth(1); - sendButton->setPenFocusWidth(3); - sendButton->activatedCallback = [=] (gui::Item& item) { - LOG_INFO("Send SMS callback" ); - CellularServiceAPI::SendSMS(application, sendNumber->getText(), sendMessage->getText()); - return true; }; + SendNumberLabel = new gui::Label(this, 10, 430, 90, 50, "Number"); + SendNumberLabel->setAlignement( + gui::Alignment(gui::Alignment::ALIGN_VERTICAL_CENTER, gui::Alignment::ALIGN_HORIZONTAL_CENTER)); + SendNumberLabel->setFont(style::window::font::small); + SendNumberLabel->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES); - sendButton->setNavigationItem(gui::NavigationDirection::UP, sendNumber); - sendNumber->setNavigationItem(gui::NavigationDirection::UP, sendMessage); + SendMessageLabel = new gui::Label(this, 10, 360, 90, 50, "Message"); + SendMessageLabel->setAlignement( + gui::Alignment(gui::Alignment::ALIGN_VERTICAL_CENTER, gui::Alignment::ALIGN_HORIZONTAL_CENTER)); + SendMessageLabel->setFont(style::window::font::small); + SendMessageLabel->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_NO_EDGES); - sendMessage->setNavigationItem(gui::NavigationDirection::DOWN, sendNumber); - sendNumber->setNavigationItem(gui::NavigationDirection::DOWN, sendButton); + sendButton = new gui::Label(this, 10, 500, 480 - 20, 50, "Send SMS"); + sendButton->setAlignement( + gui::Alignment(gui::Alignment::ALIGN_VERTICAL_CENTER, gui::Alignment::ALIGN_HORIZONTAL_CENTER)); + sendButton->setPenWidth(1); + sendButton->setPenFocusWidth(3); + sendButton->activatedCallback = [=](gui::Item &item) { + LOG_INFO("Send SMS callback"); + CellularServiceAPI::SendSMS(application, sendNumber->getText(), sendMessage->getText()); + return true; + }; + sendButton->setNavigationItem(gui::NavigationDirection::UP, sendNumber); + sendNumber->setNavigationItem(gui::NavigationDirection::UP, sendMessage); + sendMessage->setNavigationItem(gui::NavigationDirection::DOWN, sendNumber); + sendNumber->setNavigationItem(gui::NavigationDirection::DOWN, sendButton); + } + void TestMessageWindow::destroyInterface() + { + AppWindow::destroyInterface(); -} -void TestMessageWindow::destroyInterface() { - AppWindow::destroyInterface(); + this->focusItem = nullptr; - this->focusItem = nullptr; + children.clear(); + } - children.clear(); -} + TestMessageWindow::~TestMessageWindow() + {} -TestMessageWindow::~TestMessageWindow() { -} + void TestMessageWindow::onBeforeShow(ShowMode mode, SwitchData *data) + { + setFocusItem(sendButton); + } -void TestMessageWindow::onBeforeShow(ShowMode mode, SwitchData *data) { - setFocusItem( sendButton ); -} - -void TestMessageWindow::cellularMessageCallback(UTF8& number, UTF8& message) -{ - receiveNumber->setText(number); - receiveMessage->setText(message); - application->refreshWindow( RefreshModes::GUI_REFRESH_FAST ); -} + void TestMessageWindow::cellularMessageCallback(UTF8 &number, UTF8 &message) + { + receiveNumber->setText(number); + receiveMessage->setText(message); + application->refreshWindow(RefreshModes::GUI_REFRESH_FAST); + } } /* namespace gui */ diff --git a/module-apps/application-settings/windows/TestMessageWindow.hpp b/module-apps/application-settings/windows/TestMessageWindow.hpp index 103c8c12b..d0510f476 100644 --- a/module-apps/application-settings/windows/TestMessageWindow.hpp +++ b/module-apps/application-settings/windows/TestMessageWindow.hpp @@ -8,7 +8,6 @@ #ifndef MODULE_APPS_APPLICATION_SETTINGS_WINDOWS_TESTMESSAGEWINDOW_HPP_ #define MODULE_APPS_APPLICATION_SETTINGS_WINDOWS_TESTMESSAGEWINDOW_HPP_ - #include #include @@ -20,42 +19,42 @@ #include "gui/widgets/BottomBar.hpp" #include "gui/widgets/TopBar.hpp" -namespace gui { +namespace gui +{ -/* - * - */ -class TestMessageWindow: public AppWindow { -protected: - gui::Label* sendLabel; - gui::Label* sendButton; + /* + * + */ + class TestMessageWindow : public AppWindow + { + protected: + gui::Label *sendLabel; + gui::Label *sendButton; - gui::Label* receivedLabel; + gui::Label *receivedLabel; - gui::Label* SendNumberLabel; - gui::Label* SendMessageLabel; - gui::Text* sendNumber; - gui::Text* sendMessage; + gui::Label *SendNumberLabel; + gui::Label *SendMessageLabel; + gui::Text *sendNumber; + gui::Text *sendMessage; - gui::Label* RecNumberLabel; - gui::Label* RecMessageLabel; - gui::Label* receiveNumber; - gui::Text* receiveMessage; + gui::Label *RecNumberLabel; + gui::Label *RecMessageLabel; + gui::Label *receiveNumber; + gui::Text *receiveMessage; + public: + TestMessageWindow(app::Application *app); + virtual ~TestMessageWindow(); -public: - TestMessageWindow( app::Application* app ); - virtual ~TestMessageWindow(); + // virtual methods + void onBeforeShow(ShowMode mode, SwitchData *data) override; - //virtual methods - void onBeforeShow( ShowMode mode, SwitchData* data ) override; - - void rebuild() override; - void buildInterface() override; - void destroyInterface() override; - void cellularMessageCallback(UTF8& number, UTF8& message); -}; + void rebuild() override; + void buildInterface() override; + void destroyInterface() override; + void cellularMessageCallback(UTF8 &number, UTF8 &message); + }; } /* namespace gui */ - #endif /* MODULE_APPS_APPLICATION_SETTINGS_WINDOWS_TESTMESSAGEWINDOW_HPP_ */ diff --git a/module-apps/application-settings/windows/UITestWindow.cpp b/module-apps/application-settings/windows/UITestWindow.cpp index f05931560..781bcb14b 100644 --- a/module-apps/application-settings/windows/UITestWindow.cpp +++ b/module-apps/application-settings/windows/UITestWindow.cpp @@ -23,13 +23,20 @@ namespace gui bottomBar->setText(BottomBar::Side::CENTER, utils::localize.get("common_select")); bottomBar->setText(BottomBar::Side::RIGHT, utils::localize.get("common_back")); setTitle("UI TEST"); - text = new gui::Text(this, style::window::default_left_margin, title->offset_h(), style::window_width - 2 * style::window::default_left_margin, 300, - "Add text, long press * adds special char, long press # changes input (and shows it in bottom bar) arrows walk, 1 in text mode " + text = new gui::Text(this, + style::window::default_left_margin, + title->offset_h(), + style::window_width - 2 * style::window::default_left_margin, + 300, + "Add text, long press * adds special char, long press # changes input (and shows it in " + "bottom bar) arrows walk, 1 in text mode " "adds special chars too"); text->setEditMode(gui::Text::EditMode::EDIT); text->setFont(style::window::font::medium); text->setInputMode(new InputMode( - {InputMode::ABC, InputMode::abc, InputMode::digit}, [=](const UTF8 &text) { textModeShowCB(text); }, [=]() { textSelectSpecialCB(); })); + {InputMode::ABC, InputMode::abc, InputMode::digit}, + [=](const UTF8 &text) { textModeShowCB(text); }, + [=]() { textSelectSpecialCB(); })); text->setPenFocusWidth(0); setFocusItem(text); } @@ -40,8 +47,7 @@ namespace gui } void UiTestWindow::buildInterface() - { - } + {} void UiTestWindow::destroyInterface() { @@ -55,7 +61,6 @@ namespace gui } void UiTestWindow::onBeforeShow(ShowMode mode, SwitchData *data) - { - } + {} } // namespace gui diff --git a/module-apps/application-settings/windows/UITestWindow.hpp b/module-apps/application-settings/windows/UITestWindow.hpp index 2b0f2c9c9..0f7531534 100644 --- a/module-apps/application-settings/windows/UITestWindow.hpp +++ b/module-apps/application-settings/windows/UITestWindow.hpp @@ -13,19 +13,20 @@ namespace gui { -class UiTestWindow : public AppWindow -{ - protected: - gui::Text* text = nullptr; - public: - UiTestWindow(app::Application *app); - virtual ~UiTestWindow(); + class UiTestWindow : public AppWindow + { + protected: + gui::Text *text = nullptr; - // virtual methods - void onBeforeShow(ShowMode mode, SwitchData *data) override; - void rebuild() override; - void buildInterface() override; - void destroyInterface() override; - void set_navigation(); -}; + public: + UiTestWindow(app::Application *app); + virtual ~UiTestWindow(); + + // virtual methods + void onBeforeShow(ShowMode mode, SwitchData *data) override; + void rebuild() override; + void buildInterface() override; + void destroyInterface() override; + void set_navigation(); + }; } // namespace gui diff --git a/module-apps/application-special-input/AppSpecialInput.cpp b/module-apps/application-special-input/AppSpecialInput.cpp index 15fb54a9a..b0b96c3ae 100644 --- a/module-apps/application-special-input/AppSpecialInput.cpp +++ b/module-apps/application-special-input/AppSpecialInput.cpp @@ -4,7 +4,8 @@ using namespace app; -AppSpecialInput::AppSpecialInput(std::string name, std::string parent, bool startBackgound) : Application(name, parent, startBackgound) +AppSpecialInput::AppSpecialInput(std::string name, std::string parent, bool startBackgound) + : Application(name, parent, startBackgound) { auto window = new gui::UiCharSelector(this); windows.insert(std::pair(window->getName(), window)); @@ -14,20 +15,19 @@ AppSpecialInput::AppSpecialInput(std::string name, std::string parent, bool star sys::Message_t AppSpecialInput::DataReceivedHandler(sys::DataMessage *msgl, sys::ResponseMessage *resp) { auto retMsg = Application::DataReceivedHandler(msgl); - if (reinterpret_cast(retMsg.get())->retCode == sys::ReturnCodes::Success) - { + if (reinterpret_cast(retMsg.get())->retCode == sys::ReturnCodes::Success) { return retMsg; } return std::make_shared(sys::ReturnCodes::Unresolved); } -// THIS IS IMPORTANT THIS SETS APPLICATION STATE... (not for example Application(...) constructor - this wouild be too easy +// THIS IS IMPORTANT THIS SETS APPLICATION STATE... (not for example Application(...) constructor - this wouild be too +// easy sys::ReturnCodes AppSpecialInput::InitHandler() { auto ret = Application::InitHandler(); - if (ret != sys::ReturnCodes::Success) - { + if (ret != sys::ReturnCodes::Success) { LOG_ERROR(""); } setActiveWindow(gui::name::window::main_window); diff --git a/module-apps/application-special-input/AppSpecialInput.hpp b/module-apps/application-special-input/AppSpecialInput.hpp index 8f39777cd..3b866b9bd 100644 --- a/module-apps/application-special-input/AppSpecialInput.hpp +++ b/module-apps/application-special-input/AppSpecialInput.hpp @@ -7,7 +7,7 @@ namespace app { inline const std::string special_input = "AppSpecialInput"; - inline const std::string char_select = gui::name::window::main_window; + inline const std::string char_select = gui::name::window::main_window; // app just to provide input selection on UI class AppSpecialInput : public app::Application diff --git a/module-apps/application-special-input/windows/InputSelector.cpp b/module-apps/application-special-input/windows/InputSelector.cpp index f6e402f3b..70ce884db 100644 --- a/module-apps/application-special-input/windows/InputSelector.cpp +++ b/module-apps/application-special-input/windows/InputSelector.cpp @@ -9,8 +9,8 @@ using namespace gui; namespace style::design { - const inline auto char_grid_w = 80; - const inline auto char_grid_h = 80; + const inline auto char_grid_w = 80; + const inline auto char_grid_h = 80; const inline auto char_label_w = 60; const inline auto char_label_h = 60; }; // namespace style::design @@ -18,14 +18,16 @@ namespace style::design UiCharSelector::UiCharSelector(app::Application *app) : AppWindow(app, app::char_select) { AppWindow::buildInterface(); - box = new GridLayout(style::window::default_left_margin, title->offset_h(), + box = new GridLayout(style::window::default_left_margin, + title->offset_h(), style::window_width - style::window::default_left_margin - style::window::default_right_margin, - bottomBar->offset_h() - title->offset_h(), {style::design::char_grid_w, style::design::char_grid_h}); - for (auto schar : gui::special_chars) - { + bottomBar->offset_h() - title->offset_h(), + {style::design::char_grid_w, style::design::char_grid_h}); + for (auto schar : gui::special_chars) { auto el = new gui::Label(box, 0, 0, style::design::char_label_w, style::design::char_label_h); style::window::decorate(el); - el->setAlignement(gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_CENTER, gui::Alignment::ALIGN_VERTICAL_CENTER)); + el->setAlignement( + gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_CENTER, gui::Alignment::ALIGN_VERTICAL_CENTER)); el->setText(std::string(1, schar)); el->setFont(style::window::font::medium); el->activatedCallback = [=](Item &it) { @@ -33,7 +35,8 @@ UiCharSelector::UiCharSelector(app::Application *app) : AppWindow(app, app::char LOG_INFO("handled %s for %s", el->getText().c_str(), name.c_str()); setFocusItem(nullptr); sapm::ApplicationManager::messageSwitchSpecialInput( - application, std::make_unique(gui::SwitchSpecialChar::Type::Response, name, el->getText())); + application, + std::make_unique(gui::SwitchSpecialChar::Type::Response, name, el->getText())); return true; }; } @@ -44,8 +47,7 @@ UiCharSelector::UiCharSelector(app::Application *app) : AppWindow(app, app::char void UiCharSelector::onBeforeShow(ShowMode mode, SwitchData *data) { auto ret = dynamic_cast(data); - if (ret) - { + if (ret) { LOG_INFO("handle for: %s", ret->requester.c_str()); setFocusItem(box); application->refreshWindow(gui::RefreshModes::GUI_REFRESH_FAST); @@ -53,11 +55,9 @@ void UiCharSelector::onBeforeShow(ShowMode mode, SwitchData *data) } } void UiCharSelector::rebuild() -{ -} +{} void UiCharSelector::buildInterface() -{ -} +{} void UiCharSelector::destroyInterface() { setFocusItem(nullptr); diff --git a/module-apps/application-viewer/ApplicationViewer.cpp b/module-apps/application-viewer/ApplicationViewer.cpp index f5e7e3a8d..bc9b4f036 100644 --- a/module-apps/application-viewer/ApplicationViewer.cpp +++ b/module-apps/application-viewer/ApplicationViewer.cpp @@ -11,7 +11,7 @@ #include #include -//module-gui +// module-gui #include "ApplicationViewer.hpp" #include "service-appmgr/ApplicationManager.hpp" @@ -21,72 +21,80 @@ #include "gui/widgets/Image.hpp" #include "gui/widgets/Label.hpp" #include "gui/widgets/BoxLayout.hpp" -//module-utils +// module-utils #include "log/log.hpp" -//module-services +// module-services #include "service-evtmgr/EventManager.hpp" #include "service-evtmgr/messages/EVMessages.hpp" -//MessageType +// MessageType #include "MessageType.hpp" -//this module +// this module #include "windows/ViewWindow.hpp" -namespace app { +namespace app +{ -ApplicationViewer::ApplicationViewer(std::string name, std::string parent,uint32_t stackDepth,sys::ServicePriority priority) : - Application( name, parent, false, stackDepth, priority ) { -} + ApplicationViewer::ApplicationViewer(std::string name, + std::string parent, + uint32_t stackDepth, + sys::ServicePriority priority) + : Application(name, parent, false, stackDepth, priority) + {} -ApplicationViewer::~ApplicationViewer() { - // TODO Auto-generated destructor stub -} + ApplicationViewer::~ApplicationViewer() + { + // TODO Auto-generated destructor stub + } -// Invoked upon receiving data message -sys::Message_t ApplicationViewer::DataReceivedHandler(sys::DataMessage* msgl,sys::ResponseMessage* resp) { + // Invoked upon receiving data message + sys::Message_t ApplicationViewer::DataReceivedHandler(sys::DataMessage *msgl, sys::ResponseMessage *resp) + { - auto retMsg = Application::DataReceivedHandler(msgl); - //if message was handled by application's template there is no need to process further. - if( (reinterpret_cast( retMsg.get() )->retCode == - sys::ReturnCodes::Success ) ){ - return retMsg; - } + auto retMsg = Application::DataReceivedHandler(msgl); + // if message was handled by application's template there is no need to process further. + if ((reinterpret_cast(retMsg.get())->retCode == sys::ReturnCodes::Success)) { + return retMsg; + } - //this variable defines whether message was processed. - bool handled = true; + // this variable defines whether message was processed. + bool handled = true; - if( handled ) - return std::make_shared(); - else - return std::make_shared(sys::ReturnCodes::Unresolved); -} + if (handled) + return std::make_shared(); + else + return std::make_shared(sys::ReturnCodes::Unresolved); + } -// Invoked during initialization -sys::ReturnCodes ApplicationViewer::InitHandler() { + // Invoked during initialization + sys::ReturnCodes ApplicationViewer::InitHandler() + { - auto ret = Application::InitHandler(); - if( ret != sys::ReturnCodes::Success ) - return ret; + auto ret = Application::InitHandler(); + if (ret != sys::ReturnCodes::Success) + return ret; - createUserInterface(); + createUserInterface(); - setActiveWindow("Main"); + setActiveWindow("Main"); - return ret; -} + return ret; + } -sys::ReturnCodes ApplicationViewer::DeinitHandler() { - return sys::ReturnCodes::Success; -} + sys::ReturnCodes ApplicationViewer::DeinitHandler() + { + return sys::ReturnCodes::Success; + } -void ApplicationViewer::createUserInterface() { + void ApplicationViewer::createUserInterface() + { - gui::AppWindow* window = nullptr; + gui::AppWindow *window = nullptr; - window = new gui::ViewWindow(this); - windows.insert(std::pair(window->getName(), window)); -} + window = new gui::ViewWindow(this); + windows.insert(std::pair(window->getName(), window)); + } -void ApplicationViewer::destroyUserInterface() { -} + void ApplicationViewer::destroyUserInterface() + {} } /* namespace app */ diff --git a/module-apps/application-viewer/ApplicationViewer.hpp b/module-apps/application-viewer/ApplicationViewer.hpp index cb6a22dd9..24455a93f 100644 --- a/module-apps/application-viewer/ApplicationViewer.hpp +++ b/module-apps/application-viewer/ApplicationViewer.hpp @@ -14,25 +14,33 @@ #include "gui/widgets/Label.hpp" #include "gui/widgets/Progress.hpp" -namespace app { +namespace app +{ -inline const std::string name_viewer = "ApplicationViewer"; + inline const std::string name_viewer = "ApplicationViewer"; -class ApplicationViewer: public Application { + class ApplicationViewer : public Application + { -public: - ApplicationViewer(std::string name, std::string parent = "", uint32_t stackDepth=4096,sys::ServicePriority priority=sys::ServicePriority::Idle); - virtual ~ApplicationViewer(); + public: + ApplicationViewer(std::string name, + std::string parent = "", + uint32_t stackDepth = 4096, + sys::ServicePriority priority = sys::ServicePriority::Idle); + virtual ~ApplicationViewer(); - sys::Message_t DataReceivedHandler(sys::DataMessage* msgl,sys::ResponseMessage* resp) override; - sys::ReturnCodes InitHandler() override; - sys::ReturnCodes DeinitHandler() override; + sys::Message_t DataReceivedHandler(sys::DataMessage *msgl, sys::ResponseMessage *resp) override; + sys::ReturnCodes InitHandler() override; + sys::ReturnCodes DeinitHandler() override; - sys::ReturnCodes SwitchPowerModeHandler(const sys::ServicePowerMode mode) override final{return sys::ReturnCodes::Success;} + sys::ReturnCodes SwitchPowerModeHandler(const sys::ServicePowerMode mode) override final + { + return sys::ReturnCodes::Success; + } - void createUserInterface() override; - void destroyUserInterface() override; -}; + void createUserInterface() override; + void destroyUserInterface() override; + }; } /* namespace app */ diff --git a/module-apps/application-viewer/windows/ViewWindow.cpp b/module-apps/application-viewer/windows/ViewWindow.cpp index 147e72c52..7ac3fa3e8 100644 --- a/module-apps/application-viewer/windows/ViewWindow.cpp +++ b/module-apps/application-viewer/windows/ViewWindow.cpp @@ -13,146 +13,151 @@ #include "AppWindow.hpp" #include "Application.hpp" -namespace gui { +namespace gui +{ ViewWindow::ViewWindow(app::Application *app) : AppWindow(app, gui::name::window::main_window) { buildInterface(); } -void ViewWindow::rebuild() { - destroyInterface(); - buildInterface(); -} + void ViewWindow::rebuild() + { + destroyInterface(); + buildInterface(); + } -void ViewWindow::buildInterface() { - AppWindow::buildInterface(); - //load all states from file - auto file = vfs.fopen("sys/viewerStates.txt","r"); - //read line with number of states - std::string str = vfs.getline(file); - uint32_t statesCount; - std::stringstream(str) >> statesCount; + void ViewWindow::buildInterface() + { + AppWindow::buildInterface(); + // load all states from file + auto file = vfs.fopen("sys/viewerStates.txt", "r"); + // read line with number of states + std::string str = vfs.getline(file); + uint32_t statesCount; + std::stringstream(str) >> statesCount; - LOG_INFO("States count: %d", statesCount ); - bool err = false; - for( uint32_t i=0; i tokens; - std::stringstream check1(buttonStr); - std::string intermediate; + // Vector of string to save pairs of button code and image + std::vector tokens; + std::stringstream check1(buttonStr); + std::string intermediate; - // Tokenizing w.r.t. space ' ' - while(getline(check1, intermediate, ',')) - { - tokens.push_back(intermediate); - } + // Tokenizing w.r.t. space ' ' + while (getline(check1, intermediate, ',')) { + tokens.push_back(intermediate); + } - bool deepRefresh = false; - if( refreshModeStr[0] == 'F' || refreshModeStr[0] == 'f' ) - deepRefresh = true; + bool deepRefresh = false; + if (refreshModeStr[0] == 'F' || refreshModeStr[0] == 'f') + deepRefresh = true; - std::map buttons; - for(unsigned int j = 0; j < tokens.size(); j++) { - LOG_INFO("TOKEN: %s", tokens[j].c_str()); - std::vector tokens2; - std::stringstream check2(tokens[j]); - while(getline(check2, intermediate, ' ')) { - tokens2.push_back(intermediate); - } + std::map buttons; + for (unsigned int j = 0; j < tokens.size(); j++) { + LOG_INFO("TOKEN: %s", tokens[j].c_str()); + std::vector tokens2; + std::stringstream check2(tokens[j]); + while (getline(check2, intermediate, ' ')) { + tokens2.push_back(intermediate); + } - if( tokens2.size() != 2 ) - continue; + if (tokens2.size() != 2) + continue; - //convert first token to key id - auto it = buttonKeyCodes.find( tokens2[0]); - if( it != buttonKeyCodes.end()) { + // convert first token to key id + auto it = buttonKeyCodes.find(tokens2[0]); + if (it != buttonKeyCodes.end()) { - int screenCode; - std::stringstream(tokens2[1]) >> screenCode; - LOG_INFO("[%d] [%d]", it->second, screenCode ); + int screenCode; + std::stringstream(tokens2[1]) >> screenCode; + LOG_INFO("[%d] [%d]", it->second, screenCode); - buttons.insert( std::pair( it->second, screenCode )); + buttons.insert(std::pair(it->second, screenCode)); + } + } - } - } + states.push_back(ViewerState(stateName, screenName, deepRefresh, states.size(), buttons)); - states.push_back( ViewerState(stateName, screenName, deepRefresh, states.size(), buttons ) ); + LOG_INFO("State: %s Screen: %s deep: %d", stateName.c_str(), screenName.c_str(), deepRefresh); + } + else { + err = true; + LOG_FATAL("ERROR reading viwer section"); + break; + } + } + if (err) + states.clear(); - LOG_INFO( "State: %s Screen: %s deep: %d", stateName.c_str(), screenName.c_str(), deepRefresh ); - } - else { - err = true; - LOG_FATAL("ERROR reading viwer section"); - break; - } - } - if( err ) - states.clear(); + vfs.fclose(file); - vfs.fclose(file); + for (ViewerState s : states) { + gui::Image *img = new gui::Image(this, 0, 0, 0, 0); + img->set(s.screenName); + img->setVisible(false); - for( ViewerState s : states ) { - gui::Image* img = new gui::Image(this,0,0,0,0); - img->set(s.screenName); - img->setVisible(false); + images.push_back(img); + } + } + void ViewWindow::destroyInterface() + { + destroyInterface(); + for (uint32_t i = 0; i < images.size(); i++) + delete images[i]; + } - images.push_back( img ); - } -} -void ViewWindow::destroyInterface() { - destroyInterface(); - for( uint32_t i=0; isetVisible(true); + } - currentState = 0; - if( states.size() ) - images[currentState]->setVisible(true); -} + bool ViewWindow::onInput(const InputEvent &inputEvent) + { + // process only if key is released + if (inputEvent.state == InputEvent::State::keyReleasedShort) { -bool ViewWindow::onInput( const InputEvent& inputEvent ) { - //process only if key is released - if( inputEvent.state == InputEvent::State::keyReleasedShort ) { + uint32_t oldState = currentState; - uint32_t oldState = currentState; + for (auto it = states[currentState].buttons.begin(); it != states[currentState].buttons.end(); it++) + LOG_INFO("[%d %d]", it->first, it->second); - for( auto it = states[currentState].buttons.begin(); it!=states[currentState].buttons.end(); it++) - LOG_INFO("[%d %d]", it->first, it->second); + auto it = states[currentState].buttons.find(static_cast(inputEvent.keyCode)); + if (it == states[currentState].buttons.end()) + return false; - auto it = states[currentState].buttons.find(static_cast(inputEvent.keyCode)); - if( it == states[currentState].buttons.end() ) - return false; + images[oldState]->setVisible(false); + currentState = it->second; + images[currentState]->setVisible(true); + if (oldState != currentState) { + if (states[currentState].deepRefresh) + application->refreshWindow(RefreshModes::GUI_REFRESH_DEEP); + else + application->refreshWindow(RefreshModes::GUI_REFRESH_FAST); + } + return true; + } - images[oldState]->setVisible(false); - currentState = it->second; - images[currentState]->setVisible(true); - if( oldState != currentState ) { - if( states[currentState].deepRefresh ) - application->refreshWindow( RefreshModes::GUI_REFRESH_DEEP ); - else - application->refreshWindow( RefreshModes::GUI_REFRESH_FAST ); - } - return true; - } - - //check if any of the lower inheritance onInput methods catch the event - return AppWindow::onInput( inputEvent ); -} + // check if any of the lower inheritance onInput methods catch the event + return AppWindow::onInput(inputEvent); + } } /* namespace gui */ diff --git a/module-apps/application-viewer/windows/ViewWindow.hpp b/module-apps/application-viewer/windows/ViewWindow.hpp index fcad14af2..2f18a4d8c 100644 --- a/module-apps/application-viewer/windows/ViewWindow.hpp +++ b/module-apps/application-viewer/windows/ViewWindow.hpp @@ -14,70 +14,73 @@ #include "widgets/Image.hpp" #include "InputEvent.hpp" -namespace gui { +namespace gui +{ -class ViewerState { -public: - std::string stateName; - std::string screenName; - bool deepRefresh = false; - uint32_t id = 0; - std::map buttons; + class ViewerState + { + public: + std::string stateName; + std::string screenName; + bool deepRefresh = false; + uint32_t id = 0; + std::map buttons; - ViewerState( std::string stateName, std::string screenName, bool deep, uint32_t id, std::map buttons ) : - stateName{stateName}, screenName{screenName}, deepRefresh{deep}, id{id}, buttons{buttons} {}; -}; + ViewerState(std::string stateName, std::string screenName, bool deep, uint32_t id, std::map buttons) + : stateName{stateName}, screenName{screenName}, deepRefresh{deep}, id{id}, buttons{buttons} {}; + }; -/* - * - */ -class ViewWindow: public AppWindow { - uint32_t currentState = 0; - std::vector images; - std::vector states; + /* + * + */ + class ViewWindow : public AppWindow + { + uint32_t currentState = 0; + std::vector images; + std::vector states; - int convertKeyCode( std::string ); + int convertKeyCode(std::string); - std::map buttonKeyCodes = { - {"KEY_UNDEFINED", static_cast(KeyCode::KEY_UNDEFINED)}, - {"KEY_LEFT", static_cast(KeyCode::KEY_LEFT)}, - {"KEY_UP", static_cast(KeyCode::KEY_UP)}, - {"KEY_RIGHT", static_cast(KeyCode::KEY_RIGHT)}, - {"KEY_DOWN", static_cast(KeyCode::KEY_DOWN)}, - {"KEY_LF", static_cast(KeyCode::KEY_LF)}, - {"KEY_RF", static_cast(KeyCode::KEY_RF)}, - {"KEY_ENTER", static_cast(KeyCode::KEY_ENTER)}, - {"KEY_0", static_cast(KeyCode::KEY_0)}, - {"KEY_1", static_cast(KeyCode::KEY_1)}, - {"KEY_2", static_cast(KeyCode::KEY_2)}, - {"KEY_3", static_cast(KeyCode::KEY_3)}, - {"KEY_4", static_cast(KeyCode::KEY_4)}, - {"KEY_5", static_cast(KeyCode::KEY_5)}, - {"KEY_6", static_cast(KeyCode::KEY_6)}, - {"KEY_7", static_cast(KeyCode::KEY_7)}, - {"KEY_8", static_cast(KeyCode::KEY_8)}, - {"KEY_9", static_cast(KeyCode::KEY_9)}, - {"KEY_AST", static_cast(KeyCode::KEY_AST)}, - {"KEY_PND", static_cast(KeyCode::KEY_PND)}, - {"KEY_VOLUP", static_cast(KeyCode::KEY_VOLUP)}, - {"KEY_VOLDN", static_cast(KeyCode::KEY_VOLDN)}, - {"KEY_TORCH", static_cast(KeyCode::KEY_TORCH)}, - {"SWITCH_UP", static_cast(KeyCode::SWITCH_UP)}, - {"SWITCH_MID", static_cast(KeyCode::SWITCH_MID)}, - {"SWITCH_DN", static_cast(KeyCode::SWITCH_DN)}, - }; + std::map buttonKeyCodes = { + {"KEY_UNDEFINED", static_cast(KeyCode::KEY_UNDEFINED)}, + {"KEY_LEFT", static_cast(KeyCode::KEY_LEFT)}, + {"KEY_UP", static_cast(KeyCode::KEY_UP)}, + {"KEY_RIGHT", static_cast(KeyCode::KEY_RIGHT)}, + {"KEY_DOWN", static_cast(KeyCode::KEY_DOWN)}, + {"KEY_LF", static_cast(KeyCode::KEY_LF)}, + {"KEY_RF", static_cast(KeyCode::KEY_RF)}, + {"KEY_ENTER", static_cast(KeyCode::KEY_ENTER)}, + {"KEY_0", static_cast(KeyCode::KEY_0)}, + {"KEY_1", static_cast(KeyCode::KEY_1)}, + {"KEY_2", static_cast(KeyCode::KEY_2)}, + {"KEY_3", static_cast(KeyCode::KEY_3)}, + {"KEY_4", static_cast(KeyCode::KEY_4)}, + {"KEY_5", static_cast(KeyCode::KEY_5)}, + {"KEY_6", static_cast(KeyCode::KEY_6)}, + {"KEY_7", static_cast(KeyCode::KEY_7)}, + {"KEY_8", static_cast(KeyCode::KEY_8)}, + {"KEY_9", static_cast(KeyCode::KEY_9)}, + {"KEY_AST", static_cast(KeyCode::KEY_AST)}, + {"KEY_PND", static_cast(KeyCode::KEY_PND)}, + {"KEY_VOLUP", static_cast(KeyCode::KEY_VOLUP)}, + {"KEY_VOLDN", static_cast(KeyCode::KEY_VOLDN)}, + {"KEY_TORCH", static_cast(KeyCode::KEY_TORCH)}, + {"SWITCH_UP", static_cast(KeyCode::SWITCH_UP)}, + {"SWITCH_MID", static_cast(KeyCode::SWITCH_MID)}, + {"SWITCH_DN", static_cast(KeyCode::SWITCH_DN)}, + }; -public: - ViewWindow( app::Application* app ); - virtual ~ViewWindow(); + public: + ViewWindow(app::Application *app); + virtual ~ViewWindow(); - void onBeforeShow( ShowMode mode, SwitchData* data ) override; - bool onInput( const InputEvent& inputEvent ) override; + void onBeforeShow(ShowMode mode, SwitchData *data) override; + bool onInput(const InputEvent &inputEvent) override; - void rebuild() override; - void buildInterface() override; - void destroyInterface() override; -}; + void rebuild() override; + void buildInterface() override; + void destroyInterface() override; + }; } /* namespace gui */ diff --git a/module-apps/messages/AppMessage.hpp b/module-apps/messages/AppMessage.hpp index af33199b7..768f54580 100644 --- a/module-apps/messages/AppMessage.hpp +++ b/module-apps/messages/AppMessage.hpp @@ -16,104 +16,146 @@ #include #include -namespace app { +namespace app +{ -/* - * @brief Template for all messages that go to application manager - */ -class AppMessage: public sys::DataMessage { -public: - AppMessage(MessageType messageType) : sys::DataMessage(messageType){}; - virtual ~AppMessage(){}; + /* + * @brief Template for all messages that go to application manager + */ + class AppMessage : public sys::DataMessage + { + public: + AppMessage(MessageType messageType) : sys::DataMessage(messageType){}; + virtual ~AppMessage(){}; + }; -}; + // this message is used to notify application about switching event. Application will gain or lose focus upon + // receiving this message. Application gains focus when it was in init or active background state. Application loose + // focus when it was in active foreground state. if no window is specified it is assumed that MainWindow is the + // target + class AppSwitchMessage : public AppMessage + { + protected: + // name of the application to which switch is performed. + std::string targetApplication; + // name of the window to which switch should be performed. + std::string targetWindow; + // optional data for the target window. + std::unique_ptr data; + // name of the application to which switch should be performed after finishing tasks in target application and + // window. + std::string returnApplication; + // name of the window to which switch should be performed after finishing tasks in target application and + // window. + std::string returnWindow; -//this message is used to notify application about switching event. Application will gain or lose focus upon receiving this message. -//Application gains focus when it was in init or active background state. Application loose focus when it was in active foreground state. -//if no window is specified it is assumed that MainWindow is the target -class AppSwitchMessage : public AppMessage { -protected: - //name of the application to which switch is performed. - std::string targetApplication; - //name of the window to which switch should be performed. - std::string targetWindow; - //optional data for the target window. - std::unique_ptr data; - //name of the application to which switch should be performed after finishing tasks in target application and window. - std::string returnApplication; - //name of the window to which switch should be performed after finishing tasks in target application and window. - std::string returnWindow; -public: - AppSwitchMessage( const std::string& targetApplication, const std::string& targetWindow, std::unique_ptr data, - const std::string& returnApplication = "", const std::string& returnWindow = "") : - AppMessage( MessageType::AppSwitch ), - targetApplication{ targetApplication }, - targetWindow{ targetWindow }, - data {std::move(data)}, - returnApplication{ returnApplication }, - returnWindow{ returnWindow } {}; - virtual ~AppSwitchMessage() {}; + public: + AppSwitchMessage(const std::string &targetApplication, + const std::string &targetWindow, + std::unique_ptr data, + const std::string &returnApplication = "", + const std::string &returnWindow = "") + : AppMessage(MessageType::AppSwitch), targetApplication{targetApplication}, targetWindow{targetWindow}, + data{std::move(data)}, returnApplication{returnApplication}, returnWindow{returnWindow} {}; + virtual ~AppSwitchMessage(){}; - std::string getTargetWindowName() { return targetWindow; }; - std::string getReturnWindowName() { return returnWindow; }; - std::unique_ptr& getData() { return data; }; - std::string getTargetApplicationName() { return targetApplication;}; - std::string getReturnApplicationName() { return returnApplication;}; -}; + std::string getTargetWindowName() + { + return targetWindow; + }; + std::string getReturnWindowName() + { + return returnWindow; + }; + std::unique_ptr &getData() + { + return data; + }; + std::string getTargetApplicationName() + { + return targetApplication; + }; + std::string getReturnApplicationName() + { + return returnApplication; + }; + }; -class AppRefreshMessage : public AppMessage { -protected: - gui::RefreshModes mode; -public: -// AppRefreshMessage( const std::string& application, gui::RefreshModes mode ) : - AppRefreshMessage( gui::RefreshModes mode ) : - AppMessage( MessageType::AppRefresh ), - mode{ mode }{}; - virtual ~AppRefreshMessage() {}; + class AppRefreshMessage : public AppMessage + { + protected: + gui::RefreshModes mode; - const gui::RefreshModes& getMode() { return mode; }; -}; + public: + // AppRefreshMessage( const std::string& application, gui::RefreshModes mode ) : + AppRefreshMessage(gui::RefreshModes mode) : AppMessage(MessageType::AppRefresh), mode{mode} {}; + virtual ~AppRefreshMessage(){}; -class AppSwitchWindowMessage : public AppMessage { -protected: - std::string window; - std::string senderWindow; - gui::ShowMode command; - std::unique_ptr data; -public: - bool LastSeenWindow = false; - AppSwitchWindowMessage() = delete; + const gui::RefreshModes &getMode() + { + return mode; + }; + }; - AppSwitchWindowMessage(const std::string &window, const std::string senderWindow, std::unique_ptr data, - const gui::ShowMode command = gui::ShowMode::GUI_SHOW_INIT) - : AppMessage(MessageType::AppSwitchWindow), window{window}, senderWindow{senderWindow}, command{command}, data{std::move(data)} {}; - virtual ~AppSwitchWindowMessage() = default; + class AppSwitchWindowMessage : public AppMessage + { + protected: + std::string window; + std::string senderWindow; + gui::ShowMode command; + std::unique_ptr data; - const std::string &getWindowName() const - { - return window; }; - const std::string& getSenderWindowName() const { return senderWindow; }; - const gui::ShowMode& getCommand() const { return command; }; - std::unique_ptr& getData() { return data; }; -}; + public: + bool LastSeenWindow = false; + AppSwitchWindowMessage() = delete; -class AppInputEventMessage : public AppMessage { -protected: - gui::InputEvent event; -public: - AppInputEventMessage( gui::InputEvent evt ) : - AppMessage( MessageType::AppInputEvent ), - event{evt} {}; - virtual ~AppInputEventMessage() {}; + AppSwitchWindowMessage(const std::string &window, + const std::string senderWindow, + std::unique_ptr data, + const gui::ShowMode command = gui::ShowMode::GUI_SHOW_INIT) + : AppMessage(MessageType::AppSwitchWindow), window{window}, + senderWindow{senderWindow}, command{command}, data{std::move(data)} {}; + virtual ~AppSwitchWindowMessage() = default; - const gui::InputEvent& getEvent() { return event; }; -}; + const std::string &getWindowName() const + { + return window; + }; + const std::string &getSenderWindowName() const + { + return senderWindow; + }; + const gui::ShowMode &getCommand() const + { + return command; + }; + std::unique_ptr &getData() + { + return data; + }; + }; -class AppRebuildMessage : public AppMessage { -public: - AppRebuildMessage(): AppMessage( MessageType::AppRebuild ) {}; - virtual ~AppRebuildMessage() {}; -}; + class AppInputEventMessage : public AppMessage + { + protected: + gui::InputEvent event; -}; + public: + AppInputEventMessage(gui::InputEvent evt) : AppMessage(MessageType::AppInputEvent), event{evt} {}; + virtual ~AppInputEventMessage(){}; + + const gui::InputEvent &getEvent() + { + return event; + }; + }; + + class AppRebuildMessage : public AppMessage + { + public: + AppRebuildMessage() : AppMessage(MessageType::AppRebuild){}; + virtual ~AppRebuildMessage(){}; + }; + +}; // namespace app #endif /* MODULE_APPS_MESSAGES_APPMESSAGE_HPP_ */ diff --git a/module-apps/windows/AppWindow.cpp b/module-apps/windows/AppWindow.cpp index 08ee73b78..4aee04183 100644 --- a/module-apps/windows/AppWindow.cpp +++ b/module-apps/windows/AppWindow.cpp @@ -15,148 +15,161 @@ using namespace style::header; -namespace gui { - -AppWindow::AppWindow( app::Application* app, std::string name, uint32_t id ) : - Window ( name, id), application{ app } { - setSize(style::window_width, style::window_height); -} - -AppWindow::~AppWindow() { - LOG_INFO("deleting window: %s", name.c_str()); - destroyInterface(); -} - - -void AppWindow::destroyInterface() { - children.remove(bottomBar); - children.remove(topBar); - children.remove(title); - delete title; - delete bottomBar; - delete topBar; - title = nullptr; - bottomBar = nullptr; - topBar = nullptr; -} - -void AppWindow::rebuild() { -} - -void AppWindow::buildInterface() { - bottomBar = new gui::BottomBar( this, 0, 599-50, 480, 50 ); - bottomBar->setActive( BottomBar::Side::LEFT, false ); - bottomBar->setActive( BottomBar::Side::CENTER, false ); - bottomBar->setActive( BottomBar::Side::RIGHT, false ); - - title = new gui::Label(this, 0, 52, 480, 52 ); - title->setFilled( false ); - title->setFont(font::title); - title->setText(""); - title->setAlignement( gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_CENTER, gui::Alignment::ALIGN_VERTICAL_TOP)); - title->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_BOTTOM ); - title->setDotsMode(true); - title->visible = false; - - topBar = new gui::TopBar(this, 0, 0, 480, 50); - topBar->setActive(TopBar::Elements::LOCK, false ); - topBar->setActive(TopBar::Elements::BATTERY, false ); - topBar->setActive(TopBar::Elements::SIGNAL, false ); -} - -bool AppWindow::batteryCharging(bool charging) +namespace gui { - topBar->setBatteryCharging(charging); - return true; -} -bool AppWindow::setSIM() -{ - topBar->simSet(); - return true; -} - -//updates battery level in the window -bool AppWindow::updateBatteryLevel( uint32_t percentage ) { - //get old value of battery level, calcualte new level and comapre both - //if they are different make a change and return true, otherwise return false; - return topBar->setBatteryLevel(percentage); -} -// updates battery level in the window -bool AppWindow::updateSignalStrength() -{ - return topBar->updateSignalStrength(); -} - -bool AppWindow::updateTime( const UTF8& timeStr ) { - topBar->setTime(timeStr); - return true; -} - -bool AppWindow::updateTime( const uint32_t& timestamp, bool mode24H ) { - topBar->setTime( timestamp, mode24H ); - return true; -} - -void AppWindow::setTitle(const UTF8 &text) { - if(title != nullptr) { - title->setVisible(true); - title->setText(text); - } else { - LOG_ERROR("cant set title - it doesn't exist!"); - } -} - -std::list AppWindow::buildDrawList() { - return Window::buildDrawList(); -} - -bool AppWindow::onDatabaseMessage( sys::Message* msg ){ return false; } - -bool AppWindow::onInput( const InputEvent& inputEvent) { - - //check if any of the lower inheritance onInput methods catch the event - if( Window::onInput( inputEvent ) ) { - if( inputEvent.keyCode != KeyCode::KEY_ENTER ) application->render( RefreshModes::GUI_REFRESH_FAST ); - return true; - } - - if (inputEvent.state == InputEvent::State::keyReleasedLong && inputEvent.keyCode == gui::KeyCode::KEY_RF) + AppWindow::AppWindow(app::Application *app, std::string name, uint32_t id) : Window(name, id), application{app} { - LOG_INFO("exit to main menu"); - sapm::ApplicationManager::messageSwitchApplication(application, app::name_desktop, gui::name::window::main_window, nullptr); - } - //process only if key is released - if(( inputEvent.state != InputEvent::State::keyReleasedShort )) return false; - - if( inputEvent.keyCode == KeyCode::KEY_RF ) { - return returnToPreviousView(); + setSize(style::window_width, style::window_height); } - return false; -} - -bool AppWindow::returnToPreviousView() -{ - auto prevWindow = application->getPrevWindow(); - if (prevWindow == gui::name::window::no_window) + AppWindow::~AppWindow() { - LOG_INFO("Back to previous application"); - application->cleanPrevWindw(); - sapm::ApplicationManager::messageSwitchPreviousApplication(application); + LOG_INFO("deleting window: %s", name.c_str()); + destroyInterface(); } - else + + void AppWindow::destroyInterface() { - LOG_INFO("Back to previous window %s", prevWindow.c_str()); - application->switchWindow(prevWindow, gui::ShowMode::GUI_SHOW_RETURN); + children.remove(bottomBar); + children.remove(topBar); + children.remove(title); + delete title; + delete bottomBar; + delete topBar; + title = nullptr; + bottomBar = nullptr; + topBar = nullptr; + } + + void AppWindow::rebuild() + {} + + void AppWindow::buildInterface() + { + bottomBar = new gui::BottomBar(this, 0, 599 - 50, 480, 50); + bottomBar->setActive(BottomBar::Side::LEFT, false); + bottomBar->setActive(BottomBar::Side::CENTER, false); + bottomBar->setActive(BottomBar::Side::RIGHT, false); + + title = new gui::Label(this, 0, 52, 480, 52); + title->setFilled(false); + title->setFont(font::title); + title->setText(""); + title->setAlignement( + gui::Alignment(gui::Alignment::ALIGN_HORIZONTAL_CENTER, gui::Alignment::ALIGN_VERTICAL_TOP)); + title->setEdges(RectangleEdgeFlags::GUI_RECT_EDGE_BOTTOM); + title->setDotsMode(true); + title->visible = false; + + topBar = new gui::TopBar(this, 0, 0, 480, 50); + topBar->setActive(TopBar::Elements::LOCK, false); + topBar->setActive(TopBar::Elements::BATTERY, false); + topBar->setActive(TopBar::Elements::SIGNAL, false); + } + + bool AppWindow::batteryCharging(bool charging) + { + topBar->setBatteryCharging(charging); + return true; + } + + bool AppWindow::setSIM() + { + topBar->simSet(); + return true; + } + + // updates battery level in the window + bool AppWindow::updateBatteryLevel(uint32_t percentage) + { + // get old value of battery level, calcualte new level and comapre both + // if they are different make a change and return true, otherwise return false; + return topBar->setBatteryLevel(percentage); + } + // updates battery level in the window + bool AppWindow::updateSignalStrength() + { + return topBar->updateSignalStrength(); + } + + bool AppWindow::updateTime(const UTF8 &timeStr) + { + topBar->setTime(timeStr); + return true; + } + + bool AppWindow::updateTime(const uint32_t ×tamp, bool mode24H) + { + topBar->setTime(timestamp, mode24H); + return true; + } + + void AppWindow::setTitle(const UTF8 &text) + { + if (title != nullptr) { + title->setVisible(true); + title->setText(text); + } + else { + LOG_ERROR("cant set title - it doesn't exist!"); + } + } + + std::list AppWindow::buildDrawList() + { + return Window::buildDrawList(); + } + + bool AppWindow::onDatabaseMessage(sys::Message *msg) + { + return false; + } + + bool AppWindow::onInput(const InputEvent &inputEvent) + { + + // check if any of the lower inheritance onInput methods catch the event + if (Window::onInput(inputEvent)) { + if (inputEvent.keyCode != KeyCode::KEY_ENTER) + application->render(RefreshModes::GUI_REFRESH_FAST); + return true; + } + + if (inputEvent.state == InputEvent::State::keyReleasedLong && inputEvent.keyCode == gui::KeyCode::KEY_RF) { + LOG_INFO("exit to main menu"); + sapm::ApplicationManager::messageSwitchApplication( + application, app::name_desktop, gui::name::window::main_window, nullptr); + } + // process only if key is released + if ((inputEvent.state != InputEvent::State::keyReleasedShort)) + return false; + + if (inputEvent.keyCode == KeyCode::KEY_RF) { + return returnToPreviousView(); + } + + return false; + } + + bool AppWindow::returnToPreviousView() + { + auto prevWindow = application->getPrevWindow(); + if (prevWindow == gui::name::window::no_window) { + LOG_INFO("Back to previous application"); + application->cleanPrevWindw(); + sapm::ApplicationManager::messageSwitchPreviousApplication(application); + } + else { + LOG_INFO("Back to previous window %s", prevWindow.c_str()); + application->switchWindow(prevWindow, gui::ShowMode::GUI_SHOW_RETURN); + } + return true; } - return true; -} void AppWindow::textModeShowCB(const UTF8 &text) { - if (bottomBar == nullptr) - { + if (bottomBar == nullptr) { return; } bottomBar->setText(BottomBar::Side::CENTER, text); @@ -167,7 +180,8 @@ bool AppWindow::returnToPreviousView() bool AppWindow::textSelectSpecialCB() { return sapm::ApplicationManager::messageSwitchSpecialInput( - application, std::make_unique(gui::SwitchSpecialChar::Type::Request, application->GetName())); + application, + std::make_unique(gui::SwitchSpecialChar::Type::Request, application->GetName())); } } /* namespace gui */ diff --git a/module-apps/windows/AppWindow.hpp b/module-apps/windows/AppWindow.hpp index 3ce71ebd3..ffe4932f6 100644 --- a/module-apps/windows/AppWindow.hpp +++ b/module-apps/windows/AppWindow.hpp @@ -15,71 +15,77 @@ #include "Service/Service.hpp" #include "Service/Message.hpp" -namespace app { - class Application; +namespace app +{ + class Application; }; - -namespace gui { +namespace gui +{ namespace name { namespace window { const inline std::string main_window = "MainWindow"; - const inline std::string no_window = ""; + const inline std::string no_window = ""; } // namespace window } // namespace name -/* - * @brief This is wrapper for gui window used within applications. - */ -class AppWindow: public Window { -protected: + /* + * @brief This is wrapper for gui window used within applications. + */ + class AppWindow : public Window + { + protected: + /// actual built window title + gui::Label *title = nullptr; + /** + * Information bar for the buttons on the bottom of the page. + */ + gui::BottomBar *bottomBar = nullptr; + /** + * Information bar for signal, battery and lock icon on the top of the screen. + */ + gui::TopBar *topBar = nullptr; + /** + * Pointer to the application object that owns the window. + */ + app::Application *application = nullptr; - /// actual built window title - gui::Label* title = nullptr; - /** - * Information bar for the buttons on the bottom of the page. - */ - gui::BottomBar* bottomBar = nullptr; - /** - * Information bar for signal, battery and lock icon on the top of the screen. - */ - gui::TopBar* topBar = nullptr; - /** - * Pointer to the application object that owns the window. - */ - app::Application* application = nullptr; + public: + AppWindow(app::Application *app, std::string name, uint32_t id = GUIWindowID++); + AppWindow(AppWindow *win); + virtual ~AppWindow(); -public: + app::Application *getApplication() + { + return application; + }; + void setApplication(app::Application *app) + { + application = app; + }; + virtual bool onDatabaseMessage(sys::Message *msg); - AppWindow( app::Application* app, std::string name, uint32_t id=GUIWindowID++ ); - AppWindow( AppWindow* win ); - virtual ~AppWindow(); + bool batteryCharging(bool charging); + bool setSIM(); + // updates battery level in the window + bool updateBatteryLevel(uint32_t percentage); + // updates battery level in the window + bool updateSignalStrength(); + virtual bool updateTime(const UTF8 &timeStr); + virtual bool updateTime(const uint32_t ×tamp, bool mode24H); + void setTitle(const UTF8 &text); - app::Application* getApplication() { return application; }; - void setApplication( app::Application* app ) { application = app; }; - virtual bool onDatabaseMessage( sys::Message* msg ); - - bool batteryCharging(bool charging); - bool setSIM(); - //updates battery level in the window - bool updateBatteryLevel( uint32_t percentage ); - //updates battery level in the window - bool updateSignalStrength(); - virtual bool updateTime( const UTF8& timeStr ); - virtual bool updateTime( const uint32_t& timestamp, bool mode24H ); - void setTitle(const UTF8 &text); - - void rebuild() override; - void buildInterface() override; - void destroyInterface() override; - bool onInput( const InputEvent& inputEvent ) override; - std::list buildDrawList() override; - void textModeShowCB(const UTF8 &text); - bool textSelectSpecialCB(); - bool returnToPreviousView(); -}; + void rebuild() override; + void buildInterface() override; + void destroyInterface() override; + bool onInput(const InputEvent &inputEvent) override; + std::list buildDrawList() override; + void textModeShowCB(const UTF8 &text); + bool textSelectSpecialCB(); + bool returnToPreviousView(); + }; } /* namespace gui */ diff --git a/module-apps/windows/Dialog.cpp b/module-apps/windows/Dialog.cpp index fc2feb5a5..367cdec0d 100644 --- a/module-apps/windows/Dialog.cpp +++ b/module-apps/windows/Dialog.cpp @@ -4,7 +4,8 @@ using namespace gui; -Dialog::Dialog(app::Application *app, const std::string &name, const Dialog::Meta &meta) : gui::AppWindow(app, name), meta(meta) +Dialog::Dialog(app::Application *app, const std::string &name, const Dialog::Meta &meta) + : gui::AppWindow(app, name), meta(meta) { AppWindow::buildInterface(); // TODO fix elements positioning with styles ready, right now copied from Phonebook as it is @@ -59,8 +60,7 @@ bool Dialog::onInput(const InputEvent &inputEvent) } void Dialog::buildInterface() -{ -} +{} void Dialog::update(const Meta &meta) { diff --git a/module-apps/windows/Dialog.hpp b/module-apps/windows/Dialog.hpp index 94f4120d9..b0af46431 100644 --- a/module-apps/windows/Dialog.hpp +++ b/module-apps/windows/Dialog.hpp @@ -10,7 +10,7 @@ namespace gui { Label *yes = nullptr, *no = nullptr; - Text *text = nullptr; + Text *text = nullptr; Image *icon = nullptr; public: diff --git a/module-apps/windows/OptionWindow.cpp b/module-apps/windows/OptionWindow.cpp index 001b36121..4f4db287b 100644 --- a/module-apps/windows/OptionWindow.cpp +++ b/module-apps/windows/OptionWindow.cpp @@ -16,17 +16,16 @@ namespace gui } void OptionWindow::rebuild() - { - } + {} Item *newOptionLabel(const UTF8 &text, std::function activatedCallback, Arrow arrow) { // TODO fix elements positioning with styles ready, right now moved from Settings main window as it is - gui::Label *label = new gui::Label(nullptr, 20, 0, style::window_width - 2 * 20, style::window::label::big_h, text); + gui::Label *label = + new gui::Label(nullptr, 20, 0, style::window_width - 2 * 20, style::window::label::big_h, text); style::window::decorateOption(label); label->activatedCallback = activatedCallback; - if (arrow == Arrow::Enabled) - { + if (arrow == Arrow::Enabled) { new gui::Image(label, 425 - 17, 24, 0, 0, "right_label_arrow"); } return label; @@ -44,8 +43,7 @@ namespace gui void OptionWindow::addOptions(std::list