2 * Copyright (c) 2023 Samsung Electronics Co., Ltd.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #include "app-core-ui-cpp/app_core_ui_thread_base.hh"
27 #include <shared-queue.hpp>
29 #include "common/glib_private.hh"
30 #include "common/log_private.hh"
35 AppCoreUiThreadBase* context = nullptr;
39 class AppCoreUiThreadBase::Impl {
41 Impl(AppCoreUiThreadBase* parent) : parent_(parent) {
42 context_ = g_main_context_new();
43 std::string context_str = std::to_string(
44 reinterpret_cast<unsigned long int>(context_));
45 setenv("TIZEN_GLIB_CONTEXT", context_str.c_str(), 1);
49 if (thread_.joinable())
52 if (context_ != nullptr) {
53 setenv("TIZEN_GLIB_CONTEXT", "0", 1);
54 g_main_context_unref(context_);
58 void Run(int argc, char** argv) {
60 _E("Already running");
65 thread_ = std::thread([&] {
66 pthread_setname_np(pthread_self(), "UIThread+");
67 parent_->OnLoopInit(argc, argv);
70 parent_->OnLoopFinish();
78 parent_->OnLoopExit();
81 void Post(Runner runner) {
82 queue_.Push(std::move(runner));
84 guint source = GLib::IdleAdd(context_,
85 [](gpointer user_data) {
86 auto* impl = static_cast<AppCoreUiThreadBase::Impl*>(user_data);
87 auto action = std::move(impl->queue_.WaitAndPop());
89 return G_SOURCE_REMOVE;
92 _E("Failed to add idle source");
96 friend class AppCoreUiThreadBase;
97 AppCoreUiThreadBase* parent_;
101 GMainContext* context_ = nullptr;
102 tizen_base::SharedQueue<Runner> queue_;
103 bool running_ = false;
106 AppCoreUiThreadBase::AppCoreUiThreadBase() : impl_(new Impl(this)) {
107 if (context != nullptr)
108 _E("Already exists");
113 AppCoreUiThreadBase::~AppCoreUiThreadBase() {
117 void AppCoreUiThreadBase::Run(int argc, char** argv) {
118 impl_->Run(argc, argv);
121 void AppCoreUiThreadBase::Exit() {
125 void AppCoreUiThreadBase::Post(Runner runner) {
126 impl_->Post(std::move(runner));
129 void AppCoreUiThreadBase::OnLoopInit(int argc, char** argv) {
134 void AppCoreUiThreadBase::OnLoopRun() {
136 ecore_main_loop_begin();
139 void AppCoreUiThreadBase::OnLoopExit() {
141 ecore_main_loop_thread_safe_call_sync([](void* data) -> void* {
142 ecore_main_loop_quit();
147 void AppCoreUiThreadBase::OnLoopFinish() {
152 AppCoreUiThreadBase* AppCoreUiThreadBase::GetContext() {
156 } // namespace tizen_cpp