예제 #1
0
void Dart::Update(int delta)
{
	float distance = sqrt(pow(movementOffset.x, 2) + pow(movementOffset.y, 2));
	position->SetPosition(Point(position->x + movementOffset.x / distance * delta * DART_SPEED,
								position->y + movementOffset.y / distance * delta * DART_SPEED));
	ArrayList* zombies = WorldManager::Instance()->GetImagesByNameN(ZOMBIE);
	IEnumerator* pEnum = zombies->GetEnumeratorN();
	Zombie* zombie = null;
	bool found = false;
	while (pEnum->MoveNext() == E_SUCCESS && !found)
	{
		zombie = (Zombie*)pEnum->GetCurrent();
		Point offset = Point(position->x + ressource->GetWidth()/2 - zombie->position->x - zombie->ressource->GetWidth()/2, position->y + ressource->GetHeight()/2 - zombie->position->y - zombie->ressource->GetHeight()/2);
		float distance = sqrt(pow(offset.x, 2) + pow(offset.y, 2));
		if(distance < 50)
		{
			Image* bitmapDecoder = new Image();
			bitmapDecoder->Construct();
			WorldManager::Instance()->AddImage(new KImage(bitmapDecoder->DecodeN(L"/Home/Res/zombie_dead.png", BITMAP_PIXEL_FORMAT_ARGB8888), new Point(*(zombie->position)), ZOMBIE_DEAD));
			WorldManager::Instance()->DeleteImage(zombie);
			WorldManager::Instance()->DeleteImage(this);
			delete bitmapDecoder;
			found = true;
		}
	}

	delete pEnum;
	delete zombies;

}
예제 #2
0
result
User::updateFromDictionary(HashMap *dictionary)
{
	result success = E_FAILURE;

	if (dictionary && !dictionary->ContainsKey(kHTTPParamNameError)) {
		Double *idValue = static_cast<Double *>(dictionary->GetValue(kHTTPParamNameUserID));
		if (idValue) {
			_id = idValue->ToInt();
			success = E_SUCCESS;
		}

		String *usernameValue = static_cast<String *>(dictionary->GetValue(kHTTPParamNameUsername));
		if (usernameValue) {
			_username = *usernameValue;
			success = E_SUCCESS;
		}

		String *emailValue = static_cast<String *>(dictionary->GetValue(kHTTPParamNameEmail));
		if (emailValue) {
			_email = *emailValue;
			success = E_SUCCESS;
		}

		String *avatarUrlValue = static_cast<String *>(dictionary->GetValue(kHTTPParamNameAvatarUrl));
		if (avatarUrlValue) {
			_avatarUrl = *avatarUrlValue;
			success = E_SUCCESS;
		}

		HashMap *dateDictionary = static_cast<HashMap *>(dictionary->GetValue(kHTTPParamNameDateCreated));
		if (dateDictionary) {
			_dateCreated = new Date();
			result dateSuccess = _dateCreated->updateFromDictionary(dateDictionary);
			if (IsFailed(dateSuccess)) {
				delete _dateCreated;
				_dateCreated = NULL;
			} else {
				success = E_SUCCESS;
			}
		}

		if (!IsFailed(success)) {
			if (_listeners) {
				IEnumerator *iter = _listeners->GetEnumeratorN();
				while (iter->MoveNext() == E_SUCCESS) {
					UserListener *listener = static_cast<UserListener *>(iter->GetCurrent());
					listener->onUserUpdate(this);
				}
				delete iter;
			}
		}
	}

	return success;
}
예제 #3
0
v8::Handle<v8::Value> Contacts::isExistCategory(const v8::Arguments& args) {
	AppLogTag("Contacts", "Entered Contacts::isExistCategory (args: length:%d)", args.Length());

    if (args.Length() < 1 || Util::isArgumentNull(args[0])) {
        AppLog("Bad parameters");
        return v8::ThrowException(v8::String::New("Bad parameters"));
    }
    String name = null;
    v8::HandleScope scope;
    if(args[0]->IsString())
    {
    	name = UNWRAP_STRING(args[0]).c_str();
    	AppLogTag("Contacts","check Category:%ls", name.GetPointer());
    }

    if(name == null)
    {
    	AppLogTag("Contacts","category name is null");
    	return scope.Close(v8::Boolean::New(false));
    }

    AddressbookManager* pAddressbookManager = AddressbookManager::GetInstance();
    Addressbook* pAddressbook = pAddressbookManager->GetAddressbookN(DEFAULT_ADDRESSBOOK_ID);

    IList* pCategoryList = pAddressbook->GetAllCategoriesN();

    result r = GetLastResult();

    if (IsFailed(r)) {
        AppLog("Failed to get addressbook: %s", GetErrorMessage(r));
        return scope.Close(v8::Boolean::New(false));
    }

    if (pCategoryList != null && pCategoryList->GetCount() > 0) {
        IEnumerator* pCategoryEnum = pCategoryList->GetEnumeratorN();
        Category* pCategory = null;

        while (pCategoryEnum->MoveNext() == E_SUCCESS) {
            pCategory = static_cast<Category*>(pCategoryEnum->GetCurrent());
            if (pCategory->GetName().Equals(name)) {
            	AppLog("It is existed category");
            	return scope.Close(v8::Boolean::New(true));
            }
        }
    }

    AppLog("Non-exist category");
    return scope.Close(v8::Boolean::New(false));
}
예제 #4
0
v8::Handle<v8::Value> Contacts::removeCategory(const v8::Arguments& args) {
    AppLog("Entered Contacts::removeCategory (args length:%d)", args.Length());

    if (args.Length() < 2 || Util::isArgumentNull(args[0]) || Util::isArgumentNull(args[1])) {
        AppLog("Bad parameters");
        return v8::ThrowException(v8::String::New("Bad parameters"));
    }
    v8::HandleScope scope;

    String category = UNWRAP_STRING(args[0]).c_str();
    String force = UNWRAP_STRING(args[1]).c_str();

    AddressbookManager* pAddressbookManager = AddressbookManager::GetInstance();
    Addressbook* pAddressbook = pAddressbookManager->GetAddressbookN(DEFAULT_ADDRESSBOOK_ID);

    IList* pCategoryList = pAddressbook->GetAllCategoriesN();

    result r = GetLastResult();
    if (IsFailed(r)) {
        AppLog("Failed to get addressbook: %s", GetErrorMessage(r));
        return scope.Close(v8::Boolean::New(false));
    }
    if (pCategoryList != null && pCategoryList->GetCount() > 0) {
        IEnumerator* pCategoryEnum = pCategoryList->GetEnumeratorN();
        Category* pCategory = null;

        while (pCategoryEnum->MoveNext() == E_SUCCESS) {
            pCategory = static_cast<Category*>(pCategoryEnum->GetCurrent());
            if (pCategory->GetName().Equals(category)) {

                r = pAddressbook->RemoveCategory(*pCategory);
                if (IsFailed(r)) {
                    AppLog("Fail to remove category: %s", GetErrorMessage(r));
                    return scope.Close(v8::Boolean::New(false));
                } else {
                    AppLog("Succeed to remove category");
                    break;
                }
            }
        }
    }

    return scope.Close(v8::Boolean::New(true));
}
예제 #5
0
void
User::logout()
{
	_id = 0;
	_fullname = L"";
	_username = L"";
	_email = L"";
	_avatarUrl = L"";
	_dateCreated = NULL;

	if (_listeners) {
		IEnumerator *iter = _listeners->GetEnumeratorN();
		while (iter->MoveNext() == E_SUCCESS) {
			UserListener *listener = static_cast<UserListener *>(iter->GetCurrent());
			listener->onUserUpdate(this);
		}
		delete iter;
	}
}
예제 #6
0
Osp::Base::Object*
SkyBuilder::Run() {
	SkyIterator* skyIterator = SkyFactory::getStars();
	ArrayList* args = new ArrayList();
	args -> Add(*(new Integer(0)));
	args -> Add(*(new Integer(skyIterator -> GetSize())));
	Osp::App::Application::GetInstance() -> SendUserEvent(BUILD_PROGRESS_RANGE_SET, args);
	AppLog("Setting progress range from 0 to %d", skyIterator -> GetSize());
	int counter = 0;
	bool isVisible = false;
	Osp::Base::Collection::ArrayList* list;
	ConstellationComparer* comparer = new ConstellationComparer();
	list = new Osp::Base::Collection::ArrayList();
	while (skyIterator -> hasNext()) {
		SkyObject* skyObject = skyIterator -> getNext();
		isVisible = skyObject -> Draw();
		String constName = skyObject->getConstellation();
		constName.Trim();
		if (isVisible && (!list -> Contains(constName)) && constName.GetLength()>0) {
			String* str = new String(constName);
			list -> Add(*str);
		}
		counter++;
		if (counter%500 == 0) {
			args = new ArrayList();
			args -> Add(*(new Integer(counter)));
			Osp::App::Application::GetInstance() -> SendUserEvent(BUILD_PROGRESS_SET, args);
		}
	}
	args = new ArrayList();
	args -> Add(*(new Integer(skyIterator -> GetSize())));
	IEnumerator* e = list->GetEnumeratorN();
	while (e->MoveNext()==E_SUCCESS) {
		AppLog("List have %S", ((String*)e->GetCurrent())->GetPointer());
	}
	list -> Sort(*comparer);
	SkyCanvas::SetConstellations(list);
	delete comparer;
	Osp::App::Application::GetInstance() -> SendUserEvent(BUILD_PROGRESS_DONE, args);
	return null;
}
예제 #7
0
void ProjectGiraffeTab4::updateViews()
{
	AppLog("updating views");
	// Remove all views if they exist
	if (_contentViews) _contentViews->RemoveAll(true);
	delete _contentViews;
	if (_contextViews) _contextViews->RemoveAll(true);
	delete _contextViews;

	if (_items && _items->GetCount()) {
		_contentViews = new ArrayList(SingleObjectDeleter);
		_contentViews->Construct();
		_contextViews = new ArrayList(SingleObjectDeleter);
		_contextViews->Construct();

		IEnumerator *iter = _items->GetEnumeratorN();
		int width = GetSize().width;
		while (iter->MoveNext() == E_SUCCESS) {
			Graffiti *graffiti = static_cast<Graffiti *>(iter->GetCurrent());
			if (graffiti) {
				// Create content view
				GraffitiCellContentView *contentView = new GraffitiCellContentView();
				contentView->Construct(Rectangle(0, 0, width, GetDefaultItemHeight()));
				contentView->setGraffiti(graffiti);
				contentView->sizeToFit();
				_contentViews->Add((Panel *)contentView);

				// Create social context view
				GraffitiCellSocialContextView *socialContextView = new GraffitiCellSocialContextView();
				socialContextView->Construct(contentView->GetBounds());
				socialContextView->setGraffiti(graffiti);
				_contextViews->Add((Panel *)socialContextView);
			}
		}
	} else {
		_contentViews = NULL;
		_contextViews = NULL;
	}
}
예제 #8
0
v8::Handle<v8::Value> Contacts::list(const v8::Arguments& args) {
	AppLogTag("Contacts", "Entered Contacts::list (args length:%d)", args.Length());

    v8::HandleScope scope;
    AddressbookManager* pAddressbookManager = AddressbookManager::GetInstance();
    IList* pCategoryList = pAddressbookManager->GetAllCategoriesN();
    AppLogTag("Contacts", "TEST1");
    Category* pCategory = null;
    Contact* pContact = null;
    AppLogTag("Contacts", "TEST2");
    IEnumerator* pCategoryEnum = pCategoryList->GetEnumeratorN();
    v8::Local<v8::Object> categoryObject = v8::Object::New();

    while (pCategoryEnum->MoveNext() == E_SUCCESS) {
    	AppLogTag("Contacts", "TEST");
        pCategory = static_cast<Category*>(pCategoryEnum->GetCurrent());
        char category[STRING_MAX];
        IList* pContactList = pAddressbookManager->GetContactsByCategoryN(pCategory->GetRecordId());
        IEnumerator* pContactEnum = pContactList->GetEnumeratorN();
        v8::Local<v8::Array> personList = v8::Array::New();

        AppLogTag("Contacts", "Fetching category: %ls", pCategory->GetName().GetPointer());
        int person_cnt = 0;
        while (pContactEnum->MoveNext() == E_SUCCESS) {
            pContact = static_cast<Contact*>(pContactEnum->GetCurrent());
            String fullName = L"", firstName, lastName;
            v8::Local<v8::Object> personObject = v8::Object::New();
            char buf[STRING_MAX];

            pContact->GetValue(CONTACT_PROPERTY_ID_FIRST_NAME, firstName);
            pContact->GetValue(CONTACT_PROPERTY_ID_LAST_NAME, lastName);
            fullName.Append(firstName);
            fullName.Append(L" ");
            fullName.Append(lastName);

            AppLogTag("Contacts", "Getting person: %ls", fullName.GetPointer());
            IList* pPhoneNumberList = pContact->GetValuesN(CONTACT_MPROPERTY_ID_PHONE_NUMBERS);
            v8::Local<v8::Array> phoneList = v8::Array::New();
            if (pPhoneNumberList != null) {
                IEnumerator* pEnum = pPhoneNumberList->GetEnumeratorN();
                int number_cnt = 0;
                while (pEnum->MoveNext() == E_SUCCESS) {
                    PhoneNumber* pPhoneNumber = static_cast<PhoneNumber*>(pEnum->GetCurrent());
                    String number = pPhoneNumber->GetPhoneNumber();
                    AppLogTag("Contacts", "Getting person's phonenumber: %ls", number.GetPointer());

                    phoneList->Set(number_cnt++, v8::String::New(Util::toAnsi(buf, number.GetPointer(), STRING_MAX)));
                }

                delete pEnum;
                pPhoneNumberList->RemoveAll(true);
                delete pPhoneNumberList;
            }
            personObject->Set(v8::String::New("name"), v8::String::New(Util::toAnsi(buf, fullName.GetPointer(), STRING_MAX)));
            personObject->Set(v8::String::New("phoneNumber"), phoneList);
            personList->Set(person_cnt++, personObject);
        }
        categoryObject->Set(v8::String::New(Util::toAnsi(category, pCategory->GetName(), STRING_MAX)), personList);

        delete pContactEnum;
        pContactList->RemoveAll(true);
        delete pContactList;
    }
   return scope.Close(categoryObject);
}
예제 #9
0
//TODO: Is it possible to set additional information?
v8::Handle<v8::Value> Contacts::add(const v8::Arguments& args) {
    AppLog("Entered Contacts::addContact (args length:%d)", args.Length());

//    if (args.Length() < 1 || Util::isArgumentNull(args[0])) {
    if (args.Length() < 1) {
        AppLog("Bad parameters");
        return v8::ThrowException(v8::String::New("Bad parameters"));
    }
    v8::HandleScope scope;

    String category;
	String name;
	String number;

	v8::Local<v8::Object> obj = args[0]->ToObject();
    if(args[0]->IsObject())
    {
		v8::Local<v8::Value> obj_category = obj->Get(v8::String::New("category"));
		if(obj_category->IsString())
		{
			category = UNWRAP_STRING(obj_category).c_str();
			AppLogTag("Contacts","Add Contacts: [Category:%ls]", category.GetPointer());
		}

		v8::Local<v8::Value> obj_name = obj->Get(v8::String::New("name"));
		if(obj_name->IsString())
		{
			name = UNWRAP_STRING(obj_name).c_str();
			AppLogTag("Contacts","Add Contacts: [Name:%ls]", name.GetPointer());
		}
	}

    if(category == null || name == null)
    {
    	AppLogTag("Contacts","Failed to add Contact");
    	return scope.Close(v8::Boolean::New(false));
    }

    //CREATE CONTACT
    Contact contact;
    contact.SetValue(CONTACT_PROPERTY_ID_FIRST_NAME, name);

    v8::Local<v8::Value> obj_number = obj->Get(v8::String::New("number"));

	if(!obj_number->IsNull() && obj_number->IsString())
	{
		number = UNWRAP_STRING(obj_number).c_str();
		AppLogTag("Contacts","Add Contacts: [Number:%ls]", number.GetPointer());
		PhoneNumber phoneNumber;
		phoneNumber.SetPhoneNumber(number);
		contact.AddPhoneNumber(phoneNumber);
	}

	AddressbookManager* pAddressbookManager = AddressbookManager::GetInstance();
	Addressbook* pAddressbook = pAddressbookManager->GetAddressbookN(DEFAULT_ADDRESSBOOK_ID);

    //GET CATEGORIES TO ADD A CONTACT
	IList* pCategoryList = pAddressbook->GetAllCategoriesN();

	result r = GetLastResult();
	if (IsFailed(r)) {
		AppLogTag("Contacts", "Failed to get categories: %s", GetErrorMessage(r));
		return scope.Close(v8::Boolean::New(false));
	}

	if (pCategoryList != null && pCategoryList->GetCount() > 0) {
		IEnumerator* pCategoryEnum = pCategoryList->GetEnumeratorN();
		Category* pCategory = null;

		while (pCategoryEnum->MoveNext() == E_SUCCESS) {
			pCategory = static_cast<Category*>(pCategoryEnum->GetCurrent());
			if (pCategory->GetName().Equals(category)) {

				pAddressbook->AddContact(contact);
				pAddressbook->AddMemberToCategory(pCategory->GetRecordId(), contact.GetRecordId());

				if (IsFailed(GetLastResult())) {
					return scope.Close(v8::Boolean::New(false));
				} else {
					AppLogTag("Contacts", "%d", contact.GetRecordId());
					return scope.Close(v8::Boolean::New(true));
				}
			}
		}
	}

	AppLogTag("Contacts","No Categories");
	return scope.Close(v8::Boolean::New(false));
}
예제 #10
0
void
MainForm::OnParsingCompleted(ArrayList &feedData) {
	AppResource *pAppResource = Application::GetInstance()->GetAppResource();
	if (feedData.GetCount() == 0) {
		// no service this day
		String emptyText;
		pAppResource->GetString("IDS_NOSERVICE", emptyText);
		__pListFood->SetTextOfEmptyList(emptyText);
	} else {
		IEnumerator *pEnum = feedData.GetEnumeratorN();
		HashMap *pItem = null;
		int mensaIndex = -1;
		String *currentMensa = null;
		String currencySymbol;
		pAppResource->GetString("IDS_CURRENCY", currencySymbol);
		String soldOut;
		pAppResource->GetString("IDS_SOLDOUT", soldOut);

		// iterate over items (meals) in feed
		while (pEnum->MoveNext() == E_SUCCESS) {
			pItem = (HashMap *)pEnum->GetCurrent();

			// check if mensa is already in the list (we assume the feed to be ordered)
			if (!currentMensa || !(static_cast<String *>(pItem->GetValue(*(new String("author")))))->Equals(*currentMensa, false)) {
				currentMensa = static_cast<String *>(pItem->GetValue(*(new String("author"))));
				mensaIndex++;
				// Create a main item of the ExpandableList
				CustomListItem* pMainItem = new CustomListItem();
				pMainItem->Construct(100);
				pMainItem->SetItemFormat(*__pMainItemFormat);
				pMainItem->SetElement(TEXT_ID, *(new String(*currentMensa)));
				// Add the item to the ExpandableList
				__pListFood->AddItem(*pMainItem, mensaIndex);
			}

			String *title = static_cast<String *>(pItem->GetValue(*(new String("title"))));
			title->Trim();
			String priceStudents;
			String priceStaff;
			int stringLength = title->GetLength();

			// Create a sub item of the ExpandableList
			CustomListItem *pSubItem = new CustomListItem();
			pSubItem->Construct(100);
			pSubItem->SetItemFormat(*__pSubItemFormat);

			// get prices
			if (title->EndsWith(L" EUR)")) {
				// parse price
				title->SubString(stringLength - 20, 5, priceStudents);
				priceStudents.Append(currencySymbol);
				title->SubString(stringLength - 9, 5, priceStaff);
				priceStaff.Append(currencySymbol);
				title->Remove(stringLength - 22, 22);

				pSubItem->SetElement(PRICESTUDENT_ID, priceStudents);
				pSubItem->SetElement(PRICESTAFF_ID, priceStaff);
			} else if (title->EndsWith(L"(ausverkauft)")) {
				// sold out
				title->Remove(stringLength - 14, 14);
				pSubItem->SetElement(REMARK_ID, soldOut);
			}

			pSubItem->SetElement(TEXT_ID, *title);

			// Add sub item to the ExpandableList
			__pListFood->AddSubItem(mensaIndex, *pSubItem);
		}

		// clean up
		delete pEnum;
	}

	__pListFood->RequestRedraw();
	__pListFood->ScrollToTop();

	StopLoadingAnimation();
}
예제 #11
0
void HttpThread::OnTransactionHeaderCompleted(HttpSession & httpSession,
                                              HttpTransaction & httpTransaction,
                                              int headerLen, bool bAuthRequired)
{
  result r = E_SUCCESS;
  HttpResponse * pResponse = httpTransaction.GetResponse();
  if ((r = GetLastResult()) != E_SUCCESS)
  {
    LOG(LWARNING, ("httpTransaction.GetResponse error", r));
    httpSession.CancelTransaction(httpTransaction);
    httpSession.CloseTransaction(httpTransaction);
    m_callback.OnFinish(-1, m_begRange, m_endRange);
    return;
  }

  int const httpStatusCode = pResponse->GetHttpStatusCode();
  // When we didn't ask for chunks, code should be 200
  // When we asked for a chunk, code should be 206
  bool const isChunk = !(m_begRange == 0 && m_endRange < 0);
  if ((isChunk && httpStatusCode != 206) || (!isChunk && httpStatusCode != 200))
  {
    LOG(LWARNING, ("Http request to", m_url, " aborted with HTTP code", httpStatusCode));
    httpSession.CancelTransaction(httpTransaction);
    r = httpSession.CloseTransaction(httpTransaction);
    m_callback.OnFinish(-4, m_begRange, m_endRange);
    LOG(LDEBUG, ("CloseTransaction result", r));
    return;
  }
  else if (m_expectedSize > 0)
  {
    bool bGoodSize = false;
    // try to get content length from Content-Range header first
    HttpHeader * pHeader = pResponse->GetHeader();
    LOG(LDEBUG, ("Header:", FromTizenString(*pHeader->GetRawHeaderN())));
    IEnumerator * pValues = pHeader->GetFieldValuesN("Content-Range");
    if (GetLastResult() == E_SUCCESS)
    {
      bGoodSize = true;
      pValues->MoveNext(); // strange, but works
      String const * pString = dynamic_cast<String const *>(pValues->GetCurrent());

      if (pString->GetLength())
      {
        int lastInd;
        pString->LastIndexOf ('/', pString->GetLength()-1, lastInd);
        int64_t value = -1;
        String tail;
        pString->SubString(lastInd + 1, tail);
        LOG(LDEBUG, ("tail value:",FromTizenString(tail)));
        LongLong::Parse(tail, value);
        if (value != m_expectedSize)
        {
          LOG(LWARNING, ("Http request to", m_url,
                         "aborted - invalid Content-Range:", value, " expected:", m_expectedSize ));
          httpSession.CancelTransaction(httpTransaction);
          r = httpSession.CloseTransaction(httpTransaction);
          m_callback.OnFinish(-2, m_begRange, m_endRange);
          LOG(LDEBUG, ("CloseTransaction result", r));
        }
      }
    }
    else
    {
      pValues = pHeader->GetFieldValuesN("Content-Length");
      if (GetLastResult() == E_SUCCESS)
      {
        bGoodSize = true;
        pValues->MoveNext();  // strange, but works
        String const * pString = dynamic_cast<String const *>(pValues->GetCurrent());
        if (pString)
        {
          int64_t value = -1;
          LongLong::Parse(*pString, value);
          if (value != m_expectedSize)
          {
            LOG(LWARNING, ("Http request to", m_url,
                           "aborted - invalid Content-Length:", value, " expected:", m_expectedSize));
            httpSession.CancelTransaction(httpTransaction);
            r = httpSession.CloseTransaction(httpTransaction);
            m_callback.OnFinish(-2, m_begRange, m_endRange);
            LOG(LDEBUG, ("CloseTransaction result", r));
          }
        }
      }
    }

    if (!bGoodSize)
    {
      LOG(LWARNING, ("Http request to", m_url,
                     "aborted, server didn't send any valid file size"));
      httpSession.CancelTransaction(httpTransaction);
      r = httpSession.CloseTransaction(httpTransaction);
      m_callback.OnFinish(-2, m_begRange, m_endRange);
      LOG(LDEBUG, ("CloseTransaction result", r));
    }
  }
}
예제 #12
0
    bool drawText(const char * pszText, Dimension& dimensions, CCImage::ETextAlign alignment, const char * fontName = NULL, int fontSize = 0)
    {
        bool nRet = false;
        do
        {
            CC_BREAK_IF(pszText == NULL || strlen(pszText) <= 0);
            // text
            Osp::Base::String strText(pszText);
            // Set a font to the TextElement
            Font font;
            bool bUseDefaultFont = true;
            if (fontName != NULL && strlen(fontName) > 0)
            {
                String strFonName(fontName);
                if (strFonName.EndsWith(".ttf") || strFonName.EndsWith(".TTF"))
                {
                    bUseDefaultFont = false;
                    const char* pFullFontPath = CCFileUtils::fullPathFromRelativePath(fontName);
                    font.Construct(pFullFontPath, FONT_STYLE_PLAIN, fontSize);
                }
                else
                {
                    IList* pSystemFontList = Font::GetSystemFontListN();
                    if (pSystemFontList != NULL)
                    {
                        IEnumerator* pEnum = pSystemFontList->GetEnumeratorN();
                        Object* pObj = null;
                        while (pEnum->MoveNext() == E_SUCCESS)
                        {
                            pObj = pEnum->GetCurrent();
                            String* pStrName = static_cast<String*>(pObj);
                            if (pStrName->Equals(strFonName, false))
                            {
                                bUseDefaultFont = false;
                                font.Construct(*pStrName, FONT_STYLE_PLAIN, fontSize);
                                break;
                            }
                        }

                        delete pEnum;

                        pSystemFontList->RemoveAll(true);
                        delete pSystemFontList;
                    }
                }
            }

            if (bUseDefaultFont)
            {
                font.Construct(FONT_STYLE_PLAIN, fontSize);
            }

            // calculate text size
            if (dimensions.width <= 0)
            {
                Dimension dim;
                font.GetTextExtent(strText, strText.GetLength(), dim);
                dimensions.width = dim.width;
                dimensions.height = dim.height;
            }

            CC_BREAK_IF(dimensions.width <= 0);

            // Create an EnrichedText
            m_pEnrichedText = new EnrichedText();
            m_pEnrichedText->Construct(Dimension(dimensions.width, 10));

            switch (alignment)
            {
            case CCImage::kAlignCenter:
                m_pEnrichedText->SetHorizontalAlignment(TEXT_ALIGNMENT_CENTER);
                m_pEnrichedText->SetVerticalAlignment(TEXT_ALIGNMENT_MIDDLE);
                break;
            case CCImage::kAlignTop:
                m_pEnrichedText->SetHorizontalAlignment(TEXT_ALIGNMENT_CENTER);
                m_pEnrichedText->SetVerticalAlignment(TEXT_ALIGNMENT_TOP);
                break;
            case CCImage::kAlignTopRight:
                m_pEnrichedText->SetHorizontalAlignment(TEXT_ALIGNMENT_RIGHT);
                m_pEnrichedText->SetVerticalAlignment(TEXT_ALIGNMENT_TOP);
                break;
            case CCImage::kAlignRight:
                m_pEnrichedText->SetHorizontalAlignment(TEXT_ALIGNMENT_RIGHT);
                m_pEnrichedText->SetVerticalAlignment(TEXT_ALIGNMENT_MIDDLE);
                break;
            case CCImage::kAlignBottomRight:
                m_pEnrichedText->SetHorizontalAlignment(TEXT_ALIGNMENT_RIGHT);
                m_pEnrichedText->SetVerticalAlignment(TEXT_ALIGNMENT_BOTTOM);
                break;
            case CCImage::kAlignBottom:
                m_pEnrichedText->SetHorizontalAlignment(TEXT_ALIGNMENT_CENTER);
                m_pEnrichedText->SetVerticalAlignment(TEXT_ALIGNMENT_BOTTOM);
                break;
            case CCImage::kAlignBottomLeft:
                m_pEnrichedText->SetHorizontalAlignment(TEXT_ALIGNMENT_LEFT);
                m_pEnrichedText->SetVerticalAlignment(TEXT_ALIGNMENT_BOTTOM);
                break;
            case CCImage::kAlignLeft:
                m_pEnrichedText->SetHorizontalAlignment(TEXT_ALIGNMENT_LEFT);
                m_pEnrichedText->SetVerticalAlignment(TEXT_ALIGNMENT_MIDDLE);
                break;
            case CCImage::kAlignTopLeft:
                m_pEnrichedText->SetHorizontalAlignment(TEXT_ALIGNMENT_LEFT);
                m_pEnrichedText->SetVerticalAlignment(TEXT_ALIGNMENT_TOP);
                break;
            default:
                m_pEnrichedText->SetHorizontalAlignment(TEXT_ALIGNMENT_CENTER);
                m_pEnrichedText->SetVerticalAlignment(TEXT_ALIGNMENT_MIDDLE);
                break;
            }
            // Set attributes of the EnrichedText
            m_pEnrichedText->SetTextWrapStyle(TEXT_WRAP_CHARACTER_WRAP);
            m_pEnrichedText->SetTextAbbreviationEnabled(true);

            // Create a TextElement
            TextElement* pTextElement = new TextElement();
            pTextElement->Construct(strText);
            // After Adding, set attributes of the TextElement
            pTextElement->SetTextColor(Color::COLOR_WHITE);
            pTextElement->SetFont(font);
            // Add the TextElement to the EnrichedText
            m_pEnrichedText->Add(*pTextElement);

            m_pEnrichedText->Refresh();
            dimensions.height = m_pEnrichedText->GetTotalLineHeight();
            m_pEnrichedText->SetSize(dimensions.width, dimensions.height);

            CC_SAFE_DELETE(m_pCanvas);
            m_pCanvas = new Canvas();
            m_pCanvas->Construct(Rectangle(0, 0, dimensions.width, dimensions.height));
            m_pCanvas->DrawText(Point(0, 0), *m_pEnrichedText);

            m_pEnrichedText->RemoveAllTextElements(true);
            CC_SAFE_DELETE(m_pEnrichedText);

            nRet = true;
        } while (0);
        return nRet;
    }