2 * Copyright (c) 2015 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.
25 #include <dali/integration-api/debug.h>
28 #include <object/property-value-wrapper.h>
29 #include <actors/actor-wrapper.h>
30 #include <object/handle-wrapper.h>
31 #include <image/image-wrapper.h>
32 #include <render-tasks/render-task-wrapper.h>
33 #include <object/property-value-wrapper.h>
37 * Similar to DALI_LOG_ERROR except the PRETTY_FUNCTION
38 * is removed because it makes no sense for scripting errors.
40 #define DALI_LOG_SCRIPT_ERROR(format, args...) Dali::Integration::Log::LogMessage(Dali::Integration::Log::DebugError, format, ## args)
51 void Log(const v8::FunctionCallbackInfo< v8::Value >& args)
53 v8::HandleScope handleScope( args.GetIsolate());
56 for (int i = 0; i < args.Length(); i++)
66 v8::String::Utf8Value utf8_value( args[i] );
67 std::cout << *utf8_value << "\n";
71 void LogError(const v8::FunctionCallbackInfo< v8::Value >& args)
73 v8::HandleScope handleScope( args.GetIsolate());
76 for (int i = 0; i < args.Length(); i++)
86 v8::String::Utf8Value utf8_value( args[i] );
87 output += *utf8_value;
90 DALI_LOG_ERROR_NOFN( "JavaScript: %s",output.c_str() );
93 void GetFileContents(const std::string &fileName, std::string& contents)
95 std::ifstream t(fileName.c_str());
96 contents = std::string((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>());
99 void GetFileDirectory( const std::string& fileName, std::string& directory )
103 // get the position of the last slash
104 size_t pos = fileName.find_last_of("\\/");
106 // if it doesn't exist, return nothing
107 if( (std::string::npos == pos ) )
113 // check an edge case where the string ends in a forward slash "mydir/"
114 if( (pos+1) < fileName.length() )
116 directory = fileName.substr(0, pos+1);
122 void GetFileName( const std::string& fullPathName, std::string& fileName )
124 // look for last slash
125 size_t pos = fullPathName.find_last_of("\\/");
127 if( std::string::npos == pos )
129 fileName = fullPathName;
133 fileName = fullPathName.substr(pos,fileName.length());
137 void GetModuleName( const std::string& fileName, std::string& moduleName )
139 std::string fileNameNoPath;
140 GetFileName( fileName , fileNameNoPath );
141 size_t pos = fileNameNoPath.find_last_of(".");
142 if( std::string::npos == pos )
144 moduleName = fileNameNoPath;
148 moduleName = fileName.substr(0, pos );
152 void ReportException( v8::Isolate* isolate, v8::TryCatch* tryCatch)
154 v8::HandleScope handleScope( isolate );
156 v8::String::Utf8Value exception(tryCatch->Exception());
157 v8::Handle<v8::Message> message = tryCatch->Message();
159 if (message.IsEmpty())
161 // V8 didn't provide any extra information about this error; just
162 // print the exception.
163 DALI_LOG_SCRIPT_ERROR("%s\n", *exception);
168 // Print (filename):(line number): (message).
169 v8::String::Utf8Value filename(message->GetScriptResourceName());
171 DALI_LOG_SCRIPT_ERROR("\n\n====== Error found in JavaScript: ========= \n");
174 int linenum = message->GetLineNumber();
175 DALI_LOG_SCRIPT_ERROR("File: %s\n", *filename, linenum, *exception);
177 DALI_LOG_SCRIPT_ERROR("Error: :%s\n", *exception );
178 DALI_LOG_SCRIPT_ERROR("Line: :%i\n", linenum );
180 // Print line of source code.
181 v8::String::Utf8Value sourceline(message->GetSourceLine());
183 DALI_LOG_SCRIPT_ERROR("Source: %s\n", *sourceline);
185 // Print wavy underline (GetUnderline is deprecated).
187 std::stringstream msg;
189 int start = message->GetStartColumn();
190 for (int i = 0; i < start; i++)
194 int end = message->GetEndColumn();
195 for (int i = start; i < end; i++)
200 DALI_LOG_SCRIPT_ERROR(" %s\n", msg.str().c_str());
202 v8::String::Utf8Value stack_trace(tryCatch->StackTrace());
203 if (stack_trace.length() > 0)
205 DALI_LOG_SCRIPT_ERROR("%s\n", *stack_trace);
207 DALI_LOG_SCRIPT_ERROR("\n=========================================== \n");
212 std::string GetJavaScriptFunctionName( const char* functionName )
214 // @todo if we are 100% decided on lower case, go through
215 // every api and manually change the function names to lower case first character
216 std::string name( functionName );
217 name[0]=tolower( functionName[0] );
221 void Version(const v8::FunctionCallbackInfo< v8::Value >& args)
223 v8::HandleScope handleScope( args.GetIsolate());
225 v8::Handle<v8::String> ver = v8::String::NewFromUtf8(args.GetIsolate(), v8::V8::GetVersion());
227 args.GetReturnValue().Set(ver);
231 std::string v8StringToStdString( const v8::Handle<v8::Value>& value )
233 v8::String::Utf8Value utf8(value);
234 return std::string(*utf8);
238 std::string PropertyNameToJavaScriptName(const std::string& hyphenatedName)
242 ret.reserve(hyphenatedName.size());
244 bool capitlizeNext = false ;
245 for(unsigned int i = 0; i < hyphenatedName.size(); ++i)
247 char c = hyphenatedName[i];
250 capitlizeNext = true;
256 ret.push_back(std::toupper(c));
257 capitlizeNext = false;
271 std::string JavaScriptNameToPropertyName(const std::string& camelCase)
276 for(unsigned int i = 0; i < camelCase.size(); ++i)
278 if(std::isupper(camelCase[i]))
286 ret.reserve(camelCase.size() + countUpper);
288 for(unsigned int i = 0; i < camelCase.size(); ++i)
290 char c = camelCase[i];
296 ret.push_back(std::tolower(c));
307 void ScriptError( const char* function, v8::Isolate* isolate, std::string errorString )
309 v8::EscapableHandleScope scope( isolate);
310 std::string errorMsg = std::string(function) + std::string("(), ") + errorString;
312 // log out to DALI_LOG_ERROR first, so we know something has gone wrong
313 DALI_LOG_ERROR("%s \n", errorMsg.c_str() );
315 // throw a V8 exception, DALi will keep running but we will get a print out
316 // of where the error occured in the JavaScript source
317 isolate->ThrowException( v8::String::NewFromUtf8( isolate, errorMsg.c_str()) );
320 bool IsBooleanPrimitiveOrObject( const v8::Local<v8::Value>& value )
322 return ( value->IsBoolean() || value->IsBooleanObject());
325 bool GetBooleanValue( v8::Isolate* isolate, const v8::Local<v8::Value>& value )
327 v8::EscapableHandleScope scope( isolate); // may not be required.
329 if( value->IsBoolean() )
331 return value->ToBoolean()->Value();
333 else if (value->IsBooleanObject() )
335 const v8::Local<v8::BooleanObject> object = v8::Local<v8::BooleanObject>::Cast(value);
336 return object->BooleanValue();
338 DALI_SCRIPT_EXCEPTION(isolate, "no bool found");
342 bool IsNumberPrimitiveOrObject( const v8::Local<v8::Value>& value )
344 return ( value->IsNumber() || value->IsNumberObject());
347 float GetNumberValue( v8::Isolate* isolate, const v8::Local<v8::Value>& value )
349 v8::EscapableHandleScope scope( isolate); // may not be required.
351 if( value->IsNumber() )
353 return value->ToNumber()->Value();
355 else if (value->IsNumberObject() )
357 const v8::Local<v8::NumberObject> object = v8::Local<v8::NumberObject>::Cast(value);
358 return object->ValueOf();
361 DALI_SCRIPT_EXCEPTION(isolate, "no number found?");
365 bool IsStringPrimitiveOrObject( const v8::Local<v8::Value>& value )
367 return ( value->IsString() || value->IsStringObject());
370 std::string GetStringValue( v8::Isolate* isolate, const v8::Local<v8::Value>& value )
372 v8::EscapableHandleScope scope( isolate); // may not be required.
374 if( value->IsString() )
376 return V8Utils::v8StringToStdString(value);
378 else if (value->IsStringObject() )
380 const v8::Local<v8::StringObject> object = v8::Local<v8::StringObject>::Cast(value);
381 return V8Utils::v8StringToStdString( object->ValueOf() );
384 DALI_SCRIPT_EXCEPTION(isolate, "no string found?");
389 Property::Value GetPropertyValueFromObject( bool& found, v8::Isolate* isolate, const v8::Local<v8::Value >& value )
391 v8::HandleScope handleScope( isolate);
393 Property::Value daliPropertyValue;// creates a property with Property::INVALID
397 if( value->IsObject() )
399 v8::Local<v8::Object> object = v8::Handle<v8::Object>::Cast( value );
401 if( BaseWrappedObject::IsWrappedTypeAPropertyValue( object ) )
404 PropertyValueWrapper* propertyWrapper = PropertyValueWrapper::Unwrap( isolate, object );
405 return propertyWrapper->GetValue();
407 else if( value->IsArray() )
410 return PropertyValueWrapper::VectorOrMatrixFromV8Array( isolate, object);//todo check for V8 array / map?
413 else if( value->IsBoolean() )
416 v8::Local<v8::Boolean> v = value->ToBoolean();
417 return Dali::Property::Value(v->Value());
419 else if( value->IsNumber() )
422 v8::Local<v8::Number> v = value->ToNumber();
423 return Dali::Property::Value(static_cast<float>(v->Value()));
425 else if( value->IsInt32() || value->IsUint32() )
428 v8::Local<v8::Int32> v = value->ToInt32();
429 return Dali::Property::Value(static_cast<int>(v->Value()));
431 return daliPropertyValue;
435 Property::Map GetPropertyMapFromObject( v8::Isolate* isolate, const v8::Local<v8::Object>& object)
437 v8::Local<v8::Array> properties = object->GetPropertyNames();
438 Property::Map propertyMap; // empty map
440 for( unsigned int i = 0; i < properties->Length(); ++i)
443 v8::Local<v8::Value> key = properties->Get( i );
444 std::string keyString = v8StringToStdString( key );
447 v8::Local<v8::Value> value = object->Get( key );
448 std::string valueString = V8Utils::v8StringToStdString( value );
450 propertyMap[ keyString ] = valueString.c_str();
456 Actor GetActorFromObject( v8::Isolate* isolate, bool& found, v8::Local<v8::Object>& object)
458 v8::HandleScope handleScope( isolate);
461 if( BaseWrappedObject::IsWrappedType ( isolate, object, BaseWrappedObject::ACTOR ))
463 HandleWrapper* handleWrapper = HandleWrapper::Unwrap( isolate, object );
464 return Actor::DownCast( handleWrapper->mHandle );
470 int GetIntegerParameter( unsigned int index, bool& found, v8::Isolate* isolate, const v8::FunctionCallbackInfo< v8::Value >& args, int defaultValue )
473 unsigned int length = args.Length();
474 if( index >= length )
478 if( args[ index ]->IsInt32() )
481 return args[ index ]->Int32Value();
488 float GetFloatParameter( unsigned int index, bool& found, v8::Isolate* isolate, const v8::FunctionCallbackInfo< v8::Value >& args, float defaultValue )
491 unsigned int length = args.Length();
492 if( index >= length )
496 if( args[ index ]->IsNumber() )
499 return args[ index ]->NumberValue();
506 std::string GetStringParameter( unsigned int index, bool& found, v8::Isolate* isolate, const v8::FunctionCallbackInfo< v8::Value >& args )
509 unsigned int length = args.Length();
511 if( index >= length )
513 return std::string();
515 if( args[ index ]->IsString() )
518 return v8StringToStdString( args[ index ]);
522 return std::string();
526 bool GetBooleanParameter( unsigned int index, bool& found, v8::Isolate* isolate, const v8::FunctionCallbackInfo< v8::Value >& args )
528 v8::HandleScope handleScope( isolate);
531 unsigned int length = args.Length();
532 if( index >= length )
536 if( args[ index ]->IsBoolean() )
539 v8::Local<v8::Boolean> v = args[ index ]->ToBoolean();
548 Handle GetHandleParameter( unsigned int index, bool& found, v8::Isolate* isolate, const v8::FunctionCallbackInfo< v8::Value >& args )
550 v8::HandleScope handleScope( isolate);
553 unsigned int length = args.Length();
554 if( index >= length )
559 if( args[ index ]->IsObject() )
561 v8::Local<v8::Object> object = args[ index ]->ToObject();
562 v8::Local<v8::External> field = v8::Local<v8::External>::Cast( object->GetInternalField(0) );
563 void* ptr = field->Value();
567 HandleWrapper* wrapper = static_cast< HandleWrapper *>(ptr);
568 return wrapper->GetHandle();
574 Vector2 GetVector2Parameter( unsigned int index, bool& found, v8::Isolate* isolate, const v8::FunctionCallbackInfo< v8::Value >& args )
576 v8::HandleScope handleScope( isolate);
577 unsigned int length = args.Length();
583 if( args[ index ]->IsObject() )
585 Dali::Property::Value value;
586 value = PropertyValueWrapper::ExtractPropertyValue( isolate, args[index], Dali::Property::VECTOR2 );
587 if( value.GetType() == Dali::Property::VECTOR2)
594 DALI_SCRIPT_EXCEPTION(isolate, "Missing Vector2 parameter");
600 DALI_SCRIPT_EXCEPTION(isolate, "Missing Vector2 parameter");
606 Vector2 GetVector2ParameterFrom2Float( unsigned int index, bool& found, v8::Isolate* isolate, const v8::FunctionCallbackInfo< v8::Value >& args )
608 Vector2 ret(0.0f,0.0f);
610 unsigned int argCount( args.Length() );
612 if( index+2 >= argCount )
614 DALI_SCRIPT_EXCEPTION(isolate, "Missing parameter");
618 ret.x = V8Utils::GetFloatParameter( index, bFound, isolate, args, 0.0f );
619 found = found && bFound;
620 ret.y = V8Utils::GetFloatParameter( index+1, bFound, isolate, args, 0.0f );
621 found = found && bFound;
626 Vector3 GetVector3Parameter( unsigned int index, bool& found, v8::Isolate* isolate, const v8::FunctionCallbackInfo< v8::Value >& args)
628 v8::HandleScope handleScope( isolate);
629 unsigned int argCount( args.Length() );
632 if( index < argCount )
634 if( args[ index ]->IsObject() )
636 Dali::Property::Value value;
637 value = PropertyValueWrapper::ExtractPropertyValue( isolate, args[index], Dali::Property::VECTOR3 );
638 if( value.GetType() == Dali::Property::VECTOR3)
645 DALI_SCRIPT_EXCEPTION(isolate, "Missing Vector3 parameter");
651 DALI_SCRIPT_EXCEPTION(isolate, "Missing Vector3 parameter");
658 Vector4 GetVector4Parameter( unsigned int index, bool& found, v8::Isolate* isolate, const v8::FunctionCallbackInfo< v8::Value >& args)
660 v8::HandleScope handleScope( isolate);
661 unsigned int argCount( args.Length() );
665 if( index < argCount )
667 if( args[ index ]->IsObject() )
669 Dali::Property::Value value;
670 value = PropertyValueWrapper::ExtractPropertyValue( isolate, args[index], Dali::Property::VECTOR4 );
671 if( value.GetType() == Dali::Property::VECTOR4)
678 DALI_SCRIPT_EXCEPTION(isolate, "Missing Vector4 parameter");
684 DALI_SCRIPT_EXCEPTION(isolate, "Missing Vector4 parameter");
691 Rect<int> GetRectIntParameter( unsigned int index, bool& found, v8::Isolate* isolate, const v8::FunctionCallbackInfo< v8::Value >& args )
693 v8::HandleScope handleScope( isolate);
696 int length = args.Length() - index;
698 // if it's an array read the 2 numbers into a vector2
701 if( args[ 0 + index ]->IsInt32() &&
702 args[ 1 + index ]->IsInt32() &&
703 args[ 2 + index ]->IsInt32() &&
704 args[ 3 + index ]->IsInt32() )
707 Rect<int> rect( args[ 0 + index ]->Int32Value(),
708 args[ 1 + index ]->Int32Value(),
709 args[ 2 + index ]->Int32Value(),
710 args[ 3 + index ]->Int32Value() );
714 // this will extract a Vector4, if it is a Vector4 or a Javascript array object
715 if( args[ index ]->IsObject() )
717 Dali::Property::Value value;
718 value = PropertyValueWrapper::ExtractPropertyValue( isolate, args[index], Dali::Property::RECTANGLE );
719 if( value.GetType() == Dali::Property::RECTANGLE)
727 // @todo support vector4 as well?
732 Actor GetActorParameter( unsigned int index, bool& found, v8::Isolate* isolate, const v8::FunctionCallbackInfo< v8::Value >& args )
734 BaseWrappedObject* wrapper = GetWrappedDaliObjectParameter( index, BaseWrappedObject::ACTOR, isolate, args);
735 ActorWrapper* actorWrapper = static_cast< ActorWrapper*>( wrapper );
739 return actorWrapper->GetActor();
747 Layer GetLayerParameter( unsigned int index, bool& found, v8::Isolate* isolate, const v8::FunctionCallbackInfo< v8::Value >& args )
749 Actor actor = GetActorParameter( index, found, isolate, args );
750 return Layer::DownCast( actor );
753 Image GetImageParameter( unsigned int index, bool& found, v8::Isolate* isolate, const v8::FunctionCallbackInfo< v8::Value >& args )
755 BaseWrappedObject* wrappedObject = V8Utils::GetWrappedDaliObjectParameter( index, BaseWrappedObject::IMAGE, isolate, args );
759 ImageWrapper* wrapper = static_cast< ImageWrapper *>(wrappedObject);
760 return wrapper->GetImage();
768 RenderTask GetRenderTaskParameter( unsigned int paramIndex, bool& found, v8::Isolate* isolate, const v8::FunctionCallbackInfo< v8::Value >& args )
771 BaseWrappedObject* wrappedObject = V8Utils::GetWrappedDaliObjectParameter( paramIndex, BaseWrappedObject::RENDER_TASK, isolate, args );
775 RenderTaskWrapper* wrapper = static_cast< RenderTaskWrapper *>(wrappedObject);
776 return wrapper->GetRenderTask();
780 return RenderTask(); // empty handle
785 BaseWrappedObject* GetWrappedDaliObjectParameter( unsigned int index, BaseWrappedObject::Type type, v8::Isolate* isolate, const v8::FunctionCallbackInfo< v8::Value >& args )
787 v8::HandleScope handleScope( isolate);
788 unsigned int length = args.Length();
790 if( index >= length )
795 if( !args[ index ]->IsObject() )
800 v8::Local<v8::Object> object = args[ index ]->ToObject();
802 if( BaseWrappedObject::IsWrappedType ( isolate, object, type ))
804 v8::Local<v8::External> field = v8::Local<v8::External>::Cast( object->GetInternalField(0) );
805 void* ptr = field->Value();
806 BaseWrappedObject* wrapper = static_cast< BaseWrappedObject *>(ptr);
813 Property::Value GetPropertyValueParameter( unsigned int index, bool& found, v8::Isolate* isolate, const v8::FunctionCallbackInfo< v8::Value >& args )
815 v8::HandleScope handleScope( isolate);
817 Property::Value daliPropertyValue;// creates a property with Property::INVALID
820 unsigned int length = args.Length();
822 if( index >= length )
824 return daliPropertyValue;
826 v8::Local<v8::Value > value = args[ index ];
828 return GetPropertyValueFromObject( found, isolate, value);
831 Property::Map GetPropertyMapParameter( unsigned int index, bool& found, v8::Isolate* isolate, const v8::FunctionCallbackInfo< v8::Value >& args )
833 v8::HandleScope handleScope( isolate);
835 Property::Map propertyMap; // empty map
838 unsigned int length = args.Length();
840 if( index >= length )
845 if( !args[ index ]->IsObject() )
851 // go through each key value pair
852 v8::Local<v8::Object> obj = args[ index ]->ToObject();
854 return GetPropertyMapFromObject( isolate, obj );
858 void CreatePropertyMap( v8::Isolate* isolate, const Property::Map& map, v8::Local<v8::Object>& object )
860 v8::HandleScope handleScope( isolate);
862 // we're converting a dali property map in to a JavaScript property map
863 if( map.Count() == 0 )
868 for( unsigned int index = 0; index < map.Count() - 1; ++index )
870 const std::string& key = map.GetKey( index );
871 Property::Value& value = map.GetValue( index );
872 v8::Local<v8::Value> v8Value;
874 switch( value.GetType() )
876 case Dali::Property::FLOAT:
878 v8Value = v8::Number::New( isolate, value.Get<float>() );
881 case Dali::Property::BOOLEAN:
883 v8Value = v8::Boolean::New( isolate, value.Get<bool>());
886 case Dali::Property::INTEGER:
888 v8Value = v8::Integer::New( isolate, value.Get<int>());
891 case Dali::Property::STRING:
893 std::string string = value.Get< std::string >();
894 v8Value = v8::String::NewFromUtf8( isolate, string.c_str());
897 case Dali::Property::VECTOR2:
900 Vector2 vec = value.Get<Vector2>();
901 v8::Local<v8::Array> array= v8::Array::New( isolate, 2 );
902 array->Set( 0 , v8::Number::New(isolate, vec.x));
903 array->Set( 1 , v8::Number::New(isolate, vec.y));
907 case Dali::Property::VECTOR3:
910 Vector3 vec = value.Get<Vector3>();
911 v8::Local<v8::Array> array= v8::Array::New( isolate, 3 );
912 array->Set( 0 , v8::Number::New(isolate, vec.x));
913 array->Set( 1 , v8::Number::New(isolate, vec.y));
914 array->Set( 2 , v8::Number::New(isolate, vec.z));
918 case Dali::Property::VECTOR4:
921 Vector4 vec = value.Get<Vector4>();
922 v8::Local<v8::Array> array= v8::Array::New( isolate, 4 );
923 array->Set( 0 , v8::Number::New(isolate, vec.x));
924 array->Set( 1 , v8::Number::New(isolate, vec.y));
925 array->Set( 2 , v8::Number::New(isolate, vec.z));
926 array->Set( 3 , v8::Number::New(isolate, vec.w));
933 DALI_SCRIPT_EXCEPTION( isolate, "Primitive mismatch \n");
937 object->Set( v8::String::NewFromUtf8( isolate, key.c_str() ), v8Value );
941 void ReadFloatArguments( bool& foundAllArguments, float* data, unsigned int dataSize, const v8::FunctionCallbackInfo< v8::Value >& args, float defaultValue )
943 foundAllArguments = true;
944 unsigned int length = args.Length();
946 if( length < dataSize )
948 foundAllArguments = false;
951 for( unsigned int i = 0; i< dataSize ;i++ )
955 if( args[ i ]->IsNumber() )
957 data[i] = args[i]->NumberValue();
961 data[i] = defaultValue;
962 foundAllArguments = false; // bad argument
967 data[i] = defaultValue; // not enough arguments
973 void ReadIntegerArguments( bool& foundAllArguments, int* data, int dataSize, const v8::FunctionCallbackInfo< v8::Value >& args, int defaultValue )
975 foundAllArguments = true;
976 int length = args.Length();
977 if( length < dataSize )
979 foundAllArguments = false;
982 for( int i = 0; i< dataSize ;i++ )
986 if( args[ i ]->IsInt32() )
988 data[i] = args[i]->Int32Value();
992 data[i] = defaultValue;
993 foundAllArguments = false; // bad argument
998 data[i] = defaultValue; // not enough arguments
1003 } // namespace V8Utils
1005 } // namespace V8Plugin