2 * Copyright (c) 2021 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.
18 //------------------------------------------------------------------------------
21 //------------------------------------------------------------------------------
23 #include <dali-toolkit/dali-toolkit.h>
24 #include <dali-toolkit/devel-api/builder/builder.h>
25 #include <dali-toolkit/devel-api/builder/json-parser.h>
26 #include <dali-toolkit/devel-api/builder/tree-node.h>
27 #include <dali-toolkit/devel-api/controls/navigation-view/navigation-view.h>
28 #include <dali-toolkit/devel-api/controls/popup/popup.h>
29 #include <dali/dali.h>
44 #include <dali/devel-api/adaptor-framework/file-loader.h>
45 #include <dali/integration-api/debug.h>
46 #include "shared/view.h"
48 #define TOKEN_STRING(x) #x
51 using namespace Dali::Toolkit;
55 const char* BACKGROUND_IMAGE("");
56 const char* TOOLBAR_IMAGE(DEMO_IMAGE_DIR "top-bar.png");
57 const char* EDIT_IMAGE(DEMO_IMAGE_DIR "icon-change.png");
58 const char* EDIT_IMAGE_SELECTED(DEMO_IMAGE_DIR "icon-change-selected.png");
60 std::string USER_DIRECTORY;
62 std::string JSON_BROKEN(
70 'parentOrigin': 'CENTER', \
71 'text':'COULD NOT LOAD JSON FILE' \
77 std::string ReplaceQuotes(const std::string& single_quoted)
79 std::string s(single_quoted);
81 // wrong as no embedded quote but had regex link problems
82 std::replace(s.begin(), s.end(), '\'', '"');
87 std::string GetFileContents(const std::string& fn)
89 std::streampos bufferSize = 0;
90 Dali::Vector<char> fileBuffer;
91 if(!Dali::FileLoader::ReadFile(fn, bufferSize, fileBuffer, FileLoader::FileType::BINARY))
96 return std::string(&fileBuffer[0], bufferSize);
99 typedef std::vector<std::string> FileList;
101 void DirectoryFileList(const std::string& directory, FileList& files)
105 d = opendir(directory.c_str());
108 while((dir = readdir(d)) != NULL)
110 if(dir->d_type == DT_REG)
112 files.push_back(directory + std::string(dir->d_name));
120 void DirectoryFilesByType(const std::string& dir, const std::string& fileType /* ie "json" */, FileList& files)
122 typedef FileList Collection;
123 typedef FileList::iterator Iter;
126 DirectoryFileList(dir, allFiles);
128 for(Iter iter = allFiles.begin(); iter != allFiles.end(); ++iter)
130 size_t pos = (*iter).rfind('.');
131 if(pos != std::string::npos)
133 if((*iter).substr(pos + 1) == fileType)
135 files.push_back((*iter));
141 const std::string ShortName(const std::string& name)
143 size_t pos = name.rfind('/');
145 if(pos != std::string::npos)
148 return name.substr(pos);
156 //------------------------------------------------------------------------------
160 //------------------------------------------------------------------------------
166 explicit FileWatcher(const std::string& fn)
171 void SetFilename(const std::string& fn);
172 std::string GetFilename() const;
174 bool FileHasChanged(void);
175 std::string GetFileContents(void) const
177 return ::GetFileContents(mstringPath);
182 // FileWatcher(const FileWatcher&);
183 // FileWatcher &operator=(const FileWatcher &);
185 std::time_t mLastTime;
186 std::string mstringPath;
189 FileWatcher::FileWatcher(void)
194 bool FileWatcher::FileHasChanged(void)
198 if(0 != stat(mstringPath.c_str(), &buf))
204 const bool result = buf.st_mtime > mLastTime;
205 mLastTime = buf.st_mtime;
212 FileWatcher::~FileWatcher()
216 void FileWatcher::SetFilename(const std::string& fn)
219 FileHasChanged(); // update last time
222 std::string FileWatcher::GetFilename(void) const
229 //------------------------------------------------------------------------------
233 //------------------------------------------------------------------------------
234 class ExampleApp : public ConnectionTracker, public Toolkit::ItemFactory
237 ExampleApp(Application& app)
240 app.InitSignal().Connect(this, &ExampleApp::Create);
248 void SetTitle(const std::string& title)
252 mTitleActor = DemoHelper::CreateToolBarLabel("");
253 // Add title to the tool bar.
254 mToolBar.AddControl(mTitleActor, DemoHelper::DEFAULT_VIEW_STYLE.mToolBarTitlePercentage, Alignment::HORIZONTAL_CENTER);
257 mTitleActor.SetProperty(TextLabel::Property::TEXT, title);
260 bool OnBackButtonPressed(Toolkit::Button button)
268 Window window = mApp.GetWindow();
270 mTapDetector = TapGestureDetector::New();
271 mTapDetector.DetectedSignal().Connect(this, &ExampleApp::OnTap);
275 mItemView = ItemView::New(*this);
277 mItemView.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
278 mItemView.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER);
279 mLayout = DefaultItemLayout::New(DefaultItemLayout::LIST);
281 mLayout->SetItemSize(Vector3(window.GetSize().GetWidth(), 50, 1));
283 mItemView.AddLayout(*mLayout);
285 mItemView.SetProperty(Actor::Property::KEYBOARD_FOCUSABLE, true);
290 if(USER_DIRECTORY.size())
292 DirectoryFilesByType(USER_DIRECTORY, "json", files);
296 DirectoryFilesByType(DEMO_SCRIPT_DIR, "json", files);
299 std::sort(files.begin(), files.end());
301 for(FileList::iterator iter = files.begin(); iter != files.end(); ++iter)
303 JsonParser parser = JsonParser::New();
305 std::string data(GetFileContents(*iter));
309 if(parser.ParseError())
311 std::cout << "Parser Error:" << *iter << std::endl;
312 std::cout << parser.GetErrorLineNumber() << "(" << parser.GetErrorColumn() << "):" << parser.GetErrorDescription() << std::endl;
318 if(const TreeNode* node = parser.GetRoot()->Find("stage"))
320 // only those with a stage section
323 mFiles.push_back(*iter);
327 std::cout << "Ignored file (stage has no nodes?):" << *iter << std::endl;
332 std::cout << "Ignored file (no stage section):" << *iter << std::endl;
337 // Activate the layout
338 Vector3 size(window.GetSize());
339 mItemView.ActivateLayout(0, size, 0.0f /*immediate*/);
342 void OnTap(Actor actor, const TapGesture& tap)
344 ItemId id = mItemView.GetItemId(actor);
346 LoadFromFileList(id);
349 Actor MenuItem(const std::string& text)
351 TextLabel label = TextLabel::New(ShortName(text));
352 label.SetStyleName("BuilderLabel");
353 label.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::WIDTH);
355 // Hook up tap detector
356 mTapDetector.Attach(label);
363 if(mFileWatcher.FileHasChanged())
365 LoadFromFile(mFileWatcher.GetFilename());
371 void ReloadJsonFile(const std::string& filename, Builder& builder, Layer& layer)
373 Window window = mApp.GetWindow();
375 builder = Builder::New();
376 builder.QuitSignal().Connect(this, &ExampleApp::OnQuitOrBack);
378 Property::Map defaultDirs;
379 defaultDirs[TOKEN_STRING(DEMO_IMAGE_DIR)] = DEMO_IMAGE_DIR;
380 defaultDirs[TOKEN_STRING(DEMO_MODEL_DIR)] = DEMO_MODEL_DIR;
381 defaultDirs[TOKEN_STRING(DEMO_SCRIPT_DIR)] = DEMO_SCRIPT_DIR;
383 builder.AddConstants(defaultDirs);
385 // render tasks may have been setup last load so remove them
386 RenderTaskList taskList = window.GetRenderTaskList();
387 if(taskList.GetTaskCount() > 1)
389 typedef std::vector<RenderTask> Collection;
390 typedef Collection::iterator ColIter;
393 for(unsigned int i = 1; i < taskList.GetTaskCount(); ++i)
395 tasks.push_back(taskList.GetTask(i));
398 for(ColIter iter = tasks.begin(); iter != tasks.end(); ++iter)
400 taskList.RemoveTask(*iter);
403 RenderTask defaultTask = taskList.GetTask(0);
404 defaultTask.SetSourceActor(window.GetRootLayer());
405 defaultTask.SetFrameBuffer(FrameBuffer());
408 unsigned int numChildren = layer.GetChildCount();
410 for(unsigned int i = 0; i < numChildren; ++i)
412 layer.Remove(layer.GetChildAt(0));
415 std::string data(GetFileContents(filename));
419 builder.LoadFromString(data);
423 builder.LoadFromString(ReplaceQuotes(JSON_BROKEN));
426 builder.AddActors(layer);
429 void LoadFromFileList(size_t index)
431 if(index < mFiles.size())
433 const std::string& name = mFiles[index];
434 mFileWatcher.SetFilename(name);
439 void LoadFromFile(const std::string& name)
441 ReloadJsonFile(name, mBuilder, mBuilderLayer);
443 mBuilderLayer.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::BOTTOM_CENTER);
444 mBuilderLayer.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::BOTTOM_CENTER);
445 Dali::Vector3 size = mApp.GetWindow().GetRootLayer().GetCurrentProperty<Vector3>(Actor::Property::SIZE);
446 size.y -= DemoHelper::DEFAULT_VIEW_STYLE.mToolBarHeight;
447 mBuilderLayer.SetProperty(Actor::Property::SIZE, size);
449 mNavigationView.Push(mBuilderLayer);
452 void Create(Application& app)
454 Window window = app.GetWindow();
456 window.KeyEventSignal().Connect(this, &ExampleApp::OnKeyEvent);
458 Layer contents = DemoHelper::CreateView(app,
465 SetTitle("Select Example");
467 mBuilderLayer = Layer::New();
469 // Create an edit mode button. (left of toolbar)
470 Toolkit::PushButton backButton = Toolkit::PushButton::New();
471 backButton.SetProperty(Toolkit::Button::Property::UNSELECTED_BACKGROUND_VISUAL, EDIT_IMAGE);
472 backButton.SetProperty(Toolkit::Button::Property::SELECTED_BACKGROUND_VISUAL, EDIT_IMAGE_SELECTED);
473 backButton.ClickedSignal().Connect(this, &ExampleApp::OnBackButtonPressed);
474 backButton.SetProperty(Actor::Property::LEAVE_REQUIRED, true);
475 mToolBar.AddControl(backButton, DemoHelper::DEFAULT_VIEW_STYLE.mToolBarButtonPercentage, Toolkit::Alignment::HORIZONTAL_LEFT, DemoHelper::DEFAULT_MODE_SWITCH_PADDING);
477 mNavigationView = Toolkit::NavigationView::New();
478 mNavigationView.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS);
479 mNavigationView.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT);
481 window.Add(mNavigationView);
483 // Set up the background gradient.
484 Property::Array stopOffsets;
485 stopOffsets.PushBack(0.0f);
486 stopOffsets.PushBack(1.0f);
487 Property::Array stopColors;
488 stopColors.PushBack(Color::WHITE);
489 stopColors.PushBack(Vector4(0.45f, 0.70f, 0.80f, 1.0f)); // Medium bright, pastel blue
490 const float percentageWindowHeight = window.GetSize().GetHeight() * 0.6f;
492 mNavigationView.SetProperty(Toolkit::Control::Property::BACKGROUND, Dali::Property::Map().Add(Toolkit::Visual::Property::TYPE, Dali::Toolkit::Visual::GRADIENT).Add(Toolkit::GradientVisual::Property::STOP_OFFSET, stopOffsets).Add(Toolkit::GradientVisual::Property::STOP_COLOR, stopColors).Add(Toolkit::GradientVisual::Property::START_POSITION, Vector2(0.0f, -percentageWindowHeight)).Add(Toolkit::GradientVisual::Property::END_POSITION, Vector2(0.0f, percentageWindowHeight)).Add(Toolkit::GradientVisual::Property::UNITS, Toolkit::GradientVisual::Units::USER_SPACE));
495 mNavigationView.Push(mItemView);
497 mTimer = Timer::New(500); // ms
498 mTimer.TickSignal().Connect(this, &ExampleApp::OnTimer);
503 virtual unsigned int GetNumberOfItems()
505 return mFiles.size();
508 virtual Actor NewItem(unsigned int itemId)
510 DALI_ASSERT_DEBUG(itemId < mFiles.size());
511 return MenuItem(ShortName(mFiles[itemId]));
515 * Main key event handler
517 void OnKeyEvent(const KeyEvent& event)
519 if(event.GetState() == KeyEvent::DOWN)
521 if(IsKey(event, Dali::DALI_KEY_ESCAPE) || IsKey(event, Dali::DALI_KEY_BACK))
529 * Event handler when Builder wants to quit (we only want to close the shown json unless we're at the top-level)
533 if(mItemView.GetProperty<bool>(Actor::Property::CONNECTED_TO_SCENE))
539 mNavigationView.Pop();
546 ItemLayoutPtr mLayout;
548 Toolkit::NavigationView mNavigationView;
550 Toolkit::Control mView;
552 Toolkit::ToolBar mToolBar;
553 TextLabel mTitleActor;
557 TapGestureDetector mTapDetector;
564 FileWatcher mFileWatcher;
568 //------------------------------------------------------------------------------
572 //------------------------------------------------------------------------------
573 int DALI_EXPORT_API main(int argc, char** argv)
577 if(strcmp(argv[1], "-f") == 0)
579 USER_DIRECTORY = argv[2];
583 Application app = Application::New(&argc, &argv, DEMO_THEME_PATH);
585 ExampleApp dali_app(app);