2 * Copyright (c) 2014 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 //------------------------------------------------------------------------------
24 #include <dali-toolkit/dali-toolkit.h>
25 #include <dali-toolkit/public-api/builder/builder.h>
26 #include <dali-toolkit/public-api/builder/tree-node.h>
27 #include <dali-toolkit/public-api/builder/json-parser.h>
33 #include <boost/scoped_ptr.hpp>
37 //#include <boost/regex.hpp>
41 #include <dali/integration-api/debug.h>
42 #include "../shared/view.h"
44 #define TOKEN_STRING(x) #x
47 using namespace Dali::Toolkit;
52 const char* BACKGROUND_IMAGE( "" );
53 const char* TOOLBAR_IMAGE( DALI_IMAGE_DIR "top-bar.png" );
54 const char* EDIT_IMAGE( DALI_IMAGE_DIR "icon-change.png" );
56 std::string USER_DIRECTORY;
58 std::string JSON_BROKEN(" \
65 'parent-origin': 'CENTER', \
66 'text':'COULD NOT LOAD JSON FILE' \
72 std::string ReplaceQuotes(const std::string &single_quoted)
74 std::string s(single_quoted);
76 // wrong as no embedded quote but had regex link problems
77 std::replace(s.begin(), s.end(), '\'', '"');
82 std::string GetFileContents(const std::string &fn)
84 std::ifstream t(fn.c_str());
85 return std::string((std::istreambuf_iterator<char>(t)),
86 std::istreambuf_iterator<char>());
89 typedef std::vector<std::string> FileList;
91 void DirectoryFileList(const std::string& directory, FileList& files)
95 d = opendir(directory.c_str());
98 while ((dir = readdir(d)) != NULL)
100 if (dir->d_type == DT_REG)
102 files.push_back( directory + std::string(dir->d_name) );
110 void DirectoryFilesByType(const std::string& dir, const std::string& fileType /* ie "json" */, FileList& files)
112 typedef FileList Collection;
113 typedef FileList::iterator Iter;
116 DirectoryFileList(dir, allFiles);
118 for(Iter iter = allFiles.begin(); iter != allFiles.end(); ++iter)
120 size_t pos = (*iter).rfind( '.' );
121 if( pos != std::string::npos )
123 if( (*iter).substr( pos+1 ) == fileType )
125 files.push_back( (*iter) );
131 const std::string ShortName( const std::string& name )
133 size_t pos = name.rfind( '/' );
135 if( pos != std::string::npos )
137 return name.substr( pos );
145 static Vector3 SetItemSize(unsigned int numberOfColumns, float layoutWidth, float sideMargin, float columnSpacing)
147 return Vector3(layoutWidth, 50, 1);
150 //------------------------------------------------------------------------------
154 //------------------------------------------------------------------------------
160 explicit FileWatcher(const std::string &fn) { SetFilename(fn) ; };
162 void SetFilename(const std::string &fn);
163 std::string GetFilename() const;
165 bool FileHasChanged(void);
166 std::string GetFileContents(void) const { return ::GetFileContents(mstringPath) ; };
170 // FileWatcher(const FileWatcher&);
171 // FileWatcher &operator=(const FileWatcher &);
173 std::time_t mLastTime;
174 std::string mstringPath;
178 FileWatcher::FileWatcher(void) : mLastTime(0)
182 bool FileWatcher::FileHasChanged(void)
186 if(0 != stat(mstringPath.c_str(), &buf))
192 if(buf.st_mtime > mLastTime)
194 mLastTime = buf.st_mtime;
199 mLastTime = buf.st_mtime;
207 FileWatcher::~FileWatcher()
211 void FileWatcher::SetFilename(const std::string &fn)
214 FileHasChanged(); // update last time
217 std::string FileWatcher::GetFilename(void) const
226 //------------------------------------------------------------------------------
230 //------------------------------------------------------------------------------
231 class ExampleApp : public ConnectionTracker, public Toolkit::ItemFactory
234 ExampleApp(Application &app) : mApp(app)
236 app.InitSignal().Connect(this, &ExampleApp::Create);
243 void SetTitle(const std::string& title)
247 mTitleActor = TextView::New();
248 // Add title to the tool bar.
249 mToolBar.AddControl( mTitleActor, DemoHelper::DEFAULT_VIEW_STYLE.mToolBarTitlePercentage, Alignment::HorizontalCenter );
252 Font font = Font::New();
253 mTitleActor.SetText( title );
254 mTitleActor.SetSize( font.MeasureText( title ) );
255 mTitleActor.SetStyleToCurrentText(DemoHelper::GetDefaultTextStyle());
258 bool OnToolSelectLayout( Toolkit::Button button )
260 bool on = mItemView.IsVisible();
274 void LeaveSelection()
279 void EnterSelection()
281 Stage stage = Stage::GetCurrent();
285 stage.Remove( mItemView );
290 mItemView = ItemView::New(*this);
291 stage.Add( mItemView );
292 mItemView.SetParentOrigin(ParentOrigin::CENTER);
293 mItemView.SetAnchorPoint(AnchorPoint::CENTER);
294 mGridLayout = GridLayout::New();
295 mGridLayout->SetNumberOfColumns(1);
297 mGridLayout->SetItemSizeFunction(SetItemSize);
299 mGridLayout->SetTopMargin(DemoHelper::DEFAULT_VIEW_STYLE.mToolBarHeight);
301 mItemView.AddLayout(*mGridLayout);
303 Vector3 size(stage.GetSize());
304 mItemView.ActivateLayout(0, size, 0.0f/*immediate*/);
305 mItemView.SetKeyboardFocusable( true );
310 if( USER_DIRECTORY.size() )
312 DirectoryFilesByType( USER_DIRECTORY, "json", files );
316 DirectoryFilesByType( DALI_SCRIPT_DIR, "json", files );
319 std::sort(files.begin(), files.end());
322 for(FileList::iterator iter = files.begin(); iter != files.end(); ++iter)
324 JsonParser parser = JsonParser::New();
326 std::string data( GetFileContents( *iter ) );
328 parser.Parse( data );
330 if( parser.ParseError() )
332 std::cout << "Parser Error:" << *iter << std::endl;
333 std::cout << parser.GetErrorLineNumber() << "(" << parser.GetErrorColumn() << "):" << parser.GetErrorDescription() << std::endl;
337 if( parser.GetRoot() )
339 if( const TreeNode* node = parser.GetRoot()->Find("stage") )
341 // only those with a stage section
344 mFiles.push_back( *iter );
346 mItemView.InsertItem( Item(itemId,
347 MenuItem( ShortName( *iter ) ) ),
354 std::cout << "Ignored file (stage has no nodes?):" << *iter << std::endl;
359 std::cout << "Ignored file (no stage section):" << *iter << std::endl;
364 mTapDetector = TapGestureDetector::New();
366 for( unsigned int i = 0u; i < mItemView.GetChildCount(); ++i )
368 mTapDetector.Attach( mItemView.GetChildAt(i) );
371 mTapDetector.DetectedSignal().Connect( this, &ExampleApp::OnTap );
373 // Display item view on the stage
374 stage.Add( mItemView );
376 mItemView.SetVisible( true );
377 mBuilderLayer.SetVisible( false );
381 // Itemview renderes the previous items unless its scrolled. Not sure why at the moment so we force a scroll
382 mItemView.ScrollToItem(0, 0);
388 mTapDetector.Reset();
390 mItemView.SetVisible( false );
391 mBuilderLayer.SetVisible( true );
396 void OnTap( Actor actor, TapGesture tap )
398 ItemId id = mItemView.GetItemId( actor );
400 LoadFromFileList( id );
403 Actor MenuItem(const std::string& text)
405 TextView t = TextView::New();
406 t.SetMarkupProcessingEnabled(true);
408 int size = static_cast<int>(DemoHelper::ScalePointSize(6));
410 std::ostringstream fontString;
411 fontString << "<font size="<< size <<">"<< ShortName( text ) << "</font>";
413 t.SetText( fontString.str() );
415 t.SetTextAlignment( Alignment::HorizontalLeft );
421 if( mFileWatcher.FileHasChanged() )
423 LoadFromFile( mFileWatcher.GetFilename() );
429 void ReloadJsonFile(const std::string& filename, Builder& builder, Layer& layer)
431 Stage stage = Stage::GetCurrent();
433 builder = Builder::New();
434 builder.QuitSignal().Connect( this, &ExampleApp::OnBuilderQuit );
436 Property::Map defaultDirs;
437 defaultDirs[ TOKEN_STRING(DALI_IMAGE_DIR) ] = DALI_IMAGE_DIR;
438 defaultDirs[ TOKEN_STRING(DALI_MODEL_DIR) ] = DALI_MODEL_DIR;
439 defaultDirs[ TOKEN_STRING(DALI_SCRIPT_DIR) ] = DALI_SCRIPT_DIR;
441 builder.AddConstants( defaultDirs );
443 // render tasks may have been setup last load so remove them
444 RenderTaskList taskList = stage.GetRenderTaskList();
445 if( taskList.GetTaskCount() > 1 )
447 typedef std::vector<RenderTask> Collection;
448 typedef Collection::iterator ColIter;
451 for(unsigned int i = 1; i < taskList.GetTaskCount(); ++i)
453 tasks.push_back( taskList.GetTask(i) );
456 for(ColIter iter = tasks.begin(); iter != tasks.end(); ++iter)
458 taskList.RemoveTask(*iter);
461 RenderTask defaultTask = taskList.GetTask(0);
462 defaultTask.SetSourceActor( stage.GetRootLayer() );
463 defaultTask.SetTargetFrameBuffer( FrameBufferImage() );
466 unsigned int numChildren = layer.GetChildCount();
468 for(unsigned int i=0; i<numChildren; ++i)
470 layer.Remove( layer.GetChildAt(0) );
473 std::string data(GetFileContents(filename));
477 builder.LoadFromString(data);
481 builder.LoadFromString(ReplaceQuotes(JSON_BROKEN));
484 builder.AddActors( layer );
489 void LoadFromFileList( size_t index )
491 if( index < mFiles.size())
493 const std::string& name = mFiles[index];
494 mFileWatcher.SetFilename( name );
495 LoadFromFile( name );
499 void LoadFromFile( const std::string& name )
501 ReloadJsonFile( name, mBuilder, mBuilderLayer );
503 // do this here as GetCurrentSize()
504 mBuilderLayer.SetParentOrigin(ParentOrigin::CENTER);
505 mBuilderLayer.SetAnchorPoint(AnchorPoint::CENTER);
506 Dali::Vector3 size = Stage::GetCurrent().GetRootLayer().GetCurrentSize();
507 size.y -= DemoHelper::DEFAULT_VIEW_STYLE.mToolBarHeight;
508 mBuilderLayer.SetSize( size );
510 mBuilderLayer.LowerToBottom();
511 Stage::GetCurrent().GetRootLayer().RaiseToTop();
516 void Create(Application& app)
518 Stage stage = Stage::GetCurrent();
520 Stage::GetCurrent().KeyEventSignal().Connect(this, &ExampleApp::OnKeyEvent);
522 Layer contents = DemoHelper::CreateView( app,
531 mBuilderLayer = Layer::New();
532 stage.GetRootLayer().Add(mBuilderLayer);
535 // Create an edit mode button. (left of toolbar)
536 Toolkit::PushButton editButton = Toolkit::PushButton::New();
537 editButton.SetBackgroundImage( Image::New( EDIT_IMAGE ) );
538 editButton.ClickedSignal().Connect( this, &ExampleApp::OnToolSelectLayout);
539 editButton.SetLeaveRequired( true );
540 mToolBar.AddControl( editButton, DemoHelper::DEFAULT_VIEW_STYLE.mToolBarButtonPercentage, Toolkit::Alignment::HorizontalLeft, DemoHelper::DEFAULT_MODE_SWITCH_PADDING );
544 mTimer = Timer::New( 500 ); // ms
545 mTimer.TickSignal().Connect( this, &ExampleApp::OnTimer);
550 virtual unsigned int GetNumberOfItems()
552 return mFiles.size();
555 virtual Actor NewItem(unsigned int itemId)
557 DALI_ASSERT_DEBUG( itemId < mFiles.size() );
558 return MenuItem( ShortName( mFiles[itemId] ) );
562 * Main key event handler
564 void OnKeyEvent(const KeyEvent& event)
566 if(event.state == KeyEvent::Down)
568 if( IsKey( event, Dali::DALI_KEY_ESCAPE) || IsKey( event, Dali::DALI_KEY_BACK) )
570 if ( mItemView.IsVisible() )
583 * Event handler when Builder wants to quit (we only want to close the shown json unless we're at the top-level)
587 if ( mItemView.IsVisible() )
600 GridLayoutPtr mGridLayout;
604 unsigned int mOrientation;
606 Toolkit::ToolBar mToolBar;
607 TextView mTitleActor; ///< The Toolbar's Title.
611 Toolkit::Popup mMenu;
613 TapGestureDetector mTapDetector;
620 FileWatcher mFileWatcher;
626 //------------------------------------------------------------------------------
630 //------------------------------------------------------------------------------
631 int main(int argc, char **argv)
635 if(strcmp(argv[1], "-f") == 0)
637 USER_DIRECTORY = argv[2];
641 Application app = Application::New(&argc, &argv);
643 ExampleApp dali_app(app);