diff --git a/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index b1637185a7..fb7706c627 100644 --- a/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -a511bc3eca93bdbec49803fde5da4a61bd404020 \ No newline at end of file +82031186c5a74b94209ee517854294f4a1b672bc \ No newline at end of file diff --git a/cocos2dx/misc_nodes/CCClippingNode.h b/cocos2dx/misc_nodes/CCClippingNode.h index f767723461..3ad7f1f944 100644 --- a/cocos2dx/misc_nodes/CCClippingNode.h +++ b/cocos2dx/misc_nodes/CCClippingNode.h @@ -114,7 +114,7 @@ private: */ void drawFullScreenQuadClearStencil(); -private: +protected: ClippingNode(); protected: diff --git a/extensions/CocoStudio/GUI/Action/UIAction.cpp b/extensions/CocoStudio/GUI/Action/UIAction.cpp new file mode 100644 index 0000000000..5619d0cb2f --- /dev/null +++ b/extensions/CocoStudio/GUI/Action/UIAction.cpp @@ -0,0 +1,110 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "UIAction.h" +#include "UIActionNode.h" +#include "../../Json/DictionaryHelper.h" + + +NS_CC_EXT_BEGIN + +UIAction::UIAction() +{ + m_ActionNodeList = CCArray::create(); + m_ActionNodeList->retain(); +} + +UIAction::~UIAction() +{ + m_ActionNodeList->removeAllObjects(); + m_ActionNodeList->release(); +} + +void UIAction::initWithDictionary(cs::JsonDictionary *dic,UIWidget* root) +{ + setName(DICTOOL->getStringValue_json(dic, "name")); + setLoop(DICTOOL->getBooleanValue_json(dic, "loop")); + setUnitTime(DICTOOL->getFloatValue_json(dic, "unittime")); + int actionNodeCount = DICTOOL->getArrayCount_json(dic, "actionnodelist"); + for (int i=0; iautorelease(); + cs::JsonDictionary* actionNodeDic = DICTOOL->getDictionaryFromArray_json(dic, "actionnodelist", i); + actionNode->initWithDictionary(actionNodeDic,root); + m_ActionNodeList->addObject(actionNode); + CC_SAFE_DELETE(actionNodeDic); + } +} + +void UIAction::Play() +{ + Stop(); + int frameNum = m_ActionNodeList->count(); + for ( int i = 0; i < frameNum; i++ ) + { + UIActionNode* actionNode = (UIActionNode*)m_ActionNodeList->objectAtIndex(i); + actionNode->RunAction( getUnitTime(),getLoop() ); + } +} + +void UIAction::Pause() +{ + +} + +void UIAction::Stop() +{ + int frameNum = m_ActionNodeList->count(); + + for ( int i = 0; i < frameNum; i++ ) + { + UIActionNode* actionNode = (UIActionNode*)m_ActionNodeList->objectAtIndex(i); + actionNode->StopAction(); + } +} + +void UIAction::UpdateToFrameByIndex(int index) +{ + int frameNum = m_ActionNodeList->count(); + + for ( int i = 0; i < frameNum; i++ ) + { + UIActionNode* actionNode = (UIActionNode*)m_ActionNodeList->objectAtIndex(i); + + actionNode->UpdateToFrameByIndex(index); + } +} + +void UIAction::setName(const char* name) +{ + m_name = name; +} + +const char* UIAction::getName() const +{ + return m_name.c_str(); +} + +NS_CC_EXT_END \ No newline at end of file diff --git a/extensions/CocoStudio/GUI/Action/UIAction.h b/extensions/CocoStudio/GUI/Action/UIAction.h new file mode 100644 index 0000000000..eb8b8b9d83 --- /dev/null +++ b/extensions/CocoStudio/GUI/Action/UIAction.h @@ -0,0 +1,66 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __UIACTION_H__ +#define __UIACTION_H__ + +#include "cocos2d.h" +#include "ExtensionMacros.h" +#include "UIActionNode.h" +#include "../../Json/CSContentJsonDictionary.h" + +NS_CC_EXT_BEGIN + +class UIAction : public Object +{ +protected: + cocos2d::Array* m_ActionNodeList;/*actionnode*/ + std::string m_name; +public: + UIAction(); + virtual ~UIAction(); + + void Play(); + void Pause(); + void Stop(); + + void UpdateToFrameByIndex(int index); + + + // +// CC_SYNTHESIZE(std::string, m_name, Name); + // + CC_SYNTHESIZE(bool, m_loop, Loop); + // + CC_SYNTHESIZE(float, m_fUnitTime, UnitTime); + + void initWithDictionary(cs::JsonDictionary* dic,UIWidget* root); + + void setName(const char* name); + const char* getName() const; +}; + +NS_CC_EXT_END + +#endif diff --git a/extensions/CocoStudio/GUI/Action/UIActionFrame.cpp b/extensions/CocoStudio/GUI/Action/UIActionFrame.cpp new file mode 100644 index 0000000000..1275e3fd3a --- /dev/null +++ b/extensions/CocoStudio/GUI/Action/UIActionFrame.cpp @@ -0,0 +1,51 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "UIActionFrame.h" +#include "../../Json/DictionaryHelper.h" + +NS_CC_EXT_BEGIN + +UIActionFrame::UIActionFrame() +{ + +} +UIActionFrame::~UIActionFrame() +{ + +} + +void UIActionFrame::initWithDictionary(cs::JsonDictionary *dic) +{ + setFrameId(DICTOOL->getIntValue_json(dic, "frameid")); + setStartTime(DICTOOL->getFloatValue_json(dic, "starttime")); + setPosition(ccp(DICTOOL->getFloatValue_json(dic, "positionx"), DICTOOL->getFloatValue_json(dic, "positiony"))); + setScaleX(DICTOOL->getFloatValue_json(dic, "scalex")); + setScaleY(DICTOOL->getFloatValue_json(dic, "scaley")); + setRotation(DICTOOL->getFloatValue_json(dic, "rotation")); + setOpacity(DICTOOL->getIntValue_json(dic, "opacity")); + setColor(ccc3(DICTOOL->getIntValue_json(dic, "colorr"), DICTOOL->getIntValue_json(dic, "colorg"), DICTOOL->getIntValue_json(dic, "colorb"))); +} + +NS_CC_EXT_END \ No newline at end of file diff --git a/extensions/CocoStudio/GUI/Action/UIActionFrame.h b/extensions/CocoStudio/GUI/Action/UIActionFrame.h new file mode 100644 index 0000000000..03518735f3 --- /dev/null +++ b/extensions/CocoStudio/GUI/Action/UIActionFrame.h @@ -0,0 +1,64 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __UIACTIONFRAME_H__ +#define __UIACTIONFRAME_H__ + +#include "cocos2d.h" +#include "ExtensionMacros.h" +#include "../../Json/CSContentJsonDictionary.h" + +NS_CC_EXT_BEGIN + +class UIActionFrame:public Object +{ +protected: + +public: + UIActionFrame(); + virtual ~UIActionFrame(); + // + CC_SYNTHESIZE(int, m_frameId, FrameId); + // + CC_SYNTHESIZE(float, m_startTime, StartTime); + // + CC_SYNTHESIZE(Point, m_position, Position); + // + CC_SYNTHESIZE(float, m_scaleX, ScaleX); + // + CC_SYNTHESIZE(float, m_scaleY, ScaleY); + // + CC_SYNTHESIZE(float, m_rotation, Rotation); + // + CC_SYNTHESIZE(float, m_opacity, Opacity); + // + CC_SYNTHESIZE(Color3B, m_color, Color); + + void initWithDictionary(cs::JsonDictionary* dic); + +}; + +NS_CC_EXT_END + +#endif diff --git a/extensions/CocoStudio/GUI/Action/UIActionManager.cpp b/extensions/CocoStudio/GUI/Action/UIActionManager.cpp new file mode 100644 index 0000000000..9cce34b69f --- /dev/null +++ b/extensions/CocoStudio/GUI/Action/UIActionManager.cpp @@ -0,0 +1,123 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "UIActionManager.h" +#include "../../Json/DictionaryHelper.h" +#include "UIAction.h" + +NS_CC_EXT_BEGIN + +static UIActionManager* sharedActionManager = NULL; + +UIActionManager* UIActionManager::shareManager() +{ + if (!sharedActionManager) { + sharedActionManager = new UIActionManager(); + } + return sharedActionManager; +} + +void UIActionManager::purgeUIActionManager() +{ + CC_SAFE_DELETE(sharedActionManager); +} + +UIActionManager::UIActionManager() +{ +// m_ActionList = cocos2d::CCArray::create(); +// m_ActionList->retain(); + m_pActionDic = CCDictionary::create(); + m_pActionDic->retain(); +} + +UIActionManager::~UIActionManager() +{ +// m_ActionList->removeAllObjects(); +// m_ActionList->release(); + m_pActionDic->removeAllObjects(); + m_pActionDic->release(); +} + +void UIActionManager::initWithDictionary(const char* jsonName,cs::JsonDictionary *dic,UIWidget* root) +{ + std::string path = jsonName; + int pos = path.find_last_of("/"); + std::string fileName = path.substr(pos+1,path.length()); + CCLOG("filename == %s",fileName.c_str()); + Array* actionList = Array::create(); + int actionCount = DICTOOL->getArrayCount_json(dic, "actionlist"); + for (int i=0; iautorelease(); + cs::JsonDictionary* actionDic = DICTOOL->getDictionaryFromArray_json(dic, "actionlist", i); + action->initWithDictionary(actionDic,root); + actionList->addObject(action); + CC_SAFE_DELETE(actionDic); + } + m_pActionDic->setObject(actionList, fileName); +} + +UIAction* UIActionManager::GetActionByName(const char* jsonName,const char* actionName) +{ + Array* actionList = (Array*)(m_pActionDic->objectForKey(jsonName)); + if (!actionList) + { + return NULL; + } + for (unsigned int i=0; icount(); i++) + { + UIAction* action = dynamic_cast(actionList->getObjectAtIndex(i)); + if (strcmp(actionName, action->getName()) == 0) + { + return action; + } + } + return NULL; +} + +void UIActionManager::PlayActionByName(const char* jsonName,const char* actionName) +{ + UIAction* action = GetActionByName(jsonName,actionName); + if (action) + { + action->Play(); + } +} + +/*temp */ +void UIActionManager::releaseActions() +{ + m_pActionDic->removeAllObjects(); +// int times = m_ActionList->data->num; +// for (int i=0; i(m_ActionList->lastObject()); +// m_ActionList->removeObject(action); +// delete action; +// action = NULL; +// } +} + +NS_CC_EXT_END \ No newline at end of file diff --git a/extensions/CocoStudio/GUI/Action/UIActionManager.h b/extensions/CocoStudio/GUI/Action/UIActionManager.h new file mode 100644 index 0000000000..a249b5582d --- /dev/null +++ b/extensions/CocoStudio/GUI/Action/UIActionManager.h @@ -0,0 +1,57 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __UIACTIONMANAGER_H__ +#define __UIACTIONMANAGER_H__ + +#include "cocos2d.h" +#include "ExtensionMacros.h" +#include "UIAction.h" +#include "../../Json/CSContentJsonDictionary.h" + +NS_CC_EXT_BEGIN + +class UIActionManager:public Object +{ +protected: +// CCArray* m_ActionList;/*guiaction*/ + Dictionary* m_pActionDic; + +public: + UIActionManager(); + virtual ~UIActionManager(); + static UIActionManager* shareManager(); + static void purgeUIActionManager(); + + UIAction* GetActionByName(const char* jsonName,const char* actionName); + + void PlayActionByName(const char* jsonName,const char* actionName); + + void initWithDictionary(const char* jsonName, cs::JsonDictionary* dic,UIWidget* root); + void releaseActions(); +}; + +NS_CC_EXT_END + +#endif diff --git a/extensions/CocoStudio/GUI/Action/UIActionNode.cpp b/extensions/CocoStudio/GUI/Action/UIActionNode.cpp new file mode 100644 index 0000000000..944322c59a --- /dev/null +++ b/extensions/CocoStudio/GUI/Action/UIActionNode.cpp @@ -0,0 +1,255 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "UIActionNode.h" +#include "UIActionFrame.h" +#include "../../Json/DictionaryHelper.h" +#include "../System/UIHelper.h" + +NS_CC_EXT_BEGIN + +UIActionNode::UIActionNode() +{ + currentIndex = 0; + m_actionNode = NULL; + + m_action = NULL; + + m_ActionFrameList = CCArray::create(); + m_ActionFrameList->retain(); +} + +UIActionNode::~UIActionNode() +{ + if (m_action != NULL) + { + m_action->release(); + } + if (m_actionNode) + { + m_actionNode->setBindingAction(NULL); + } + m_ActionFrameList->removeAllObjects(); + m_ActionFrameList->release(); +} + +void UIActionNode::initWithDictionary(cs::JsonDictionary *dic,UIWidget* root) +{ + setActionTag(DICTOOL->getIntValue_json(dic, "ActionTag")); + int actionFrameCount = DICTOOL->getArrayCount_json(dic, "actionframelist"); + UIWidget* bindingWidget = CCUIHELPER->seekActionWidgetByActionTag(root, getActionTag()); + if (bindingWidget) + { + SetActionNode(bindingWidget); + bindingWidget->setBindingAction(this); + } + + for (int i=0; iautorelease(); + cs::JsonDictionary* actionFrameDic = DICTOOL->getDictionaryFromArray_json(dic, "actionframelist", i); + actionFrame->initWithDictionary(actionFrameDic); + m_ActionFrameList->addObject(actionFrame); + CC_SAFE_DELETE(actionFrameDic); + } +} + +void UIActionNode::SetActionNode(UIWidget* widget) +{ + m_actionNode = widget; + + //UpdateToFrameByIndex(currentIndex); +} + +void UIActionNode::releaseBindingWidget() +{ + m_actionNode = NULL; +} + +void UIActionNode::InsertFrame(int index, UIActionFrame* frame) +{ + m_ActionFrameList->insertObject(frame,index); +} + +void UIActionNode::AddFrame(UIActionFrame* frame) +{ + m_ActionFrameList->addObject(frame); +} + +void UIActionNode::DeleteFrame(UIActionFrame* frame) +{ + m_ActionFrameList->removeObject(frame); +} + +void UIActionNode::ClearAllFrame() +{ + m_ActionFrameList->removeAllObjects(); +} + +void UIActionNode::UpdateToFrameByIndex(int index) +{ + currentIndex = index; + + int frameNum = m_ActionFrameList->count(); + + bool bFindFrame = false; + + UIActionFrame* frame = NULL; + for (int i = 0; i < frameNum; i++) + { + frame = (UIActionFrame*)m_ActionFrameList->objectAtIndex(index); + if (frame->getFrameId() == index) + { + bFindFrame = true; + UpdateToFrame(frame); + break; + } + } + + if (!bFindFrame) + { + m_actionNode->setVisible(false); + } +} + +void UIActionNode::UpdateToFrame(UIActionFrame* frame) +{ + if ( m_actionNode == NULL || frame == NULL ) + { + return; + } + + m_actionNode->setRotation(frame->getRotation()); + m_actionNode->setScaleX(frame->getScaleX()); + m_actionNode->setScaleY(frame->getScaleY()); + m_actionNode->setPosition(frame->getPosition()); + m_actionNode->setOpacity(frame->getOpacity()); + m_actionNode->setColor(frame->getColor()); + +} + +void UIActionNode::RunAction(float fUnitTime, bool bloop) +{ + int frameNum = m_ActionFrameList->count(); + + if ( m_actionNode == NULL || frameNum <= 0 ) + { + return; + } + + CCArray* actionFrame = CCArray::create(); + + for ( int i = 0; i < frameNum; i++ ) + { + float duration; + + UIActionFrame* frame = (UIActionFrame*)m_ActionFrameList->objectAtIndex(i); + + if ( i == 0 ) + { + //duration = frame->getFrameId() * fUnitTime; + duration = 0.01f; + } + else + { + UIActionFrame* frame_pre = (UIActionFrame*)m_ActionFrameList->objectAtIndex(i-1); + duration = (frame->getFrameId() - frame_pre->getFrameId()) * fUnitTime; + } + + CCMoveTo* action_1 = CCMoveTo::create(duration,frame->getPosition()); + CCRotateTo* action_2 = CCRotateTo::create(duration,frame->getRotation()); + CCScaleTo* action_3 = CCScaleTo::create(duration,frame->getScaleX(),frame->getScaleY()); + CCFadeTo* action_4 = CCFadeTo::create(duration,frame->getOpacity()); + CCTintTo* action_5 = CCTintTo::create(duration,frame->getColor().r,frame->getColor().g,frame->getColor().b); + + CCSpawn * actionSpawn = CCSpawn::create(action_1,action_2,action_3,action_4,action_5, NULL); + actionFrame->addObject( actionSpawn ); + } + + if (bloop) + { + CCActionInterval* actionInterval = dynamic_cast(CCSequence::create(actionFrame)); + if (actionInterval) + { + if (m_actionNode) { + if (m_action!=NULL) + { + m_action->release(); + } + m_action = CCRepeatForever::create(actionInterval); + m_action->retain(); + m_actionNode->runAction(m_action); + } + } + } + else + { + if (m_actionNode) { + if (m_action!=NULL) + { + m_action->release(); + } + m_action = CCSequence::create(actionFrame); + m_action->retain(); + m_actionNode->runAction(m_action); + } + } +} + +void UIActionNode::StopAction() +{ + if (m_actionNode) { + m_actionNode->stopAction(m_action); + } +} + +//void UIActionNode::RunToFrameByIndex(int index) +//{ +// int frameNum = m_ActionFrameList->size(); +// +// if ( index < 0 || index >= frameNum ) +// { +// if (m_actionNode != NULL) +// { +// m_actionNode->setVisible(false); +// } +// +// return; +// } +// +// CocoGUIActionFrame* frame = (CocoGUIActionFrame*)m_ActionFrameList->at(index); +// +// RunToFrame(frame); +//} +// +//void UIActionNode::RunToFrame(CocoGUIActionFrame* frame) +//{ +// if ( m_actionNode == NULL || frame == NULL ) +// { +// return; +// } +//} + +NS_CC_EXT_END \ No newline at end of file diff --git a/extensions/CocoStudio/GUI/Action/UIActionNode.h b/extensions/CocoStudio/GUI/Action/UIActionNode.h new file mode 100644 index 0000000000..412e1a5136 --- /dev/null +++ b/extensions/CocoStudio/GUI/Action/UIActionNode.h @@ -0,0 +1,67 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __UIACTIONNODE_H__ +#define __UIACTIONNODE_H__ + +#include "cocos2d.h" +#include "ExtensionMacros.h" +#include "../BaseClasses/UIWidget.h" +#include "UIActionFrame.h" +#include "../../Json/CSContentJsonDictionary.h" + +NS_CC_EXT_BEGIN + +class UIActionNode:public CCObject +{ +protected: + int currentIndex; + CCAction* m_action; + UIWidget* m_actionNode; + //data + CCArray* m_ActionFrameList;/*action frame*/ + CC_SYNTHESIZE(int, m_nActionTag, ActionTag); +public: + UIActionNode(); + virtual ~UIActionNode(); + + void SetActionNode(UIWidget* widget); + + void InsertFrame(int index, UIActionFrame* frame); + void AddFrame(UIActionFrame* frame); + void DeleteFrame(UIActionFrame* frame); + void ClearAllFrame(); + + void UpdateToFrameByIndex(int index); + void UpdateToFrame(UIActionFrame* frame); + + void RunAction(float fUnitTime, bool bloop); + void StopAction(); + void initWithDictionary(cs::JsonDictionary* dic,UIWidget* root); + void releaseBindingWidget(); +}; + +NS_CC_EXT_END + +#endif diff --git a/extensions/CocoStudio/GUI/BaseClasses/UIRootWidget.cpp b/extensions/CocoStudio/GUI/BaseClasses/UIRootWidget.cpp new file mode 100644 index 0000000000..e2b7a69ceb --- /dev/null +++ b/extensions/CocoStudio/GUI/BaseClasses/UIRootWidget.cpp @@ -0,0 +1,59 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "UIRootWidget.h" + +NS_CC_EXT_BEGIN + +UIRootWidget::UIRootWidget() +{ +} + +UIRootWidget::~UIRootWidget() +{ +} + +UIRootWidget* UIRootWidget::create() +{ + UIRootWidget* widget = new UIRootWidget(); + if (widget && widget->init()) + { + widget->autorelease(); + return widget; + } + CC_SAFE_DELETE(widget); + return NULL; +} + +bool UIRootWidget::init() +{ + if (Layout::init()) + { + setSize(Director::getInstance()->getWinSize()); + return true; + } + return false; +} + +NS_CC_EXT_END \ No newline at end of file diff --git a/extensions/CocoStudio/GUI/BaseClasses/UIRootWidget.h b/extensions/CocoStudio/GUI/BaseClasses/UIRootWidget.h new file mode 100644 index 0000000000..59ba41a498 --- /dev/null +++ b/extensions/CocoStudio/GUI/BaseClasses/UIRootWidget.h @@ -0,0 +1,56 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __UIROOTWIDGET_H__ +#define __UIROOTWIDGET_H__ + +#include "../Layouts/Layout.h" + +NS_CC_EXT_BEGIN + +class UIRootWidget : public Layout +{ +public: + /** + * Default constructor + */ + UIRootWidget(); + + /** + * Default destructor + */ + virtual ~UIRootWidget(); + + /** + * Allocates and initializes a widget. + */ + static UIRootWidget* create(); +protected: + //initializes state of widget. + virtual bool init(); +}; + +NS_CC_EXT_END + +#endif /* defined(__CocoGUI__RootWidget__) */ diff --git a/extensions/CocoStudio/GUI/BaseClasses/UIWidget.cpp b/extensions/CocoStudio/GUI/BaseClasses/UIWidget.cpp new file mode 100644 index 0000000000..939792797f --- /dev/null +++ b/extensions/CocoStudio/GUI/BaseClasses/UIWidget.cpp @@ -0,0 +1,1221 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "UIWidget.h" +#include "../System/UILayer.h" +#include "../Layouts/Layout.h" +#include "../System/UIHelper.h" + +NS_CC_EXT_BEGIN + +#define DYNAMIC_CAST_CCBLENDPROTOCOL dynamic_cast(m_pRenderer) + +#define DYNAMIC_CAST_CCRGBAPROTOCOL dynamic_cast(m_pRenderer) + +#define DYNAMIC_CAST_CCNODERGBA dynamic_cast(m_pRenderer) + +UIWidget::UIWidget(): +m_bEnabled(true), +m_bVisible(true), +m_bBright(true), +m_bTouchEnabled(false), +m_bTouchPassedEnabled(false), +m_bFocus(false), +m_nWidgetZOrder(0), +m_anchorPoint(Point(0.5f, 0.5f)), +m_pWidgetParent(NULL), +m_eBrightStyle(BRIGHT_NONE), +m_bUpdateEnabled(false), +m_pRenderer(NULL), +m_touchStartPos(Point::ZERO), +m_touchMovePos(Point::ZERO), +m_touchEndPos(Point::ZERO), +m_pTouchEventListener(NULL), +m_pfnTouchEventSelector(NULL), +m_nWidgetTag(-1), +m_strName("default"), +m_WidgetType(WidgetTypeWidget), +m_nActionTag(0), +m_size(Size::ZERO), +m_customSize(Size::ZERO), +m_pLayoutParameter(NULL), +m_bIgnoreSize(false), +m_children(NULL), +m_bAffectByClipping(false), +m_pScheduler(NULL), +m_eSizeType(SIZE_ABSOLUTE), +m_sizePercent(Point::ZERO), +m_ePositionType(POSITION_ABSOLUTE), +m_positionPercent(Point::ZERO), +m_bIsRunning(false), + +/*temp action*/ +m_pBindingAction(NULL) +{ + +} + +UIWidget::~UIWidget() +{ + releaseResoures(); + setParent(NULL); + CC_SAFE_RELEASE_NULL(m_pLayoutParameter); + CC_SAFE_RELEASE(m_pScheduler); +} + +UIWidget* UIWidget::create() +{ + UIWidget* widget = new UIWidget(); + if (widget && widget->init()) + { + widget->autorelease(); + return widget; + } + CC_SAFE_DELETE(widget); + return NULL; +} + +bool UIWidget::init() +{ + m_children = Array::create(); + m_children->retain(); + initRenderer(); + m_pRenderer->retain(); + m_pRenderer->setZOrder(m_nWidgetZOrder); + RGBAProtocol* renderRGBA = DYNAMIC_CAST_CCRGBAPROTOCOL; + if (renderRGBA) + { + renderRGBA->setCascadeColorEnabled(true); + renderRGBA->setCascadeOpacityEnabled(true); + } + setBright(true); + ignoreContentAdaptWithSize(true); + m_pScheduler = Director::getInstance()->getScheduler(); + CC_SAFE_RETAIN(m_pScheduler); + return true; +} + +void UIWidget::releaseResoures() +{ + setUpdateEnabled(false); + removeAllChildren(); + m_children->release(); + m_pRenderer->removeAllChildrenWithCleanup(true); + m_pRenderer->removeFromParentAndCleanup(true); + m_pRenderer->release(); +} + +void UIWidget::onEnter() +{ + arrayMakeObjectsPerformSelector(m_children, onEnter, UIWidget*); + m_bIsRunning = true; + updateSizeAndPosition(); +} + +void UIWidget::onExit() +{ + m_bIsRunning = false; + arrayMakeObjectsPerformSelector(m_children, onExit, UIWidget*); +} + +bool UIWidget::addChild(UIWidget *child) +{ + if (!child) + { + return false; + } + if (m_children->containsObject(child)) + { + return false; + } + child->setParent(this); + int childrenCount = m_children->data->num; + if (childrenCount <= 0) + { + m_children->addObject(child); + } + else + { + bool seekSucceed = false; + ccArray* arrayChildren = m_children->data; + for (int i=childrenCount-1; i>=0; --i) + { + UIWidget* widget = (UIWidget*)(arrayChildren->arr[i]); + if (child->getZOrder() >= widget->getZOrder()) + { + if (i == childrenCount-1) + { + m_children->addObject(child); + seekSucceed = true; + break; + } + else + { + m_children->insertObject(child, i+1); + seekSucceed = true; + break; + } + } + } + if (!seekSucceed) + { + m_children->insertObject(child,0); + } + } + child->getRenderer()->setZOrder(child->getZOrder()); + m_pRenderer->addChild(child->getRenderer()); + if (m_bIsRunning) + { + child->onEnter(); + } + return true; +} + +bool UIWidget::removeChild(UIWidget *child) +{ + if (!child) + { + return false; + } + if (m_children->containsObject(child)) + { + if (m_bIsRunning) + { + child->onExit(); + } + child->disableUpdate(); + child->setParent(NULL); + m_pRenderer->removeChild(child->getRenderer()); + m_children->removeObject(child); + return true; + } + return false; +} + +void UIWidget::removeFromParent() +{ + if (m_pWidgetParent) + { + m_pWidgetParent->removeChild(this); + } +} + +void UIWidget::removeAllChildren() +{ + if (!m_children || m_children->count() <= 0) + { + return; + } + int times = m_children->data->num; + for (int i=0; igetLastObject()); + removeChild(lastChild); + } +} + +void UIWidget::reorderChild(UIWidget* child) +{ + CC_SAFE_RETAIN(child); + m_children->removeObject(child); + int childrenCount = m_children->data->num; + if (childrenCount <= 0) + { + m_children->addObject(child); + } + else + { + bool seekSucceed = false; + ccArray* arrayChildren = m_children->data; + for (int i=childrenCount-1; i>=0; --i) + { + UIWidget* widget = (UIWidget*)(arrayChildren->arr[i]); + if (child->getZOrder() >= widget->getZOrder()) + { + if (i == childrenCount-1) + { + m_children->addObject(child); + seekSucceed = true; + break; + } + else + { + m_children->insertObject(child, i+1); + seekSucceed = true; + break; + } + } + } + if (!seekSucceed) + { + m_children->insertObject(child,0); + } + } + CC_SAFE_RELEASE(child); +} + +void UIWidget::disableUpdate() +{ + if (m_pScheduler) + { + m_pScheduler->unscheduleUpdateForTarget(this); + } + int childrenCount = m_children->data->num; + ccArray* arrayChildren = m_children->data; + for (int i=0; iarr[i]); + child->disableUpdate(); + } +} + +void UIWidget::setEnabled(bool enabled) +{ + m_bEnabled = enabled; + GUIRenderer* renderer = DYNAMIC_CAST_CCNODERGBA; + if (renderer) + { + renderer->setEnabled(enabled); + } + else + { + dynamic_cast(m_pRenderer)->setEnabled(enabled); + } + ccArray* arrayChildren = m_children->data; + int childrenCount = arrayChildren->num; + for (int i = 0; i < childrenCount; i++) + { + UIWidget* child = dynamic_cast(arrayChildren->arr[i]); + child->setEnabled(enabled); + } +} + +UIWidget* UIWidget::getChildByName(const char *name) +{ + return CCUIHELPER->seekWidgetByName(this, name); +} + +UIWidget* UIWidget::getChildByTag(int tag) +{ + return CCUIHELPER->seekWidgetByTag(this, tag); +} + +Array* UIWidget::getChildren() +{ + return m_children; +} + +void UIWidget::initRenderer() +{ + m_pRenderer = GUIRenderer::create(); +} + +void UIWidget::setSize(const Size &size) +{ + m_customSize = size; + if (m_bIgnoreSize) + { + m_size = getContentSize(); + } + else + { + m_size = size; + } + if (m_bIsRunning) + { + m_sizePercent = (m_pWidgetParent == NULL) ? Point::ZERO : Point(m_customSize.width / m_pWidgetParent->getSize().width, m_customSize.height / m_pWidgetParent->getSize().height); + } + onSizeChanged(); +} + +void UIWidget::setSizePercent(const Point &percent) +{ + m_sizePercent = percent; + if (!m_bIsRunning) + { + return; + } + Size cSize = (m_pWidgetParent == NULL) ? Size::ZERO : Size(m_pWidgetParent->getSize().width * percent.x , m_pWidgetParent->getSize().height * percent.y); + if (m_bIgnoreSize) + { + m_size = getContentSize(); + } + else + { + m_size = cSize; + } + m_customSize = cSize; + onSizeChanged(); +} + +void UIWidget::updateSizeAndPosition() +{ + switch (m_eSizeType) + { + case SIZE_ABSOLUTE: + if (m_bIgnoreSize) + { + m_size = getContentSize(); + } + else + { + m_size = m_customSize; + } + m_sizePercent = (m_pWidgetParent == NULL) ? Point::ZERO : Point(m_customSize.width / m_pWidgetParent->getSize().width, m_customSize.height / m_pWidgetParent->getSize().height); + break; + case SIZE_PERCENT: + { + Size cSize = (m_pWidgetParent == NULL) ? Size::ZERO : Size(m_pWidgetParent->getSize().width * m_sizePercent.x , m_pWidgetParent->getSize().height * m_sizePercent.y); + if (m_bIgnoreSize) + { + m_size = getContentSize(); + } + else + { + m_size = cSize; + } + m_customSize = cSize; + } + break; + default: + break; + } + onSizeChanged(); + Point absPos = getPosition(); + switch (m_ePositionType) + { + case POSITION_ABSOLUTE: + m_positionPercent = (m_pWidgetParent == NULL) ? Point::ZERO : Point(absPos.x / m_pWidgetParent->getSize().width, absPos.y / m_pWidgetParent->getSize().height); + break; + case POSITION_PERCENT: + { + Size parentSize = m_pWidgetParent->getSize(); + absPos = Point(parentSize.width * m_positionPercent.x, parentSize.height * m_positionPercent.y); + } + break; + default: + break; + } + m_pRenderer->setPosition(absPos); +} + +void UIWidget::setSizeType(SizeType type) +{ + m_eSizeType = type; +} + +SizeType UIWidget::getSizeType() const +{ + return m_eSizeType; +} + +void UIWidget::ignoreContentAdaptWithSize(bool ignore) +{ + m_bIgnoreSize = ignore; + if (m_bIgnoreSize) + { + Size s = getContentSize(); + m_size = s; + } + else + { + m_size = m_customSize; + } + onSizeChanged(); +} + +bool UIWidget::isIgnoreContentAdaptWithSize() const +{ + return m_bIgnoreSize; +} + +const Size& UIWidget::getSize() const +{ + return m_size; +} + +const Point& UIWidget::getSizePercent() const +{ + return m_sizePercent; +} + +Point UIWidget::getWorldPosition() +{ + return m_pRenderer->convertToWorldSpace(Point::ZERO); +} + +Point UIWidget::convertToWorldSpace(const Point& pt) +{ + return m_pRenderer->convertToWorldSpace(pt); +} + +Node* UIWidget::getVirtualRenderer() +{ + return m_pRenderer; +} + +void UIWidget::onSizeChanged() +{ + +} + +const Size& UIWidget::getContentSize() const +{ + return m_size; +} + +void UIWidget::setZOrder(int z) +{ + m_nWidgetZOrder = z; + m_pRenderer->setZOrder(z); + if (m_pWidgetParent) + { + m_pWidgetParent->reorderChild(this); + } +} + +int UIWidget::getZOrder() +{ + return m_nWidgetZOrder; +} + +void UIWidget::setTouchEnabled(bool enable) +{ + m_bTouchEnabled = enable; +} + +bool UIWidget::isTouchEnabled() const +{ + return m_bTouchEnabled; +} + +void UIWidget::setUpdateEnabled(bool enable) +{ + m_bUpdateEnabled = enable; + if (enable) + { + if (m_pScheduler) + { + m_pScheduler->scheduleUpdateForTarget(this, 0, false); + } + } + else + { + if (m_pScheduler) + { + m_pScheduler->unscheduleUpdateForTarget(this); + } + } +} + +bool UIWidget::isUpdateEnabled() +{ + return m_bUpdateEnabled; +} + +bool UIWidget::isFocused() const +{ + return m_bFocus; +} + +void UIWidget::setFocused(bool fucos) +{ + if (fucos == m_bFocus) + { + return; + } + m_bFocus = fucos; + if (m_bBright) + { + if (m_bFocus) + { + setBrightStyle(BRIGHT_HIGHLIGHT); + } + else + { + setBrightStyle(BRIGHT_NORMAL); + } + } + else + { + onPressStateChangedToDisabled(); + } +} + +void UIWidget::setBright(bool bright) +{ + m_bBright = bright; + if (m_bBright) + { + m_eBrightStyle = BRIGHT_NONE; + setBrightStyle(BRIGHT_NORMAL); + } + else + { + onPressStateChangedToDisabled(); + } +} + +void UIWidget::setBrightStyle(BrightStyle style) +{ + if (m_eBrightStyle == style) + { + return; + } + m_eBrightStyle = style; + switch (m_eBrightStyle) + { + case BRIGHT_NORMAL: + onPressStateChangedToNormal(); + break; + case BRIGHT_HIGHLIGHT: + onPressStateChangedToPressed(); + break; + default: + break; + } +} + +void UIWidget::onPressStateChangedToNormal() +{ + +} + +void UIWidget::onPressStateChangedToPressed() +{ + +} + +void UIWidget::onPressStateChangedToDisabled() +{ + +} + +void UIWidget::didNotSelectSelf() +{ + +} + +bool UIWidget::onTouchBegan(const Point &touchPoint) +{ + setFocused(true); + m_touchStartPos.x = touchPoint.x; + m_touchStartPos.y = touchPoint.y; + if (m_pWidgetParent) + { + m_pWidgetParent->checkChildInfo(0,this,touchPoint); + } + pushDownEvent(); + return m_bTouchPassedEnabled; +} + +void UIWidget::onTouchMoved(const Point &touchPoint) +{ + m_touchMovePos.x = touchPoint.x; + m_touchMovePos.y = touchPoint.y; + setFocused(hitTest(touchPoint)); + if (m_pWidgetParent) + { + m_pWidgetParent->checkChildInfo(1,this,touchPoint); + } + moveEvent(); +} + +void UIWidget::onTouchEnded(const Point &touchPoint) +{ + m_touchEndPos.x = touchPoint.x; + m_touchEndPos.y = touchPoint.y; + bool focus = m_bFocus; + setFocused(false); + if (m_pWidgetParent) + { + m_pWidgetParent->checkChildInfo(2,this,touchPoint); + } + if (focus) + { + releaseUpEvent(); + } + else + { + cancelUpEvent(); + } +} + +void UIWidget::onTouchCancelled(const Point &touchPoint) +{ + setFocused(false); + cancelUpEvent(); +} + +void UIWidget::onTouchLongClicked(const Point &touchPoint) +{ + longClickEvent(); +} + +void UIWidget::pushDownEvent() +{ + if (m_pTouchEventListener && m_pfnTouchEventSelector) + { + (m_pTouchEventListener->*m_pfnTouchEventSelector)(this,TOUCH_EVENT_BEGAN); + } +} + +void UIWidget::moveEvent() +{ + if (m_pTouchEventListener && m_pfnTouchEventSelector) + { + (m_pTouchEventListener->*m_pfnTouchEventSelector)(this,TOUCH_EVENT_MOVED); + } +} + +void UIWidget::releaseUpEvent() +{ + if (m_pTouchEventListener && m_pfnTouchEventSelector) + { + (m_pTouchEventListener->*m_pfnTouchEventSelector)(this,TOUCH_EVENT_ENDED); + } +} + +void UIWidget::cancelUpEvent() +{ + if (m_pTouchEventListener && m_pfnTouchEventSelector) + { + (m_pTouchEventListener->*m_pfnTouchEventSelector)(this,TOUCH_EVENT_CANCELED); + } +} + +void UIWidget::longClickEvent() +{ + +} + +void UIWidget::addTouchEventListener(Object *target, SEL_TouchEvent selector) +{ + m_pTouchEventListener = target; + m_pfnTouchEventSelector = selector; +} + +Node* UIWidget::getRenderer() +{ + return m_pRenderer; +} + +void UIWidget::addRenderer(Node* renderer, int zOrder) +{ + m_pRenderer->addChild(renderer, zOrder); +} + +void UIWidget::removeRenderer(Node* renderer, bool cleanup) +{ + m_pRenderer->removeChild(renderer,cleanup); +} + +bool UIWidget::hitTest(const Point &pt) +{ + Point nsp = m_pRenderer->convertToNodeSpace(pt); + Rect bb = Rect(-m_size.width * m_anchorPoint.x, -m_size.height * m_anchorPoint.y, m_size.width, m_size.height); + if (nsp.x >= bb.origin.x && nsp.x <= bb.origin.x + bb.size.width && nsp.y >= bb.origin.y && nsp.y <= bb.origin.y + bb.size.height) + { + return true; + } + return false; +} + +bool UIWidget::clippingParentAreaContainPoint(const Point &pt) +{ + m_bAffectByClipping = false; + UIWidget* parent = getParent(); + UIWidget* clippingParent = NULL; + while (parent) + { + Layout* layoutParent = dynamic_cast(parent); + if (layoutParent) + { + if (layoutParent->isClippingEnabled()) + { + m_bAffectByClipping = true; + clippingParent = layoutParent; + break; + } + } + parent = parent->getParent(); + } + + if (!m_bAffectByClipping) + { + return true; + } + + + if (clippingParent) + { + bool bRet = false; + if (clippingParent->hitTest(pt)) + { + bRet = true; + } + if (bRet) + { + return clippingParent->clippingParentAreaContainPoint(pt); + } + return false; + } + return true; +} + +void UIWidget::checkChildInfo(int handleState, UIWidget *sender, const Point &touchPoint) +{ + if (m_pWidgetParent) + { + m_pWidgetParent->checkChildInfo(handleState,sender,touchPoint); + } +} + +void UIWidget::setPosition(const Point &pos) +{ + if (m_bIsRunning) + { + m_positionPercent = (m_pWidgetParent == NULL) ? Point::ZERO : Point(pos.x / m_pWidgetParent->getSize().width, pos.y / m_pWidgetParent->getSize().height); + } + m_pRenderer->setPosition(pos); +} + +void UIWidget::setPositionPercent(const Point &percent) +{ + m_positionPercent = percent; + if (m_bIsRunning) + { + Size parentSize = m_pWidgetParent->getSize(); + Point absPos = Point(parentSize.width * m_positionPercent.x, parentSize.height * m_positionPercent.y); + m_pRenderer->setPosition(absPos); + } +} + +void UIWidget::setAnchorPoint(const Point &pt) +{ + m_anchorPoint = pt; + m_pRenderer->setAnchorPoint(pt); +} + +void UIWidget::updateAnchorPoint() +{ + setAnchorPoint(m_anchorPoint); +} + +const Point& UIWidget::getPosition() +{ + return m_pRenderer->getPosition(); +} + +const Point& UIWidget::getPositionPercent() +{ + return m_positionPercent; +} + +void UIWidget::setPositionType(PositionType type) +{ + m_ePositionType = type; +} + +PositionType UIWidget::getPositionType() const +{ + return m_ePositionType; +} + +const Point& UIWidget::getAnchorPoint() +{ + return m_anchorPoint; +} + +void UIWidget::setScale(float scale) +{ + m_pRenderer->setScale(scale); +} + +float UIWidget::getScale() +{ + return m_pRenderer->getScale(); +} + +void UIWidget::setScaleX(float scaleX) +{ + m_pRenderer->setScaleX(scaleX); +} + +float UIWidget::getScaleX() +{ + return m_pRenderer->getScaleX(); +} + +void UIWidget::setScaleY(float scaleY) +{ + m_pRenderer->setScaleY(scaleY); +} + +float UIWidget::getScaleY() +{ + return m_pRenderer->getScaleY(); +} + +void UIWidget::setRotation(float rotation) +{ + m_pRenderer->setRotation(rotation); +} + +float UIWidget::getRotation() +{ + return m_pRenderer->getRotation(); +} + +void UIWidget::setRotationX(float rotationX) +{ + m_pRenderer->setRotationX(rotationX); +} + +float UIWidget::getRotationX() +{ + return m_pRenderer->getRotationX(); +} + +void UIWidget::setRotationY(float rotationY) +{ + m_pRenderer->setRotationY(rotationY); +} + +float UIWidget::getRotationY() +{ + return m_pRenderer->getRotationY(); +} + +void UIWidget::setVisible(bool visible) +{ + m_bVisible = visible; + m_pRenderer->setVisible(visible); +} + +bool UIWidget::isVisible() const +{ + return m_bVisible; +} + +bool UIWidget::isBright() const +{ + return m_bBright; +} + +bool UIWidget::isEnabled() const +{ + return m_bEnabled; +} + +float UIWidget::getLeftInParent() +{ + float leftPos = 0.0f; + switch (m_WidgetType) + { + case WidgetTypeWidget: + leftPos = getPosition().x - getAnchorPoint().x * m_size.width; + break; + case WidgetTypeContainer: + leftPos = getPosition().x; + break; + default: + break; + } + return leftPos; +} + +float UIWidget::getBottomInParent() +{ + float bottomPos = 0.0f; + switch (m_WidgetType) + { + case WidgetTypeWidget: + bottomPos = getPosition().y - getAnchorPoint().y * m_size.height; + break; + case WidgetTypeContainer: + bottomPos = getPosition().y; + break; + default: + break; + } + return bottomPos; +} + +float UIWidget::getRightInParent() +{ + return getLeftInParent() + m_size.width; +} + +float UIWidget::getTopInParent() +{ + return getBottomInParent() + m_size.height; +} + +UIWidget* UIWidget::getParent() +{ + return m_pWidgetParent; +} + +void UIWidget::setParent(UIWidget* parent) +{ + m_pWidgetParent = parent; +} + +Action* UIWidget::runAction(Action *action) +{ + return m_pRenderer->runAction(action); +} + +void UIWidget::setActionManager(ActionManager *actionManager) +{ + m_pRenderer->setActionManager(actionManager); +} + +ActionManager* UIWidget::getActionManager() +{ + return m_pRenderer->getActionManager(); +} + +void UIWidget::stopAllActions() +{ + m_pRenderer->stopAllActions(); +} + +void UIWidget::stopAction(Action *action) +{ + m_pRenderer->stopAction(action); +} + +void UIWidget::stopActionByTag(int tag) +{ + m_pRenderer->stopActionByTag(tag); +} + +Action* UIWidget::getActionByTag(int tag) +{ + return m_pRenderer->getActionByTag(tag); +} + +void UIWidget::setColor(const Color3B &color) +{ + RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; + if (rgbap) + { + rgbap->setColor(color); + } +} + +const Color3B& UIWidget::getColor() +{ + RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; + if (rgbap) + { + return rgbap->getColor(); + } + return Color3B::WHITE; +} + +void UIWidget::setOpacity(int opacity) +{ + RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; + if (rgbap) + { + rgbap->setOpacity(opacity); + } +} + +int UIWidget::getOpacity() +{ + RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; + if (rgbap) + { + return rgbap->getOpacity(); + } + return 255; +} + +bool UIWidget::isCascadeOpacityEnabled() +{ + RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; + if (rgbap) + { + return rgbap->isCascadeOpacityEnabled(); + } + return false; +} + +void UIWidget::setCascadeOpacityEnabled(bool cascadeOpacityEnabled) +{ + RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; + if (rgbap) + { + rgbap->setCascadeOpacityEnabled(cascadeOpacityEnabled); + } +} + +bool UIWidget::isCascadeColorEnabled() +{ + RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; + if (rgbap) + { + return rgbap->isCascadeColorEnabled(); + } + return false; +} + +void UIWidget::setCascadeColorEnabled(bool cascadeColorEnabled) +{ + RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; + if (rgbap) + { + rgbap->setCascadeColorEnabled(cascadeColorEnabled); + } +} + +void UIWidget::setBlendFunc(BlendFunc blendFunc) +{ + BlendProtocol * blendNode = DYNAMIC_CAST_CCBLENDPROTOCOL; + if (blendNode) + { + blendNode->setBlendFunc(blendFunc); + } +} + +const Point& UIWidget::getTouchStartPos() +{ + return m_touchStartPos; +} + +const Point& UIWidget::getTouchMovePos() +{ + return m_touchMovePos; +} + +const Point& UIWidget::getTouchEndPos() +{ + return m_touchEndPos; +} + +void UIWidget::setTag(int tag) +{ + m_nWidgetTag = tag; +} + +int UIWidget::getTag() const +{ + return m_nWidgetTag; +} + +void UIWidget::setName(const char* name) +{ + m_strName = name; +} + +const char* UIWidget::getName() const +{ + return m_strName.c_str(); +} + +WidgetType UIWidget::getWidgetType() const +{ + return m_WidgetType; +} + +void UIWidget::setLayoutParameter(LayoutParameter *parameter) +{ + if (m_pLayoutParameter) + { + CC_SAFE_RELEASE_NULL(m_pLayoutParameter); + } + m_pLayoutParameter = parameter; + CC_SAFE_RETAIN(m_pLayoutParameter); +} + +LayoutParameter* UIWidget::getLayoutParameter() +{ + return m_pLayoutParameter; +} + +/*temp action*/ +void UIWidget::setActionTag(int tag) +{ + m_nActionTag = tag; +} + +int UIWidget::getActionTag() +{ + return m_nActionTag; +} + +void UIWidget::setBindingAction(UIActionNode *actionNode) +{ + m_pBindingAction = actionNode; +} + +GUIRenderer::GUIRenderer(): +m_bEnabled(true) +{ + +} + +GUIRenderer::~GUIRenderer() +{ + +} + +GUIRenderer* GUIRenderer::create() +{ + GUIRenderer* renderer = new GUIRenderer(); + if (renderer && renderer->init()) + { + renderer->autorelease(); + } + else + { + CC_SAFE_DELETE(renderer); + } + return renderer; +} + +void GUIRenderer::setEnabled(bool enabled) +{ + m_bEnabled = enabled; +} + +bool GUIRenderer::isEnabled() const +{ + return m_bEnabled; +} + +void GUIRenderer::visit() +{ + if (!m_bEnabled) + { + return; + } + NodeRGBA::visit(); +} + +NS_CC_EXT_END diff --git a/extensions/CocoStudio/GUI/BaseClasses/UIWidget.h b/extensions/CocoStudio/GUI/BaseClasses/UIWidget.h new file mode 100644 index 0000000000..71e826e1c3 --- /dev/null +++ b/extensions/CocoStudio/GUI/BaseClasses/UIWidget.h @@ -0,0 +1,973 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __UIWIDGET_H__ +#define __UIWIDGET_H__ + +#include "cocos2d.h" +#include "ExtensionMacros.h" +#include "../Layouts/UILayoutDefine.h" +#include "../Layouts/LayoutParameter.h" +NS_CC_EXT_BEGIN + + +typedef enum +{ + BRIGHT_NONE = -1, + BRIGHT_NORMAL, + BRIGHT_HIGHLIGHT +}BrightStyle; + +typedef enum +{ + WidgetTypeWidget, //control + WidgetTypeContainer //container +}WidgetType; + +typedef enum +{ + UI_TEX_TYPE_LOCAL, + UI_TEX_TYPE_PLIST +}TextureResType; + +typedef enum +{ + TOUCH_EVENT_BEGAN, + TOUCH_EVENT_MOVED, + TOUCH_EVENT_ENDED, + TOUCH_EVENT_CANCELED +}TouchEventType; + +typedef enum +{ + SIZE_ABSOLUTE, + SIZE_PERCENT +}SizeType; + +typedef enum +{ + POSITION_ABSOLUTE, + POSITION_PERCENT +}PositionType; + +typedef void (Object::*SEL_TouchEvent)(Object*,TouchEventType); +#define toucheventselector(_SELECTOR) (cocos2d::extension::SEL_TouchEvent)(&_SELECTOR) + +//class UILayer; +/*temp action*/ +class UIActionNode; + +class UIWidget : public Object +{ +public: + /** + * Default constructor + */ + UIWidget(void); + + /** + * Default destructor + */ + virtual ~UIWidget(); + + /** + * Allocates and initializes a widget. + */ + static UIWidget* create(); + + /** + * Sets whether the widget is enabled + * + * Highest control of widget. + * The default value is true, a widget is default to enabled + * + * @param enabled true if the widget is enabled, widget may be touched and visible, false if the widget is disabled, widget cannot be touched and hidden. + */ + virtual void setEnabled(bool enabled); + + /** + * Determines if the widget is enabled + * + * @return true if the widget is enabled, false if the widget is disabled. + */ + bool isEnabled() const; + + /** + * Sets whether the widget is visible + * + * The default value is true, a widget is default to visible + * + * @param visible true if the widget is visible, false if the widget is hidden. + */ + void setVisible(bool visible); + + /** + * Determines if the widget is visible + * + * @return true if the widget is visible, false if the widget is hidden. + */ + bool isVisible() const; + + /** + * Sets whether the widget is bright + * + * The default value is true, a widget is default to bright + * + * @param visible true if the widget is bright, false if the widget is dark. + */ + void setBright(bool bright); + + /** + * Determines if the widget is bright + * + * @return true if the widget is bright, false if the widget is dark. + */ + bool isBright() const; + + /** + * Sets whether the widget is touch enabled + * + * The default value is false, a widget is default to touch disabled + * + * @param visible true if the widget is touch enabled, false if the widget is touch disabled. + */ + virtual void setTouchEnabled(bool enabled); + + /** + * To set the bright style of widget. + * + * @see BrightStyle + * + * @param style BRIGHT_NORMAL the widget is normal state, BRIGHT_HIGHLIGHT the widget is height light state. + */ + void setBrightStyle(BrightStyle style); + + /** + * Determines if the widget is touch enabled + * + * @return true if the widget is touch enabled, false if the widget is touch disabled. + */ + bool isTouchEnabled() const; + + /** + * Determines if the widget is on focused + * + * @return true if the widget is on focused, false if the widget is not on focused. + */ + bool isFocused() const; + + /** + * Sets whether the widget is on focused + * + * The default value is false, a widget is default to not on focused + * + * @param fucosed true if the widget is on focused, false if the widget is not on focused. + */ + void setFocused(bool fucosed); + + /** + * Sets the Z order which stands for the drawing order, and reorder this widget in its parent's children array. + * + * The Z order of widget is relative to its "brothers": children of the same parent. + * It's nothing to do with OpenGL's z vertex. This one only affects the draw order of widgets in cocos2d. + * The larger number it is, the later this widget will be drawn in each message loop. + * Please refer to setVertexZ(float) for the difference. + * + * @param nZOrder Z order of this widget. + */ + void setZOrder(int z); + + /** + * Gets the Z order of this widget. + * + * @see setZOrder(int) + * + * @return The Z order. + */ + int getZOrder(); + + /** + * Gets the left boundary position of this widget. + * + * @return The left boundary position of this widget. + */ + float getLeftInParent(); + + /** + * Gets the bottom boundary position of this widget. + * + * @return The bottom boundary position of this widget. + */ + float getBottomInParent(); + + /** + * Gets the right boundary position of this widget. + * + * @return The right boundary position of this widget. + */ + float getRightInParent(); + + /** + * Gets the top boundary position of this widget. + * + * @return The top boundary position of this widget. + */ + float getTopInParent(); + + /** + * Adds a child to the container. + * + * @param child A child widget + */ + virtual bool addChild(UIWidget* child); + + /** + * Removes a child from the container with a cleanup + * + * @param child The child widget which will be removed. + * + * @return the result of removing, succeeded or failed. + */ + virtual bool removeChild(UIWidget* child); + + /** + * Removes this widget itself from its parent widget. + * If the widget orphan, then it will destroy itself. + */ + virtual void removeFromParent(); + + /** + * Removes all children from the container, and do a cleanup to all running actions depending on the cleanup parameter. + */ + virtual void removeAllChildren(); + + /** + * Unschedules the "update" method. + */ + void disableUpdate(); + + /** + * Reorders a child according to a new z value. + * + * @param child An already added child node. It MUST be already added. + * @param zOrder Z order for drawing priority and touched priority. Please refer to setZOrder(int) + */ + virtual void reorderChild(UIWidget* child); + + /** + * Gets a child from the container with its name + * + * @param name An key to find the child widget. + * + * @return a UIWidget object whose name equals to the input parameter + */ + UIWidget* getChildByName(const char* name); + + /** + * Gets a child from the container with its tag + * + * @param tag An identifier to find the child widget. + * + * @return a UIWidget object whose tag equals to the input parameter + */ + UIWidget* getChildByTag(int tag); + + /** + * Return an array of children + * + * Composing a "tree" structure is a very important feature of UIWidget + * + * @return An array of children + */ + virtual Array* getChildren(); + + /** + * Gets the renderer of widget + * + * renderer is a CCNode, it's for drawing + * + * @return a CCNode object + */ + Node* getRenderer(); + + /** + * Add a CCNode for rendering. + * + * renderer is a CCNode, it's for drawing + * + * @param renderer A render node + * + * @param zOrder Z order for drawing priority. Please refer to CCNode::setZOrder(int) + */ + void addRenderer(Node* renderer, int zOrder); + + /** + * Remove a CCNode from widget. + * + * renderer is a CCNode, it's for drawing + * + * @param renderer A render node which needs to be removed + * + * @param cleanup true if all running actions and callbacks on the render node will be cleanup, false otherwise. + */ + void removeRenderer(Node* renderer, bool cleanup); + + /** + * Sets the parent widget + * + * @param parent A pointer to the parnet widget + */ + void setParent(UIWidget* parent); + + /** + * Returns a pointer to the parent widget + * + * @see setParent(UIWidget*) + * + * @returns A pointer to the parnet widget + */ + UIWidget* getParent(); + + /** + * Sets the touch event target/selector of the menu item + */ + void addTouchEventListener(Object* target,SEL_TouchEvent selector); + + + //cocos2d property + + /** + * Changes the position (x,y) of the widget in OpenGL coordinates + * + * Usually we use ccp(x,y) to compose Point object. + * The original point (0,0) is at the left-bottom corner of screen. + * + * @param position The position (x,y) of the widget in OpenGL coordinates + */ + void setPosition(const Point &pos); + + /** + * Changes the position (x,y) of the widget in OpenGL coordinates + * + * Usually we use ccp(x,y) to compose Point object. + * The original point (0,0) is at the left-bottom corner of screen. + * + * @param percent The percent (x,y) of the widget in OpenGL coordinates + */ + void setPositionPercent(const Point &percent); + + /** + * Gets the position (x,y) of the widget in OpenGL coordinates + * + * @see setPosition(const Point&) + * + * @return The position (x,y) of the widget in OpenGL coordinates + */ + const Point& getPosition(); + + /** + * Gets the percent (x,y) of the widget in OpenGL coordinates + * + * @see setPosition(const Point&) + * + * @return The percent (x,y) of the widget in OpenGL coordinates + */ + const Point& getPositionPercent(); + + /** + * Changes the position type of the widget + * + * @see PositionType + * + * @param type the position type of widget + */ + void setPositionType(PositionType type); + + /** + * Gets the position type of the widget + * + * @see PositionType + * + * @return type the position type of widget + */ + PositionType getPositionType() const; + + /** + * Sets the anchor point in percent. + * + * anchorPoint is the point around which all transformations and positioning manipulations take place. + * It's like a pin in the widget where it is "attached" to its parent. + * The anchorPoint is normalized, like a percentage. (0,0) means the bottom-left corner and (1,1) means the top-right corner. + * But you can use values higher than (1,1) and lower than (0,0) too. + * The default anchorPoint is (0.5,0.5), so it starts in the center of the widget. + * + * @param anchorPoint The anchor point of widget. + */ + virtual void setAnchorPoint(const Point &pt); + + /** + * Returns the anchor point in percent. + * + * @see setAnchorPoint(const Point&) + * + * @return The anchor point of widget. + */ + const Point& getAnchorPoint(); + + /** + * Changes both X and Y scale factor of the widget. + * + * 1.0 is the default scale factor. It modifies the X and Y scale at the same time. + * + * @param scale The scale factor for both X and Y axis. + */ + virtual void setScale(float fScale); + + /** + * Gets the scale factor of the widget, when X and Y have the same scale factor. + * + * @warning Assert when m_fScaleX != m_fScaleY. + * @see setScale(float) + * + * @return The scale factor of the widget. + */ + float getScale(); + + /** + * Changes the scale factor on X axis of this widget + * + * The deafult value is 1.0 if you haven't changed it before + * + * @param fScaleX The scale factor on X axis. + */ + virtual void setScaleX(float fScaleX); + + /** + * Returns the scale factor on X axis of this widget + * + * @see setScaleX(float) + * + * @return The scale factor on X axis. + */ + float getScaleX(); + + /** + * Changes the scale factor on Y axis of this widget + * + * The Default value is 1.0 if you haven't changed it before. + * + * @param fScaleY The scale factor on Y axis. + */ + virtual void setScaleY(float fScaleY); + + /** + * Returns the scale factor on Y axis of this widget + * + * @see setScaleY(float) + * + * @return The scale factor on Y axis. + */ + float getScaleY(); + + /** + * Sets the rotation (angle) of the widget in degrees. + * + * 0 is the default rotation angle. + * Positive values rotate widget clockwise, and negative values for anti-clockwise. + * + * @param fRotation The roration of the widget in degrees. + */ + void setRotation(float rotation); + + /** + * Returns the rotation of the widget in degrees. + * + * @see setRotation(float) + * + * @return The rotation of the widget in degrees. + */ + float getRotation(); + + /** + * Sets the X rotation (angle) of the widget in degrees which performs a horizontal rotational skew. + * + * 0 is the default rotation angle. + * Positive values rotate widget clockwise, and negative values for anti-clockwise. + * + * @param fRotationX The X rotation in degrees which performs a horizontal rotational skew. + */ + void setRotationX(float rotationX); + + /** + * Gets the X rotation (angle) of the widget in degrees which performs a horizontal rotation skew. + * + * @see setRotationX(float) + * + * @return The X rotation in degrees. + */ + float getRotationX(); + + /** + * Sets the Y rotation (angle) of the widget in degrees which performs a vertical rotational skew. + * + * 0 is the default rotation angle. + * Positive values rotate widget clockwise, and negative values for anti-clockwise. + * + * @param fRotationY The Y rotation in degrees. + */ + void setRotationY(float rotationY); + + /** + * Gets the Y rotation (angle) of the widget in degrees which performs a vertical rotational skew. + * + * @see setRotationY(float) + * + * @return The Y rotation in degrees. + */ + float getRotationY(); + + /** + * Sets whether the widget should be flipped horizontally or not. + * + * @param bFlipX true if the widget should be flipped horizaontally, false otherwise. + */ + virtual void setFlipX(bool flipX){}; + + /** + * Returns the flag which indicates whether the widget is flipped horizontally or not. + * + * It only flips the texture of the widget, and not the texture of the widget's children. + * Also, flipping the texture doesn't alter the anchorPoint. + * If you want to flip the anchorPoint too, and/or to flip the children too use: + * widget->setScaleX(sprite->getScaleX() * -1); + * + * @return true if the widget is flipped horizaontally, false otherwise. + */ + virtual bool isFlipX(){return false;}; + + /** + * Sets whether the widget should be flipped vertically or not. + * + * @param bFlipY true if the widget should be flipped vertically, flase otherwise. + */ + virtual void setFlipY(bool flipY){}; + + /** + * Return the flag which indicates whether the widget is flipped vertically or not. + * + * It only flips the texture of the widget, and not the texture of the widget's children. + * Also, flipping the texture doesn't alter the anchorPoint. + * If you want to flip the anchorPoint too, and/or to flip the children too use: + * widget->setScaleY(widget->getScaleY() * -1); + * + * @return true if the widget is flipped vertically, flase otherwise. + */ + virtual bool isFlipY(){return false;}; + + /** + * Sets color to widget + * + * It default change the color of widget's children. + * + * @param color + */ + virtual void setColor(const Color3B &color); + + /** + * Gets color of widget + * + * @return color + */ + virtual const Color3B& getColor(); + + /** + * Sets opacity to widget + * + * It default change the opacity of widget's children. + * + * @param color + */ + virtual void setOpacity(int opacity); + + /** + * Gets opacity of widget + * + * @return opacity + */ + virtual int getOpacity(); + virtual bool isCascadeOpacityEnabled(); + virtual void setCascadeOpacityEnabled(bool cascadeOpacityEnabled); + virtual bool isCascadeColorEnabled(); + virtual void setCascadeColorEnabled(bool cascadeColorEnabled); + void setBlendFunc(BlendFunc blendFunc); + + //cocos action + virtual void setActionManager(ActionManager* actionManager); + virtual ActionManager* getActionManager(); + Action* runAction(Action* action); + void stopAllActions(void); + void stopAction(Action* action); + void stopActionByTag(int tag); + Action* getActionByTag(int tag); + + /** + * A call back function when widget lost of focus. + */ + void didNotSelectSelf(); + + /* + * Checks a point if in parent's area. + * + * @param point + * + * @return true if the point is in parent's area, flase otherwise. + */ + bool clippingParentAreaContainPoint(const Point &pt); + + /* + * Sends the touch event to widget's parent + */ + virtual void checkChildInfo(int handleState,UIWidget* sender,const Point &touchPoint); + + /* + * Gets the touch began point of widget when widget is selected. + * + * @return the touch began point. + */ + const Point& getTouchStartPos(); + + /* + * Gets the touch move point of widget when widget is selected. + * + * @return the touch move point. + */ + const Point& getTouchMovePos(); + + /* + * Gets the touch end point of widget when widget is selected. + * + * @return the touch end point. + */ + const Point& getTouchEndPos(); + + /** + * Changes the tag that is used to identify the widget easily. + * + * @param A interger that indentifies the widget. + */ + void setTag(int tag); + + /** + * Returns a tag that is used to identify the widget easily. + * + * You can set tags to widget then identify them easily. + * + * @return A interger that identifies the widget. + */ + int getTag() const; + + /** + * Changes the name that is used to identify the widget easily. + * + * @param A const char* that indentifies the widget. + */ + void setName(const char* name); + + /** + * Returns a name that is used to identify the widget easily. + * + * You can set tags to widget then identify them easily. + * + * @return A const char* that identifies the widget. + */ + const char* getName() const; + + /** + * Returns a type that is widget's type + * + * @see WidgetType + * + * @return A WidgetType + */ + WidgetType getWidgetType() const; + + /** + * Changes the size that is widget's size + * + * @param size that is widget's size + */ + virtual void setSize(const Size &size); + + /** + * Changes the percent that is widget's percent size + * + * @param percent that is widget's percent size + */ + virtual void setSizePercent(const Point &percent); + + /** + * Changes the size type of widget. + * + * @see SizeType + * + * @param type that is widget's size type + */ + void setSizeType(SizeType type); + + /** + * Gets the size type of widget. + * + * @see SizeType + * + * @param type that is widget's size type + */ + SizeType getSizeType() const; + + /** + * Returns size of widget + * + * @return size + */ + const Size& getSize() const; + + /** + * Returns size percent of widget + * + * @return size percent + */ + const Point& getSizePercent() const; + + /** + * Checks a point if is in widget's space + * + * @param point + * + * @return true if the point is in widget's space, flase otherwise. + */ + virtual bool hitTest(const Point &pt); + + /** + * A call back function called when widget is selected, and on touch began. + * + * @param touch point + * + * @return true if the event should be pass to parent, flase otherwise. + */ + virtual bool onTouchBegan(const Point &touchPoint); + + /** + * A call back function called when widget is selected, and on touch moved. + * + * @param touch point + */ + virtual void onTouchMoved(const Point &touchPoint); + + /** + * A call back function called when widget is selected, and on touch ended. + * + * @param touch point + */ + virtual void onTouchEnded(const Point &touchPoint); + + /** + * A call back function called when widget is selected, and on touch canceled. + * + * @param touch point + */ + virtual void onTouchCancelled(const Point &touchPoint); + + /** + * A call back function called when widget is selected, and on touch long clicked. + * + * @param touch point + */ + virtual void onTouchLongClicked(const Point &touchPoint); + + /** + * Sets a LayoutParameter to widget. + * + * @see LayoutParameter + * + * @param LayoutParameter pointer + */ + void setLayoutParameter(LayoutParameter* parameter); + + /** + * Gets LayoutParameter of widget. + * + * @see LayoutParameter + */ + LayoutParameter* getLayoutParameter(); + + /** + * Ignore the widget size + * + * @param ignore, true that widget will ignore it's size, use texture size, false otherwise. Default value is true. + */ + virtual void ignoreContentAdaptWithSize(bool ignore); + + /** + * Gets the widget if is ignore it's size. + * + * @param ignore, true that widget will ignore it's size, use texture size, false otherwise. Default value is true. + */ + bool isIgnoreContentAdaptWithSize() const; + + /** + * Gets world position of widget. + * + * @return world position of widget. + */ + Point getWorldPosition(); + + /** + * Converts a Point to world space coordinates. The result is in Points. + */ + Point convertToWorldSpace(const Point& pt); + + /** + * Gets the Virtual Renderer of widget. + * + * For example, a button's Virtual Renderer is it's texture renderer. + * + * @return CCNode pointer. + */ + virtual Node* getVirtualRenderer(); + + /** + * Schedules the "update" method. + */ + void setUpdateEnabled(bool enable); + + /** + * is the "update" method scheduled. + */ + bool isUpdateEnabled(); + + /** + * Gets the content size of widget. + * + * Content size is widget's texture size. + */ + virtual const Size& getContentSize() const; + + virtual void onEnter(); + virtual void onExit(); + + /*temp action*/ + void setActionTag(int tag); + int getActionTag(); + void setBindingAction(UIActionNode* actionNode); +protected: + //call back function called when size changed. + virtual void onSizeChanged(); + + //initializes state of widget. + virtual bool init(); + + //initializes renderer of widget. + virtual void initRenderer(); + + //call back function called widget's state changed to normal. + virtual void onPressStateChangedToNormal(); + + //call back function called widget's state changed to selected. + virtual void onPressStateChangedToPressed(); + + //call back function called widget's state changed to dark. + virtual void onPressStateChangedToDisabled(); + void pushDownEvent(); + void moveEvent(); + void releaseUpEvent(); + void cancelUpEvent(); + void longClickEvent(); + void updateAnchorPoint(); + /** + * Release texture resoures of widget. + * Release renderer. + * If you override releaseResoures, you shall call its parent's one, e.g. UIWidget::releaseResoures(). + */ + virtual void releaseResoures(); + void updateSizeAndPosition(); +protected: + bool m_bEnabled; ///< Highest control of widget + bool m_bVisible; ///< is this widget visible + bool m_bBright; ///< is this widget bright + bool m_bTouchEnabled; ///< is this widget touch endabled + bool m_bTouchPassedEnabled; ///< is the touch event should be passed + bool m_bFocus; ///< is the widget on focus + int m_nWidgetZOrder; ///< z-order value that affects the draw order and touch order + Point m_anchorPoint; ///< anchor point normalized + UIWidget* m_pWidgetParent; ///< parent of widget + BrightStyle m_eBrightStyle; ///< bright style + bool m_bUpdateEnabled; ///< is "update" method scheduled + Node* m_pRenderer; ///< base renderer + Point m_touchStartPos; ///< touch began point + Point m_touchMovePos; ///< touch moved point + Point m_touchEndPos; ///< touch ended point + + Object* m_pTouchEventListener; + SEL_TouchEvent m_pfnTouchEventSelector; + + + + int m_nWidgetTag; + std::string m_strName; + WidgetType m_WidgetType; + int m_nActionTag; + Size m_size; + Size m_customSize; + LayoutParameter* m_pLayoutParameter; + bool m_bIgnoreSize; + Array* m_children; + bool m_bAffectByClipping; + + Scheduler* m_pScheduler; + + SizeType m_eSizeType; + Point m_sizePercent; + PositionType m_ePositionType; + Point m_positionPercent; + bool m_bIsRunning; + + /*temp action*/ + UIActionNode* m_pBindingAction; +}; + +class GUIRenderer : public NodeRGBA +{ +public: + GUIRenderer(); + virtual ~GUIRenderer(); + virtual void visit(void); + static GUIRenderer* create(); + void setEnabled(bool enabled); + bool isEnabled() const; +protected: + bool m_bEnabled; +}; + +NS_CC_EXT_END + +#endif /* defined(__UIWidget__) */ diff --git a/extensions/CocoStudio/GUI/Layouts/Layout.cpp b/extensions/CocoStudio/GUI/Layouts/Layout.cpp new file mode 100644 index 0000000000..502f3a17ad --- /dev/null +++ b/extensions/CocoStudio/GUI/Layouts/Layout.cpp @@ -0,0 +1,519 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "Layout.h" +#include "../System/UILayer.h" +#include "../../../GUI/CCControlExtension/CCScale9Sprite.h" + +NS_CC_EXT_BEGIN + +#define DYNAMIC_CAST_CLIPPINGLAYER dynamic_cast(m_pRenderer) + +Layout::Layout(): +m_bClippingEnabled(false), +m_pLayoutExecutant(NULL), +m_bBackGroundScale9Enable(false), +m_pBackGroundImage(NULL), +m_strBackGroundImageFileName(""), +m_backGroundImageCapInsets(Rect::ZERO), +m_colorType(LAYOUT_COLOR_NONE), +m_eBGImageTexType(UI_TEX_TYPE_LOCAL), +m_pColorRender(NULL), +m_pGradientRender(NULL), +m_cColor(Color3B::WHITE), +m_gStartColor(Color3B::WHITE), +m_gEndColor(Color3B::WHITE), +m_AlongVector(Point(0.0f, -1.0f)), +m_nCOpacity(255), +m_backGroundImageTextureSize(Size::ZERO) +{ + m_WidgetType = WidgetTypeContainer; +} + +Layout::~Layout() +{ + CC_SAFE_RELEASE_NULL(m_pLayoutExecutant); +} + +Layout* Layout::create() +{ + Layout* layout = new Layout(); + if (layout && layout->init()) + { + layout->autorelease(); + return layout; + } + CC_SAFE_DELETE(layout); + return NULL; +} + +bool Layout::init() +{ + m_children = CCArray::create(); + m_children->retain(); + initRenderer(); + m_pRenderer->retain(); + m_pRenderer->setZOrder(m_nWidgetZOrder); + RGBAProtocol* renderRGBA = dynamic_cast(m_pRenderer); + if (renderRGBA) + { + renderRGBA->setCascadeColorEnabled(false); + renderRGBA->setCascadeOpacityEnabled(false); + } + ignoreContentAdaptWithSize(false); + setSize(Size::ZERO); + setBright(true); + setAnchorPoint(Point(0, 0)); + m_pScheduler = Director::getInstance()->getScheduler(); + CC_SAFE_RETAIN(m_pScheduler); + return true; +} + +void Layout::setLayoutExecutant(LayoutExecutant *exe) +{ + if (m_pLayoutExecutant) + { + CC_SAFE_RELEASE_NULL(m_pLayoutExecutant); + } + m_pLayoutExecutant = exe; + m_pLayoutExecutant->setLayout(this); + CC_SAFE_RETAIN(m_pLayoutExecutant); +} + +LayoutExecutant* Layout::getLayoutExecutant() const +{ + return m_pLayoutExecutant; +} + +void Layout::initRenderer() +{ + m_pRenderer = RectClippingNode::create(); +} + +bool Layout::isClippingEnabled() +{ + return m_bClippingEnabled; +} + +bool Layout::hitTest(const Point &pt) +{ + Point nsp = m_pRenderer->convertToNodeSpace(pt); + Rect bb = Rect(0.0f, 0.0f, m_size.width, m_size.height); + if (nsp.x >= bb.origin.x && nsp.x <= bb.origin.x + bb.size.width && nsp.y >= bb.origin.y && nsp.y <= bb.origin.y + bb.size.height) + { + return true; + } + return false; +} + +void Layout::setClippingEnabled(bool able) +{ + m_bClippingEnabled = able; + DYNAMIC_CAST_CLIPPINGLAYER->setClippingEnabled(able); +} + +void Layout::onSizeChanged() +{ + DYNAMIC_CAST_CLIPPINGLAYER->setClippingSize(m_size); + if (m_pLayoutExecutant) + { + m_pLayoutExecutant->doLayout(); + } + if (m_pBackGroundImage) + { + m_pBackGroundImage->setPosition(Point(m_size.width/2.0f, m_size.height/2.0f)); + if (m_bBackGroundScale9Enable) + { + dynamic_cast(m_pBackGroundImage)->setPreferredSize(m_size); + } + } + if (m_pColorRender) + { + m_pColorRender->setContentSize(m_size); + } + if (m_pGradientRender) + { + m_pGradientRender->setContentSize(m_size); + } +} + +void Layout::setBackGroundImageScale9Enabled(bool able) +{ + if (m_bBackGroundScale9Enable == able) + { + return; + } + m_pRenderer->removeChild(m_pBackGroundImage, true); + m_pBackGroundImage = NULL; + m_bBackGroundScale9Enable = able; + if (m_bBackGroundScale9Enable) + { + m_pBackGroundImage = Scale9Sprite::create(); + m_pRenderer->addChild(m_pBackGroundImage); + } + else + { + m_pBackGroundImage = CCSprite::create(); + m_pRenderer->addChild(m_pBackGroundImage); + } + m_pBackGroundImage->setZOrder(-1); + setBackGroundImage(m_strBackGroundImageFileName.c_str(),m_eBGImageTexType); + setBackGroundImageCapInsets(m_backGroundImageCapInsets); +} + +void Layout::setBackGroundImage(const char* fileName,TextureResType texType) +{ + if (!fileName || strcmp(fileName, "") == 0) + { + return; + } + if (m_pBackGroundImage == NULL) + { + addBackGroundImage(); + } + m_strBackGroundImageFileName = fileName; + m_eBGImageTexType = texType; + if (m_bBackGroundScale9Enable) + { + switch (m_eBGImageTexType) + { + case UI_TEX_TYPE_LOCAL: + dynamic_cast(m_pBackGroundImage)->initWithFile(fileName); + break; + case UI_TEX_TYPE_PLIST: + dynamic_cast(m_pBackGroundImage)->initWithSpriteFrameName(fileName); + break; + default: + break; + } + dynamic_cast(m_pBackGroundImage)->setPreferredSize(m_size); + } + else + { + switch (m_eBGImageTexType) + { + case UI_TEX_TYPE_LOCAL: + dynamic_cast(m_pBackGroundImage)->initWithFile(fileName); + break; + case UI_TEX_TYPE_PLIST: + dynamic_cast(m_pBackGroundImage)->initWithSpriteFrameName(fileName); + break; + default: + break; + } + } + if (m_bBackGroundScale9Enable) + { + dynamic_cast(m_pBackGroundImage)->setColor(getColor()); + dynamic_cast(m_pBackGroundImage)->setOpacity(getOpacity()); + } + else + { + dynamic_cast(m_pBackGroundImage)->setColor(getColor()); + dynamic_cast(m_pBackGroundImage)->setOpacity(getOpacity()); + } + m_backGroundImageTextureSize = m_pBackGroundImage->getContentSize(); + m_pBackGroundImage->setPosition(Point(m_size.width/2.0f, m_size.height/2.0f)); +} + +void Layout::setBackGroundImageCapInsets(const Rect &capInsets) +{ + m_backGroundImageCapInsets = capInsets; + if (m_bBackGroundScale9Enable) + { + dynamic_cast(m_pBackGroundImage)->setCapInsets(capInsets); + } +} + +void Layout::addBackGroundImage() +{ + if (m_bBackGroundScale9Enable) + { + m_pBackGroundImage = Scale9Sprite::create(); + m_pBackGroundImage->setZOrder(-1); + m_pRenderer->addChild(m_pBackGroundImage); + dynamic_cast(m_pBackGroundImage)->setPreferredSize(m_size); + } + else + { + m_pBackGroundImage = CCSprite::create(); + m_pBackGroundImage->setZOrder(-1); + m_pRenderer->addChild(m_pBackGroundImage); + } + m_pBackGroundImage->setPosition(Point(m_size.width/2.0f, m_size.height/2.0f)); +} + +void Layout::removeBackGroundImage() +{ + if (!m_pBackGroundImage) + { + return; + } + m_pRenderer->removeChild(m_pBackGroundImage, true); + m_pBackGroundImage = NULL; + m_strBackGroundImageFileName = ""; + m_backGroundImageTextureSize = Size::ZERO; +} + +void Layout::setBackGroundColorType(LayoutBackGroundColorType type) +{ + if (m_colorType == type) + { + return; + } + switch (m_colorType) + { + case LAYOUT_COLOR_NONE: + if (m_pColorRender) + { + m_pRenderer->removeChild(m_pColorRender, true); + m_pColorRender = NULL; + } + if (m_pGradientRender) + { + m_pRenderer->removeChild(m_pGradientRender, true); + m_pGradientRender = NULL; + } + break; + case LAYOUT_COLOR_SOLID: + if (m_pColorRender) + { + m_pRenderer->removeChild(m_pColorRender, true); + m_pColorRender = NULL; + } + break; + case LAYOUT_COLOR_GRADIENT: + if (m_pGradientRender) + { + m_pRenderer->removeChild(m_pGradientRender, true); + m_pGradientRender = NULL; + } + break; + default: + break; + } + m_colorType = type; + switch (m_colorType) + { + case LAYOUT_COLOR_NONE: + break; + case LAYOUT_COLOR_SOLID: + m_pColorRender = CCLayerColor::create(); + m_pColorRender->setContentSize(m_size); + m_pColorRender->setOpacity(m_nCOpacity); + m_pColorRender->setColor(m_cColor); + m_pRenderer->addChild(m_pColorRender,-2); + break; + case LAYOUT_COLOR_GRADIENT: + m_pGradientRender = CCLayerGradient::create(); + m_pGradientRender->setContentSize(m_size); + m_pGradientRender->setOpacity(m_nCOpacity); + m_pGradientRender->setStartColor(m_gStartColor); + m_pGradientRender->setEndColor(m_gEndColor); + m_pGradientRender->setVector(m_AlongVector); + m_pRenderer->addChild(m_pGradientRender,-2); + break; + default: + break; + } +} + +void Layout::setBackGroundColor(const Color3B &color) +{ + m_cColor = color; + if (m_pColorRender) + { + m_pColorRender->setColor(color); + } +} + +void Layout::setBackGroundColor(const Color3B &startColor, const Color3B &endColor) +{ + m_gStartColor = startColor; + if (m_pGradientRender) + { + m_pGradientRender->setStartColor(startColor); + } + m_gEndColor = endColor; + if (m_pGradientRender) + { + m_pGradientRender->setEndColor(endColor); + } +} + +void Layout::setBackGroundColorOpacity(int opacity) +{ + m_nCOpacity = opacity; + switch (m_colorType) + { + case LAYOUT_COLOR_NONE: + break; + case LAYOUT_COLOR_SOLID: + m_pColorRender->setOpacity(opacity); + break; + case LAYOUT_COLOR_GRADIENT: + m_pGradientRender->setOpacity(opacity); + break; + default: + break; + } +} + +void Layout::setBackGroundColorVector(const Point &vector) +{ + m_AlongVector = vector; + if (m_pGradientRender) + { + m_pGradientRender->setVector(vector); + } +} + +void Layout::setColor(const Color3B &color) +{ + UIWidget::setColor(color); + if (m_pBackGroundImage) + { + RGBAProtocol* rgbap = dynamic_cast(m_pBackGroundImage); + if (rgbap) + { + rgbap->setColor(color); + } + } +} + +void Layout::setOpacity(int opacity) +{ + UIWidget::setOpacity(opacity); + if (m_pBackGroundImage) + { + RGBAProtocol* rgbap = dynamic_cast(m_pBackGroundImage); + if (rgbap) + { + rgbap->setOpacity(opacity); + } + } +} + +const Size& Layout::getBackGroundImageTextureSize() const +{ + return m_backGroundImageTextureSize; +} + +const Size& Layout::getContentSize() const +{ + return m_pRenderer->getContentSize(); +} + +RectClippingNode::RectClippingNode(): +m_pInnerStencil(NULL), +m_bEnabled(true), +m_clippingSize(Size(50.0f, 50.0f)), +m_bClippingEnabled(false) +{ + +} + +RectClippingNode::~RectClippingNode() +{ + +} + +RectClippingNode* RectClippingNode::create() +{ + RectClippingNode *pRet = new RectClippingNode(); + if (pRet && pRet->init()) + { + pRet->autorelease(); + } + else + { + CC_SAFE_DELETE(pRet); + } + + return pRet; +} + +bool RectClippingNode::init() +{ + m_pInnerStencil = CCDrawNode::create(); + rect[0] = Point(0, 0); + rect[1] = Point(m_clippingSize.width, 0); + rect[2] = Point(m_clippingSize.width, m_clippingSize.height); + rect[3] = Point(0, m_clippingSize.height); + + Color4F green = {0, 1, 0, 1}; + m_pInnerStencil->drawPolygon(rect, 4, green, 0, green); + if (CCClippingNode::init(m_pInnerStencil)) + { + return true; + } + return false; +} + + +void RectClippingNode::setClippingSize(const Size &size) +{ + setContentSize(size); + m_clippingSize = size; + rect[0] = Point(0, 0); + rect[1] = Point(m_clippingSize.width, 0); + rect[2] = Point(m_clippingSize.width, m_clippingSize.height); + rect[3] = Point(0, m_clippingSize.height); + Color4F green = {0, 1, 0, 1}; + m_pInnerStencil->clear(); + m_pInnerStencil->drawPolygon(rect, 4, green, 0, green); +} + +void RectClippingNode::setClippingEnabled(bool enabled) +{ + m_bClippingEnabled = enabled; +} + +void RectClippingNode::visit() +{ + if (!m_bEnabled) + { + return; + } + if (m_bClippingEnabled) + { + CCClippingNode::visit(); + } + else + { + CCNode::visit(); + } +} + +void RectClippingNode::setEnabled(bool enabled) +{ + m_bEnabled = enabled; +} + +bool RectClippingNode::isEnabled() const +{ + return m_bEnabled; +} + +NS_CC_EXT_END \ No newline at end of file diff --git a/extensions/CocoStudio/GUI/Layouts/Layout.h b/extensions/CocoStudio/GUI/Layouts/Layout.h new file mode 100644 index 0000000000..0aef9a32cd --- /dev/null +++ b/extensions/CocoStudio/GUI/Layouts/Layout.h @@ -0,0 +1,238 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __LAYOUT_H__ +#define __LAYOUT_H__ + +#include "../BaseClasses/UIWidget.h" +#include "LayoutExecutant.h" + +NS_CC_EXT_BEGIN + +typedef enum +{ + LAYOUT_COLOR_NONE, + LAYOUT_COLOR_SOLID, + LAYOUT_COLOR_GRADIENT +}LayoutBackGroundColorType; + +class Layout : public UIWidget +{ +public: + /** + * Default constructor + */ + Layout(); + + /** + * Default destructor + */ + virtual ~Layout(); + + /** + * Allocates and initializes a layout. + */ + static Layout* create(); + + /** + * Sets a LayoutExecutant for doing layout. + * + * @see LayoutExecutant + * + * @param LayoutExecutant pointer. + */ + virtual void setLayoutExecutant(LayoutExecutant* exe); + + /** + * Gets the LayoutExecutant of Layout + * + * @see LayoutExecutant + * + * @return LayoutExecutant pointer. + */ + virtual LayoutExecutant* getLayoutExecutant() const; + + //override "hitTest" method of widget. + virtual bool hitTest(const Point &pt); + + //background + /** + * Sets a background image for layout + * + * @param fileName image file path. + * + * @param texType @see TextureResType. UI_TEX_TYPE_LOCAL means local file, UI_TEX_TYPE_PLIST means sprite frame. + */ + void setBackGroundImage(const char* fileName,TextureResType texType = UI_TEX_TYPE_LOCAL); + + /** + * Sets a background image capinsets for layout, if the background image is a scale9 render. + * + * @param capinsets of background image. + * + */ + void setBackGroundImageCapInsets(const Rect& capInsets); + + /** + * Sets Color Type for layout. + * + * @param type @see LayoutBackGroundColorType. + */ + void setBackGroundColorType(LayoutBackGroundColorType type); + + /** + * Sets background iamge use scale9 renderer. + * + * @param enabled true that use scale9 renderer, false otherwise. + */ + void setBackGroundImageScale9Enabled(bool enabled); + + /** + * Sets background color for layout, if color type is LAYOUT_COLOR_SOLID + * + * @param color + */ + void setBackGroundColor(const Color3B &color); + + /** + * Sets background color for layout, if color type is LAYOUT_COLOR_GRADIENT + * + * @param start color + * + * @param end color + */ + void setBackGroundColor(const Color3B &startColor, const Color3B &endColor); + + /** + * Sets background opacity layout. + * + * @param opacity + */ + void setBackGroundColorOpacity(int opacity); + + /** + * Sets background color vector for layout, if color type is LAYOUT_COLOR_GRADIENT + * + * @param vector + */ + void setBackGroundColorVector(const Point &vector); + + //override "setColor" method of widget. + virtual void setColor(const Color3B &color); + + //override "setOpacity" method of widget. + virtual void setOpacity(int opacity); + + /** + * Remove the background image of layout. + */ + void removeBackGroundImage(); + + /** + * Gets background image texture size. + * + * @return background image texture size. + */ + const Size& getBackGroundImageTextureSize() const; + + /** + * Changes if layout can clip it's content and child. + * + * If you really need this, please enable it. But it would reduce the rendering efficiency. + * + * @param clipping enabled. + */ + virtual void setClippingEnabled(bool able); + + /** + * Gets if layout is clipping enabled. + * + * @return if layout is clipping enabled. + */ + virtual bool isClippingEnabled(); + + /** + * Gets the content size of widget. + * + * Content size is widget's texture size. + */ + virtual const Size& getContentSize() const; + +protected: + //override "init" method of widget. + virtual bool init(); + + //override "initRenderer" method of widget. + virtual void initRenderer(); + + //override "onSizeChanged" method of widget. + virtual void onSizeChanged(); + + //init background image renderer. + void addBackGroundImage(); +protected: + bool m_bClippingEnabled; + LayoutExecutant* m_pLayoutExecutant; + + //background + bool m_bBackGroundScale9Enable; + Node* m_pBackGroundImage; + std::string m_strBackGroundImageFileName; + Rect m_backGroundImageCapInsets; + LayoutBackGroundColorType m_colorType; + TextureResType m_eBGImageTexType; + LayerColor* m_pColorRender; + LayerGradient* m_pGradientRender; + Color3B m_cColor; + Color3B m_gStartColor; + Color3B m_gEndColor; + Point m_AlongVector; + int m_nCOpacity; + Size m_backGroundImageTextureSize; +}; + +class RectClippingNode : public ClippingNode +{ +public: + virtual ~RectClippingNode(); + virtual bool init(); + static RectClippingNode* create(); + void setClippingSize(const Size& size); + void setClippingEnabled(bool enabled); + virtual void visit(); + void setEnabled(bool enabled); + bool isEnabled() const; +protected: + DrawNode* m_pInnerStencil; + bool m_bEnabled; +private: + RectClippingNode(); + Point rect[4]; + Size m_clippingSize; + bool m_bClippingEnabled; +}; + +NS_CC_EXT_END + +#endif /* defined(__Layout__) */ diff --git a/extensions/CocoStudio/GUI/Layouts/LayoutExecutant.cpp b/extensions/CocoStudio/GUI/Layouts/LayoutExecutant.cpp new file mode 100644 index 0000000000..2a8cd40fed --- /dev/null +++ b/extensions/CocoStudio/GUI/Layouts/LayoutExecutant.cpp @@ -0,0 +1,342 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "LayoutExecutant.h" +#include "Layout.h" +#include "../System/UIHelper.h" + +NS_CC_EXT_BEGIN + +void LayoutExecutant::setLayout(Layout *layout) +{ + m_pLayout = layout; +} + +Layout* LayoutExecutant::getLayout() const +{ + return m_pLayout; +} + +LinearVerticalLayoutExecutant* LinearVerticalLayoutExecutant::create() +{ + LinearVerticalLayoutExecutant* executant = new LinearVerticalLayoutExecutant(); + if (executant) + { + executant->autorelease(); + return executant; + } + CC_SAFE_DELETE(executant); + return NULL; +} + +LinearHorizontalLayoutExecutant* LinearHorizontalLayoutExecutant::create() +{ + LinearHorizontalLayoutExecutant* executant = new LinearHorizontalLayoutExecutant(); + if (executant) + { + executant->autorelease(); + return executant; + } + CC_SAFE_DELETE(executant); + return NULL; +} + +RelativeLayoutExecutant* RelativeLayoutExecutant::create() +{ + RelativeLayoutExecutant* executant = new RelativeLayoutExecutant(); + if (executant) + { + executant->autorelease(); + return executant; + } + CC_SAFE_DELETE(executant); + return NULL; +} + +void LinearVerticalLayoutExecutant::doLayout() +{ + if (m_pLayout) + { + ccArray* layoutChildrenArray = m_pLayout->getChildren()->data; + int length = layoutChildrenArray->num; + Size layoutSize = m_pLayout->getSize(); + float topBoundary = layoutSize.height; + for (int i=0; i(layoutChildrenArray->arr[i]); + LinearLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter()); + + if (layoutParameter) + { + WidgetType childType = child->getWidgetType(); + UILinearGravity childGravity = layoutParameter->getGravity(); + Point ap = child->getAnchorPoint(); + Size cs = child->getSize(); + float finalPosX = childType == WidgetTypeWidget ? ap.x * cs.width : 0.0f; + float finalPosY = childType == WidgetTypeWidget ? topBoundary - ((1.0f-ap.y) * cs.height) : topBoundary - cs.height; + switch (childGravity) + { + case LINEAR_GRAVITY_NONE: + case LINEAR_GRAVITY_LEFT: + break; + case LINEAR_GRAVITY_RIGHT: + finalPosX = childType == WidgetTypeWidget ? layoutSize.width - ((1.0f - ap.x) * cs.width) : layoutSize.width - cs.width; + break; + case LINEAR_GRAVITY_CENTER_HORIZONTAL: + finalPosX = childType == WidgetTypeWidget ? layoutSize.width / 2.0f - cs.width * (0.5f-ap.x) : (layoutSize.width - cs.width) * 0.5f; + break; + default: + break; + } + UIMargin mg = layoutParameter->getMargin(); + finalPosX += mg.left; + finalPosY -= mg.top; + child->setPosition(Point(finalPosX, finalPosY)); + topBoundary = child->getBottomInParent() - mg.bottom; + } + } + } +} + +void LinearHorizontalLayoutExecutant::doLayout() +{ + if (m_pLayout) + { + ccArray* layoutChildrenArray = m_pLayout->getChildren()->data; + int length = layoutChildrenArray->num; + Size layoutSize = m_pLayout->getSize(); + float leftBoundary = 0.0f; + for (int i=0; i(layoutChildrenArray->arr[i]); + LinearLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter()); + + if (layoutParameter) + { + WidgetType childType = child->getWidgetType(); + UILinearGravity childGravity = layoutParameter->getGravity(); + Point ap = child->getAnchorPoint(); + Size cs = child->getSize(); + float finalPosX = childType == WidgetTypeWidget ? leftBoundary + (ap.x * cs.width) : leftBoundary; + float finalPosY = childType == WidgetTypeWidget ? layoutSize.height - (1.0f - ap.y) * cs.height : layoutSize.height - cs.height; + switch (childGravity) + { + case LINEAR_GRAVITY_NONE: + case LINEAR_GRAVITY_TOP: + break; + case LINEAR_GRAVITY_BOTTOM: + finalPosY = childType == WidgetTypeWidget ? ap.y * cs.height : 0.0f; + break; + case LINEAR_GRAVITY_CENTER_VERTICAL: + finalPosY = childType == WidgetTypeWidget ? layoutSize.height/2.0f - cs.height * (0.5f - ap.y) : (layoutSize.height - cs.height) * 0.5f; + break; + default: + break; + } + UIMargin mg = layoutParameter->getMargin(); + finalPosX += mg.left; + finalPosY -= mg.top; + child->setPosition(Point(finalPosX, finalPosY)); + leftBoundary = child->getRightInParent() + mg.right; + } + } + } +} + +void RelativeLayoutExecutant::doLayout() +{ + if (m_pLayout) + { + ccArray* layoutChildrenArray = m_pLayout->getChildren()->data; + int length = layoutChildrenArray->num; + Size layoutSize = m_pLayout->getSize(); + for (int i=0; i(layoutChildrenArray->arr[i]); + WidgetType childType = child->getWidgetType(); + Point ap = child->getAnchorPoint(); + Size cs = child->getSize(); + RelativeLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter()); + if (layoutParameter) + { + float finalPosX = childType == WidgetTypeWidget ? ap.x * cs.width : 0.0f; + float finalPosY = childType == WidgetTypeWidget ? layoutSize.height - ((1.0f - ap.y) * cs.height) : layoutSize.height - cs.height; + UIRelativeAlign align = layoutParameter->getAlign(); + const char* relativeName = layoutParameter->getRelativeToWidgetName(); + UIWidget* relativeWidget = NULL; + if (relativeName && strcmp(relativeName, "")) + { + relativeWidget = CCUIHELPER->seekWidgetByRelativeName(m_pLayout, relativeName); + } + switch (align) + { + case RELATIVE_ALIGN_NONE: + break; + case RELATIVE_ALIGN_PARENT_LEFT: + break; + case RELATIVE_ALIGN_PARENT_TOP: + break; + case RELATIVE_ALIGN_PARENT_RIGHT: + finalPosX = childType == WidgetTypeWidget ? layoutSize.width - ((1.0f - ap.x) * cs.width) : layoutSize.width - cs.width; + break; + case RELATIVE_ALIGN_PARENT_BOTTOM: + finalPosY = childType == WidgetTypeWidget ? ap.y * cs.height : 0.0f; + break; + case RELATIVE_CENTER_IN_PARENT: + finalPosX = childType == WidgetTypeWidget ? layoutSize.width * 0.5f - cs.width * (0.5f - ap.x) : (layoutSize.width - cs.width) * 0.5f; + finalPosY = childType == WidgetTypeWidget ? layoutSize.height * 0.5f - cs.height * (0.5f - ap.y) : (layoutSize.height - cs.height) * 0.5f; + break; + case RELATIVE_CENTER_HORIZONTAL: + finalPosX = childType == WidgetTypeWidget ? layoutSize.width * 0.5f - cs.width * (0.5f - ap.x) : (layoutSize.width - cs.width) * 0.5f; + break; + case RELATIVE_CENTER_VERTICAL: + finalPosY = childType == WidgetTypeWidget ? layoutSize.height * 0.5f - cs.height * (0.5f - ap.y) : (layoutSize.height - cs.height) * 0.5f; + break; + case RELATIVE_LOCATION_LEFT_OF_TOPALIGN: + if (relativeWidget) + { + float locationTop = relativeWidget->getTopInParent(); + float locationRight = relativeWidget->getLeftInParent(); + finalPosY = childType == WidgetTypeWidget ? locationTop - ap.y * cs.height : locationTop - cs.height; + finalPosX = childType == WidgetTypeWidget ? locationRight - (1.0f - ap.x) * cs.width : locationRight - cs.width; + } + break; + case RELATIVE_LOCATION_LEFT_OF_CENTER: + break; + case RELATIVE_LOCATION_LEFT_OF_BOTTOMALIGN: + if (relativeWidget) + { + float locationRight = relativeWidget->getLeftInParent(); + float locationBottom = relativeWidget->getBottomInParent(); + finalPosY = childType == WidgetTypeWidget ? locationBottom + ap.y * cs.height : locationBottom; + finalPosX = childType == WidgetTypeWidget ? locationRight - (1.0f - ap.x) * cs.width : locationRight - cs.width; + } + break; + case RELATIVE_LOCATION_RIGHT_OF_TOPALIGN: + if (relativeWidget) + { + float locationTop = relativeWidget->getTopInParent(); + float locationLeft = relativeWidget->getRightInParent(); + finalPosY = childType == WidgetTypeWidget ? locationTop - ap.y * cs.height : locationTop - cs.height; + finalPosX = childType == WidgetTypeWidget ? locationLeft + ap.x * cs.width : locationLeft; + } + break; + case RELATIVE_LOCATION_RIGHT_OF_CENTER: + break; + case RELATIVE_LOCATION_RIGHT_OF_BOTTOMALIGN: + if (relativeWidget) + { + float locationLeft = relativeWidget->getRightInParent(); + float locationBottom = relativeWidget->getBottomInParent(); + finalPosY = childType == WidgetTypeWidget ? locationBottom + ap.y * cs.height : locationBottom; + finalPosX = childType == WidgetTypeWidget ? locationLeft + ap.x * cs.width : locationLeft; + } + break; + case RELATIVE_LOCATION_ABOVE_LEFTALIGN: + if (relativeWidget) + { + float locationBottom = relativeWidget->getTopInParent(); + float locationLeft = relativeWidget->getLeftInParent(); + finalPosY = childType == WidgetTypeWidget ? locationBottom + ap.y * cs.height : locationBottom; + finalPosX = childType == WidgetTypeWidget ? locationLeft + ap.x * cs.width : locationLeft; + } + break; + case RELATIVE_LOCATION_ABOVE_CENTER: + break; + case RELATIVE_LOCATION_ABOVE_RIGHTALIGN: + if (relativeWidget) + { + float locationBottom = relativeWidget->getTopInParent(); + float locationRight = relativeWidget->getRightInParent(); + finalPosY = childType == WidgetTypeWidget ? locationBottom + ap.y * cs.height : locationBottom; + finalPosX = childType == WidgetTypeWidget ? locationRight - (1.0f - ap.x) * cs.width : locationRight - cs.width; + } + break; + case RELATIVE_LOCATION_BELOW_LEFTALIGN: + if (relativeWidget) + { + float locationTop = relativeWidget->getBottomInParent(); + float locationLeft = relativeWidget->getLeftInParent(); + finalPosY = childType == WidgetTypeWidget ? locationTop - (1.0f - ap.y) * cs.height : locationTop - cs.height; + finalPosX = childType == WidgetTypeWidget ? locationLeft + ap.x * cs.width : locationLeft; + } + break; + case RELATIVE_LOCATION_BELOW_CENTER: + break; + case RELATIVE_LOCATION_BELOW_RIGHTALIGN: + if (relativeWidget) + { + float locationTop = relativeWidget->getBottomInParent(); + float locationRight = relativeWidget->getRightInParent(); + finalPosY = childType == WidgetTypeWidget ? locationTop - (1.0f - ap.y) * cs.height : locationTop - cs.height; + finalPosX = childType == WidgetTypeWidget ? locationRight - (1.0f - ap.x) * cs.width : locationRight - cs.width; + } + break; + default: + break; + } + UIMargin relativeWidgetMargin; + UIMargin mg; + if (relativeWidget) + { + relativeWidgetMargin = relativeWidget->getLayoutParameter()->getMargin(); + mg = child->getLayoutParameter()->getMargin(); + } + //handle margin + switch (align) + { + case RELATIVE_LOCATION_ABOVE_LEFTALIGN: + case RELATIVE_LOCATION_ABOVE_RIGHTALIGN: + case RELATIVE_LOCATION_ABOVE_CENTER: + finalPosY += relativeWidgetMargin.top; + finalPosY += mg.bottom; + break; + case RELATIVE_LOCATION_BELOW_LEFTALIGN: + case RELATIVE_LOCATION_BELOW_RIGHTALIGN: + case RELATIVE_LOCATION_BELOW_CENTER: + finalPosY -= relativeWidgetMargin.bottom; + finalPosY -= mg.top; + break; + case RELATIVE_LOCATION_LEFT_OF_TOPALIGN: + case RELATIVE_LOCATION_LEFT_OF_BOTTOMALIGN: + case RELATIVE_LOCATION_LEFT_OF_CENTER: + finalPosX -= relativeWidgetMargin.left; + finalPosX -= mg.right; + break; + case RELATIVE_LOCATION_RIGHT_OF_TOPALIGN: + case RELATIVE_LOCATION_RIGHT_OF_BOTTOMALIGN: + case RELATIVE_LOCATION_RIGHT_OF_CENTER: + finalPosX += relativeWidgetMargin.right; + finalPosX += mg.left; + break; + default: + break; + } + child->setPosition(Point(finalPosX, finalPosY)); + } + } + } +} + +NS_CC_EXT_END \ No newline at end of file diff --git a/extensions/CocoStudio/GUI/Layouts/LayoutExecutant.h b/extensions/CocoStudio/GUI/Layouts/LayoutExecutant.h new file mode 100644 index 0000000000..47870bb025 --- /dev/null +++ b/extensions/CocoStudio/GUI/Layouts/LayoutExecutant.h @@ -0,0 +1,158 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __LAYOUTEXECUTANT_H__ +#define __LAYOUTEXECUTANT_H__ + +#include "LayoutParameter.h" + +NS_CC_EXT_BEGIN + +typedef enum +{ + LAYOUT_DEFAULT, + LAYOUT_LINEAR_VERTICAL, + LAYOUT_LINEAR_HORIZONTAL, + LAYOUT_RELATIVE +}LayoutType; + +class Layout; + +class LayoutExecutant : public Object +{ +public: + /** + * Default constructor + */ + LayoutExecutant() : m_pLayout(NULL){m_eLayoutType = LAYOUT_DEFAULT;}; + + /** + * Default destructor + */ + virtual ~LayoutExecutant(){m_pLayout = NULL;}; + + /** + * To do layout. Need to be overrided. + */ + virtual void doLayout()=0; + + /** + * Gets LayoutType. + * + * @see LayoutType + * + * @return LayoutType + */ + LayoutType getLayoutType(){return m_eLayoutType;}; + + /** + * Binding a Layout to LayoutExecutant. + * + * @param Layout + */ + void setLayout(Layout* layout); + + /** + * Gets the Layout of LayoutExecutant. + * + * @return Layout + */ + Layout* getLayout() const; +protected: + LayoutType m_eLayoutType; + Layout* m_pLayout; +}; + +class LinearVerticalLayoutExecutant : public LayoutExecutant +{ +public: + /** + * Default constructor + */ + LinearVerticalLayoutExecutant(){m_eLayoutType = LAYOUT_LINEAR_VERTICAL;}; + + /** + * Default destructor + */ + virtual ~LinearVerticalLayoutExecutant(){}; + + /** + * Allocates and initializes. + * @return A initialized LayoutExecutant which is marked as "autorelease". + */ + static LinearVerticalLayoutExecutant* create(); + + //To do layout. + virtual void doLayout(); +}; + +class LinearHorizontalLayoutExecutant : public LayoutExecutant +{ +public: + /** + * Default constructor + */ + LinearHorizontalLayoutExecutant(){m_eLayoutType = LAYOUT_LINEAR_HORIZONTAL;}; + + /** + * Default destructor + */ + virtual ~LinearHorizontalLayoutExecutant(){}; + + /** + * Allocates and initializes. + * @return A initialized LayoutExecutant which is marked as "autorelease". + */ + static LinearHorizontalLayoutExecutant* create(); + + //To do layout. + virtual void doLayout(); +}; + +class RelativeLayoutExecutant : public LayoutExecutant +{ +public: + /** + * Default constructor + */ + RelativeLayoutExecutant(){m_eLayoutType = LAYOUT_RELATIVE;}; + + /** + * Default destructor + */ + virtual ~RelativeLayoutExecutant(){}; + + /** + * Allocates and initializes. + * @return A initialized LayoutExecutant which is marked as "autorelease". + */ + static RelativeLayoutExecutant* create(); + + //To do layout. + virtual void doLayout(); +}; + +NS_CC_EXT_END + +#endif /* defined(__LayoutExecutant__) */ diff --git a/extensions/CocoStudio/GUI/Layouts/LayoutParameter.cpp b/extensions/CocoStudio/GUI/Layouts/LayoutParameter.cpp new file mode 100644 index 0000000000..358dc8d3b0 --- /dev/null +++ b/extensions/CocoStudio/GUI/Layouts/LayoutParameter.cpp @@ -0,0 +1,206 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "LayoutParameter.h" +#include "Layout.h" + +NS_CC_EXT_BEGIN + +LayoutParameter* LayoutParameter::create() +{ + LayoutParameter* parameter = new LayoutParameter(); + if (parameter) + { + parameter->autorelease(); + return parameter; + } + CC_SAFE_DELETE(parameter); + return NULL; +} + +void LayoutParameter::setMargin(const UIMargin &margin) +{ + m_margin = margin; + UIWidget* subClass = dynamic_cast(this); + if (subClass) + { + UIWidget* parent = subClass->getParent(); + if (parent) + { + Layout* containerParent = dynamic_cast(parent); + if (containerParent) + { + LayoutExecutant* exe = containerParent->getLayoutExecutant(); + if (exe) + { + exe->doLayout(); + } + } + } + } +} + +const UIMargin& LayoutParameter::getMargin() const +{ + return m_margin; +} + +LayoutParameterType LayoutParameter::getLayoutType() const +{ + return m_eLayoutParameterType; +} + +LinearLayoutParameter* LinearLayoutParameter::create() +{ + LinearLayoutParameter* parameter = new LinearLayoutParameter(); + if (parameter) + { + parameter->autorelease(); + return parameter; + } + CC_SAFE_DELETE(parameter); + return NULL; +} + +void LinearLayoutParameter::setGravity(UILinearGravity gravity) +{ + m_eLinearGravity = gravity; + UIWidget* subClass = dynamic_cast(this); + if (subClass) + { + UIWidget* parent = subClass->getParent(); + if (parent) + { + Layout* containerParent = dynamic_cast(parent); + if (containerParent) + { + LayoutExecutant* exe = containerParent->getLayoutExecutant(); + if (exe && (exe->getLayoutType() == LAYOUT_LINEAR_HORIZONTAL || exe->getLayoutType() == LAYOUT_LINEAR_VERTICAL)) + { + exe->doLayout(); + } + } + } + } +} + +UILinearGravity LinearLayoutParameter::getGravity() const +{ + return m_eLinearGravity; +} + +RelativeLayoutParameter* RelativeLayoutParameter::create() +{ + RelativeLayoutParameter* parameter = new RelativeLayoutParameter(); + if (parameter) + { + parameter->autorelease(); + return parameter; + } + CC_SAFE_DELETE(parameter); + return NULL; +} + +void RelativeLayoutParameter::setAlign(UIRelativeAlign align) +{ + m_eRelativeAlign = align; + UIWidget* subClass = dynamic_cast(this); + if (subClass) + { + UIWidget* parent = subClass->getParent(); + if (parent) + { + Layout* containerParent = dynamic_cast(parent); + if (containerParent) + { + LayoutExecutant* exe = containerParent->getLayoutExecutant(); + if (exe && (exe->getLayoutType() == LAYOUT_RELATIVE)) + { + exe->doLayout(); + } + } + } + } +} + +UIRelativeAlign RelativeLayoutParameter::getAlign() const +{ + return m_eRelativeAlign; +} + +void RelativeLayoutParameter::setRelativeToWidgetName(const char *name) +{ + m_strRelativeWidgetName = name; + UIWidget* subClass = dynamic_cast(this); + if (subClass) + { + UIWidget* parent = subClass->getParent(); + if (parent) + { + Layout* containerParent = dynamic_cast(parent); + if (containerParent) + { + LayoutExecutant* exe = containerParent->getLayoutExecutant(); + if (exe && (exe->getLayoutType() == LAYOUT_RELATIVE)) + { + exe->doLayout(); + } + } + } + } +} + +const char* RelativeLayoutParameter::getRelativeToWidgetName() const +{ + return m_strRelativeWidgetName.c_str(); +} + +void RelativeLayoutParameter::setRelativeName(const char* name) +{ + m_strRelativeLayoutName = name; + UIWidget* subClass = dynamic_cast(this); + if (subClass) + { + UIWidget* parent = subClass->getParent(); + if (parent) + { + Layout* containerParent = dynamic_cast(parent); + if (containerParent) + { + LayoutExecutant* exe = containerParent->getLayoutExecutant(); + if (exe && (exe->getLayoutType() == LAYOUT_RELATIVE)) + { + exe->doLayout(); + } + } + } + } +} + +const char* RelativeLayoutParameter::getRelativeName() const +{ + return m_strRelativeLayoutName.c_str(); +} + +NS_CC_EXT_END \ No newline at end of file diff --git a/extensions/CocoStudio/GUI/Layouts/LayoutParameter.h b/extensions/CocoStudio/GUI/Layouts/LayoutParameter.h new file mode 100644 index 0000000000..c670055cbf --- /dev/null +++ b/extensions/CocoStudio/GUI/Layouts/LayoutParameter.h @@ -0,0 +1,201 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __LAYOUTPARMETER_H__ +#define __LAYOUTPARMETER_H__ + +#include "UILayoutDefine.h" + +NS_CC_EXT_BEGIN + +typedef enum +{ + LAYOUT_PARAMETER_NONE, + LAYOUT_PARAMETER_LINEAR, + LAYOUT_PARAMETER_RELATIVE +}LayoutParameterType; + +class LayoutParameter : public Object +{ +public: + /** + * Default constructor + */ + LayoutParameter() : m_margin(UIMargin()){m_eLayoutParameterType = LAYOUT_PARAMETER_NONE;}; + + /** + * Default destructor + */ + virtual ~LayoutParameter(){}; + + /** + * Allocates and initializes. + * @return A initialized LayoutParameter which is marked as "autorelease". + */ + static LayoutParameter* create(); + + /** + * Sets Margin parameter for LayoutParameter. + * + * @see UIMargin + * + * @param margin + */ + void setMargin(const UIMargin& margin); + + /** + * Gets Margin parameter of LayoutParameter. + * + * @see UIMargin + * + * @return const UIMargin& + */ + const UIMargin& getMargin() const; + + /** + * Gets LayoutParameterType of LayoutParameter. + * + * @see LayoutParameterType + * + * @return LayoutParameterType + */ + LayoutParameterType getLayoutType() const; +protected: + UIMargin m_margin; + LayoutParameterType m_eLayoutParameterType; +}; + +class LinearLayoutParameter : public LayoutParameter +{ +public: + /** + * Default constructor + */ + LinearLayoutParameter() : m_eLinearGravity(LINEAR_GRAVITY_NONE){m_eLayoutParameterType = LAYOUT_PARAMETER_LINEAR;}; + + /** + * Default destructor + */ + virtual ~LinearLayoutParameter(){}; + + /** + * Allocates and initializes. + * @return A initialized LayoutParameter which is marked as "autorelease". + */ + static LinearLayoutParameter* create(); + + /** + * Sets UILinearGravity parameter for LayoutParameter. + * + * @see UILinearGravity + * + * @param UILinearGravity + */ + void setGravity(UILinearGravity gravity); + + /** + * Gets UILinearGravity parameter for LayoutParameter. + * + * @see UILinearGravity + * + * @return UILinearGravity + */ + UILinearGravity getGravity() const; +protected: + UILinearGravity m_eLinearGravity; +}; + +class RelativeLayoutParameter : public LayoutParameter +{ +public: + /** + * Default constructor + */ + RelativeLayoutParameter() : m_eRelativeAlign(RELATIVE_ALIGN_NONE),m_strRelativeWidgetName(""),m_strRelativeLayoutName(""){m_eLayoutParameterType = LAYOUT_PARAMETER_RELATIVE;}; + + /** + * Default destructor + */ + virtual ~RelativeLayoutParameter(){}; + + /** + * Allocates and initializes. + * @return A initialized LayoutParameter which is marked as "autorelease". + */ + static RelativeLayoutParameter* create(); + + /** + * Sets UIRelativeAlign parameter for LayoutParameter. + * + * @see UIRelativeAlign + * + * @param UIRelativeAlign + */ + void setAlign(UIRelativeAlign align); + + /** + * Gets UIRelativeAlign parameter for LayoutParameter. + * + * @see UIRelativeAlign + * + * @return UIRelativeAlign + */ + UIRelativeAlign getAlign() const; + + /** + * Sets a key for LayoutParameter. Witch widget named this is relative to. + * + * @param name + */ + void setRelativeToWidgetName(const char* name); + + /** + * Gets the key of LayoutParameter. Witch widget named this is relative to. + * + * @return name + */ + const char* getRelativeToWidgetName() const; + + /** + * Sets a name in Relative Layout for LayoutParameter. + * + * @param name + */ + void setRelativeName(const char* name); + + /** + * Gets a name in Relative Layout of LayoutParameter. + * + * @return name + */ + const char* getRelativeName() const; +protected: + UIRelativeAlign m_eRelativeAlign; + std::string m_strRelativeWidgetName; + std::string m_strRelativeLayoutName; +}; + +NS_CC_EXT_END + +#endif /* defined(__LayoutParameter__) */ diff --git a/extensions/CocoStudio/GUI/Layouts/UILayoutDefine.cpp b/extensions/CocoStudio/GUI/Layouts/UILayoutDefine.cpp new file mode 100644 index 0000000000..54b8451c78 --- /dev/null +++ b/extensions/CocoStudio/GUI/Layouts/UILayoutDefine.cpp @@ -0,0 +1,60 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ +#include "UILayoutDefine.h" + +NS_CC_EXT_BEGIN + + +UIMargin::UIMargin(void) : left(0), top(0), right(0), bottom(0) +{ +} + +UIMargin::UIMargin(float l, float t, float r, float b) : left(l), top(t), right(r), bottom(b) +{ +} + +UIMargin::UIMargin(const UIMargin& other) : left(other.left), top(other.top), right(other.right), bottom(other.bottom) +{ +} + +UIMargin& UIMargin::operator= (const UIMargin& other) +{ + setMargin(other.left, other.top, other.right, other.bottom); + return *this; +} + +void UIMargin::setMargin(float l, float t, float r, float b) +{ + left = l; + top = t; + right = r; + bottom = b; +} + +bool UIMargin::equals(const UIMargin &target) const +{ + return (left == target.left && top == target.top && right == target.right && bottom == target.bottom); +} + +NS_CC_EXT_END \ No newline at end of file diff --git a/extensions/CocoStudio/GUI/Layouts/UILayoutDefine.h b/extensions/CocoStudio/GUI/Layouts/UILayoutDefine.h new file mode 100644 index 0000000000..ac2df8ca65 --- /dev/null +++ b/extensions/CocoStudio/GUI/Layouts/UILayoutDefine.h @@ -0,0 +1,88 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __UILAYOUTDEFINE_H__ +#define __UILAYOUTDEFINE_H__ + +#include "cocos2d.h" +#include "ExtensionMacros.h" + +NS_CC_EXT_BEGIN + +class UIMargin +{ +public: + float left; + float top; + float right; + float bottom; + +public: + UIMargin(); + UIMargin(float l, float t, float r, float b); + UIMargin(const UIMargin& other); + UIMargin& operator= (const UIMargin& other); + void setMargin(float l, float t, float r, float b); + bool equals(const UIMargin& target) const; +}; + + +typedef enum +{ + LINEAR_GRAVITY_NONE, + LINEAR_GRAVITY_LEFT, + LINEAR_GRAVITY_TOP, + LINEAR_GRAVITY_RIGHT, + LINEAR_GRAVITY_BOTTOM, + LINEAR_GRAVITY_CENTER_VERTICAL, + LINEAR_GRAVITY_CENTER_HORIZONTAL +}UILinearGravity; + +typedef enum +{ + RELATIVE_ALIGN_NONE, + RELATIVE_ALIGN_PARENT_LEFT, + RELATIVE_ALIGN_PARENT_TOP, + RELATIVE_ALIGN_PARENT_RIGHT, + RELATIVE_ALIGN_PARENT_BOTTOM, + RELATIVE_CENTER_IN_PARENT, + RELATIVE_CENTER_HORIZONTAL, + RELATIVE_CENTER_VERTICAL, + RELATIVE_LOCATION_LEFT_OF_TOPALIGN, + RELATIVE_LOCATION_LEFT_OF_CENTER, + RELATIVE_LOCATION_LEFT_OF_BOTTOMALIGN, + RELATIVE_LOCATION_RIGHT_OF_TOPALIGN, + RELATIVE_LOCATION_RIGHT_OF_CENTER, + RELATIVE_LOCATION_RIGHT_OF_BOTTOMALIGN, + RELATIVE_LOCATION_ABOVE_LEFTALIGN, + RELATIVE_LOCATION_ABOVE_CENTER, + RELATIVE_LOCATION_ABOVE_RIGHTALIGN, + RELATIVE_LOCATION_BELOW_LEFTALIGN, + RELATIVE_LOCATION_BELOW_CENTER, + RELATIVE_LOCATION_BELOW_RIGHTALIGN +}UIRelativeAlign; + +NS_CC_EXT_END + +#endif /* defined(__UILayoutDefine__) */ diff --git a/extensions/CocoStudio/GUI/System/CocosGUI.cpp b/extensions/CocoStudio/GUI/System/CocosGUI.cpp new file mode 100644 index 0000000000..a8e7b9fe3d --- /dev/null +++ b/extensions/CocoStudio/GUI/System/CocosGUI.cpp @@ -0,0 +1,34 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "CocosGUI.h" + +NS_CC_EXT_BEGIN + +const char* CocosGUIVersion() +{ + return "CocosGUI v0.3.0.0"; +} + +NS_CC_EXT_END diff --git a/extensions/CocoStudio/GUI/System/CocosGUI.h b/extensions/CocoStudio/GUI/System/CocosGUI.h new file mode 100644 index 0000000000..8fb10a5a4d --- /dev/null +++ b/extensions/CocoStudio/GUI/System/CocosGUI.h @@ -0,0 +1,57 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __COCOSGUI_H__ +#define __COCOSGUI_H__ + + +#include "../BaseClasses/UIWidget.h" +#include "../Layouts/Layout.h" +#include "../BaseClasses/UIRootWidget.h" +#include "../UIWidgets/UIButton.h" +#include "../UIWidgets/UICheckBox.h" +#include "../UIWidgets/UIImageView.h" +#include "../UIWidgets/UILabel.h" +#include "../UIWidgets/UILabelAtlas.h" +#include "../UIWidgets/UILoadingBar.h" +#include "../UIWidgets/ScrollWidget/UIScrollView.h" +#include "../UIWidgets/UISlider.h" +#include "../UIWidgets/UITextField.h" +#include "../UIWidgets/ScrollWidget/UIListView.h" +#include "../UIWidgets/ScrollWidget/UIDragPanel.h" +#include "../UIWidgets/UILabelBMFont.h" +#include "../UIWidgets/ScrollWidget/UIPageView.h" +#include "UIHelper.h" +#include "../../Reader/CCSGUIReader.h" +#include "UILayer.h" +#include "../Layouts/LayoutExecutant.h" +/*temp action*/ +#include "../Action/UIActionManager.h" +NS_CC_EXT_BEGIN + +const char* CocosGUIVersion(); + +NS_CC_EXT_END + +#endif /* defined(__CocosGUITest__Cocos__) */ diff --git a/extensions/CocoStudio/GUI/System/UIHelper.cpp b/extensions/CocoStudio/GUI/System/UIHelper.cpp new file mode 100644 index 0000000000..b6aeceb906 --- /dev/null +++ b/extensions/CocoStudio/GUI/System/UIHelper.cpp @@ -0,0 +1,239 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "UIHelper.h" +#include "../../Json/DictionaryHelper.h" +#include "cocos2d.h" +#include "../../Reader/CCSGUIReader.h" + + +NS_CC_EXT_BEGIN + +static UIHelper* helperInstance = NULL; + +UIHelper* UIHelper::instance() +{ + if (!helperInstance) + { + helperInstance = new UIHelper(); + } + return helperInstance; +} + +void UIHelper::purgeUIHelper() +{ + CC_SAFE_DELETE(helperInstance); +} + +UIHelper::UIHelper(): +m_textureFiles(NULL) +{ + Size winSize = Director::getInstance()->getWinSize(); + m_fFileDesignWidth = winSize.width; + m_fFileDesignHeight = winSize.height; + init(); +} + +UIHelper::~UIHelper() +{ + cocos2d::extension::CCSGUIReader::purgeCCSGUIReader(); +} + +void UIHelper::init() +{ + m_textureFiles = CCArray::create(); + m_textureFiles->retain(); +} + +UIWidget* UIHelper::createWidgetFromJsonFile(const char *fileName) +{ + return CCSGUIReader::shareReader()->widgetFromJsonFile(fileName); +} + +void UIHelper::addSpriteFrame(const char *fileName) +{ + if (!fileName || strcmp(fileName, "") == 0) + { + return; + } + ccArray* arrayTextures = m_textureFiles->data; + int length = arrayTextures->num; + for (int i=0;iarr[i]); + if (strcmp(file->_string.c_str(), fileName) == 0) + { + return; + } + } + m_textureFiles->addObject(CCString::create(fileName)); + SpriteFrameCache::getInstance()->addSpriteFramesWithFile(fileName); +} + +void UIHelper::removeSpriteFrame(const char *fileName) +{ + if (!fileName || strcmp(fileName, "") == 0) + { + return; + } + ccArray* arrayTextures = m_textureFiles->data; + int length = arrayTextures->num; + for (int i=0;iarr[i]); + if (strcmp(file->_string.c_str(), fileName) == 0) + { + SpriteFrameCache::getInstance()->removeSpriteFrameByName(fileName); + m_textureFiles->removeObject(file); + return; + } + } +} + +void UIHelper::removeAllSpriteFrame() +{ + ccArray* arrayTextures = m_textureFiles->data; + int length = arrayTextures->num; + for (int i=0;iarr[i]); + SpriteFrameCache::getInstance()->removeSpriteFrameByName(file->_string.c_str()); + } + m_textureFiles->removeAllObjects(); +} + +UIWidget* UIHelper::seekWidgetByTag(UIWidget* root, int tag) +{ + if (!root) + { + return NULL; + } + if (root->getTag() == tag) + { + return root; + } + ccArray* arrayRootChildren = root->getChildren()->data; + int length = arrayRootChildren->num; + for (int i=0;iarr[i]); + UIWidget* res = seekWidgetByTag(child,tag); + if (res != NULL) + { + return res; + } + } + return NULL; +} + +UIWidget* UIHelper::seekWidgetByName(UIWidget* root, const char *name) +{ + if (!root) + { + return NULL; + } + if (strcmp(root->getName(), name) == 0) + { + return root; + } + ccArray* arrayRootChildren = root->getChildren()->data; + int length = arrayRootChildren->num; + for (int i=0;iarr[i]); + UIWidget* res = seekWidgetByName(child,name); + if (res != NULL) + { + return res; + } + } + return NULL; +} + +UIWidget* UIHelper::seekWidgetByRelativeName(UIWidget *root, const char *name) +{ + if (!root) + { + return NULL; + } + ccArray* arrayRootChildren = root->getChildren()->data; + int length = arrayRootChildren->num; + for (int i=0;iarr[i]); + RelativeLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter()); + if (layoutParameter && strcmp(layoutParameter->getRelativeName(), name) == 0) + { + return child; + } + } + return NULL; +} + +void UIHelper::setFileDesignWidth(float width) +{ + m_fFileDesignWidth = width; +} + +float UIHelper::getFileDesignWidth() +{ + return m_fFileDesignWidth; +} + +void UIHelper::setFileDesignHeight(float height) +{ + m_fFileDesignHeight = height; +} + +float UIHelper::getFileDesignHeight() +{ + return m_fFileDesignHeight; +} + +/*temp action*/ +UIWidget* UIHelper::seekActionWidgetByActionTag(UIWidget* root, int tag) +{ + if (!root) + { + return NULL; + } + if (root->getActionTag() == tag) + { + return root; + } + ccArray* arrayRootChildren = root->getChildren()->data; + int length = arrayRootChildren->num; + for (int i=0;iarr[i]); + UIWidget* res = seekActionWidgetByActionTag(child,tag); + if (res != NULL) + { + return res; + } + } + return NULL; +} + +NS_CC_EXT_END \ No newline at end of file diff --git a/extensions/CocoStudio/GUI/System/UIHelper.h b/extensions/CocoStudio/GUI/System/UIHelper.h new file mode 100644 index 0000000000..a57f74aa00 --- /dev/null +++ b/extensions/CocoStudio/GUI/System/UIHelper.h @@ -0,0 +1,124 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __UIHELPER_H__ +#define __UIHELPER_H__ + +#include "UIInputManager.h" +#include "../../Json/CSContentJsonDictionary.h" + + +#define CCUIHELPER cocos2d::extension::UIHelper::instance() + +NS_CC_EXT_BEGIN + +class UIHelper +{ +public: + /** + * Default constructor + */ + UIHelper(); + + /** + * Default destructor + */ + ~UIHelper(); + + //initializes state of UIHelper. + void init(); + + /** + * Load a widget with json file. + * + * @return a widget created with json file. + */ + UIWidget* createWidgetFromJsonFile(const char* fileName); + + //get instance + static UIHelper* instance(); + + //release instance + static void purgeUIHelper(); + + //add a plist file for loading widget's texture. + void addSpriteFrame(const char* fileName); + + //remove a plist file for loading widget's texture. + void removeSpriteFrame(const char* fileName); + + //remove all plist files for loading widget's texture. + void removeAllSpriteFrame(); + + /** + * Finds a widget whose tag equals to param tag from root widget. + * + * @param root widget which will be seeked. + * + * @tag tag value. + * + * @return finded result. + */ + UIWidget* seekWidgetByTag(UIWidget* root, int tag); + + /** + * Finds a widget whose name equals to param name from root widget. + * + * @param root widget which will be seeked. + * + * @name name value. + * + * @return finded result. + */ + UIWidget* seekWidgetByName(UIWidget* root, const char* name); + + /** + * Finds a widget whose name equals to param name from root widget. + * + * RelativeLayout will call this method to find the widget witch is needed. + * + * @param root widget which will be seeked. + * + * @name name value. + * + * @return finded result. + */ + UIWidget* seekWidgetByRelativeName(UIWidget* root, const char* name); + void setFileDesignWidth(float width); + float getFileDesignWidth(); + void setFileDesignHeight(float height); + float getFileDesignHeight(); + /*temp action*/ + UIWidget* seekActionWidgetByActionTag(UIWidget* root, int tag); +protected: + + float m_fFileDesignWidth; + float m_fFileDesignHeight; + //texture + CCArray* m_textureFiles; +}; + +NS_CC_EXT_END + +#endif /* defined(__CocoGUI__UISystem__) */ diff --git a/extensions/CocoStudio/GUI/System/UIInputManager.cpp b/extensions/CocoStudio/GUI/System/UIInputManager.cpp new file mode 100644 index 0000000000..55f7c4dda0 --- /dev/null +++ b/extensions/CocoStudio/GUI/System/UIInputManager.cpp @@ -0,0 +1,214 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "UIInputManager.h" +#include "UIHelper.h" + +NS_CC_EXT_BEGIN + +UIInputManager::UIInputManager(): +m_manageredWidget(NULL), +m_bWidgetBeSorted(false), +m_bTouchDown(false), +m_fLongClickTime(0.0), +m_fLongClickRecordTime(0.0), +checkedDoubleClickWidget(NULL), +m_pRootWidget(NULL) +{ + m_manageredWidget = CCArray::create(); + m_manageredWidget->retain(); + checkedDoubleClickWidget = CCArray::create(); + checkedDoubleClickWidget->retain(); + m_pSelectedWidgets = CCArray::create(); + m_pSelectedWidgets->retain(); +} + +UIInputManager::~UIInputManager() +{ + m_manageredWidget->removeAllObjects(); + CC_SAFE_RELEASE_NULL(m_manageredWidget); + checkedDoubleClickWidget->removeAllObjects(); + CC_SAFE_RELEASE_NULL(checkedDoubleClickWidget); + m_pSelectedWidgets->removeAllObjects(); + CC_SAFE_RELEASE_NULL(m_pSelectedWidgets); +} + +void UIInputManager::registWidget(UIWidget* widget) +{ + if (!widget) + { + return; + } + if (m_manageredWidget->containsObject(widget)) + { + return; + } + m_manageredWidget->addObject(widget); +} + +void UIInputManager::uiSceneHasChanged() +{ + m_bWidgetBeSorted = false; +} + +bool UIInputManager::checkTouchEvent(UIWidget *root, const Point &touchPoint) +{ + ccArray* arrayRootChildren = root->getChildren()->data; + int length = arrayRootChildren->num; + for (int i=length-1; i >= 0; i--) + { + UIWidget* widget = (UIWidget*)(arrayRootChildren->arr[i]); + if (checkTouchEvent(widget, touchPoint)) + { + return true; + } + } + if (root->isEnabled() && root->isTouchEnabled() && root->hitTest(touchPoint) && root->clippingParentAreaContainPoint(touchPoint)) + { + m_pSelectedWidgets->addObject(root); + root->onTouchBegan(touchPoint); + return true; + } + return false; +} + +void UIInputManager::removeManageredWidget(UIWidget* widget) +{ + if (!widget) + { + return; + } + if (!m_manageredWidget->containsObject(widget)) + { + return; + } + m_manageredWidget->removeObject(widget); +} + +bool UIInputManager::checkEventWidget(const Point &touchPoint) +{ + checkTouchEvent(m_pRootWidget,touchPoint); + return (m_pSelectedWidgets->count() > 0); +} + +void UIInputManager::addCheckedDoubleClickWidget(UIWidget* widget) +{ + if (checkedDoubleClickWidget->containsObject(widget)) + { + return; + } + checkedDoubleClickWidget->addObject(widget); +} + +void UIInputManager::update(float dt) +{ + if (m_bTouchDown) + { + m_fLongClickRecordTime += dt; + if (m_fLongClickRecordTime >= m_fLongClickTime) + { + m_fLongClickRecordTime = 0; + m_bTouchDown = false; +// m_pCurSelectedWidget->onTouchLongClicked(touchBeganedPoint); + } + } + ccArray* arrayWidget = checkedDoubleClickWidget->data; + int widgetCount = arrayWidget->num; + for (int i=0;iarr[i]); + if (!widget->isVisible()) + { + continue; + } + } +} + +bool UIInputManager::onTouchBegan(Touch* touch) +{ + touchBeganedPoint.x = touch->getLocation().x; + touchBeganedPoint.y = touch->getLocation().y; + m_bTouchDown = true; + return checkEventWidget(touchBeganedPoint); +} + +void UIInputManager::onTouchMoved(Touch* touch) +{ + touchMovedPoint.x = touch->getLocation().x; + touchMovedPoint.y = touch->getLocation().y; + ccArray* selectedWidgetArray = m_pSelectedWidgets->data; + int length = selectedWidgetArray->num; + for (int i=0; iarr[i]); + hitWidget->onTouchMoved(touchMovedPoint); + } + if (m_bTouchDown) + { + m_fLongClickRecordTime = 0; + m_bTouchDown = false; + } +} + +void UIInputManager::onTouchEnd(Touch* touch) +{ + m_bTouchDown = false; + touchEndedPoint.x = touch->getLocation().x; + touchEndedPoint.y = touch->getLocation().y; + ccArray* selectedWidgetArray = m_pSelectedWidgets->data; + int length = selectedWidgetArray->num; + for (int i=0; iarr[i]); + hitWidget->onTouchEnded(touchEndedPoint); + } + m_pSelectedWidgets->removeAllObjects(); +} + +void UIInputManager::onTouchCancelled(Touch* touch) +{ + m_bTouchDown = false; + touchEndedPoint.x = touch->getLocation().x; + touchEndedPoint.y = touch->getLocation().y; + ccArray* selectedWidgetArray = m_pSelectedWidgets->data; + int length = selectedWidgetArray->num; + for (int i=0; iarr[i]); + hitWidget->onTouchCancelled(touchEndedPoint); + } + m_pSelectedWidgets->removeAllObjects(); +} + +void UIInputManager::setRootWidget(UIWidget *root) +{ + m_pRootWidget = root; +} + +UIWidget* UIInputManager::getRootWidget() +{ + return m_pRootWidget; +} + +NS_CC_EXT_END \ No newline at end of file diff --git a/extensions/CocoStudio/GUI/System/UIInputManager.h b/extensions/CocoStudio/GUI/System/UIInputManager.h new file mode 100644 index 0000000000..dd86f7586e --- /dev/null +++ b/extensions/CocoStudio/GUI/System/UIInputManager.h @@ -0,0 +1,105 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __UIINPUTMANAGER_H__ +#define __UIINPUTMANAGER_H__ + +#include "cocos2d.h" +#include "../Layouts/Layout.h" + +NS_CC_EXT_BEGIN + +class UIInputManager +{ +public: + /** + * Default constructor + */ + UIInputManager(); + + /** + * Default destructor + */ + ~UIInputManager(); + + /** + * Regist a widget to input manager. + * + * @param widget registed widget can be touched. + */ + void registWidget(UIWidget* widget); + + /** + * A call back function called when widget tree struct has changed. + * + * If widget tree struct has changed, uiinputmanager will resort registed widgets. + */ + void uiSceneHasChanged(); + + /** + * Remove a registed widget from input manager. + * + * @param widget widget which will be removed. + */ + void removeManageredWidget(UIWidget* widget); + + /** + * Finds a widget which is selected and call it's "onTouchBegan" method. + * + * @param touch point. + * + * @return true that find a widget selected, false otherwise. + */ + bool checkEventWidget(const Point &touchPoint); + + + void update(float dt); + bool onTouchBegan(Touch* touch); + void onTouchMoved(Touch* touch); + void onTouchEnd(Touch* touch); + void onTouchCancelled(Touch* touch); + + void setRootWidget(UIWidget* root); + UIWidget* getRootWidget(); + void addCheckedDoubleClickWidget(UIWidget* widget); +protected: + bool checkTouchEvent(UIWidget* root, const Point& touchPoint); +protected: + Array* m_manageredWidget; + Array* m_pSelectedWidgets; + Point touchBeganedPoint; + Point touchMovedPoint; + Point touchEndedPoint; + Point touchCanceledPoint; + bool m_bWidgetBeSorted; + bool m_bTouchDown; + float m_fLongClickTime; + float m_fLongClickRecordTime; + Array* checkedDoubleClickWidget; + UIWidget* m_pRootWidget; +}; + +NS_CC_EXT_END + +#endif /* defined(__CocoGUI__UIInputManager__) */ diff --git a/extensions/CocoStudio/GUI/System/UILayer.cpp b/extensions/CocoStudio/GUI/System/UILayer.cpp new file mode 100644 index 0000000000..bd3b328db6 --- /dev/null +++ b/extensions/CocoStudio/GUI/System/UILayer.cpp @@ -0,0 +1,210 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "UILayer.h" +#include "UIHelper.h" + +NS_CC_EXT_BEGIN + +UILayer::UILayer(): +m_pRootWidget(NULL), +m_pInputManager(NULL), +m_updateEnableWidget(NULL) +{ + +} + +UILayer::~UILayer() +{ + m_pRootWidget->release(); + CC_SAFE_DELETE(m_pInputManager); + m_updateEnableWidget->removeAllObjects(); + CC_SAFE_RELEASE_NULL(m_updateEnableWidget); +} + +bool UILayer::init() +{ + if (CCLayer::init()) + { + m_pRootWidget = UIRootWidget::create(); + m_pRootWidget->retain(); + m_pRootWidget->onEnter(); + addChild(m_pRootWidget->getRenderer()); + m_pInputManager = new UIInputManager(); + m_pInputManager->setRootWidget(m_pRootWidget); + m_updateEnableWidget = CCArray::create(); + m_updateEnableWidget->retain(); + return true; + } + return false; +} + +UILayer* UILayer::create(void) +{ + UILayer *pRet = new UILayer(); + if (pRet && pRet->init()) + { + pRet->autorelease(); + return pRet; + } + else + { + CC_SAFE_DELETE(pRet); + return NULL; + } +} + +void UILayer::onEnter() +{ + setTouchMode(Touch::DispatchMode::ONE_BY_ONE); + setTouchEnabled(true); + CCLayer::onEnter(); + +} + +void UILayer::onExit() +{ + setTouchEnabled(false); + CCLayer::onExit(); +} + +void UILayer::onEnterTransitionDidFinish() +{ + CCLayer::onEnterTransitionDidFinish(); +} + +void UILayer::addWidget(UIWidget* widget) +{ + m_pRootWidget->addChild(widget); +} + +void UILayer::removeWidget(UIWidget* widget) +{ + m_pRootWidget->removeChild(widget); +} + +void UILayer::setVisible(bool visible) +{ + CCLayer::setVisible(visible); + m_pRootWidget->setVisible(visible); +} + +void UILayer::update(float dt) +{ + if (!m_updateEnableWidget) + { + return; + } + ccArray* arrayWidget = m_updateEnableWidget->data; + int length = arrayWidget->num; + for (int i=0; i(arrayWidget->arr[i])->update(dt); + } +} + +void UILayer::addUpdateEnableWidget(UIWidget* widget) +{ + if (!widget || !m_updateEnableWidget) + { + return; + } + if (m_updateEnableWidget->containsObject(widget)) + { + return; + } + m_updateEnableWidget->addObject(widget); +} + +void UILayer::removeUpdateEnableWidget(UIWidget* widget) +{ + if (!widget || !m_updateEnableWidget) + { + return; + } + if (!m_updateEnableWidget->containsObject(widget)) + { + return; + } + m_updateEnableWidget->removeObject(widget); +} + +UIWidget* UILayer::getWidgetByTag(int tag) +{ + if (!m_pRootWidget) + { + return NULL; + } + return CCUIHELPER->seekWidgetByTag(m_pRootWidget, tag); +} + +UIWidget* UILayer::getWidgetByName(const char* name) +{ + if (!m_pRootWidget) + { + return NULL; + } + return CCUIHELPER->seekWidgetByName(m_pRootWidget, name); +} + +UIRootWidget* UILayer::getRootWidget() +{ + return m_pRootWidget; +} + +UIInputManager* UILayer::getInputManager() +{ + return m_pInputManager; +} + +void UILayer::clear() +{ + m_pRootWidget->removeAllChildren(); +} + +bool UILayer::ccTouchBegan(Touch *pTouch, Event *pEvent) +{ + if (m_pInputManager && m_pInputManager->onTouchBegan(pTouch)) + { + return true; + } + return false; +} + +void UILayer::ccTouchMoved(Touch *pTouch, Event *pEvent) +{ + m_pInputManager->onTouchMoved(pTouch); +} + +void UILayer::ccTouchEnded(Touch *pTouch, Event *pEvent) +{ + m_pInputManager->onTouchEnd(pTouch); +} + +void UILayer::ccTouchCancelled(Touch *pTouch, Event *pEvent) +{ + m_pInputManager->onTouchCancelled(pTouch); +} + +NS_CC_EXT_END \ No newline at end of file diff --git a/extensions/CocoStudio/GUI/System/UILayer.h b/extensions/CocoStudio/GUI/System/UILayer.h new file mode 100644 index 0000000000..d7242f8509 --- /dev/null +++ b/extensions/CocoStudio/GUI/System/UILayer.h @@ -0,0 +1,143 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + + +#ifndef __UILAYER_H__ +#define __UILAYER_H__ + +#include "cocos2d.h" +#include "ExtensionMacros.h" +#include "../BaseClasses/UIRootWidget.h" +#include "../System/UIInputManager.h" + +NS_CC_EXT_BEGIN + + +class UILayer : public Layer +{ + +public: + /** + * Default constructor + */ + UILayer(); + + /** + * Default destructor + */ + virtual ~UILayer(); + + /** + * Allocates and initializes a widget. + */ + static UILayer *create(void); + + //initializes state of uilayer. + virtual bool init(); + + virtual void onEnter(); + virtual void onExit(); + virtual void onEnterTransitionDidFinish(); + + virtual bool ccTouchBegan(Touch *pTouch, Event *pEvent); + virtual void ccTouchMoved(Touch *pTouch, Event *pEvent); + virtual void ccTouchEnded(Touch *pTouch, Event *pEvent); + virtual void ccTouchCancelled(Touch *pTouch, Event *pEvent); + + /** + * Add a widget to UILayer, for drawing. + * + * @param widget. + */ + void addWidget(UIWidget* widget); + + /** + * Remove a widget from UILayer. + * + * @param widget. + * + * @param cleanup true if all running actions on all children widgets should be cleanup, false otherwise. + */ + void removeWidget(UIWidget* widget); + + /** + * Sets whether the UILayer is visible + * + * The default value is true, a UILayer is default to visible + * + * @param visible true if the UILayer is visible, false if the UILayer is hidden. + */ + virtual void setVisible(bool visible); + + /** + * Finds a widget whose tag is equal tag param from widget tree. + * + * @param tag. + */ + UIWidget* getWidgetByTag(int tag); + + /** + * Seek a widget whose name is equal name param from widget tree. + * + * @param name. + */ + UIWidget* getWidgetByName(const char* name); + + /** + * Gets UIInputManager. + * + * UIInputManager is the touch manager of UILayer. + * + * @return UIInputManager. + */ + UIInputManager* getInputManager(); + + /** + * Remove and clean up all of UILayer's widget. + */ + virtual void clear(); + + /** + * Gets root widget of UILayer. + * + * @return UIRootWidget, "UIRootWidget" is the root widget of UILayer. + */ + UIRootWidget* getRootWidget(); + + //update method + void update(float dt); + void addUpdateEnableWidget(UIWidget* widget); + void removeUpdateEnableWidget(UIWidget* widget); + +protected: + UIRootWidget* m_pRootWidget; + UIInputManager* m_pInputManager; + Array* m_updateEnableWidget; +}; + +NS_CC_EXT_END + + + +#endif /* defined(__UILAYER_H__) */ diff --git a/extensions/CocoStudio/GUI/UIWidgets/ScrollWidget/UIDragPanel.cpp b/extensions/CocoStudio/GUI/UIWidgets/ScrollWidget/UIDragPanel.cpp new file mode 100644 index 0000000000..550d67765f --- /dev/null +++ b/extensions/CocoStudio/GUI/UIWidgets/ScrollWidget/UIDragPanel.cpp @@ -0,0 +1,1374 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "UIDragPanel.h" +#include "../../System/UILayer.h" + +NS_CC_EXT_BEGIN + +UIDragPanel::UIDragPanel() +: m_pInnerContainer(NULL) +, m_bTouchPressed(false) +, m_bTouchMoved(false) +, m_bTouchReleased(false) +, m_bTouchCanceld(false) +, m_touchStartNodeSpace(Point::ZERO) +, m_touchStartWorldSpace(Point::ZERO) +, m_touchEndWorldSpace(Point::ZERO) +, m_fSlidTime(0.0f) +, m_eMoveType(DRAGPANEL_MOVE_TYPE_AUTOMOVE) +, m_fAutoMoveDuration(0.5f) +, m_fAutoMoveEaseRate(2.0f) +, m_eBerthDirection(DRAGPANEL_BERTH_DIR_NONE) +, m_pBerthToLeftListener(NULL) +, m_pfnBerthToLeftSelector(NULL) +, m_pBerthToRightListener(NULL) +, m_pfnBerthToRightSelector(NULL) +, m_pBerthToTopListener(NULL) +, m_pfnBerthToTopSelector(NULL) +, m_pBerthToBottomListener(NULL) +, m_pfnBerthToBottomSelector(NULL) +, m_pBerthToLeftBottomListener(NULL) +, m_pfnBerthToLeftBottomSelector(NULL) +, m_pBerthToLeftTopListener(NULL) +, m_pfnBerthToLeftTopSelector(NULL) +, m_pBerthToRightBottomListener(NULL) +, m_pfnBerthToRightBottomSelector(NULL) +, m_pBerthToRightTopListener(NULL) +, m_pfnBerthToRightTopSelector(NULL) +, m_bBounceEnable(false) +, m_eBounceDirection(DRAGPANEL_BOUNCE_DIR_NONE) +, m_fBounceDuration(0.5f) +, m_fBounceEaseRate(2.0f) +, m_pBounceOverListener(NULL) +, m_pfnBounceOverSelector(NULL) +, m_pBounceToLeftBottomListener(NULL) +, m_pfnBounceToLeftBottomSelector(NULL) +, m_pBounceToLeftTopListener(NULL) +, m_pfnBounceToLeftTopSelector(NULL) +, m_pBounceToRightBottomListener(NULL) +, m_pfnBounceToRightBottomSelector(NULL) +, m_pBounceToRightTopListener(NULL) +, m_pfnBounceToRightTopSelector(NULL) +, m_pBounceToLeftListener(NULL) +, m_pfnBounceToLeftSelector(NULL) +, m_pBounceToTopListener(NULL) +, m_pfnBounceToTopSelector(NULL) +, m_pBounceToRightListener(NULL) +, m_pfnBounceToRightSelector(NULL) +, m_pBounceToBottomListener(NULL) +, m_pfnBounceToBottomSelector(NULL) +, m_bRunningAction(false) +, m_nActionType(0) +, m_pActionWidget(NULL) +, m_fDuration(0.0f) +, m_elapsed(0.0f) +, m_bFirstTick(false) +, m_positionDelta(Point::ZERO) +, m_startPosition(Point::ZERO) +, m_previousPosition(Point::ZERO) +, m_endPosition(Point::ZERO) +{ + +} + +UIDragPanel::~UIDragPanel() +{ + +} + +UIDragPanel* UIDragPanel::create() +{ + UIDragPanel* widget = new UIDragPanel(); + if (widget && widget->init()) + { + widget->autorelease(); + return widget; + } + CC_SAFE_DELETE(widget); + return NULL; +} + +bool UIDragPanel::init() +{ + if (Layout::init()) + { + setUpdateEnabled(true); + setTouchEnabled(true); + setClippingEnabled(true); + return true; + } + return false; +} + +void UIDragPanel::initRenderer() +{ + Layout::initRenderer(); + + m_pInnerContainer = Layout::create(); + Layout::addChild(m_pInnerContainer); + +} + +void UIDragPanel::releaseResoures() +{ + setUpdateEnabled(false); + removeAllChildren(); + m_pRenderer->removeAllChildrenWithCleanup(true); + m_pRenderer->removeFromParentAndCleanup(true); + m_pRenderer->release(); + + Layout::removeChild(m_pInnerContainer); + + m_children->release(); +} + +bool UIDragPanel::onTouchBegan(const Point &touchPoint) +{ + bool pass = Layout::onTouchBegan(touchPoint); + handlePressLogic(touchPoint); + return pass; +} + +void UIDragPanel::onTouchMoved(const Point &touchPoint) +{ + Layout::onTouchMoved(touchPoint); + handleMoveLogic(touchPoint); +} + +void UIDragPanel::onTouchEnded(const Point &touchPoint) +{ + Layout::onTouchEnded(touchPoint); + handleReleaseLogic(touchPoint); +} + +void UIDragPanel::onTouchCancelled(const Point &touchPoint) +{ + Layout::onTouchCancelled(touchPoint); +} + +void UIDragPanel::onTouchLongClicked(const Point &touchPoint) +{ + +} + +void UIDragPanel::update(float dt) +{ + // widget action + if (m_bRunningAction) + { + if (actionIsDone()) + { + actionDone(); + actionStop(); + } + else + { + actionStep(dt); + } + } + + recordSlidTime(dt); +} + +bool UIDragPanel::addChild(UIWidget *widget) +{ + m_pInnerContainer->addChild(widget); + return true; +} + +bool UIDragPanel::removeChild(UIWidget *child) +{ + bool value = false; + if (m_pInnerContainer->removeChild(child)) + { + value = true; + } + + return value; +} + +void UIDragPanel::removeAllChildren() +{ + m_pInnerContainer->removeAllChildren(); +} + +Array* UIDragPanel::getChildren() +{ + return m_pInnerContainer->getChildren(); +} + +void UIDragPanel::onSizeChanged() +{ + Layout::onSizeChanged(); + Size innerSize = m_pInnerContainer->getSize(); + float orginInnerSizeWidth = innerSize.width; + float orginInnerSizeHeight = innerSize.height; + float innerSizeWidth = MAX(orginInnerSizeWidth, m_size.width); + float innerSizeHeight = MAX(orginInnerSizeHeight, m_size.height); + m_pInnerContainer->setSize(Size(innerSizeWidth, innerSizeHeight)); +} + +const Size& UIDragPanel::getInnerContainerSize() const +{ + return m_pInnerContainer->getContentSize(); +} + +void UIDragPanel::setInnerContainerSize(const cocos2d::Size &size) +{ + float innerSizeWidth = m_size.width; + float innerSizeHeight = m_size.height; + if (size.width < m_size.width) + { + CCLOG("Inner width <= scrollview width, it will be force sized!"); + } + else + { + innerSizeWidth = size.width; + } + if (size.height < m_size.height) + { + CCLOG("Inner height <= scrollview height, it will be force sized!"); + } + else + { + innerSizeHeight = size.height; + } + m_pInnerContainer->setSize(Size(innerSizeWidth, innerSizeHeight)); + m_pInnerContainer->setPosition(Point(0, m_size.height - m_pInnerContainer->getSize().height)); +} + +const Point& UIDragPanel::getInnerContainerPosition() const +{ + return m_pInnerContainer->getPosition(); +} + +void UIDragPanel::setInnerContainerPosition(const Point &point, bool animated) +{ + Point delta = point - m_pInnerContainer->getPosition(); + setInnerContainerOffset(delta, animated); +} + +void UIDragPanel::setInnerContainerOffset(const Point &offset, bool animated) +{ + if (animated) + { + Point delta = offset; + + if (checkToBoundaryWithDeltaPosition(delta)) + { + delta = calculateToBoundaryDeltaPosition(delta); + } + actionStartWithWidget(m_pInnerContainer); + moveByWithDuration(m_fAutoMoveDuration, delta); + } + else + { + setInnerContainerOffset(offset); + } +} + +void UIDragPanel::setInnerContainerOffset(const Point &offset) +{ + Point delta = offset; + + if (checkToBoundaryWithDeltaPosition(delta)) + { + delta = calculateToBoundaryDeltaPosition(delta); + } + moveWithDelta(delta); + if (checkBerth()) + { + berthEvent(); + } +} + + +void UIDragPanel::handlePressLogic(const Point &touchPoint) +{ + // check inner rect < drag panel rect + if (checkContainInnerRect()) + { + m_bTouchPressed = false; + return; + } + + m_bTouchPressed = true; + m_bTouchMoved = false; + m_bTouchReleased = false; + m_bTouchCanceld = false; + + if (m_bRunningAction) + { + switch (m_eMoveType) + { + case DRAGPANEL_MOVE_TYPE_AUTOMOVE: + stopAutoMove(); + actionStop(); + break; + + case DRAGPANEL_MOVE_TYPE_BOUNCE: + m_bTouchPressed = false; + break; + + default: + break; + } + } + + Point nsp = m_pRenderer->convertToNodeSpace(touchPoint); + m_touchStartNodeSpace = nsp; + + m_touchStartWorldSpace = touchPoint; +} + +void UIDragPanel::handleMoveLogic(const Point &touchPoint) +{ + if (!m_bTouchPressed) + { + return; + } + + // check touch out of drag panel boundary + if (m_bTouchCanceld) + { + return; + } + + m_bTouchMoved = true; + + Point nsp = m_pRenderer->convertToNodeSpace(touchPoint); + Point delta = nsp - m_touchStartNodeSpace; + m_touchStartNodeSpace = nsp; + + // reset berth dir to none + if (!m_bBounceEnable) + { + m_eBerthDirection = DRAGPANEL_BERTH_DIR_NONE; + } + + // check will berth (bounce disable) + if (!m_bBounceEnable) + { + if (checkToBoundaryWithDeltaPosition(delta)) + { + delta = calculateToBoundaryDeltaPosition(delta); + } + } + // move + moveWithDelta(delta); + // check bounce or berth + if (m_bBounceEnable) + { + // bounce + if (!hitTest(touchPoint)) + { + m_bTouchMoved = false; + + if (checkNeedBounce()) + { + m_bTouchCanceld = true; + startBounce(); + } + } + } + else + { + // berth + if (checkBerth()) + { + berthEvent(); + } + } +} + +void UIDragPanel::handleReleaseLogic(const Point &touchPoint) +{ + if (!m_bTouchPressed) + { + return; + } + + m_bTouchPressed = false; + m_bTouchMoved = false; + m_bTouchReleased = true; + m_bTouchCanceld = false; + + // check touch out of drag panel boundary + if (m_bTouchCanceld) + { + return; + } + + if (hitTest(touchPoint)) + { + m_touchEndWorldSpace = touchPoint; + startAutoMove(); + } +} + +void UIDragPanel::checkChildInfo(int handleState, UIWidget *sender, const Point &touchPoint) +{ + interceptTouchEvent(handleState, sender, touchPoint); +} + +void UIDragPanel::interceptTouchEvent(int handleState, UIWidget *sender, const Point &touchPoint) +{ + switch (handleState) + { + case 0: + handlePressLogic(touchPoint); + break; + + case 1: + { + float offset = sender->getTouchStartPos().getDistance(touchPoint); + if (offset > 5.0) + { + sender->setFocused(false); + handleMoveLogic(touchPoint); + } + } + break; + + case 2: + handleReleaseLogic(touchPoint); + break; + + case 3: + break; + } +} + +void UIDragPanel::recordSlidTime(float dt) +{ + if (m_bTouchPressed) + { + m_fSlidTime += dt; + } +} + +// check if dragpanel rect contain inner rect +bool UIDragPanel::checkContainInnerRect() +{ + float width = m_size.width; + float height = m_size.height; + float innerWidth = m_pInnerContainer->getSize().width; + float innerHeight = m_pInnerContainer->getSize().height; + + if (innerWidth <= width && innerHeight <= height) + { + return true; + } + + return false; +} + +// move +void UIDragPanel::moveWithDelta(const Point &delta) +{ + Point newPos = m_pInnerContainer->getPosition() + delta; + m_pInnerContainer->setPosition(newPos); +} + +// auto move +void UIDragPanel::autoMove() +{ + if (m_bBounceEnable) + { + if (checkNeedBounce()) + { + stopAutoMove(); + startBounce(); + } + } +} + +void UIDragPanel::autoMoveOver() +{ + stopAutoMove(); + + if (checkBerth()) + { + berthEvent(); + m_eBerthDirection = DRAGPANEL_BERTH_DIR_NONE; + } +} + +void UIDragPanel::startAutoMove() +{ + m_eMoveType = DRAGPANEL_MOVE_TYPE_AUTOMOVE; + + actionStop(); + + Point delta = m_touchEndWorldSpace - m_touchStartWorldSpace; + delta.x /= m_fSlidTime * 60; + delta.y /= m_fSlidTime * 60; + m_fSlidTime = 0.0; + + // bounceEnable is disable + if (!m_bBounceEnable) + { + if (checkToBoundaryWithDeltaPosition(delta)) + { + delta = calculateToBoundaryDeltaPosition(delta); + } + } + actionStartWithWidget(m_pInnerContainer); + moveByWithDuration(m_fAutoMoveDuration, delta); +} + +void UIDragPanel::stopAutoMove() +{ + m_eMoveType = DRAGPANEL_MOVE_TYPE_NONE; +} + +void UIDragPanel::setAutoMoveDuration(float duration) +{ + m_fAutoMoveDuration = duration; +} + +void UIDragPanel::setAutoMoveEaseRate(float rate) +{ + m_fAutoMoveEaseRate = rate; +} + +// berth + +// check if move to boundary + +bool UIDragPanel::checkToBoundaryWithDeltaPosition(const Point& delta) +{ + float innerLeft = m_pInnerContainer->getLeftInParent(); + float innerTop = m_pInnerContainer->getTopInParent(); + float innerRight = m_pInnerContainer->getRightInParent(); + float innerBottom = m_pInnerContainer->getBottomInParent(); + + float left = 0; + float top = m_size.height; + float right = m_size.width; + float bottom = 0; + + bool toLeftBottom = false; + bool toLeftTop = false; + bool toRightBottom = false; + bool toRightTop = false; + bool toLeft = false; + bool toRight = false; + bool toTop = false; + bool toBottom = false; + + if (innerLeft + delta.x > left && innerBottom + delta.y > bottom) // left bottom + { + toLeftBottom = true; + } + else if (innerLeft + delta.x > left && innerTop + delta.y < top) // left top + { + toLeftTop = true; + } + else if (innerRight + delta.x < right && innerBottom + delta.y > bottom) // right bottom + { + toRightBottom = true; + } + else if (innerRight + delta.x < right && innerTop + delta.y < top) // right top + { + toRightTop = true; + } + else if (innerLeft + delta.x > left) // left + { + toLeft = true; + } + else if (innerRight + delta.x < right) // right + { + toRight = true; + } + else if (innerTop + delta.y < top) // top + { + toTop = true; + } + else if (innerBottom + delta.y > bottom) // bottom + { + toBottom = true; + } + + if (toLeft || toTop || toRight || toBottom + || toLeftBottom || toLeftTop || toRightBottom || toRightTop) + { + return true; + } + + return false; +} + +Point UIDragPanel::calculateToBoundaryDeltaPosition(const Point& paramDelta) +{ + float innerLeft = m_pInnerContainer->getLeftInParent(); + float innerTop = m_pInnerContainer->getTopInParent(); + float innerRight = m_pInnerContainer->getRightInParent(); + float innerBottom = m_pInnerContainer->getBottomInParent(); + + float left = 0; + float top = m_size.height; + float right = m_size.width; + float bottom = 0; + + Point delta = paramDelta; + + if (innerLeft + delta.x > left && innerBottom + delta.y > bottom) // left bottom + { + delta.x = left - innerLeft; + delta.y = bottom - innerBottom; + } + else if (innerLeft + delta.x > left && innerTop + delta.y < top) // left top + { + delta.x = left - innerLeft; + delta.y = top - innerTop; + } + else if (innerRight + delta.x < right && innerBottom + delta.y > bottom) // right bottom + { + delta.x = right - innerRight; + delta.y = bottom - innerBottom; + } + else if (innerRight + delta.x < right && innerTop + delta.y < top) // right bottom + { + delta.x = right - innerRight; + delta.y = top - innerTop; + } + else if (innerLeft + delta.x > left) // left + { + delta.x = left - innerLeft; + } + else if (innerRight + delta.x < right) // right + { + delta.x = right - innerRight; + } + else if (innerTop + delta.y < top) // top + { + delta.y = top - innerTop; + } + else if (innerBottom + delta.y > bottom) // bottom + { + delta.y = bottom - innerBottom; + } + + return delta; +} + +bool UIDragPanel::isBerth() +{ + return m_eBerthDirection != DRAGPANEL_BERTH_DIR_NONE; +} + +// check berth +bool UIDragPanel::checkBerth() +{ + float innerLeft = m_pInnerContainer->getLeftInParent(); + float innerTop = m_pInnerContainer->getTopInParent(); + float innerRight = m_pInnerContainer->getRightInParent(); + float innerBottom = m_pInnerContainer->getBottomInParent(); + + float left = 0; + float top = m_size.height; + float right = m_size.width; + float bottom = 0; + + if (innerLeft == left && innerBottom == bottom) // left bottom + { + m_eBerthDirection = DRAGPANEL_BERTH_DIR_LEFTBOTTOM; + } + else if (innerLeft == left && innerTop == top) // left top + { + m_eBerthDirection = DRAGPANEL_BERTH_DIR_LFETTOP; + } + else if (innerRight == right && innerBottom == bottom) // right bottom + { + m_eBerthDirection = DRAGPANEL_BERTH_DIR_RIGHTBOTTOM; + } + else if (innerRight == right && innerTop == top) // right top + { + m_eBerthDirection = DRAGPANEL_BERTH_DIR_RIGHTTOP; + } + else if (innerLeft == left) // left + { + m_eBerthDirection = DRAGPANEL_BERTH_DIR_LEFT; + } + else if (innerRight == right) // right + { + m_eBerthDirection = DRAGPANEL_BERTH_DIR_RIGHT; + } + else if (innerTop == top) // top + { + m_eBerthDirection = DRAGPANEL_BERTH_DIR_TOP; + } + else if (innerBottom == bottom) // bottom + { + m_eBerthDirection = DRAGPANEL_BERTH_DIR_BOTTOM; + } + + if (m_eBerthDirection != DRAGPANEL_BERTH_DIR_NONE) + { + return true; + } + + return false; +} + +void UIDragPanel::berthEvent() +{ + switch (m_eBerthDirection) + { + case DRAGPANEL_BERTH_DIR_LEFTBOTTOM: + berthToLeftBottomEvent(); + break; + + case DRAGPANEL_BERTH_DIR_LFETTOP: + berthToLeftTopEvent(); + break; + + case DRAGPANEL_BERTH_DIR_RIGHTBOTTOM: + berthToRightBottomEvent(); + break; + + case DRAGPANEL_BERTH_DIR_RIGHTTOP: + berthToRightTopEvent(); + break; + + case DRAGPANEL_BERTH_DIR_LEFT: + berthToLeftEvent(); + break; + + case DRAGPANEL_BERTH_DIR_TOP: + berthToTopEvent(); + break; + + case DRAGPANEL_BERTH_DIR_RIGHT: + berthToRightEvent(); + break; + + case DRAGPANEL_BERTH_DIR_BOTTOM: + berthToBottomEvent(); + break; + + default: + break; + } +} + +void UIDragPanel::berthToLeftBottomEvent() +{ + if (m_pBerthToLeftBottomListener && m_pfnBerthToLeftBottomSelector) + { + (m_pBerthToLeftBottomListener->*m_pfnBerthToLeftBottomSelector)(this); + } +} + +void UIDragPanel::berthToLeftTopEvent() +{ + if (m_pBerthToLeftTopListener && m_pfnBerthToLeftTopSelector) + { + (m_pBerthToLeftTopListener->*m_pfnBerthToLeftTopSelector)(this); + } +} + +void UIDragPanel::berthToRightBottomEvent() +{ + if (m_pBerthToRightBottomListener && m_pfnBerthToRightBottomSelector) + { + (m_pBerthToRightBottomListener->*m_pfnBerthToRightBottomSelector)(this); + } +} + +void UIDragPanel::berthToRightTopEvent() +{ + if (m_pBerthToRightTopListener && m_pfnBerthToRightTopSelector) + { + (m_pBerthToRightTopListener->*m_pfnBerthToRightTopSelector)(this); + } +} + +void UIDragPanel::berthToLeftEvent() +{ + if (m_pBerthToLeftListener && m_pfnBerthToLeftSelector) + { + (m_pBerthToLeftListener->*m_pfnBerthToLeftSelector)(this); + } +} + +void UIDragPanel::berthToTopEvent() +{ + if (m_pBerthToTopListener && m_pfnBerthToTopSelector) + { + (m_pBerthToTopListener->*m_pfnBerthToTopSelector)(this); + } +} + +void UIDragPanel::berthToRightEvent() +{ + if (m_pBerthToRightListener && m_pfnBerthToRightSelector) + { + (m_pBerthToRightListener->*m_pfnBerthToRightSelector)(this); + } +} + +void UIDragPanel::berthToBottomEvent() +{ + if (m_pBerthToBottomListener && m_pfnBerthToBottomSelector) + { + (m_pBerthToBottomListener->*m_pfnBerthToBottomSelector)(this); + } +} + +void UIDragPanel::addBerthToLeftBottomEvent(Object *target, SEL_DragPanelBerthToLeftBottomEvent selector) +{ + m_pBerthToLeftBottomListener = target; + m_pfnBerthToLeftBottomSelector = selector; +} + +void UIDragPanel::addBerthToLeftTopEvent(Object *target, SEL_DragPanelBerthToLeftTopEvent selector) +{ + m_pBerthToLeftTopListener = target; + m_pfnBerthToLeftTopSelector = selector; +} + +void UIDragPanel::addBerthToRightBottomEvent(Object *target, SEL_DragPanelBerthToRightBottomEvent selector) +{ + m_pBerthToRightBottomListener = target; + m_pfnBerthToRightBottomSelector = selector; +} + +void UIDragPanel::addBerthToRightTopEvent(Object *target, SEL_DragPanelBerthToRightTopEvent selector) +{ + m_pBerthToRightTopListener = target; + m_pfnBerthToRightTopSelector = selector; +} + +void UIDragPanel::addBerthToLeftEvent(Object *target, SEL_DragPanelBerthToLeftEvent selector) +{ + m_pBerthToLeftListener = target; + m_pfnBerthToLeftSelector = selector; +} + +void UIDragPanel::addBerthToTopEvent(Object *target, SEL_DragPanelBerthToTopEvent selector) +{ + m_pBerthToTopListener = target; + m_pfnBerthToTopSelector = selector; +} + +void UIDragPanel::addBerthToRightEvent(Object *target, SEL_DragPanelBerthToRightEvent selector) +{ + m_pBerthToRightListener = target; + m_pfnBerthToRightSelector = selector; +} + +void UIDragPanel::addBerthToBottomEvent(Object *target, SEL_DragPanelBerthToBottomEvent selector) +{ + m_pBerthToBottomListener = target; + m_pfnBerthToBottomSelector = selector; +} + + +// bounce +bool UIDragPanel::isBounceEnable() +{ + return m_bBounceEnable; +} + +void UIDragPanel::setBounceEnable(bool bounce) +{ + m_bBounceEnable = bounce; +} + +bool UIDragPanel::checkNeedBounce() +{ + float innerLeft = m_pInnerContainer->getLeftInParent(); + float innerTop = m_pInnerContainer->getTopInParent(); + float innerRight = m_pInnerContainer->getRightInParent(); + float innerBottom = m_pInnerContainer->getBottomInParent(); + + float left = 0; + float top = m_size.height; + float right = m_size.width; + float bottom = 0; + + bool need = ((innerLeft > left && innerBottom > bottom) + || (innerLeft > left && innerTop < top) + || (innerRight < right && innerBottom > bottom) + || (innerRight < right && innerTop < top) + || (innerLeft > left) + || (innerTop < top) + || (innerRight < right) + || (innerBottom > bottom)); + return need; +} + +void UIDragPanel::startBounce() +{ + if (m_eMoveType == DRAGPANEL_MOVE_TYPE_BOUNCE) + { + return; + } + + actionStop(); + m_eMoveType = DRAGPANEL_MOVE_TYPE_BOUNCE; + bounceToCorner(); +} + +void UIDragPanel::stopBounce() +{ + m_eMoveType = DRAGPANEL_MOVE_TYPE_NONE; +} + +void UIDragPanel::bounceToCorner() +{ + float innerLeft = m_pInnerContainer->getLeftInParent(); + float innerTop = m_pInnerContainer->getTopInParent(); + float innerRight = m_pInnerContainer->getRightInParent(); + float innerBottom = m_pInnerContainer->getBottomInParent(); + + float width = m_size.width; + float height = m_size.height; + float left = 0; + float top = height; + float right = width; + float bottom = 0; + + float from_x = 0; + float from_y = 0; + float to_x = 0; + float to_y = 0; + Point delta = Point::ZERO; + + if (innerLeft > left && innerBottom > bottom) // left bottom + { + from_x = innerLeft; + from_y = innerBottom; + to_x = left; + to_y = bottom; + + m_eBounceDirection = DRAGPANEL_BOUNCE_DIR_LEFTBOTTOM; + } + else if (innerLeft > left && innerTop < top) // left top + { + from_x = innerLeft; + from_y = innerTop; + to_x = left; + to_y = top; + + m_eBounceDirection = DRAGPANEL_BOUNCE_DIR_LEFTTOP; + } + else if (innerRight < right && innerBottom > bottom) // right bottom + { + from_x = innerRight; + from_y = innerBottom; + to_x = right; + to_y = bottom; + + m_eBounceDirection = DRAGPANEL_BOUNCE_DIR_RIGHTBOTTOM; + } + else if (innerRight < right && innerTop < top) // right top + { + from_x = innerRight; + from_y = innerTop; + to_x = right; + to_y = top; + + m_eBounceDirection = DRAGPANEL_BOUNCE_DIR_RIGHTTOP; + } + else if (innerLeft > left) // left + { + from_x = innerLeft; + from_y = innerBottom; + to_x = left; + to_y = from_y; + + m_eBounceDirection = DRAGPANEL_BOUNCE_DIR_LEFT; + } + else if (innerTop < top) // top + { + from_x = innerLeft; + from_y = innerTop; + to_x = from_x; + to_y = top; + + m_eBounceDirection = DRAGPANEL_BOUNCE_DIR_TOP; + } + else if (innerRight < right) // right + { + from_x = innerRight; + from_y = innerBottom; + to_x = right; + to_y = from_y; + + m_eBounceDirection = DRAGPANEL_BOUNCE_DIR_RIGHT; + } + else if (innerBottom > bottom) // bottom + { + from_x = innerLeft; + from_y = innerBottom; + to_x = from_x; + to_y = bottom; + + m_eBounceDirection = DRAGPANEL_BOUNCE_DIR_BOTTOM; + } + delta = Point(to_x, to_y) + Point(from_x, from_y); + + actionStartWithWidget(m_pInnerContainer); + moveByWithDuration(m_fBounceDuration, delta); +} + +void UIDragPanel::bounceOver() +{ + stopBounce(); + + bounceOverEvent(); + + switch (m_eBounceDirection) + { + case DRAGPANEL_BOUNCE_DIR_LEFTBOTTOM: + bounceToLeftBottomEvent(); + break; + + case DRAGPANEL_BOUNCE_DIR_LEFTTOP: + bounceToLeftTopEvent(); + break; + + case DRAGPANEL_BOUNCE_DIR_RIGHTBOTTOM: + bounceToRightBottomEvent(); + break; + + case DRAGPANEL_BOUNCE_DIR_RIGHTTOP: + bounceToRightTopEvent(); + break; + + case DRAGPANEL_BOUNCE_DIR_LEFT: + bounceToLeftEvent(); + break; + + case DRAGPANEL_BOUNCE_DIR_TOP: + bounceToTopEvent(); + break; + + case DRAGPANEL_BOUNCE_DIR_RIGHT: + bounceToRightEvent(); + break; + + case DRAGPANEL_BOUNCE_DIR_BOTTOM: + bounceToBottomEvent(); + break; + + default: + break; + } + + m_eBounceDirection = DRAGPANEL_BOUNCE_DIR_NONE; +} + +void UIDragPanel::bounceOverEvent() +{ + if (m_pBounceOverListener && m_pfnBounceOverSelector) + { + (m_pBounceOverListener->*m_pfnBounceOverSelector)(this); + } +} + +void UIDragPanel::bounceToLeftBottomEvent() +{ + if (m_pBounceToLeftBottomListener && m_pfnBounceToLeftBottomSelector) + { + (m_pBounceToLeftBottomListener->*m_pfnBounceToLeftBottomSelector)(this); + } +} + +void UIDragPanel::bounceToLeftTopEvent() +{ + if (m_pBounceToLeftTopListener && m_pfnBounceToLeftTopSelector) + { + (m_pBounceToLeftTopListener->*m_pfnBounceToLeftTopSelector)(this); + } +} + +void UIDragPanel::bounceToRightBottomEvent() +{ + if (m_pBounceToRightBottomListener && m_pfnBounceToRightBottomSelector) + { + (m_pBounceToRightBottomListener->*m_pfnBounceToRightBottomSelector)(this); + } +} + +void UIDragPanel::bounceToRightTopEvent() +{ + if (m_pBounceToRightTopListener && m_pfnBounceToRightTopSelector) + { + (m_pBounceToRightTopListener->*m_pfnBounceToRightTopSelector)(this); + } +} + +void UIDragPanel::bounceToLeftEvent() +{ + if (m_pBounceToLeftListener && m_pfnBounceToLeftSelector) + { + (m_pBounceToLeftListener->*m_pfnBounceToLeftSelector)(this); + } +} + +void UIDragPanel::bounceToTopEvent() +{ + if (m_pBounceToTopListener && m_pfnBounceToTopSelector) + { + (m_pBounceToTopListener->*m_pfnBounceToTopSelector)(this); + } +} + +void UIDragPanel::bounceToRightEvent() +{ + if (m_pBounceToRightListener && m_pfnBounceToRightSelector) + { + (m_pBounceToRightListener->*m_pfnBounceToRightSelector)(this); + } +} + +void UIDragPanel::bounceToBottomEvent() +{ + if (m_pBounceToBottomListener && m_pfnBounceToBottomSelector) + { + (m_pBounceToBottomListener->*m_pfnBounceToBottomSelector)(this); + } +} + +void UIDragPanel::addBounceOverEvent(Object *target, SEL_DragPanelBounceOverEvent selector) +{ + m_pBounceOverListener = target; + m_pfnBounceOverSelector = selector; +} + +void UIDragPanel::addBounceToLeftBottomEvent(Object *target, SEL_DragPanelBounceToLeftBottomEvent selector) +{ + m_pBounceToLeftBottomListener = target; + m_pfnBounceToLeftBottomSelector = selector; +} + +void UIDragPanel::addBounceToLeftTopEvent(Object *target, SEL_DragPanelBounceToLeftTopEvent selector) +{ + m_pBounceToLeftTopListener = target; + m_pfnBounceToLeftTopSelector = selector; +} + +void UIDragPanel::addBounceToRightBottomEvent(Object *target, SEL_DragPanelBounceToRightBottomEvent selector) +{ + m_pBounceToRightBottomListener = target; + m_pfnBounceToRightBottomSelector = selector; +} + +void UIDragPanel::addBounceToRightTopEvent(Object *target, SEL_DragPanelBounceToRightTopEvent selector) +{ + m_pBounceToRightTopListener = target; + m_pfnBounceToRightTopSelector = selector; +} + +void UIDragPanel::addBounceToLeftEvent(Object *target, SEL_DragPanelBounceToLeftEvent selector) +{ + m_pBounceToLeftListener = target; + m_pfnBounceToLeftSelector = selector; +} + +void UIDragPanel::addBounceToTopEvent(Object *target, SEL_DragPanelBounceToTopEvent selector) +{ + m_pBounceToTopListener = target; + m_pfnBounceToTopSelector = selector; +} + +void UIDragPanel::addBounceToRightEvent(Object *target, SEL_DragPanelBounceToRightEvent selector) +{ + m_pBounceToRightListener = target; + m_pfnBounceToRightSelector = selector; +} + +void UIDragPanel::addBounceToBottomEvent(Object *target, SEL_DragPanelBounceToBottomEvent selector) +{ + m_pBounceToBottomListener = target; + m_pfnBounceToBottomSelector = selector; +} + +// widget action +void UIDragPanel::actionWithDuration(float duration) +{ + m_fDuration = duration; + + if (m_fDuration == 0) + { + m_fDuration = FLT_EPSILON; + } + + m_elapsed = 0; + m_bFirstTick = true; +} + +bool UIDragPanel::actionIsDone() +{ + bool value = (m_elapsed >= m_fDuration); + return value; +} + +void UIDragPanel::actionStartWithWidget(UIWidget *widget) +{ + m_bRunningAction = true; + m_pActionWidget = widget; +} + +void UIDragPanel::actionStep(float dt) +{ + if (m_bFirstTick) + { + m_bFirstTick = false; + m_elapsed = 0; + } + else + { + m_elapsed += dt; + } + + actionUpdate(MAX (0, + MIN(1, m_elapsed / + MAX(m_fDuration, FLT_EPSILON) + ) + ) + ); +} + +void UIDragPanel::actionUpdate(float dt) +{ + switch (m_nActionType) + { + case 1: // move by + moveByUpdate(dt); + break; + + case 2: // move to + moveToUpdate(dt); + break; + + default: + break; + } +} + +void UIDragPanel::actionStop() +{ + m_bRunningAction = false; +} + +void UIDragPanel::actionDone() +{ + switch (m_eMoveType) + { + case DRAGPANEL_MOVE_TYPE_AUTOMOVE: + autoMoveOver(); + break; + + case DRAGPANEL_MOVE_TYPE_BOUNCE: + bounceOver(); + break; + + default: + break; + } +} + +// move by +void UIDragPanel::moveByWithDuration(float duration, const Point& deltaPosition) +{ + actionWithDuration(duration); + m_positionDelta = deltaPosition; + moveByInit(); + m_nActionType = 1; +} + +void UIDragPanel::moveByInit() +{ + m_previousPosition = m_startPosition = m_pActionWidget->getPosition(); +} + +void UIDragPanel::moveByUpdate(float t) +{ + float easeRate = 0.0f; + switch (m_eMoveType) + { + case DRAGPANEL_MOVE_TYPE_AUTOMOVE: + easeRate = m_fAutoMoveEaseRate; + break; + + case DRAGPANEL_MOVE_TYPE_BOUNCE: + easeRate = m_fBounceEaseRate; + break; + + default: + break; + } + t = powf(t, 1 / easeRate); + + Point currentPos = m_pActionWidget->getPosition(); + Point diff = currentPos - m_previousPosition; + m_startPosition = m_startPosition + diff; + + Point newPos = m_startPosition + (m_positionDelta * t); + m_pActionWidget->setPosition(newPos); + m_previousPosition = newPos; + + switch (m_eMoveType) + { + case DRAGPANEL_MOVE_TYPE_AUTOMOVE: + autoMove(); + break; + + default: + break; + } +} + +// move to +void UIDragPanel::moveToWithDuration(float duration, const Point& position) +{ + actionWithDuration(duration); + m_endPosition = position; + moveToInit(); + m_nActionType = 2; +} + +void UIDragPanel::moveToInit() +{ + moveByInit(); + m_positionDelta = m_endPosition - m_pActionWidget->getPosition(); +} + +void UIDragPanel::moveToUpdate(float t) +{ + moveByUpdate(t); +} + +Layout* UIDragPanel::getInnerContainer() +{ + return m_pInnerContainer; +} + +NS_CC_EXT_END \ No newline at end of file diff --git a/extensions/CocoStudio/GUI/UIWidgets/ScrollWidget/UIDragPanel.h b/extensions/CocoStudio/GUI/UIWidgets/ScrollWidget/UIDragPanel.h new file mode 100644 index 0000000000..b1e9efc35b --- /dev/null +++ b/extensions/CocoStudio/GUI/UIWidgets/ScrollWidget/UIDragPanel.h @@ -0,0 +1,407 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __UIDRAGPANEL_H__ +#define __UIDRAGPANEL_H__ + +#include "../../Layouts/Layout.h" +#include "UIScrollInterface.h" + +NS_CC_EXT_BEGIN + +/** + * drag panel move type + */ +enum DRAGPANEL_MOVE_TYPE +{ + DRAGPANEL_MOVE_TYPE_NONE, + DRAGPANEL_MOVE_TYPE_AUTOMOVE, + DRAGPANEL_MOVE_TYPE_BOUNCE, +}; + +/** + * dragpanel berth direction + */ +enum DRAGPANEL_BERTH_DIR +{ + DRAGPANEL_BERTH_DIR_NONE, + DRAGPANEL_BERTH_DIR_LEFTBOTTOM, + DRAGPANEL_BERTH_DIR_LFETTOP, + DRAGPANEL_BERTH_DIR_RIGHTBOTTOM, + DRAGPANEL_BERTH_DIR_RIGHTTOP, + DRAGPANEL_BERTH_DIR_LEFT, + DRAGPANEL_BERTH_DIR_TOP, + DRAGPANEL_BERTH_DIR_RIGHT, + DRAGPANEL_BERTH_DIR_BOTTOM, +}; + +/** + * dragpanel bounce direction + */ +enum DRAGPANEL_BOUNCE_DIR +{ + DRAGPANEL_BOUNCE_DIR_NONE, + DRAGPANEL_BOUNCE_DIR_LEFTBOTTOM, + DRAGPANEL_BOUNCE_DIR_LEFTTOP, + DRAGPANEL_BOUNCE_DIR_RIGHTBOTTOM, + DRAGPANEL_BOUNCE_DIR_RIGHTTOP, + DRAGPANEL_BOUNCE_DIR_LEFT, + DRAGPANEL_BOUNCE_DIR_TOP, + DRAGPANEL_BOUNCE_DIR_RIGHT, + DRAGPANEL_BOUNCE_DIR_BOTTOM, +}; + +/** + * dragpanel berth event + */ +typedef void (Object::*SEL_DragPanelBerthToLeftBottomEvent)(Object*); +#define coco_DragPane_BerthToLeftBottom_selector(_SELECTOR) (SEL_DragPanelBerthToLeftBottomEvent)(&_SELECTOR) +typedef void (Object::*SEL_DragPanelBerthToLeftTopEvent)(Object*); +#define coco_DragPanel_BerthToLeftTop_selector(_SELECTOR) (SEL_DragPanelBerthToLeftTopEvent)(&_SELECTOR) +typedef void (Object::*SEL_DragPanelBerthToRightBottomEvent)(Object*); +#define coco_DragPanel_BerthToRightBottom_selector(_SELECTOR) (SEL_DragPanelBerthToRightBottomEvent)(&_SELECTOR) +typedef void (Object::*SEL_DragPanelBerthToRightTopEvent)(Object*); +#define coco_DragPanel_BerthToRightTop_selector(_SELECTOR) (SEL_DragPanelBerthToRightTopEvent)(&_SELECTOR) +typedef void (Object::*SEL_DragPanelBerthToLeftEvent)(Object*); +#define coco_DragPanel_BerthToLeft_selector(_SELECTOR) (SEL_DragPanelBerthToLeftEvent)(&_SELECTOR) +typedef void (Object::*SEL_DragPanelBerthToRightEvent)(Object*); +#define coco_DragPanel_BerthToRight_selector(_SELECTOR) (SEL_DragPanelBerthToRightEvent)(&_SELECTOR) +typedef void (Object::*SEL_DragPanelBerthToTopEvent)(Object*); +#define coco_DragPanel_BerthToTop_selector(_SELECTOR) (SEL_DragPanelBerthToTopEvent)(&_SELECTOR) +typedef void (Object::*SEL_DragPanelBerthToBottomEvent)(Object*); +#define coco_DragPanel_BerthToBottom_selector(_SELECTOR) (SEL_DragPanelBerthToBottomEvent)(&_SELECTOR) + +/** + * dragpanel bounce event + */ +typedef void (Object::*SEL_DragPanelBounceOverEvent)(Object*); +#define coco_DragPanel_BounceOver_selector(_SELECTOR) (SEL_DragPanelBounceOverEvent)(&_SELECTOR) +typedef void (Object::*SEL_DragPanelBounceToLeftBottomEvent)(Object*); +#define coco_DragPanel_BounceToLeftBottom_selector(_SELECTOR) (SEL_DragPanelBounceToLeftBottomEvent)(&_SELECTOR) +typedef void (Object::*SEL_DragPanelBounceToLeftTopEvent)(Object*); +#define coco_DragPanel_BounceToLeftTop_selector(_SELECTOR) (SEL_DragPanelBounceToLeftTopEvent)(&_SELECTOR) +typedef void (Object::*SEL_DragPanelBounceToRightBottomEvent)(Object*); +#define coco_DragPanel_BounceToRightBottom_selector(_SELECTOR) (SEL_DragPanelBounceToRightBottomEvent)(&_SELECTOR) +typedef void (Object::*SEL_DragPanelBounceToRightTopEvent)(Object*); +#define coco_DragPanel_BounceToRightTop_selector(_SELECTOR) (SEL_DragPanelBounceToRightTopEvent)(&_SELECTOR) +typedef void (Object::*SEL_DragPanelBounceToLeftEvent)(Object*); +#define coco_DragPanel_BounceToLeft_selector(_SELECTOR) (SEL_DragPanelBounceToLeftEvent)(&_SELECTOR) +typedef void (Object::*SEL_DragPanelBounceToTopEvent)(Object*); +#define coco_DragPanel_BounceToTop_selector(_SELECTOR) (SEL_DragPanelBounceToTopEvent)(&_SELECTOR) +typedef void (Object::*SEL_DragPanelBounceToRightEvent)(Object*); +#define coco_DragPanel_BounceToRight_selector(_SELECTOR) (SEL_DragPanelBounceToRightEvent)(&_SELECTOR) +typedef void (Object::*SEL_DragPanelBounceToBottomEvent)(Object*); +#define coco_DragPanel_BounceToBottom_selector(_SELECTOR) (SEL_DragPanelBounceToBottomEvent)(&_SELECTOR) + +class UIDragPanel : public Layout, public UIScrollInterface +{ +public: + UIDragPanel(); + virtual ~UIDragPanel(); + + static UIDragPanel* create(); + + virtual bool onTouchBegan(const Point &touchPoint); + virtual void onTouchMoved(const Point &touchPoint); + virtual void onTouchEnded(const Point &touchPoint); + virtual void onTouchCancelled(const Point &touchPoint); + virtual void onTouchLongClicked(const Point &touchPoint); + + virtual void update(float dt); + + /** + * add widget child override + */ + virtual bool addChild(UIWidget* widget); + /** + * remove widget child override + */ + virtual bool removeChild(UIWidget* child); + /** + * remove all widget children override + */ + virtual void removeAllChildren(); + /** + * get widget children of inner container + */ + virtual Array* getChildren(); + /* gui mark */ + /** + * get and set inner container size + */ + const Size& getInnerContainerSize() const; + void setInnerContainerSize(const Size &size); + /** + * get and set inner container position + */ + const Point& getInnerContainerPosition() const; + void setInnerContainerPosition(const Point& point, bool animated); + /** + * set inner container offset + */ + void setInnerContainerOffset(const Point& offset, bool animated); + /**/ + + // auto move + /** + * set auto move duration + */ + void setAutoMoveDuration(float duration); + /** + * set auto move ease rate + */ + void setAutoMoveEaseRate(float rate); + + // berth + /** + * get berth or not + */ + bool isBerth(); + + /** + * berth event by direction + */ + void addBerthToLeftBottomEvent(Object* target, SEL_DragPanelBerthToLeftBottomEvent selector); + void addBerthToLeftTopEvent(Object* target, SEL_DragPanelBerthToLeftTopEvent selector); + void addBerthToRightBottomEvent(Object* target, SEL_DragPanelBerthToRightBottomEvent selector); + void addBerthToRightTopEvent(Object* target, SEL_DragPanelBerthToRightTopEvent selector); + void addBerthToLeftEvent(Object* target, SEL_DragPanelBerthToLeftEvent selector); + void addBerthToTopEvent(Object* target, SEL_DragPanelBerthToTopEvent selector); + void addBerthToRightEvent(Object* target, SEL_DragPanelBerthToRightEvent selector); + void addBerthToBottomEvent(Object* target, SEL_DragPanelBerthToBottomEvent selector); + + /** + * get and set bounce enable + */ + bool isBounceEnable(); + void setBounceEnable(bool bounce); + /** + * set bounce duration + */ + void setBounceDuratoin(float duration); + /** + * set bounce ease rate + */ + void setBounceEaseRate(float rate); + /** + * bounce event by dircetion + */ + void addBounceOverEvent(Object* target, SEL_DragPanelBounceOverEvent selector); + void addBounceToLeftBottomEvent(Object* target, SEL_DragPanelBounceToLeftBottomEvent selector); + void addBounceToLeftTopEvent(Object* target, SEL_DragPanelBounceToLeftTopEvent selector); + void addBounceToRightBottomEvent(Object* target, SEL_DragPanelBounceToRightBottomEvent selector); + void addBounceToRightTopEvent(Object* target, SEL_DragPanelBounceToRightTopEvent selector); + void addBounceToLeftEvent(Object* target, SEL_DragPanelBounceToLeftEvent selector); + void addBounceToTopEvent(Object* target, SEL_DragPanelBounceToTopEvent selector); + void addBounceToRightEvent(Object* target, SEL_DragPanelBounceToRightEvent selector); + void addBounceToBottomEvent(Object* target, SEL_DragPanelBounceToBottomEvent selector); + + /** + * Gets inner container of dragpanel. + * + * Inner container is the container of dragpanel's children. + * + * @return inner container. + */ + Layout* getInnerContainer(); + +protected: + virtual bool init(); + virtual void initRenderer(); + virtual void releaseResoures(); + + virtual void handlePressLogic(const Point &touchPoint); + virtual void handleMoveLogic(const Point &touchPoint); + virtual void handleReleaseLogic(const Point &touchPoint); + virtual void interceptTouchEvent(int handleState,UIWidget* sender, const Point &touchPoint); + /* gui mark */ +// virtual bool isInScrollDegreeRange(UIWidget* widget); + /**/ + virtual void checkChildInfo(int handleState, UIWidget *sender, const Point &touchPoint); +// void updateWidthAndHeight(); + void recordSlidTime(float dt); + + /* gui mark */ + void setInnerContainerOffset(const Point& offset); + /**/ + + // check if dragpanel rect contain inner rect + bool checkContainInnerRect(); + + // move + void moveWithDelta(const Point& delta); + + // auto move + void autoMove(); + void autoMoveOver(); + void startAutoMove(); + void stopAutoMove(); + + // berth + // check if move to boundary with update + bool checkToBoundaryWithDeltaPosition(const Point& delta); + + // calculate to boundary delta + Point calculateToBoundaryDeltaPosition(const Point& paramDelta); + + // check berth + bool checkBerth(); + + // berth event + void berthEvent(); + void berthToLeftEvent(); + void berthToRightEvent(); + void berthToTopEvent(); + void berthToBottomEvent(); + void berthToLeftBottomEvent(); + void berthToLeftTopEvent(); + void berthToRightBottomEvent(); + void berthToRightTopEvent(); + + // bounce + bool checkNeedBounce(); + void startBounce(); + void stopBounce(); + void bounceToCorner(); + void bounceOver(); + // bounce event + void bounceOverEvent(); + void bounceToLeftBottomEvent(); + void bounceToRightBottomEvent(); + void bounceToLeftTopEvent(); + void bounceToRightTopEvent(); + void bounceToLeftEvent(); + void bounceToTopEvent(); + void bounceToRightEvent(); + void bounceToBottomEvent(); + + void actionWithDuration(float duration); + bool actionIsDone(); + void actionStartWithWidget(UIWidget* widget); + void actionStep(float dt); + void actionUpdate(float dt); + void actionStop(); + void actionDone(); + void moveByWithDuration(float duration, const Point& deltaPosition); + void moveByInit(); + void moveByUpdate(float t); + void moveToWithDuration(float duration, const Point& position); + void moveToInit(); + void moveToUpdate(float t); + virtual void onSizeChanged(); + virtual void setClippingEnabled(bool able){Layout::setClippingEnabled(able);}; +protected: + Layout* m_pInnerContainer; + + /* + DRAGPANEL_DIR m_eDirection; + DRAGPANEL_MOVE_DIR m_eMoveDirection; + */ + + bool m_bTouchPressed; + bool m_bTouchMoved; + bool m_bTouchReleased; + bool m_bTouchCanceld; // check touch out of drag panel boundary + + Point m_touchStartNodeSpace; + Point m_touchStartWorldSpace; + Point m_touchEndWorldSpace; + + float m_fSlidTime; + + // move type + DRAGPANEL_MOVE_TYPE m_eMoveType; + + // auto move + float m_fAutoMoveDuration; + float m_fAutoMoveEaseRate; + + // berth + DRAGPANEL_BERTH_DIR m_eBerthDirection; + + // berth event + Object* m_pBerthToLeftListener; + SEL_DragPanelBerthToLeftEvent m_pfnBerthToLeftSelector; + Object* m_pBerthToRightListener; + SEL_DragPanelBerthToRightEvent m_pfnBerthToRightSelector; + Object* m_pBerthToTopListener; + SEL_DragPanelBerthToTopEvent m_pfnBerthToTopSelector; + Object* m_pBerthToBottomListener; + SEL_DragPanelBerthToBottomEvent m_pfnBerthToBottomSelector; + Object* m_pBerthToLeftBottomListener; + SEL_DragPanelBerthToLeftBottomEvent m_pfnBerthToLeftBottomSelector; + Object* m_pBerthToLeftTopListener; + SEL_DragPanelBerthToLeftTopEvent m_pfnBerthToLeftTopSelector; + Object* m_pBerthToRightBottomListener; + SEL_DragPanelBerthToRightBottomEvent m_pfnBerthToRightBottomSelector; + Object* m_pBerthToRightTopListener; + SEL_DragPanelBerthToRightTopEvent m_pfnBerthToRightTopSelector; + + // bounce + bool m_bBounceEnable; + DRAGPANEL_BOUNCE_DIR m_eBounceDirection; + float m_fBounceDuration; + float m_fBounceEaseRate; + + // bounce event + Object* m_pBounceOverListener; + SEL_DragPanelBounceOverEvent m_pfnBounceOverSelector; + Object* m_pBounceToLeftBottomListener; + SEL_DragPanelBounceToLeftBottomEvent m_pfnBounceToLeftBottomSelector; + Object* m_pBounceToLeftTopListener; + SEL_DragPanelBounceToLeftTopEvent m_pfnBounceToLeftTopSelector; + Object* m_pBounceToRightBottomListener; + SEL_DragPanelBounceToRightBottomEvent m_pfnBounceToRightBottomSelector; + Object* m_pBounceToRightTopListener; + SEL_DragPanelBounceToRightTopEvent m_pfnBounceToRightTopSelector; + Object* m_pBounceToLeftListener; + SEL_DragPanelBounceToLeftEvent m_pfnBounceToLeftSelector; + Object* m_pBounceToTopListener; + SEL_DragPanelBounceToTopEvent m_pfnBounceToTopSelector; + Object* m_pBounceToRightListener; + SEL_DragPanelBounceToRightEvent m_pfnBounceToRightSelector; + Object* m_pBounceToBottomListener; + SEL_DragPanelBounceToBottomEvent m_pfnBounceToBottomSelector; + + + + float m_bRunningAction; + int m_nActionType; + + UIWidget* m_pActionWidget; + + float m_fDuration; + float m_elapsed; + bool m_bFirstTick; + + Point m_positionDelta; + Point m_startPosition; + Point m_previousPosition; + + Point m_endPosition; +}; + +NS_CC_EXT_END + +#endif /* defined(__TestCpp__UIDragPanel__) */ diff --git a/extensions/CocoStudio/GUI/UIWidgets/ScrollWidget/UIListView.cpp b/extensions/CocoStudio/GUI/UIWidgets/ScrollWidget/UIListView.cpp new file mode 100644 index 0000000000..23a76d033d --- /dev/null +++ b/extensions/CocoStudio/GUI/UIWidgets/ScrollWidget/UIListView.cpp @@ -0,0 +1,1460 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "UIListView.h" + +NS_CC_EXT_BEGIN + +UIListView::UIListView() +: m_eDirection(LISTVIEW_DIR_VERTICAL) +, m_eMoveDirection(LISTVIEW_MOVE_DIR_NONE) +, m_fTouchStartLocation(0.0f) +, m_fTouchEndLocation(0.0f) +, m_fTouchMoveStartLocation(0.0f) +, m_fTopBoundary(0.0f) +, m_fBottomBoundary(0.0f) +, m_fLeftBoundary(0.0f) +, m_fRightBoundary(0.0f) +, m_bAutoScroll(false) +, m_fAutoScrollOriginalSpeed(0.0f) +, m_fAutoScrollAcceleration(600.0f) +, m_bBePressed(false) +, m_fSlidTime(0.0f) +, m_fChildFocusCancelOffset(5.0f) +, m_pInitChildListener(NULL) +, m_pfnInitChildSelector(NULL) +, m_pUpdateChildListener(NULL) +, m_pfnUpdateChildSelector(NULL) +, m_pChildPool(NULL) +, m_pUpdatePool(NULL) +, m_nDataLength(0) +, m_nBegin(0) +, m_nEnd(0) +, m_pUpdateChild(NULL) +, m_nUpdateDataIndex(-1) +, m_bUpdateSuccess(false) +, m_overTopArray(NULL) +, m_overBottomArray(NULL) +, m_overLeftArray(NULL) +, m_overRightArray(NULL) +, m_fDisBoundaryToChild_0(0.0f) +, m_fDisBetweenChild(0.0f) +, m_fScrollDegreeRange(45.0f) +{ +} + +UIListView::~UIListView() +{ + CC_SAFE_RELEASE_NULL(m_pChildPool); + CC_SAFE_RELEASE_NULL(m_pUpdatePool); + CC_SAFE_RELEASE_NULL(m_overTopArray); + CC_SAFE_RELEASE_NULL(m_overBottomArray); + CC_SAFE_RELEASE_NULL(m_overLeftArray); + CC_SAFE_RELEASE_NULL(m_overRightArray); +} + +UIListView* UIListView::create() +{ + UIListView* widget = new UIListView(); + if (widget && widget->init()) + { + widget->autorelease(); + return widget; + } + CC_SAFE_DELETE(widget); + return NULL; +} + +bool UIListView::init() +{ + if (Layout::init()) + { + setUpdateEnabled(true); + setTouchEnabled(true); + setClippingEnabled(true); + + m_pChildPool = CCArray::create(); + m_pUpdatePool = CCArray::create(); + CC_SAFE_RETAIN(m_pChildPool); + CC_SAFE_RETAIN(m_pUpdatePool); + m_overTopArray = cocos2d::CCArray::create(); + m_overBottomArray = cocos2d::CCArray::create(); + m_overLeftArray = cocos2d::CCArray::create(); + m_overRightArray = cocos2d::CCArray::create(); + CC_SAFE_RETAIN(m_overTopArray); + CC_SAFE_RETAIN(m_overBottomArray); + CC_SAFE_RETAIN(m_overLeftArray); + CC_SAFE_RETAIN(m_overRightArray); + + return true; + } + return false; +} + +void UIListView::onSizeChanged() +{ + Layout::onSizeChanged(); + m_fTopBoundary = m_size.height; + m_fRightBoundary = m_size.width; +} + +bool UIListView::addChild(UIWidget* widget) +{ + Layout::addChild(widget); + resetProperty(); + return true; +} + +void UIListView::removeAllChildren() +{ + m_pUpdatePool->removeAllObjects(); + m_pChildPool->removeAllObjects(); + Layout::removeAllChildren(); +} + +bool UIListView::removeChild(UIWidget* child) +{ + bool value = false; + + if (Layout::removeChild(child)) + { + value = true; + resetProperty(); + } + + return value; +} + +bool UIListView::onTouchBegan(const Point &touchPoint) +{ + bool pass = Layout::onTouchBegan(touchPoint); + handlePressLogic(touchPoint); + return pass; +} + +void UIListView::onTouchMoved(const Point &touchPoint) +{ + Layout::onTouchMoved(touchPoint); + handleMoveLogic(touchPoint); +} + +void UIListView::onTouchEnded(const Point &touchPoint) +{ + Layout::onTouchEnded(touchPoint); + handleReleaseLogic(touchPoint); +} + +void UIListView::onTouchCancelled(const Point &touchPoint) +{ + Layout::onTouchCancelled(touchPoint); +} + +void UIListView::onTouchLongClicked(const Point &touchPoint) +{ + +} + +void UIListView::update(float dt) +{ + if (m_bAutoScroll) + { + autoScrollChildren(dt); + } + recordSlidTime(dt); +} + +void UIListView::setDirection(ListViewDirection dir) +{ + m_eDirection = dir; +} + +ListViewDirection UIListView::getDirection() +{ + return m_eDirection; +} + +void UIListView::resetProperty() +{ + ccArray* arrayChildren = m_children->data; + + if (arrayChildren->num <= 0) + { + return; + } + + switch (m_eDirection) + { + case LISTVIEW_DIR_VERTICAL: // vertical + if (m_fTopBoundary == 0) + { + return; + } + break; + + case LISTVIEW_DIR_HORIZONTAL: // horizontal + if (m_fRightBoundary == 0) + { + return; + } + break; + + default: + break; + } + + float scroll_top = m_fTopBoundary; + float scroll_left = m_fLeftBoundary; + + switch (m_children->count()) + { + case 1: + { + UIWidget* child_0 = dynamic_cast(arrayChildren->arr[0]); + + switch (m_eDirection) + { + case LISTVIEW_DIR_VERTICAL: // vertical + { + float child_0_top = child_0->getTopInParent(); + m_fDisBoundaryToChild_0 = scroll_top - child_0_top; + } + break; + + case LISTVIEW_DIR_HORIZONTAL: // horizontal + { + float child_0_left = child_0->getLeftInParent(); + m_fDisBoundaryToChild_0 = child_0_left - scroll_left; + } + break; + + default: + break; + } + } + break; + + default: + { + UIWidget* child_0 = dynamic_cast(arrayChildren->arr[0]); + UIWidget* child_1 = dynamic_cast(arrayChildren->arr[1]); + + switch (m_eDirection) + { + case LISTVIEW_DIR_VERTICAL: // vertical + { + float child_0_top = child_0->getTopInParent(); + m_fDisBoundaryToChild_0 = scroll_top - child_0_top; + m_fDisBetweenChild = child_0->getPosition().y - child_1->getPosition().y; + } + break; + + case LISTVIEW_DIR_HORIZONTAL: // horizontal + { + float child_0_left = child_0->getLeftInParent(); + m_fDisBoundaryToChild_0 = child_0_left - scroll_left; + m_fDisBetweenChild = child_1->getPosition().x - child_0->getPosition().x; + } + break; + + default: + break; + } + } + break; + } +} + +void UIListView::handlePressLogic(const Point &touchPoint) +{ + Point nsp = m_pRenderer->convertToNodeSpace(touchPoint); + + switch (m_eDirection) + { + case LISTVIEW_DIR_VERTICAL: // vertical + m_fTouchMoveStartLocation = nsp.y; + m_fTouchStartLocation = nsp.y; + break; + + case LISTVIEW_DIR_HORIZONTAL: // horizontal + m_fTouchMoveStartLocation = nsp.x; + m_fTouchStartLocation = nsp.x; + break; + + default: + break; + } + startRecordSlidAction(); + clearCollectOverArray(); +} + +void UIListView::handleMoveLogic(const Point &touchPoint) +{ + Point nsp = m_pRenderer->convertToNodeSpace(touchPoint); + float offset = 0.0f; + + switch (m_eDirection) + { + case LISTVIEW_DIR_VERTICAL: // vertical + { + float moveY = nsp.y; + offset = moveY - m_fTouchMoveStartLocation; + m_fTouchMoveStartLocation = moveY; + + if (offset < 0.0f) + { + m_eMoveDirection = LISTVIEW_MOVE_DIR_DOWN; // down + } + else if (offset > 0.0f) + { + m_eMoveDirection = LISTVIEW_MOVE_DIR_UP; // up + } + } + break; + + case LISTVIEW_DIR_HORIZONTAL: // horizontal + { + float moveX = nsp.x; + offset = moveX - m_fTouchMoveStartLocation; + m_fTouchMoveStartLocation = moveX; + + if (offset < 0) + { + m_eMoveDirection = LISTVIEW_MOVE_DIR_LEFT; // left + } + else if (offset > 0) + { + m_eMoveDirection = LISTVIEW_MOVE_DIR_RIGHT; // right + } + } + break; + + default: + break; + } + scrollChildren(offset); +} + +void UIListView::handleReleaseLogic(const Point &touchPoint) +{ + Point nsp = m_pRenderer->convertToNodeSpace(touchPoint); + + switch (m_eDirection) + { + case LISTVIEW_DIR_VERTICAL: // vertical + m_fTouchEndLocation = nsp.y; + break; + + case LISTVIEW_DIR_HORIZONTAL: // horizontal + m_fTouchEndLocation = nsp.x; + break; + + default: + break; + } + endRecordSlidAction(); +} + +void UIListView::interceptTouchEvent(int handleState, UIWidget *sender, const Point &touchPoint) +{ + switch (handleState) + { + case 0: + handlePressLogic(touchPoint); + break; + + case 1: + { + float offset = 0; + switch (m_eDirection) + { + case LISTVIEW_DIR_VERTICAL: // vertical + offset = fabs(sender->getTouchStartPos().y - touchPoint.y); + break; + + case LISTVIEW_DIR_HORIZONTAL: // horizontal + offset = fabs(sender->getTouchStartPos().x - touchPoint.x); + break; + + default: + break; + } + if (offset > m_fChildFocusCancelOffset) + { + sender->setFocused(false); + handleMoveLogic(touchPoint); + } + } + break; + + case 2: + handleReleaseLogic(touchPoint); + break; + + case 3: + break; + } +} + +void UIListView::checkChildInfo(int handleState,UIWidget* sender,const Point &touchPoint) +{ + interceptTouchEvent(handleState, sender, touchPoint); +} + +void UIListView::moveChildren(float offset) +{ + switch (m_eDirection) + { + case LISTVIEW_DIR_VERTICAL: // vertical + { + ccArray* arrayChildren = m_children->data; + int childrenCount = arrayChildren->num; + for (int i = 0; i < childrenCount; i++) + { + UIWidget* child = (UIWidget*)(arrayChildren->arr[i]); + moveChildPoint.x = child->getPosition().x; + moveChildPoint.y = child->getPosition().y + offset; + child->setPosition(moveChildPoint); + } + break; + } + + case LISTVIEW_DIR_HORIZONTAL: // horizontal + { + ccArray* arrayChildren = m_children->data; + int childrenCount = arrayChildren->num; + for (int i=0;iarr[i]); + moveChildPoint.x = child->getPosition().x + offset; + moveChildPoint.y = child->getPosition().y; + child->setPosition(moveChildPoint); + } + break; + } + + default: + break; + } +} + +bool UIListView::scrollChildren(float touchOffset) +{ + float realOffset = touchOffset; + + switch (m_eDirection) + { + case LISTVIEW_DIR_VERTICAL: // vertical + switch (m_eMoveDirection) + { + case LISTVIEW_MOVE_DIR_UP: // up + { + realOffset = MIN(realOffset, m_fDisBetweenChild); + + UIWidget* child_last = dynamic_cast(m_pChildPool->getLastObject()); + float child_last_bottom = child_last->getBottomInParent(); + float scroll_bottom = m_fBottomBoundary; + + if (m_nEnd == m_nDataLength - 1) + { + if (realOffset > scroll_bottom + m_fDisBoundaryToChild_0 - child_last_bottom) + { + realOffset = scroll_bottom + m_fDisBoundaryToChild_0 - child_last_bottom; + } + moveChildren(realOffset); + return false; + } + moveChildren(realOffset); + + if (m_nEnd < m_nDataLength - 1) + { + collectOverTopChild(); + unsigned int count = m_overTopArray->count(); + if (count > 0) + { + updateChild(); + setLoopPosition(); + m_overTopArray->removeAllObjects(); + } + } + } + break; + + case LISTVIEW_MOVE_DIR_DOWN: // down + { + realOffset = MAX(realOffset, -m_fDisBetweenChild); + + UIWidget* child_0 = dynamic_cast(m_pChildPool->getObjectAtIndex(0)); + float child_0_top = child_0->getTopInParent(); + float scroll_top = m_fTopBoundary; + + if (m_nBegin == 0) + { + if (realOffset < scroll_top - m_fDisBoundaryToChild_0 - child_0_top) + { + realOffset = scroll_top - m_fDisBoundaryToChild_0 - child_0_top; + } + moveChildren(realOffset); + return false; + } + moveChildren(realOffset); + + if (m_nBegin > 0) + { + collectOverBottomChild(); + int count = m_overBottomArray->count(); + if (count > 0) + { + updateChild(); + setLoopPosition(); + m_overBottomArray->removeAllObjects(); + } + } + } + break; + + default: + break; + } + return true; + break; + + case LISTVIEW_DIR_HORIZONTAL: // horizontal + switch (m_eMoveDirection) + { + case LISTVIEW_MOVE_DIR_LEFT: // left + { + realOffset = MAX(realOffset, -m_fDisBetweenChild); + + UIWidget* child_last = dynamic_cast(m_pChildPool->getLastObject()); + float child_last_right = child_last->getRightInParent(); + float scroll_right = m_fRightBoundary; + + if (m_nEnd == m_nDataLength - 1) + { + if (realOffset < scroll_right - m_fDisBoundaryToChild_0 - child_last_right) + { + realOffset = scroll_right - m_fDisBoundaryToChild_0 - child_last_right; + } + moveChildren(realOffset); + return false; + } + moveChildren(realOffset); + + if (m_nEnd < m_nDataLength - 1) + { + collectOverLeftChild(); + int count = m_overLeftArray->count(); + if (count > 0) + { + updateChild(); + setLoopPosition(); + m_overLeftArray->removeAllObjects(); + } + } + } + break; + + case LISTVIEW_MOVE_DIR_RIGHT: // right + { + realOffset = MIN(realOffset, m_fDisBetweenChild); + + UIWidget* child_0 = dynamic_cast(m_pChildPool->getObjectAtIndex(0)); + float child_0_left = child_0->getLeftInParent(); + float scroll_left = m_fLeftBoundary; + + if (m_nBegin == 0) + { + if (realOffset > scroll_left + m_fDisBoundaryToChild_0 - child_0_left) + { + realOffset = scroll_left + m_fDisBoundaryToChild_0 - child_0_left; + } + moveChildren(realOffset); + return false; + } + moveChildren(realOffset); + + collectOverRightChild(); + int count = m_overRightArray->count(); + if (count > 0) + { + updateChild(); + setLoopPosition(); + m_overRightArray->removeAllObjects(); + } + } + break; + + default: + break; + } + return true; + break; + + default: + break; + } + + return false; +} + +void UIListView::autoScrollChildren(float dt) +{ + switch (m_eDirection) + { + case LISTVIEW_DIR_VERTICAL: // vertical + switch (m_eMoveDirection) + { + case LISTVIEW_MOVE_DIR_UP: // up + { + float curDis = getCurAutoScrollDistance(dt); + if (curDis <= 0) + { + curDis = 0; + stopAutoScrollChildren(); + } + if (!scrollChildren(curDis)) + { + stopAutoScrollChildren(); + } + } + break; + + case LISTVIEW_MOVE_DIR_DOWN: // down + { + float curDis = getCurAutoScrollDistance(dt); + if (curDis <= 0) + { + curDis = 0; + stopAutoScrollChildren(); + } + if (!scrollChildren(-curDis)) + { + stopAutoScrollChildren(); + } + } + break; + + default: + break; + } + break; + + case LISTVIEW_DIR_HORIZONTAL: // horizontal + switch (m_eMoveDirection) + { + case LISTVIEW_MOVE_DIR_LEFT: // left + { + float curDis = getCurAutoScrollDistance(dt); + if (curDis <= 0) + { + curDis = 0; + stopAutoScrollChildren(); + } + if (!scrollChildren(-curDis)) + { + stopAutoScrollChildren(); + } + } + break; + + case LISTVIEW_MOVE_DIR_RIGHT: // right + { + float curDis = getCurAutoScrollDistance(dt); + if (curDis <= 0) + { + curDis = 0; + stopAutoScrollChildren(); + } + if (!scrollChildren(curDis)) + { + stopAutoScrollChildren(); + } + } + break; + + default: + break; + } + break; + + default: + break; + } +} + +float UIListView::getCurAutoScrollDistance(float time) +{ + float dt = time; + m_fAutoScrollOriginalSpeed -= m_fAutoScrollAcceleration*dt; + return m_fAutoScrollOriginalSpeed*dt; +} + +void UIListView::startAutoScrollChildren(float v) +{ + m_fAutoScrollOriginalSpeed = v; + m_bAutoScroll = true; +} + +void UIListView::stopAutoScrollChildren() +{ + m_bAutoScroll = false; + m_fAutoScrollOriginalSpeed = 0.0f; +} + +void UIListView::recordSlidTime(float dt) +{ + if (m_bBePressed) + { + m_fSlidTime += dt; + } +} + +void UIListView::startRecordSlidAction() +{ + if (m_children->count() <= 0) + { + return; + } + if (m_bAutoScroll) + { + stopAutoScrollChildren(); + } + m_bBePressed = true; + m_fSlidTime = 0.0; +} + +void UIListView::endRecordSlidAction() +{ + if (m_children->count() <= 0) + { + return; + } + if (m_fSlidTime <= 0.016f) + { + return; + } + float totalDis = 0; + totalDis = m_fTouchEndLocation-m_fTouchStartLocation; + float orSpeed = fabs(totalDis)/(m_fSlidTime); + startAutoScrollChildren(orSpeed / 4); + + m_bBePressed = false; + m_fSlidTime = 0.0; +} + +UIWidget* UIListView::getCheckPositionChild() +{ + UIWidget* child = NULL; + + switch (m_eDirection) + { + case LISTVIEW_DIR_VERTICAL: // vertical + switch (m_eMoveDirection) + { + case LISTVIEW_MOVE_DIR_UP: // up + child = dynamic_cast(m_pChildPool->getLastObject()); + break; + + case LISTVIEW_MOVE_DIR_DOWN: // down + child = dynamic_cast(m_pChildPool->getObjectAtIndex(0)); + break; + + default: + break; + } + break; + + case LISTVIEW_DIR_HORIZONTAL: // horizontal + switch (m_eMoveDirection) + { + case LISTVIEW_MOVE_DIR_LEFT: // left + child = dynamic_cast(m_pChildPool->getLastObject()); + break; + + case LISTVIEW_MOVE_DIR_RIGHT: // right + child = dynamic_cast(m_pChildPool->getObjectAtIndex(0)); + break; + + default: + break; + } + break; + + default: + break; + } + + return child; +} + +void UIListView::initChildWithDataLength(int length) +{ + m_nDataLength = length; + m_nBegin = 0; + m_nEnd = 0; + + // init child pool + ccArray* arrayChildren = m_children->data; + int times = arrayChildren->num; + for (int i = 0; i < times; ++i) + { + UIWidget* child = dynamic_cast(arrayChildren->arr[i]); + setUpdateChild(child); + setUpdateDataIndex(i); + initChildEvent(); + m_pChildPool->addObject(child); + m_nEnd = i; + } +} + +UIWidget* UIListView::getChildFromUpdatePool() +{ + UIWidget* child = dynamic_cast(m_pUpdatePool->getLastObject()); + m_pUpdatePool->removeLastObject(); + return child; +} + +void UIListView::pushChildToPool() +{ + switch (m_eDirection) + { + case LISTVIEW_DIR_VERTICAL: // vertical + switch (m_eMoveDirection) + { + case LISTVIEW_MOVE_DIR_UP: // up + { + UIWidget* child = dynamic_cast(m_pChildPool->getObjectAtIndex(0)); + m_pUpdatePool->insertObject(child, 0); + m_pChildPool->removeObjectAtIndex(0); + } + break; + + case LISTVIEW_MOVE_DIR_DOWN: // down + { + UIWidget* child = dynamic_cast(m_pChildPool->getLastObject()); + m_pUpdatePool->insertObject(child, 0); + m_pChildPool->removeLastObject(); + + } + break; + + default: + break; + } + break; + + case LISTVIEW_DIR_HORIZONTAL: // horizontal + switch (m_eMoveDirection) + { + case LISTVIEW_MOVE_DIR_LEFT: // left + { + UIWidget* child = dynamic_cast(m_pChildPool->getObjectAtIndex(0)); + m_pUpdatePool->insertObject(child, 0); + m_pChildPool->removeObjectAtIndex(0); + } + break; + + case LISTVIEW_MOVE_DIR_RIGHT: // right + { + UIWidget* child = dynamic_cast(m_pChildPool->getLastObject()); + m_pUpdatePool->insertObject(child, 0); + m_pChildPool->removeLastObject(); + } + break; + + default: + break; + } + break; + + default: + break; + } +} + +void UIListView::getAndCallback() +{ + UIWidget* child = getChildFromUpdatePool(); + + if (child == NULL) + { + return; + } + + switch (m_eDirection) + { + case LISTVIEW_DIR_VERTICAL: // vertical + switch (m_eMoveDirection) + { + case LISTVIEW_MOVE_DIR_UP: // up + ++m_nEnd; + setUpdateChild(child); + setUpdateDataIndex(m_nEnd); + updateChildEvent(); + + if (m_bUpdateSuccess == false) + { + --m_nEnd; + m_pChildPool->insertObject(child, 0); + return; + } + ++m_nBegin; + break; + + case LISTVIEW_MOVE_DIR_DOWN: // down + --m_nBegin; + setUpdateChild(child); + setUpdateDataIndex(m_nBegin); + updateChildEvent(); + + if (m_bUpdateSuccess == false) + { + ++m_nBegin; + m_pChildPool->addObject(child); + return; + } + --m_nEnd; + break; + + default: + break; + } + break; + + case LISTVIEW_DIR_HORIZONTAL: // horizontal + switch (m_eMoveDirection) + { + case LISTVIEW_MOVE_DIR_LEFT: // left + ++m_nEnd; + setUpdateChild(child); + setUpdateDataIndex(m_nEnd); + updateChildEvent(); + + if (m_bUpdateSuccess == false) + { + --m_nEnd; + m_pChildPool->insertObject(child, 0); + return; + } + ++m_nBegin; + break; + + case LISTVIEW_MOVE_DIR_RIGHT: // right + --m_nBegin; + setUpdateChild(child); + setUpdateDataIndex(m_nBegin); + updateChildEvent(); + + if (m_bUpdateSuccess == false) + { + ++m_nBegin; + m_pChildPool->addObject(child); + return; + } + --m_nEnd; + break; + + default: + break; + } + break; + + default: + break; + } + + switch (m_eDirection) + { + case LISTVIEW_DIR_VERTICAL: // vertical + switch (m_eMoveDirection) + { + case LISTVIEW_MOVE_DIR_UP: // up + m_pChildPool->addObject(child); + break; + + case LISTVIEW_MOVE_DIR_DOWN: // down + m_pChildPool->insertObject(child, 0); + break; + + default: + break; + } + break; + + case LISTVIEW_DIR_HORIZONTAL: // horizontal + switch (m_eMoveDirection) + { + case LISTVIEW_MOVE_DIR_LEFT: // left + m_pChildPool->addObject(child); + break; + case LISTVIEW_MOVE_DIR_RIGHT: // right + m_pChildPool->insertObject(child, 0); + break; + + default: + break; + } + break; + + default: + break; + } +} + +int UIListView::getDataLength() +{ + return m_nDataLength; +} + +UIWidget* UIListView::getUpdateChild() +{ + return m_pUpdateChild; +} + +void UIListView::setUpdateChild(UIWidget* child) +{ + m_pUpdateChild = child; +} + +int UIListView::getUpdateDataIndex() +{ + return m_nUpdateDataIndex; +} + +void UIListView::setUpdateDataIndex(int index) +{ + m_nUpdateDataIndex = index; +} + +bool UIListView::getUpdateSuccess() +{ + return m_bUpdateSuccess; +} + +void UIListView::setUpdateSuccess(bool sucess) +{ + m_bUpdateSuccess = sucess; +} + +void UIListView::clearCollectOverArray() +{ + switch (m_eDirection) + { + case LISTVIEW_DIR_VERTICAL: + m_overTopArray->removeAllObjects(); + m_overBottomArray->removeAllObjects(); + break; + + case LISTVIEW_DIR_HORIZONTAL: + m_overLeftArray->removeAllObjects(); + m_overRightArray->removeAllObjects(); + break; + + default: + break; + } +} + +void UIListView::collectOverTopChild() +{ + float scroll_top = m_fTopBoundary; + + ccArray* arrayChildren = m_children->data; + int times = arrayChildren->num; + for (int i = 0; i < times; ++i) + { + UIWidget* child = dynamic_cast(arrayChildren->arr[i]); + float child_bottom = child->getBottomInParent(); + + if (child_bottom >= scroll_top) + { + m_overTopArray->addObject(child); + } + } +} + +void UIListView::collectOverBottomChild() +{ + float scroll_bottom = m_fBottomBoundary; + + ccArray* arrayChildren = m_children->data; + int times = arrayChildren->num; + for (int i = 0; i < times; ++i) + { + UIWidget* child = dynamic_cast(arrayChildren->arr[i]); + float child_top = child->getTopInParent(); + + if (child_top <= scroll_bottom) + { + m_overBottomArray->addObject(child); + } + } +} + +void UIListView::collectOverLeftChild() +{ + float scroll_left = m_fLeftBoundary; + + ccArray* arrayChildren = m_children->data; + int times = arrayChildren->num; + for (int i = 0; i < times; ++i) + { + UIWidget* child = dynamic_cast(arrayChildren->arr[i]); + float child_right = child->getRightInParent(); + + if (child_right <= scroll_left) + { + m_overLeftArray->addObject(child); + } + } +} + +void UIListView::collectOverRightChild() +{ + float scroll_right = m_fRightBoundary; + + ccArray* arrayChildren = m_children->data; + int times = arrayChildren->num; + for (int i = 0; i < times; ++i) + { + UIWidget* child = dynamic_cast(arrayChildren->arr[i]); + float child_left = child->getLeftInParent(); + if (child_left >= scroll_right) + { + m_overRightArray->addObject(child); + } + } +} + +void UIListView::setLoopPosition() +{ + switch (m_eDirection) + { + case LISTVIEW_DIR_VERTICAL: // vertical + switch (m_eMoveDirection) + { + case LISTVIEW_MOVE_DIR_UP: // up + { + ccArray* arrayChildren = m_children->data; + unsigned int childrenCount = arrayChildren->num; + + if (m_overTopArray->count() == childrenCount) + { + unsigned int count = childrenCount; + for (unsigned int i = 0; i < count; ++i) + { + UIWidget* child = dynamic_cast(m_overTopArray->getObjectAtIndex(i)); + + if (i == 0) + { + float height = child->getSize().height; + float offset = (child->getWidgetType() == WidgetTypeWidget) ? height / 2 : height; + float y = m_fTopBoundary - m_fDisBoundaryToChild_0 - offset; + child->setPosition(Point(child->getPosition().x, y)); + } + else + { + UIWidget* prev_child = dynamic_cast(m_overTopArray->getObjectAtIndex(i - 1)); + child->setPosition(Point(child->getPosition().x, prev_child->getPosition().y - m_fDisBetweenChild)); + } + } + } + else + { + float scroll_top = m_fTopBoundary; + + ccArray* arrayChildren = m_children->data; + int count = arrayChildren->num; + for (int i = 0; i < count; ++i) + { + UIWidget* child = dynamic_cast(arrayChildren->arr[i]); + float child_bottom = child->getBottomInParent(); + + if (child_bottom >= scroll_top) + { + int index = (i == 0) ? (count - 1) : (i - 1); + UIWidget* prev_child = dynamic_cast(arrayChildren->arr[index]); + child->setPosition(Point(child->getPosition().x, prev_child->getPosition().y - m_fDisBetweenChild)); + } + } + } + } + break; + + case LISTVIEW_MOVE_DIR_DOWN: // down + { + ccArray* arrayChildren = m_children->data; + unsigned int childrenCount = arrayChildren->num; + + if (m_overBottomArray->count() == childrenCount) + { + unsigned int count = childrenCount; + for (unsigned int i = 0; i < count; ++i) + { + UIWidget* child = dynamic_cast(m_overBottomArray->getObjectAtIndex(i)); + + if (i == 0) + { + float y = m_fBottomBoundary + m_fDisBoundaryToChild_0 - m_fDisBetweenChild; + child->setPosition(Point(child->getPosition().x, y)); + } + else + { + UIWidget* prev_child = dynamic_cast(m_overBottomArray->getObjectAtIndex(i - 1)); + child->setPosition(Point(child->getPosition().x, prev_child->getPosition().y + m_fDisBetweenChild)); + } + } + } + else + { + float scroll_bottom = m_fBottomBoundary; + + ccArray* arrayChildren = m_children->data; + int count = arrayChildren->num; + for (int i = count - 1; i >= 0; --i) + { + UIWidget* child = dynamic_cast(arrayChildren->arr[i]); + float child_top = child->getTopInParent(); + + if (child_top <= scroll_bottom) + { + int index = (i == count - 1) ? 0 : (i + 1); + UIWidget* next_child = dynamic_cast(arrayChildren->arr[index]); + child->setPosition(Point(child->getPosition().x, next_child->getPosition().y + m_fDisBetweenChild)); + } + } + } + } + break; + + default: + break; + } + break; + + case LISTVIEW_DIR_HORIZONTAL: // horizontal + switch (m_eMoveDirection) + { + case LISTVIEW_MOVE_DIR_LEFT: // left + { + ccArray* arrayChildren = m_children->data; + unsigned int childrenCount = arrayChildren->num; + + if (m_overLeftArray->count() == childrenCount) + { + unsigned int count = childrenCount; + for (unsigned int i = 0; i < count; ++i) + { + UIWidget* child = dynamic_cast(m_overLeftArray->getObjectAtIndex(i)); + + if (i == 0) + { + float width = child->getSize().width; + float offset = (child->getWidgetType() == WidgetTypeWidget) ? (width / 2) : 0; + float x = m_fLeftBoundary + m_fDisBoundaryToChild_0 + width + offset; + child->setPosition(Point(x, child->getPosition().y)); + } + else + { + UIWidget* prev_child = dynamic_cast(m_overLeftArray->getObjectAtIndex(i - 1)); + child->setPosition(Point(prev_child->getPosition().x + m_fDisBetweenChild, child->getPosition().y)); + } + } + } + else + { + float scroll_left = m_fLeftBoundary; + + ccArray* arrayChildren = m_children->data; + int count = arrayChildren->num; + for (int i = 0; i < count; ++i) + { + UIWidget* child = dynamic_cast(arrayChildren->arr[i]); + float child_right = child->getRightInParent(); + + if (child_right <= scroll_left) + { + int index = (i == 0) ? (count - 1) : (i - 1); + UIWidget* prev_child = dynamic_cast(arrayChildren->arr[index]); + child->setPosition(Point(prev_child->getPosition().x + m_fDisBetweenChild, child->getPosition().y)); + } + } + } + } + break; + + case LISTVIEW_MOVE_DIR_RIGHT: // right + { + ccArray* arrayChildren = m_children->data; + unsigned int childrenCount = arrayChildren->num; + + if (m_overRightArray->count() == childrenCount) + { + unsigned int count = childrenCount; + for (unsigned int i = 0; i < count; ++i) + { + UIWidget* child = dynamic_cast(m_overRightArray->getObjectAtIndex(i)); + + if (i == 0) + { + float x = m_fRightBoundary - m_fDisBoundaryToChild_0 + m_fDisBetweenChild; + child->setPosition(Point(x, child->getPosition().y)); + } + else + { + UIWidget* prev_child = dynamic_cast(m_overRightArray->getObjectAtIndex(i - 1)); + child->setPosition(Point(prev_child->getPosition().x - m_fDisBetweenChild, child->getPosition().y)); + } + } + } + else + { + float scroll_right = m_fRightBoundary; + + ccArray* arrayChildren = m_children->data; + int count = arrayChildren->num; + for (int i = count - 1; i >= 0; --i) + { + UIWidget* child = dynamic_cast(arrayChildren->arr[i]); + float child_left = child->getLeftInParent(); + + if (child_left >= scroll_right) + { + int index = (i == count - 1) ? 0 : (i + 1); + UIWidget* next_child = dynamic_cast(arrayChildren->arr[index]); + child->setPosition(Point(next_child->getPosition().x - m_fDisBetweenChild, child->getPosition().y)); + } + } + } + } + break; + + default: + break; + } + break; + + default: + break; + } +} + +void UIListView::updateChild() +{ + switch (m_eDirection) + { + case LISTVIEW_DIR_VERTICAL: // vertical + switch (m_eMoveDirection) + { + case LISTVIEW_MOVE_DIR_UP: // up + { + int count = m_overTopArray->count(); + for (int i = 0; i < count; ++i) + { + pushChildToPool(); + getAndCallback(); + } + } + break; + + case LISTVIEW_MOVE_DIR_DOWN: // down + { + int count = m_overBottomArray->count(); + for (int i = 0; i < count; ++i) + { + pushChildToPool(); + getAndCallback(); + } + } + break; + + default: + break; + } + break; + + case LISTVIEW_DIR_HORIZONTAL: // horizontal + switch (m_eMoveDirection) + { + case LISTVIEW_MOVE_DIR_LEFT: // left + { + int count = m_overLeftArray->count(); + for (int i = 0; i < count; ++i) + { + pushChildToPool(); + getAndCallback(); + } + } + break; + + case LISTVIEW_MOVE_DIR_RIGHT: // right + { + int count = m_overRightArray->count(); + for (int i = 0; i < count; ++i) + { + pushChildToPool(); + getAndCallback(); + } + } + break; + + default: + break; + } + break; + + default: + break; + } +} + +void UIListView::initChildEvent() +{ + if (m_pInitChildListener && m_pfnInitChildSelector) + { + (m_pInitChildListener->*m_pfnInitChildSelector)(this); + } +} + +void UIListView::updateChildEvent() +{ + if (m_pUpdateChildListener && m_pfnUpdateChildSelector) + { + (m_pUpdateChildListener->*m_pfnUpdateChildSelector)(this); + } +} + +void UIListView::addInitChildEvent(Object *target, SEL_ListViewInitChildEvent seletor) +{ + m_pInitChildListener = target; + m_pfnInitChildSelector = seletor; +} + +void UIListView::addUpdateChildEvent(Object *target, SEL_ListViewUpdateChildEvent selector) +{ + m_pUpdateChildListener = target; + m_pfnUpdateChildSelector = selector; +} + +NS_CC_EXT_END \ No newline at end of file diff --git a/extensions/CocoStudio/GUI/UIWidgets/ScrollWidget/UIListView.h b/extensions/CocoStudio/GUI/UIWidgets/ScrollWidget/UIListView.h new file mode 100644 index 0000000000..8f4954c365 --- /dev/null +++ b/extensions/CocoStudio/GUI/UIWidgets/ScrollWidget/UIListView.h @@ -0,0 +1,243 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __UILISTVIEW_H__ +#define __UILISTVIEW_H__ + +/* gui mark */ +#include "../../Layouts/Layout.h" +/**/ + +NS_CC_EXT_BEGIN + +/** + * list view direction + */ +typedef enum LISTVIEW_DIR +{ + LISTVIEW_DIR_NONE, + LISTVIEW_DIR_VERTICAL, + LISTVIEW_DIR_HORIZONTAL +}ListViewDirection; + +/** + * list view scroll direction + */ +typedef enum LISTVIEW_MOVE_DIR +{ + LISTVIEW_MOVE_DIR_NONE, + LISTVIEW_MOVE_DIR_UP, + LISTVIEW_MOVE_DIR_DOWN, + LISTVIEW_MOVE_DIR_LEFT, + LISTVIEW_MOVE_DIR_RIGHT, +}ListViewMoveDirection; + +/** + * list view event + */ +typedef void (cocos2d::Object::*SEL_ListViewInitChildEvent)(cocos2d::Object*); +typedef void (cocos2d::Object::*SEL_ListViewUpdateChildEvent)(cocos2d::Object*); +#define coco_ListView_InitChild_selector(_SELECTOR) (SEL_ListViewInitChildEvent)(&_SELECTOR) +#define coco_ListView_UpdateChild_selector(_SELECTOR) (SEL_ListViewUpdateChildEvent)(&_SELECTOR) + +class UIListView : public Layout +{ +public: + UIListView(); + virtual ~UIListView(); + static UIListView* create(); + + /** + * add widget child override + */ + virtual bool addChild(UIWidget* widget); + /** + * remove all widget children override + */ + virtual void removeAllChildren(); + /** + * remove widget child override + */ + virtual bool removeChild(UIWidget* child); + + virtual bool onTouchBegan(const Point &touchPoint); + virtual void onTouchMoved(const Point &touchPoint); + virtual void onTouchEnded(const Point &touchPoint); + virtual void onTouchCancelled(const Point &touchPoint); + virtual void onTouchLongClicked(const Point &touchPoint); + + /** + * set and get direction + */ + void setDirection(ListViewDirection dir); + ListViewDirection getDirection(); + + /** + * initialze data length + * and create children with parameter length + */ + void initChildWithDataLength(int length); + /** + * get data length + */ + int getDataLength(); + + /** + * update child function whetn trigger update child event + */ + /** + * get update widget child + */ + UIWidget* getUpdateChild(); + /** + * get update data index + */ + int getUpdateDataIndex(); + /** + * get and set update success or not + */ + bool getUpdateSuccess(); + void setUpdateSuccess(bool sucess); + + /** + * add event call-back function + */ + /** + * add init child event + */ + void addInitChildEvent(cocos2d::Object* target, SEL_ListViewInitChildEvent seletor); + /** + * add udpate child event + */ + void addUpdateChildEvent(cocos2d::Object* target, SEL_ListViewUpdateChildEvent selector); + + /* gui mark */ + /** + * get and set degree range for checking move or not with scrolling + */ + /**/ + virtual void update(float dt); + +protected: + virtual bool init(); + + virtual void onSizeChanged(); + + void setMoveDirection(ListViewMoveDirection dir); + ListViewMoveDirection getMoveDirection(); + + virtual void resetProperty(); + + virtual void handlePressLogic(const Point &touchPoint); + virtual void handleMoveLogic(const Point &touchPoint); + virtual void handleReleaseLogic(const Point &touchPoint); + virtual void interceptTouchEvent(int handleState,UIWidget* sender,const Point &touchPoint); + /* gui mark */ +// virtual bool isInScrollDegreeRange(UIWidget* widget); + /**/ + virtual void checkChildInfo(int handleState,UIWidget* sender,const Point &touchPoint); + + void moveChildren(float offset); + virtual bool scrollChildren(float touchOffset); + void autoScrollChildren(float dt); + float getCurAutoScrollDistance(float time); + void startAutoScrollChildren(float v); + void stopAutoScrollChildren(); + void recordSlidTime(float dt); + void startRecordSlidAction(); + virtual void endRecordSlidAction(); + + UIWidget* getCheckPositionChild(); + UIWidget* getChildFromUpdatePool(); + void pushChildToPool(); + void getAndCallback(); + + void setUpdateChild(UIWidget* child); + void setUpdateDataIndex(int index); + void clearCollectOverArray(); + void collectOverTopChild(); + void collectOverBottomChild(); + void collectOverLeftChild(); + void collectOverRightChild(); + void setLoopPosition(); + void updateChild(); + + void initChildEvent(); + void updateChildEvent(); + + virtual void setClippingEnabled(bool able){Layout::setClippingEnabled(able);}; +protected: + ListViewDirection m_eDirection; + ListViewMoveDirection m_eMoveDirection; + + float m_fTouchStartLocation; + float m_fTouchEndLocation; + float m_fTouchMoveStartLocation; + float m_fTopBoundary;//test + float m_fBottomBoundary;//test + float m_fLeftBoundary; + float m_fRightBoundary; + + bool m_bAutoScroll; + + float m_fAutoScrollOriginalSpeed; + float m_fAutoScrollAcceleration; + + bool m_bBePressed; + float m_fSlidTime; + Point moveChildPoint; + float m_fChildFocusCancelOffset; + + cocos2d::Object* m_pInitChildListener; + SEL_ListViewInitChildEvent m_pfnInitChildSelector; + cocos2d::Object* m_pUpdateChildListener; + SEL_ListViewUpdateChildEvent m_pfnUpdateChildSelector; + + Array* m_pChildPool; + Array* m_pUpdatePool; + + int m_nDataLength; + int m_nBegin; + int m_nEnd; + UIWidget* m_pUpdateChild; + int m_nUpdateDataIndex; + bool m_bUpdateSuccess; + + Array* m_overTopArray; + Array* m_overBottomArray; + Array* m_overLeftArray; + Array* m_overRightArray; + + float m_fDisBoundaryToChild_0; + float m_fDisBetweenChild; + + /* gui mark */ + float m_fScrollDegreeRange; + /**/ +}; + +NS_CC_EXT_END + + +#endif /* defined(__Test__UIListView__) */ diff --git a/extensions/CocoStudio/GUI/UIWidgets/ScrollWidget/UIPageView.cpp b/extensions/CocoStudio/GUI/UIWidgets/ScrollWidget/UIPageView.cpp new file mode 100644 index 0000000000..ab35bfb581 --- /dev/null +++ b/extensions/CocoStudio/GUI/UIWidgets/ScrollWidget/UIPageView.cpp @@ -0,0 +1,569 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "UIPageView.h" + +NS_CC_EXT_BEGIN + +UIPageView::UIPageView(): +m_nCurPageIdx(0), +m_pages(NULL), +m_touchMoveDir(PAGEVIEW_TOUCHLEFT), +m_fTouchStartLocation(0.0f), +m_fTouchEndLocation(0.0f), +m_fTouchMoveStartLocation(0.0f), +movePagePoint(Point::ZERO), +m_pLeftChild(NULL), +m_pRightChild(NULL), +m_fLeftBoundary(0.0f), +m_fRightBoundary(0.0f), +m_bIsAutoScrolling(false), +m_fAutoScrollDistance(0.0f), +m_fAutoScrollSpeed(0.0f), +m_nAutoScrollDir(0), +m_fChildFocusCancelOffset(5.0f), +m_pPageTurningListener(NULL), +m_pfnPageTurningSelector(NULL), +m_fScrollDegreeRange(45.0f) +{ +} + +UIPageView::~UIPageView() +{ + m_pages->release(); +} + +UIPageView* UIPageView::create() +{ + UIPageView* widget = new UIPageView(); + if (widget && widget->init()) + { + widget->autorelease(); + return widget; + } + CC_SAFE_DELETE(widget); + return NULL; +} + +bool UIPageView::init() +{ + if (Layout::init()) + { + m_pages = CCArray::create(); + m_pages->retain(); + setClippingEnabled(true); + setUpdateEnabled(true); + return true; + } + return false; +} + +void UIPageView::addWidgetToPage(UIWidget *widget, int pageIdx, bool forceCreate) +{ + if (!widget) + { + return; + } + int pageCount = m_pages->count(); + if (pageIdx < 0 || pageIdx >= pageCount) + { + if (forceCreate) + { + if (pageIdx > pageCount) + { + CCLOG("pageIdx is %d, it will be added as page id [%d]",pageIdx,pageCount); + } + Layout* newPage = createPage(); + newPage->addChild(widget); + addPage(newPage); + } + } + else + { + Layout * page = dynamic_cast(m_pages->getObjectAtIndex(pageIdx)); + if (page) + { + page->addChild(widget); + } + } + +} + +Layout* UIPageView::createPage() +{ + Layout* newPage = Layout::create(); + newPage->setSize(getSize()); + return newPage; +} + +void UIPageView::addPage(Layout* page) +{ + if (!page) + { + return; + } + if (page->getWidgetType() != WidgetTypeContainer) + { + return; + } + if (m_pages->containsObject(page)) + { + return; + } + Size pSize = page->getSize(); + Size pvSize = getSize(); + if (!pSize.equals(pvSize)) + { + CCLOG("page size does not match pageview size, it will be force sized!"); + page->setSize(pvSize); + } + page->setPosition(Point(getPositionXByIndex(m_pages->count()), 0)); + m_pages->addObject(page); + addChild(page); + updateBoundaryPages(); +} + +void UIPageView::insertPage(Layout* page, int idx) +{ + if (idx < 0) + { + return; + } + if (!page) + { + return; + } + if (page->getWidgetType() != WidgetTypeContainer) + { + return; + } + if (m_pages->containsObject(page)) + { + return; + } + + int pageCount = m_pages->count(); + if (idx >= pageCount) + { + addPage(page); + } + else + { + m_pages->insertObject(page, idx); + page->setPosition(Point(getPositionXByIndex(idx), 0)); + addChild(page); + Size pSize = page->getSize(); + Size pvSize = getSize(); + if (!pSize.equals(pvSize)) + { + CCLOG("page size does not match pageview size, it will be force sized!"); + page->setSize(pvSize); + } + ccArray* arrayPages = m_pages->data; + int length = arrayPages->num; + for (int i=(idx+1); i(arrayPages->arr[i]); + Point formerPos = behindPage->getPosition(); + behindPage->setPosition(Point(formerPos.x+getSize().width, 0)); + } + updateBoundaryPages(); + } +} + +void UIPageView::removePage(Layout* page) +{ + if (!page) + { + return; + } + removeChild(page); + updateChildrenPosition(); + updateBoundaryPages(); +} + +void UIPageView::removePageAtIndex(int index) +{ + if (index < 0 || index >= (int)(m_pages->count())) + { + return; + } + Layout* page = dynamic_cast(m_pages->getObjectAtIndex(index)); + if (page) + { + removePage(page); + } +} + +void UIPageView::updateBoundaryPages() +{ + if (m_pages->count() <= 0) + { + m_pLeftChild = NULL; + m_pRightChild = NULL; + } + m_pLeftChild = dynamic_cast(m_pages->getObjectAtIndex(0)); + m_pRightChild = dynamic_cast(m_pages->getLastObject()); +} + +float UIPageView::getPositionXByIndex(int idx) +{ + return (getSize().width*(idx-m_nCurPageIdx)); +} + +bool UIPageView::addChild(UIWidget* widget) +{ + return Layout::addChild(widget); +} + +bool UIPageView::removeChild(UIWidget* widget) +{ + if (m_pages->containsObject(widget)) + { + m_pages->removeObject(widget); + return Layout::removeChild(widget); + } + return false; +} + +void UIPageView::onSizeChanged() +{ + Layout::onSizeChanged(); + m_fRightBoundary = getSize().width; + updateChildrenSize(); + updateChildrenPosition(); +} + +void UIPageView::updateChildrenSize() +{ + if (!m_pages) + { + return; + } + + Size selfSize = getSize(); + for (unsigned int i=0; icount(); i++) + { + Layout* page = dynamic_cast(m_pages->getObjectAtIndex(i)); + page->setSize(selfSize); + } +} + +void UIPageView::updateChildrenPosition() +{ + if (!m_pages) + { + return; + } + + int pageCount = m_pages->data->num; + if (pageCount <= 0) + { + m_nCurPageIdx = 0; + return; + } + if (m_nCurPageIdx >= pageCount) + { + m_nCurPageIdx = pageCount-1; + } + float pageWidth = getSize().width; + ccArray* arrayPages = m_pages->data; + for (int i=0; i(arrayPages->arr[i]); + page->setPosition(Point((i-m_nCurPageIdx)*pageWidth, 0)); + } +} + +void UIPageView::removeAllChildren() +{ + m_pages->removeAllObjects(); + Layout::removeAllChildren(); +} + +void UIPageView::scrollToPage(int idx) +{ + if (idx < 0 || idx >= (int)(m_pages->count())) + { + return; + } + m_nCurPageIdx = idx; + UIWidget* curPage = dynamic_cast(m_pages->getObjectAtIndex(idx)); + m_fAutoScrollDistance = -(curPage->getPosition().x); + m_fAutoScrollSpeed = fabs(m_fAutoScrollDistance)/0.2f; + m_nAutoScrollDir = m_fAutoScrollDistance > 0 ? 1 : 0; + m_bIsAutoScrolling = true; +} + +void UIPageView::update(float dt) +{ + if (m_bIsAutoScrolling) + { + switch (m_nAutoScrollDir) + { + case 0: + { + float step = m_fAutoScrollSpeed*dt; + if (m_fAutoScrollDistance + step >= 0.0f) + { + step = -m_fAutoScrollDistance; + m_fAutoScrollDistance = 0.0f; + m_bIsAutoScrolling = false; + pageTurningEvent(); + } + else + { + m_fAutoScrollDistance += step; + } + scrollPages(-step); + break; + } + break; + case 1: + { + float step = m_fAutoScrollSpeed*dt; + if (m_fAutoScrollDistance - step <= 0.0f) + { + step = m_fAutoScrollDistance; + m_fAutoScrollDistance = 0.0f; + m_bIsAutoScrolling = false; + pageTurningEvent(); + } + else + { + m_fAutoScrollDistance -= step; + } + scrollPages(step); + break; + } + default: + break; + } + } +} + +bool UIPageView::onTouchBegan(const Point &touchPoint) +{ + bool pass = Layout::onTouchBegan(touchPoint); + handlePressLogic(touchPoint); + return pass; +} + +void UIPageView::onTouchMoved(const Point &touchPoint) +{ + m_touchMovePos.x = touchPoint.x; + m_touchMovePos.y = touchPoint.y; + handleMoveLogic(touchPoint); + if (m_pWidgetParent) + { + m_pWidgetParent->checkChildInfo(1,this,touchPoint); + } + moveEvent(); + if (!hitTest(touchPoint)) + { + setFocused(false); + onTouchEnded(touchPoint); + } +} + +void UIPageView::onTouchEnded(const Point &touchPoint) +{ + Layout::onTouchEnded(touchPoint); + handleReleaseLogic(touchPoint); +} + +void UIPageView::movePages(float offset) +{ + ccArray* arrayPages = m_pages->data; + int length = arrayPages->num; + for (int i = 0; i < length; i++) + { + UIWidget* child = (UIWidget*)(arrayPages->arr[i]); + movePagePoint.x = child->getPosition().x + offset; + movePagePoint.y = child->getPosition().y; + child->setPosition(movePagePoint); + } +} + +bool UIPageView::scrollPages(float touchOffset) +{ + if (m_pages->count() <= 0) + { + return false; + } + + if (!m_pLeftChild || !m_pRightChild) + { + return false; + } + + float realOffset = touchOffset; + + switch (m_touchMoveDir) + { + case PAGEVIEW_TOUCHLEFT: // left + if (m_pRightChild->getRightInParent() + touchOffset <= m_fRightBoundary) + { + realOffset = m_fRightBoundary - m_pRightChild->getRightInParent(); + movePages(realOffset); + return false; + } + break; + + case PAGEVIEW_TOUCHRIGHT: // right + if (m_pLeftChild->getLeftInParent() + touchOffset >= m_fLeftBoundary) + { + realOffset = m_fLeftBoundary - m_pLeftChild->getLeftInParent(); + movePages(realOffset); + return false; + } + break; + default: + break; + } + + movePages(realOffset); + return true; +} + +void UIPageView::onTouchCancelled(const Point &touchPoint) +{ + Layout::onTouchCancelled(touchPoint); +} + +void UIPageView::handlePressLogic(const Point &touchPoint) +{ + Point nsp = m_pRenderer->convertToNodeSpace(touchPoint); + m_fTouchMoveStartLocation = nsp.x; + m_fTouchStartLocation = nsp.x; +} + +void UIPageView::handleMoveLogic(const Point &touchPoint) +{ + Point nsp = m_pRenderer->convertToNodeSpace(touchPoint); + float offset = 0.0; + float moveX = nsp.x; + offset = moveX - m_fTouchMoveStartLocation; + m_fTouchMoveStartLocation = moveX; + if (offset < 0) + { + m_touchMoveDir = PAGEVIEW_TOUCHLEFT; + } + else if (offset > 0) + { + m_touchMoveDir = PAGEVIEW_TOUCHRIGHT; + } + scrollPages(offset); +} + +void UIPageView::handleReleaseLogic(const Point &touchPoint) +{ + UIWidget* curPage = dynamic_cast(m_pages->getObjectAtIndex(m_nCurPageIdx)); + if (curPage) + { + Point curPagePos = curPage->getPosition(); + int pageCount = m_pages->count(); + float curPageLocation = curPagePos.x; + float pageWidth = getSize().width; + float boundary = pageWidth/2.0f; + if (curPageLocation <= -boundary) + { + if (m_nCurPageIdx >= pageCount-1) + { + scrollPages(-curPageLocation); + } + else + { + scrollToPage(m_nCurPageIdx+1); + } + } + else if (curPageLocation >= boundary) + { + if (m_nCurPageIdx <= 0) + { + scrollPages(-curPageLocation); + } + else + { + scrollToPage(m_nCurPageIdx-1); + } + } + else + { + scrollToPage(m_nCurPageIdx); + } + } +} + +void UIPageView::checkChildInfo(int handleState,UIWidget* sender, const Point &touchPoint) +{ + interceptTouchEvent(handleState, sender, touchPoint); +} + +void UIPageView::interceptTouchEvent(int handleState, UIWidget *sender, const Point &touchPoint) +{ + switch (handleState) + { + case 0: + handlePressLogic(touchPoint); + break; + case 1: + { + float offset = 0; + offset = fabs(sender->getTouchStartPos().x - touchPoint.x); + if (offset > m_fChildFocusCancelOffset) + { + sender->setFocused(false); + handleMoveLogic(touchPoint); + } + } + break; + case 2: + handleReleaseLogic(touchPoint); + break; + + case 3: + break; + } +} + +void UIPageView::pageTurningEvent() +{ + if (m_pPageTurningListener && m_pfnPageTurningSelector) + { + (m_pPageTurningListener->*m_pfnPageTurningSelector)(this); + } +} + +void UIPageView::addPageTurningEvent(Object *target, SEL_PageViewPageTurningEvent selector) +{ + m_pPageTurningListener = target; + m_pfnPageTurningSelector = selector; +} + +int UIPageView::getCurPageIndex() const +{ + return m_nCurPageIdx; +} + +NS_CC_EXT_END \ No newline at end of file diff --git a/extensions/CocoStudio/GUI/UIWidgets/ScrollWidget/UIPageView.h b/extensions/CocoStudio/GUI/UIWidgets/ScrollWidget/UIPageView.h new file mode 100644 index 0000000000..05f99e5c81 --- /dev/null +++ b/extensions/CocoStudio/GUI/UIWidgets/ScrollWidget/UIPageView.h @@ -0,0 +1,180 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __UIPAGEVIEW_H__ +#define __UIPAGEVIEW_H__ + +#include "../../Layouts/Layout.h" +#include "UIScrollInterface.h" + +NS_CC_EXT_BEGIN + +typedef void (Object::*SEL_PageViewPageTurningEvent)(Object*); +#define coco_PageView_PageTurning_selector(_SELECTOR) (SEL_PageViewPageTurningEvent)(&_SELECTOR) + +typedef enum { + PAGEVIEW_TOUCHLEFT, + PAGEVIEW_TOUCHRIGHT +}PVTouchDir; + +class UIPageView : public Layout , public UIScrollInterface +{ + +public: + /** + * Default constructor + */ + UIPageView(); + + /** + * Default destructor + */ + virtual ~UIPageView(); + + /** + * Allocates and initializes. + */ + static UIPageView* create(); + + /** + * Add a widget to a page of pageview. + * + * @param widget widget to be added to pageview. + * + * @param pageIdx index of page. + * + * @param forceCreate if force create and there is no page exsit, pageview would create a default page for adding widget. + */ + void addWidgetToPage(UIWidget* widget, int pageIdx, bool forceCreate); + + /** + * Push back a page to pageview. + * + * @param page page to be added to pageview. + */ + void addPage(Layout* page); + + /** + * Inert a page to pageview. + * + * @param page page to be added to pageview. + */ + void insertPage(Layout* page, int idx); + + /** + * Remove a page of pageview. + * + * @param page page which will be removed. + */ + void removePage(Layout* page); + + /** + * Remove a page at index of pageview. + * + * @param index index of page. + */ + void removePageAtIndex(int index); + + /** + * scroll pageview to index. + * + * @param idx index of page. + */ + void scrollToPage(int idx); + + /** + * Gets current page index. + * + * @return current page index. + */ + int getCurPageIndex() const; + + //Add call back function called when page turning. + void addPageTurningEvent(Object *target, SEL_PageViewPageTurningEvent selector); + + //override "removeChild" method of widget. + virtual bool removeChild(UIWidget* widget); + + //override "removeAllChildrenAndCleanUp" method of widget. + virtual void removeAllChildren(); + + //override "onTouchBegan" method of widget. + virtual bool onTouchBegan(const Point &touchPoint); + + //override "onTouchMoved" method of widget. + virtual void onTouchMoved(const Point &touchPoint); + + //override "onTouchEnded" method of widget. + virtual void onTouchEnded(const Point &touchPoint); + + //override "onTouchCancelled" method of widget. + virtual void onTouchCancelled(const Point &touchPoint); + + //override "update" method of widget. + virtual void update(float dt); + +protected: + virtual bool addChild(UIWidget* widget); + virtual bool init(); + Layout* createPage(); + float getPositionXByIndex(int idx); + void updateBoundaryPages(); + virtual void handlePressLogic(const Point &touchPoint); + virtual void handleMoveLogic(const Point &touchPoint); + virtual void handleReleaseLogic(const Point &touchPoint); + virtual void interceptTouchEvent(int handleState, UIWidget* sender, const Point &touchPoint); + virtual void checkChildInfo(int handleState, UIWidget* sender, const Point &touchPoint); + virtual bool scrollPages(float touchOffset); + void movePages(float offset); + void pageTurningEvent(); + void updateChildrenSize(); + void updateChildrenPosition(); + virtual void onSizeChanged(); + + virtual void setClippingEnabled(bool able){Layout::setClippingEnabled(able);}; +protected: + int m_nCurPageIdx; + Array* m_pages; + PVTouchDir m_touchMoveDir; + float m_fTouchStartLocation; + float m_fTouchEndLocation; + float m_fTouchMoveStartLocation; + Point movePagePoint; + UIWidget* m_pLeftChild; + UIWidget* m_pRightChild; + float m_fLeftBoundary; + float m_fRightBoundary; + bool m_bIsAutoScrolling; + float m_fAutoScrollDistance; + float m_fAutoScrollSpeed; + int m_nAutoScrollDir; + float m_fChildFocusCancelOffset; + Object* m_pPageTurningListener; + SEL_PageViewPageTurningEvent m_pfnPageTurningSelector; + float m_fScrollDegreeRange; +}; + +NS_CC_EXT_END + +#endif /* defined(__UIPageView__) */ diff --git a/extensions/CocoStudio/GUI/UIWidgets/ScrollWidget/UIScrollInterface.h b/extensions/CocoStudio/GUI/UIWidgets/ScrollWidget/UIScrollInterface.h new file mode 100644 index 0000000000..df8566fc53 --- /dev/null +++ b/extensions/CocoStudio/GUI/UIWidgets/ScrollWidget/UIScrollInterface.h @@ -0,0 +1,44 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __UISCROLLDELEGATE_H__ +#define __UISCROLLDELEGATE_H__ + +#include "../../BaseClasses/UIWidget.h" + +NS_CC_EXT_BEGIN + +class UIScrollInterface +{ +protected: + virtual void handlePressLogic(const Point &touchPoint) = 0; + virtual void handleMoveLogic(const Point &touchPoint) = 0; + virtual void handleReleaseLogic(const Point &touchPoint) = 0; + virtual void interceptTouchEvent(int handleState, UIWidget* sender, const Point &touchPoint) = 0; +// virtual bool isInScrollDegreeRange(UIWidget* widget) = 0; +}; + +NS_CC_EXT_END + +#endif /* defined(__UIScrollDelegate__) */ diff --git a/extensions/CocoStudio/GUI/UIWidgets/ScrollWidget/UIScrollView.cpp b/extensions/CocoStudio/GUI/UIWidgets/ScrollWidget/UIScrollView.cpp new file mode 100644 index 0000000000..e93676f6d4 --- /dev/null +++ b/extensions/CocoStudio/GUI/UIWidgets/ScrollWidget/UIScrollView.cpp @@ -0,0 +1,703 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "UIScrollView.h" +#include "../../System/UILayer.h" + +NS_CC_EXT_BEGIN + +UIScrollView::UIScrollView(): +m_eDirection(SCROLLVIEW_DIR_VERTICAL), +m_eMoveDirection(SCROLLVIEW_MOVE_DIR_NONE), +m_fTouchStartLocation(0.0f), +m_fTouchEndLocation(0.0f), +m_fTouchMoveStartLocation(0.0f), +m_fTopBoundary(0.0f), +m_fBottomBoundary(0.0f), +m_fLeftBoundary(0.0f), +m_fRightBoundary(0.0f), +m_nMoveDirection(0), +m_bTopEnd(false), +m_bBottomEnd(false), +m_bLeftEnd(false), +m_bRightEnd(false), +m_bAutoScroll(false), +m_fAutoScrollOriginalSpeed(0.0f), +m_fAutoScrollAcceleration(600.0f), +m_bBePressed(false), +m_fSlidTime(0.0f), +moveChildPoint(Point::ZERO), +m_fChildFocusCancelOffset(5.0f), +m_pScrollToTopListener(NULL), +m_pfnScrollToTopSelector(NULL), +m_pScrollToBottomListener(NULL), +m_pfnScrollToBottomSelector(NULL), +m_pScrollToLeftListener(NULL), +m_pfnScrollToLeftSelector(NULL), +m_pScrollToRightListener(NULL), +m_pfnScrollToRightSelector(NULL), +m_pInnerContainer(NULL), +m_fScrollDegreeRange(45.0f) +{ +} + +UIScrollView::~UIScrollView() +{ + +} + +UIScrollView* UIScrollView::create() +{ + UIScrollView* widget = new UIScrollView(); + if (widget && widget->init()) + { + widget->autorelease(); + return widget; + } + CC_SAFE_DELETE(widget); + return NULL; +} + +void UIScrollView::releaseResoures() +{ + setUpdateEnabled(false); + removeAllChildren(); + m_pRenderer->removeAllChildrenWithCleanup(true); + m_pRenderer->removeFromParentAndCleanup(true); + m_pRenderer->release(); + + Layout::removeChild(m_pInnerContainer); + + m_children->release(); +} + +bool UIScrollView::init() +{ + if (Layout::init()) + { + setUpdateEnabled(true); + setTouchEnabled(true); + setClippingEnabled(true); + m_pInnerContainer->setTouchEnabled(false); + return true; + } + return false; +} + +void UIScrollView::initRenderer() +{ + Layout::initRenderer(); + m_pInnerContainer = Layout::create(); + Layout::addChild(m_pInnerContainer); +} + +void UIScrollView::onSizeChanged() +{ + Layout::onSizeChanged(); + m_fTopBoundary = m_size.height; + m_fRightBoundary = m_size.width; + Size innerSize = m_pInnerContainer->getSize(); + float orginInnerSizeWidth = innerSize.width; + float orginInnerSizeHeight = innerSize.height; + float innerSizeWidth = MAX(orginInnerSizeWidth, m_size.width); + float innerSizeHeight = MAX(orginInnerSizeHeight, m_size.height); + m_pInnerContainer->setSize(Size(innerSizeWidth, innerSizeHeight)); + m_pInnerContainer->setPosition(Point(0, m_size.height - m_pInnerContainer->getSize().height)); +} + +void UIScrollView::setInnerContainerSize(const Size &size) +{ + float innerSizeWidth = m_size.width; + float innerSizeHeight = m_size.height; + if (size.width < m_size.width) + { + CCLOG("Inner width <= scrollview width, it will be force sized!"); + } + else + { + innerSizeWidth = size.width; + } + if (size.height < m_size.height) + { + CCLOG("Inner height <= scrollview height, it will be force sized!"); + } + else + { + innerSizeHeight = size.height; + } + m_pInnerContainer->setSize(Size(innerSizeWidth, innerSizeHeight)); + m_pInnerContainer->setPosition(Point(0, m_size.height - m_pInnerContainer->getSize().height)); +} + +const Size& UIScrollView::getInnerContainerSize() const +{ + return m_pInnerContainer->getSize(); +} + +bool UIScrollView::addChild(UIWidget* widget) +{ + return m_pInnerContainer->addChild(widget); +} + +void UIScrollView::removeAllChildren() +{ + m_pInnerContainer->removeAllChildren(); +} + +bool UIScrollView::removeChild(UIWidget* child) +{ + return m_pInnerContainer->removeChild(child); +} + +Array* UIScrollView::getChildren() +{ + return m_pInnerContainer->getChildren(); +} + +void UIScrollView::moveChildren(float offset) +{ + switch (m_eDirection) + { + case SCROLLVIEW_DIR_VERTICAL: // vertical + { + moveChildPoint.x = m_pInnerContainer->getPosition().x; + moveChildPoint.y = m_pInnerContainer->getPosition().y + offset; + m_pInnerContainer->setPosition(moveChildPoint); + break; + } + case SCROLLVIEW_DIR_HORIZONTAL: // horizontal + { + moveChildPoint.x = m_pInnerContainer->getPosition().x + offset; + moveChildPoint.y = m_pInnerContainer->getPosition().y; + m_pInnerContainer->setPosition(moveChildPoint); + break; + } + default: + break; + } +} + +void UIScrollView::autoScrollChildren(float dt) +{ + switch (m_eDirection) + { + case SCROLLVIEW_DIR_VERTICAL: // vertical + switch (m_eMoveDirection) + { + case SCROLLVIEW_MOVE_DIR_UP: // up + { + float curDis = getCurAutoScrollDistance(dt); + if (curDis <= 0) + { + curDis = 0; + stopAutoScrollChildren(); + } + if (!scrollChildren(curDis)) + { + stopAutoScrollChildren(); + } + } + break; + case SCROLLVIEW_MOVE_DIR_DOWN: // down + { + float curDis = getCurAutoScrollDistance(dt); + if (curDis <= 0) + { + curDis = 0; + stopAutoScrollChildren(); + } + if (!scrollChildren(-curDis)) + { + stopAutoScrollChildren(); + } + } + break; + default: + break; + } + break; + + case SCROLLVIEW_DIR_HORIZONTAL: // horizontal + switch (m_eMoveDirection) + { + case SCROLLVIEW_MOVE_DIR_LEFT: // left + { + float curDis = getCurAutoScrollDistance(dt); + if (curDis <= 0) + { + curDis = 0; + stopAutoScrollChildren(); + } + if (!scrollChildren(-curDis)) + { + stopAutoScrollChildren(); + } + } + break; + + case SCROLLVIEW_MOVE_DIR_RIGHT: // right + { + float curDis = getCurAutoScrollDistance(dt); + if (curDis <= 0) + { + curDis = 0; + stopAutoScrollChildren(); + } + if (!scrollChildren(curDis)) + { + stopAutoScrollChildren(); + } + } + break; + + default: + break; + } + break; + + default: + break; + } +} + +void UIScrollView::startAutoScrollChildren(float v) +{ + m_fAutoScrollOriginalSpeed = v; + m_bAutoScroll = true; +} + +void UIScrollView::stopAutoScrollChildren() +{ + m_bAutoScroll = false; + m_fAutoScrollOriginalSpeed = 0.0f; +} + +float UIScrollView::getCurAutoScrollDistance(float time) +{ + float dt = time; + m_fAutoScrollOriginalSpeed -= m_fAutoScrollAcceleration*dt; + return m_fAutoScrollOriginalSpeed*dt; +} + +bool UIScrollView::scrollChildren(float touchOffset) +{ + float realOffset = touchOffset; + + switch (m_eDirection) + { + case SCROLLVIEW_DIR_VERTICAL: // vertical + switch (m_eMoveDirection) + { + case SCROLLVIEW_MOVE_DIR_UP: // up + { + float icBottomPos = m_pInnerContainer->getBottomInParent(); + if (icBottomPos + touchOffset >= m_fBottomBoundary) + { + realOffset = m_fBottomBoundary - icBottomPos; + moveChildren(realOffset); + m_bBottomEnd = true; + scrollToBottomEvent(); + return false; + } + break; + } + case SCROLLVIEW_MOVE_DIR_DOWN: // down + { + float icTopPos = m_pInnerContainer->getTopInParent(); + if (icTopPos + touchOffset <= m_fTopBoundary) + { + realOffset = m_fTopBoundary - icTopPos; + moveChildren(realOffset); + m_bTopEnd = true; + scrollToTopEvent(); + return false; + } + break; + } + default: + break; + } + moveChildren(realOffset); + m_bTopEnd = false; + m_bBottomEnd = false; + return true; + break; + case SCROLLVIEW_DIR_HORIZONTAL: // horizontal + switch (m_eMoveDirection) + { + case SCROLLVIEW_MOVE_DIR_LEFT: // left + { + float icRightPos = m_pInnerContainer->getRightInParent(); + if (icRightPos + touchOffset <= m_fRightBoundary) + { + realOffset = m_fRightBoundary - icRightPos; + moveChildren(realOffset); + m_bRightEnd = true; + scrollToRightEvent(); + return false; + } + break; + } + case SCROLLVIEW_MOVE_DIR_RIGHT: // right + { + float icLeftPos = m_pInnerContainer->getLeftInParent(); + if (icLeftPos + touchOffset >= m_fLeftBoundary) + { + realOffset = m_fLeftBoundary - icLeftPos; + moveChildren(realOffset); + m_bLeftEnd = true; + scrollToLeftEvent(); + return false; + } + break; + } + default: + break; + } + moveChildren(realOffset); + m_bLeftEnd = false; + m_bRightEnd = false; + return true; + break; + + default: + break; + } + + return false; +} + +void UIScrollView::scrollToBottom() +{ + m_eMoveDirection = SCROLLVIEW_MOVE_DIR_UP; // up + scrollChildren(m_pInnerContainer->getSize().height); +} + +void UIScrollView::scrollToTop() +{ + m_eMoveDirection = SCROLLVIEW_MOVE_DIR_DOWN; // down + scrollChildren(-m_pInnerContainer->getSize().height); +} + +void UIScrollView::startRecordSlidAction() +{ + if (m_children->count() <= 0) + { + return; + } + if (m_bAutoScroll){ + stopAutoScrollChildren(); + } + m_bBePressed = true; + m_fSlidTime = 0.0; +} + +void UIScrollView::endRecordSlidAction() +{ + if (m_children->count() <= 0) + { + return; + } + if (m_fSlidTime <= 0.016f) + { + return; + } + float totalDis = 0; + totalDis = m_fTouchEndLocation-m_fTouchStartLocation; + float orSpeed = fabs(totalDis)/(m_fSlidTime); + startAutoScrollChildren(orSpeed); + + m_bBePressed = false; + m_fSlidTime = 0.0; +} + +void UIScrollView::handlePressLogic(const Point &touchPoint) +{ + Point nsp = m_pRenderer->convertToNodeSpace(touchPoint); + switch (m_eDirection) + { + case SCROLLVIEW_DIR_VERTICAL: // vertical + m_fTouchMoveStartLocation = nsp.y; + m_fTouchStartLocation = nsp.y; + break; + case SCROLLVIEW_DIR_HORIZONTAL: // horizontal + m_fTouchMoveStartLocation = nsp.x; + m_fTouchStartLocation = nsp.x; + break; + default: + break; + } + startRecordSlidAction(); +} + +void UIScrollView::handleMoveLogic(const CCPoint &touchPoint) +{ + CCPoint nsp = m_pRenderer->convertToNodeSpace(touchPoint); + float offset = 0.0f; + + switch (m_eDirection) + { + case SCROLLVIEW_DIR_VERTICAL: // vertical + { + float moveY = nsp.y; + offset = moveY - m_fTouchMoveStartLocation; + m_fTouchMoveStartLocation = moveY; + + if (offset < 0.0f) + { + m_eMoveDirection = SCROLLVIEW_MOVE_DIR_DOWN; // down + } + else if (offset > 0.0f) + { + m_eMoveDirection = SCROLLVIEW_MOVE_DIR_UP; // up + } + } + break; + + case SCROLLVIEW_DIR_HORIZONTAL: // horizontal + { + float moveX = nsp.x; + offset = moveX - m_fTouchMoveStartLocation; + m_fTouchMoveStartLocation = moveX; + + if (offset < 0) + { + m_eMoveDirection = SCROLLVIEW_MOVE_DIR_LEFT; // left + } + else if (offset > 0) + { + m_eMoveDirection = SCROLLVIEW_MOVE_DIR_RIGHT; // right + } + } + break; + + default: + break; + } + scrollChildren(offset); +} + +void UIScrollView::handleReleaseLogic(const Point &touchPoint) +{ + Point nsp = m_pRenderer->convertToNodeSpace(touchPoint); + switch (m_eDirection) + { + case SCROLLVIEW_DIR_VERTICAL: // vertical + m_fTouchEndLocation = nsp.y; + break; + + case SCROLLVIEW_DIR_HORIZONTAL: // horizontal + m_fTouchEndLocation = nsp.x; + break; + + default: + break; + } + endRecordSlidAction(); +} + +bool UIScrollView::onTouchBegan(const Point &touchPoint) +{ + bool pass = Layout::onTouchBegan(touchPoint); + handlePressLogic(touchPoint); + return pass; +} + +void UIScrollView::onTouchMoved(const Point &touchPoint) +{ + Layout::onTouchMoved(touchPoint); + handleMoveLogic(touchPoint); +} + +void UIScrollView::onTouchEnded(const Point &touchPoint) +{ + Layout::onTouchEnded(touchPoint); + handleReleaseLogic(touchPoint); +} + +void UIScrollView::onTouchCancelled(const Point &touchPoint) +{ + Layout::onTouchCancelled(touchPoint); +} + +void UIScrollView::onTouchLongClicked(const Point &touchPoint) +{ + +} + +void UIScrollView::update(float dt) +{ + if (m_bAutoScroll) + { + autoScrollChildren(dt); + } + recordSlidTime(dt); +} + +void UIScrollView::recordSlidTime(float dt) +{ + if (m_bBePressed) + { + m_fSlidTime += dt; + } +} + +void UIScrollView::interceptTouchEvent(int handleState, UIWidget *sender, const Point &touchPoint) +{ + switch (handleState) + { + case 0: + handlePressLogic(touchPoint); + break; + + case 1: + { + float offset = 0; + switch (m_eDirection) + { + case SCROLLVIEW_DIR_VERTICAL: // vertical + offset = fabs(sender->getTouchStartPos().y - touchPoint.y); + break; + + case SCROLLVIEW_DIR_HORIZONTAL: // horizontal + offset = fabs(sender->getTouchStartPos().x - touchPoint.x); + break; + + default: + break; + } + if (offset > m_fChildFocusCancelOffset) + { + sender->setFocused(false); + handleMoveLogic(touchPoint); + } + } + break; + + case 2: + handleReleaseLogic(touchPoint); + break; + + case 3: + break; + } +} + +void UIScrollView::checkChildInfo(int handleState,UIWidget* sender,const Point &touchPoint) +{ + interceptTouchEvent(handleState, sender, touchPoint); +} + +void UIScrollView::scrollToTopEvent() +{ + if (m_pScrollToTopListener && m_pfnScrollToTopSelector) + { + (m_pScrollToTopListener->*m_pfnScrollToTopSelector)(this); + } +} + +void UIScrollView::scrollToBottomEvent() +{ + if (m_pScrollToBottomListener && m_pfnScrollToBottomSelector) + { + (m_pScrollToBottomListener->*m_pfnScrollToBottomSelector)(this); + } +} + +void UIScrollView::scrollToLeftEvent() +{ + if (m_pScrollToLeftListener && m_pfnScrollToLeftSelector) + { + (m_pScrollToLeftListener->*m_pfnScrollToLeftSelector)(this); + } +} + +void UIScrollView::scrollToRightEvent() +{ + if (m_pScrollToRightListener && m_pfnScrollToRightSelector) + { + (m_pScrollToRightListener->*m_pfnScrollToRightSelector)(this); + } +} + +void UIScrollView::addScrollToTopEvent(Object *target, SEL_ScrollToTopEvent selector) +{ + m_pScrollToTopListener = target; + m_pfnScrollToTopSelector = selector; +} + +void UIScrollView::addScrollToBottomEvent(Object *target, SEL_ScrollToBottomEvent selector) +{ + m_pScrollToBottomListener = target; + m_pfnScrollToBottomSelector = selector; +} + +void UIScrollView::addScrollToLeftEvent(Object *target, SEL_ScrollToLeftEvent selector) +{ + m_pScrollToLeftListener = target; + m_pfnScrollToLeftSelector = selector; +} + +void UIScrollView::addScrollToRightEvent(Object *target, SEL_ScrollToRightEvent selector) +{ + m_pScrollToRightListener = target; + m_pfnScrollToRightSelector = selector; +} + +void UIScrollView::setDirection(SCROLLVIEW_DIR dir) +{ + m_eDirection = dir; +} + +SCROLLVIEW_DIR UIScrollView::getDirection() +{ + return m_eDirection; +} + +void UIScrollView::setMoveDirection(SCROLLVIEW_MOVE_DIR dir) +{ + m_eMoveDirection = dir; +} + +SCROLLVIEW_MOVE_DIR UIScrollView::getMoveDirection() +{ + return m_eMoveDirection; +} + +Layout* UIScrollView::getInnerContainer() +{ + return m_pInnerContainer; +} + +void UIScrollView::setLayoutExecutant(LayoutExecutant *exe) +{ + m_pInnerContainer->setLayoutExecutant(exe); +} + +LayoutExecutant* UIScrollView::getLayoutExecutant() const +{ + return m_pInnerContainer->getLayoutExecutant(); +} + +NS_CC_EXT_END \ No newline at end of file diff --git a/extensions/CocoStudio/GUI/UIWidgets/ScrollWidget/UIScrollView.h b/extensions/CocoStudio/GUI/UIWidgets/ScrollWidget/UIScrollView.h new file mode 100644 index 0000000000..0b521dd2e8 --- /dev/null +++ b/extensions/CocoStudio/GUI/UIWidgets/ScrollWidget/UIScrollView.h @@ -0,0 +1,258 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __UISCROLLVIEW_H__ +#define __UISCROLLVIEW_H__ + +#include "../../Layouts/Layout.h" +#include "UIScrollInterface.h" + +NS_CC_EXT_BEGIN + +enum SCROLLVIEW_DIR +{ + SCROLLVIEW_DIR_NONE, + SCROLLVIEW_DIR_VERTICAL, + SCROLLVIEW_DIR_HORIZONTAL +}; + +enum SCROLLVIEW_MOVE_DIR +{ + SCROLLVIEW_MOVE_DIR_NONE, + SCROLLVIEW_MOVE_DIR_UP, + SCROLLVIEW_MOVE_DIR_DOWN, + SCROLLVIEW_MOVE_DIR_LEFT, + SCROLLVIEW_MOVE_DIR_RIGHT, +}; + +typedef void (Object::*SEL_ScrollToTopEvent)(Object*); +typedef void (Object::*SEL_ScrollToBottomEvent)(Object*); +typedef void (Object::*SEL_ScrollToLeftEvent)(Object*); +typedef void (Object::*SEL_ScrollToRightEvent)(Object*); +#define coco_ScrollToTopSelector(_SELECTOR) (cocos2d::extension::SEL_ScrollToTopEvent)(&_SELECTOR) +#define coco_ScrollToBottomSelector(_SELECTOR) (cocos2d::extension::SEL_ScrollToBottomEvent)(&_SELECTOR) +#define coco_ScrollToLeftSelector(_SELECTOR) (cocos2d::extension::SEL_ScrollToLeftEvent)(&_SELECTOR) +#define coco_ScrollToRightSelector(_SELECTOR) (cocos2d::extension::SEL_ScrollToRightEvent)(&_SELECTOR) + + +class UIScrollView : public Layout , public UIScrollInterface +{ +public: + /** + * Default constructor + */ + UIScrollView(); + + /** + * Default destructor + */ + virtual ~UIScrollView(); + + /** + * Allocates and initializes. + */ + static UIScrollView* create(); + + /** + * Changes scroll direction of scrollview. + * + * @see SCROLLVIEW_DIR SCROLLVIEW_DIR_VERTICAL means vertical scroll, SCROLLVIEW_DIR_HORIZONTAL means horizontal scroll + * + * @param SCROLLVIEW_DIR + */ + void setDirection(SCROLLVIEW_DIR dir); + + /** + * Gets scroll direction of scrollview. + * + * @see SCROLLVIEW_DIR SCROLLVIEW_DIR_VERTICAL means vertical scroll, SCROLLVIEW_DIR_HORIZONTAL means horizontal scroll + * + * @return SCROLLVIEW_DIR + */ + SCROLLVIEW_DIR getDirection(); + + /** + * Gets inner container of scrollview. + * + * Inner container is the container of scrollview's children. + * + * @return inner container. + */ + Layout* getInnerContainer(); + + /** + * Scroll inner container to bottom boundary of scrollview. + */ + void scrollToBottom(); + + /** + * Scroll inner container to top boundary of scrollview. + */ + void scrollToTop(); + + /** + * Changes inner container size of scrollview. + * + * Inner container size must be larger than or equal scrollview's size. + * + * @param inner container size. + */ + void setInnerContainerSize(const Size &size); + + /** + * Gets inner container size of scrollview. + * + * Inner container size must be larger than or equal scrollview's size. + * + * @return inner container size. + */ + const Size& getInnerContainerSize() const; + + /** + * Add call back function called when scrollview scrolled to top. + */ + void addScrollToTopEvent(Object* target, SEL_ScrollToTopEvent selector); + + /** + * Add call back function called when scrollview scrolled to bottom. + */ + void addScrollToBottomEvent(Object* target, SEL_ScrollToBottomEvent selector); + + /** + * Add call back function called when scrollview scrolled to left. + */ + void addScrollToLeftEvent(Object* target, SEL_ScrollToLeftEvent selector); + + /** + * Add call back function called when scrollview scrolled to right. + */ + void addScrollToRightEvent(Object* target, SEL_ScrollToRightEvent selector); + + //override "setLayoutExecutant" method of widget. + virtual void setLayoutExecutant(LayoutExecutant* exe); + + //override "getLayoutExecutant" method of widget. + virtual LayoutExecutant* getLayoutExecutant() const; + + //override "addChild" method of widget. + virtual bool addChild(UIWidget* widget); + + //override "removeAllChildrenAndCleanUp" method of widget. + virtual void removeAllChildren(); + + //override "removeChild" method of widget. + virtual bool removeChild(UIWidget* child); + + //override "getChildren" method of widget. + virtual Array* getChildren(); + + //override "onTouchBegan" method of widget. + virtual bool onTouchBegan(const Point &touchPoint); + + //override "onTouchMoved" method of widget. + virtual void onTouchMoved(const Point &touchPoint); + + //override "onTouchEnded" method of widget. + virtual void onTouchEnded(const Point &touchPoint); + + //override "onTouchCancelled" method of widget. + virtual void onTouchCancelled(const Point &touchPoint); + + //override "onTouchLongClicked" method of widget. + virtual void onTouchLongClicked(const Point &touchPoint); + + virtual void update(float dt); +protected: + virtual bool init(); + virtual void initRenderer(); + void moveChildren(float offset); + void autoScrollChildren(float dt); + void startAutoScrollChildren(float v); + void stopAutoScrollChildren(); + float getCurAutoScrollDistance(float time); + virtual bool scrollChildren(float touchOffset); + void startRecordSlidAction(); + virtual void endRecordSlidAction(); + virtual void handlePressLogic(const Point &touchPoint); + virtual void handleMoveLogic(const Point &touchPoint); + virtual void handleReleaseLogic(const Point &touchPoint); + virtual void interceptTouchEvent(int handleState,UIWidget* sender,const Point &touchPoint); + virtual void checkChildInfo(int handleState,UIWidget* sender,const Point &touchPoint); + void recordSlidTime(float dt); + //override "releaseResoures" method of widget. + virtual void releaseResoures(); + + void scrollToTopEvent(); + void scrollToBottomEvent(); + void scrollToLeftEvent(); + void scrollToRightEvent(); + void setMoveDirection(SCROLLVIEW_MOVE_DIR dir); + SCROLLVIEW_MOVE_DIR getMoveDirection(); + virtual void onSizeChanged(); + virtual void setClippingEnabled(bool able){Layout::setClippingEnabled(able);}; +protected: + SCROLLVIEW_DIR m_eDirection; + SCROLLVIEW_MOVE_DIR m_eMoveDirection; + float m_fTouchStartLocation; + float m_fTouchEndLocation; + float m_fTouchMoveStartLocation; + float m_fTopBoundary;//test + float m_fBottomBoundary;//test + float m_fLeftBoundary; + float m_fRightBoundary; + + + int m_nMoveDirection;//0 pull down, 1 push up + + bool m_bTopEnd; + bool m_bBottomEnd; + bool m_bLeftEnd; + bool m_bRightEnd; + + bool m_bAutoScroll; + + float m_fAutoScrollOriginalSpeed; + float m_fAutoScrollAcceleration; + + bool m_bBePressed; + float m_fSlidTime; + Point moveChildPoint; + float m_fChildFocusCancelOffset; + + Object* m_pScrollToTopListener; + SEL_ScrollToTopEvent m_pfnScrollToTopSelector; + Object* m_pScrollToBottomListener; + SEL_ScrollToBottomEvent m_pfnScrollToBottomSelector; + Object* m_pScrollToLeftListener; + SEL_ScrollToLeftEvent m_pfnScrollToLeftSelector; + Object* m_pScrollToRightListener; + SEL_ScrollToRightEvent m_pfnScrollToRightSelector; + + Layout* m_pInnerContainer; + float m_fScrollDegreeRange; +}; + +NS_CC_EXT_END + +#endif /* defined(__CocoGUI__UIScrollView__) */ diff --git a/extensions/CocoStudio/GUI/UIWidgets/UIButton.cpp b/extensions/CocoStudio/GUI/UIWidgets/UIButton.cpp new file mode 100644 index 0000000000..a86db69f95 --- /dev/null +++ b/extensions/CocoStudio/GUI/UIWidgets/UIButton.cpp @@ -0,0 +1,660 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "UIButton.h" +#include "../../../GUI/CCControlExtension/CCScale9Sprite.h" + +NS_CC_EXT_BEGIN + +#define NORMALRENDERERZ (0) +#define PRESSEDRENDERERZ (0) +#define DISABLEDRENDERERZ (0) +#define TITLERENDERERZ (1) + +UIButton::UIButton(): +m_pButtonNormalRenderer(NULL), +m_pButtonClickedRenderer(NULL), +m_pButtonDisableRenderer(NULL), +m_pTitleRenderer(NULL), +m_strNormalFileName(""), +m_strClickedFileName(""), +m_strDisabledFileName(""), +m_bPrevIgnoreSize(true), +m_bScale9Enabled(false), +m_capInsetsNormal(Rect::ZERO), +m_capInsetsPressed(Rect::ZERO), +m_capInsetsDisabled(Rect::ZERO), +m_eNormalTexType(UI_TEX_TYPE_LOCAL), +m_ePressedTexType(UI_TEX_TYPE_LOCAL), +m_eDisabledTexType(UI_TEX_TYPE_LOCAL), +m_normalTextureSize(m_size), +m_pressedTextureSize(m_size), +m_disabledTextureSize(m_size), +m_bPressedActionEnabled(false), +m_titleColor(Color3B::WHITE) +{ + +} + +UIButton::~UIButton() +{ +} + +UIButton* UIButton::create() +{ + UIButton* widget = new UIButton(); + if (widget && widget->init()) + { + widget->autorelease(); + return widget; + } + CC_SAFE_DELETE(widget); + return NULL; +} + +bool UIButton::init() +{ + if (UIWidget::init()) + { + return true; + } + return false; +} + +void UIButton::initRenderer() +{ + UIWidget::initRenderer(); + m_pButtonNormalRenderer = CCSprite::create(); + m_pButtonClickedRenderer = CCSprite::create(); + m_pButtonDisableRenderer = CCSprite::create(); + m_pTitleRenderer = CCLabelTTF::create(); + m_pRenderer->addChild(m_pButtonNormalRenderer,NORMALRENDERERZ); + m_pRenderer->addChild(m_pButtonClickedRenderer,PRESSEDRENDERERZ); + m_pRenderer->addChild(m_pButtonDisableRenderer,DISABLEDRENDERERZ); + m_pRenderer->addChild(m_pTitleRenderer,TITLERENDERERZ); +} + +void UIButton::setScale9Enabled(bool able) +{ + if (m_bScale9Enabled == able) + { + return; + } + m_eBrightStyle = BRIGHT_NONE; + m_bScale9Enabled = able; + + + m_pRenderer->removeChild(m_pButtonNormalRenderer, true); + m_pRenderer->removeChild(m_pButtonClickedRenderer, true); + m_pRenderer->removeChild(m_pButtonDisableRenderer, true); + + m_pButtonNormalRenderer = NULL; + m_pButtonClickedRenderer = NULL; + m_pButtonDisableRenderer = NULL; + if (m_bScale9Enabled) + { + m_pButtonNormalRenderer = Scale9Sprite::create(); + m_pButtonClickedRenderer = Scale9Sprite::create(); + m_pButtonDisableRenderer = Scale9Sprite::create(); + } + else + { + m_pButtonNormalRenderer = CCSprite::create(); + m_pButtonClickedRenderer = CCSprite::create(); + m_pButtonDisableRenderer = CCSprite::create(); + } + + loadTextureNormal(m_strNormalFileName.c_str(), m_eNormalTexType); + loadTexturePressed(m_strClickedFileName.c_str(), m_ePressedTexType); + loadTextureDisabled(m_strDisabledFileName.c_str(), m_eDisabledTexType); + m_pRenderer->addChild(m_pButtonNormalRenderer,NORMALRENDERERZ); + m_pRenderer->addChild(m_pButtonClickedRenderer,PRESSEDRENDERERZ); + m_pRenderer->addChild(m_pButtonDisableRenderer,DISABLEDRENDERERZ); + if (m_bScale9Enabled) + { + bool ignoreBefore = m_bIgnoreSize; + ignoreContentAdaptWithSize(false); + m_bPrevIgnoreSize = ignoreBefore; + } + else + { + ignoreContentAdaptWithSize(m_bPrevIgnoreSize); + } + setCapInsetsNormalRenderer(m_capInsetsNormal); + setCapInsetsPressedRenderer(m_capInsetsPressed); + setCapInsetsDisabledRenderer(m_capInsetsDisabled); + setBright(m_bBright); +} + +void UIButton::ignoreContentAdaptWithSize(bool ignore) +{ + if (!m_bScale9Enabled || (m_bScale9Enabled && !ignore)) + { + UIWidget::ignoreContentAdaptWithSize(ignore); + m_bPrevIgnoreSize = ignore; + } +} + +void UIButton::loadTextures(const char* normal,const char* selected,const char* disabled,TextureResType texType) +{ + loadTextureNormal(normal,texType); + loadTexturePressed(selected,texType); + loadTextureDisabled(disabled,texType); +} + +void UIButton::loadTextureNormal(const char* normal,TextureResType texType) +{ + if (!normal || strcmp(normal, "") == 0) + { + return; + } + m_strNormalFileName = normal; + m_eNormalTexType = texType; + if (m_bScale9Enabled) + { + switch (m_eNormalTexType) + { + case UI_TEX_TYPE_LOCAL: + dynamic_cast(m_pButtonNormalRenderer)->initWithFile(normal); + break; + case UI_TEX_TYPE_PLIST: + dynamic_cast(m_pButtonNormalRenderer)->initWithSpriteFrameName(normal); + break; + default: + break; + } + dynamic_cast(m_pButtonNormalRenderer)->setColor(getColor()); + dynamic_cast(m_pButtonNormalRenderer)->setOpacity(getOpacity()); + } + else + { + switch (m_eNormalTexType) + { + case UI_TEX_TYPE_LOCAL: + dynamic_cast(m_pButtonNormalRenderer)->initWithFile(normal); + break; + case UI_TEX_TYPE_PLIST: + dynamic_cast(m_pButtonNormalRenderer)->initWithSpriteFrameName(normal); + break; + default: + break; + } + dynamic_cast(m_pButtonNormalRenderer)->setColor(getColor()); + dynamic_cast(m_pButtonNormalRenderer)->setOpacity(getOpacity()); + } + m_normalTextureSize = m_pButtonNormalRenderer->getContentSize(); + updateAnchorPoint(); + normalTextureScaleChangedWithSize(); +} + +void UIButton::loadTexturePressed(const char* selected,TextureResType texType) +{ + if (!selected || strcmp(selected, "") == 0) + { + return; + } + m_strClickedFileName = selected; + m_ePressedTexType = texType; + if (m_bScale9Enabled) + { + switch (m_ePressedTexType) + { + case UI_TEX_TYPE_LOCAL: + dynamic_cast(m_pButtonClickedRenderer)->initWithFile(selected); + break; + case UI_TEX_TYPE_PLIST: + dynamic_cast(m_pButtonClickedRenderer)->initWithSpriteFrameName(selected); + break; + default: + break; + } + dynamic_cast(m_pButtonClickedRenderer)->setColor(getColor()); + dynamic_cast(m_pButtonClickedRenderer)->setOpacity(getOpacity()); + } + else + { + switch (m_ePressedTexType) + { + case UI_TEX_TYPE_LOCAL: + dynamic_cast(m_pButtonClickedRenderer)->initWithFile(selected); + break; + case UI_TEX_TYPE_PLIST: + dynamic_cast(m_pButtonClickedRenderer)->initWithSpriteFrameName(selected); + break; + default: + break; + } + dynamic_cast(m_pButtonClickedRenderer)->setColor(getColor()); + dynamic_cast(m_pButtonClickedRenderer)->setOpacity(getOpacity()); + } + m_pressedTextureSize = m_pButtonClickedRenderer->getContentSize(); + updateAnchorPoint(); + pressedTextureScaleChangedWithSize(); +} + +void UIButton::loadTextureDisabled(const char* disabled,TextureResType texType) +{ + if (!disabled || strcmp(disabled, "") == 0) + { + return; + } + m_strDisabledFileName = disabled; + m_eDisabledTexType = texType; + if (m_bScale9Enabled) + { + switch (m_eDisabledTexType) + { + case UI_TEX_TYPE_LOCAL: + dynamic_cast(m_pButtonDisableRenderer)->initWithFile(disabled); + break; + case UI_TEX_TYPE_PLIST: + dynamic_cast(m_pButtonDisableRenderer)->initWithSpriteFrameName(disabled); + break; + default: + break; + } + dynamic_cast(m_pButtonDisableRenderer)->setColor(getColor()); + dynamic_cast(m_pButtonDisableRenderer)->setOpacity(getOpacity()); + } + else + { + switch (m_eDisabledTexType) + { + case UI_TEX_TYPE_LOCAL: + dynamic_cast(m_pButtonDisableRenderer)->initWithFile(disabled); + break; + case UI_TEX_TYPE_PLIST: + dynamic_cast(m_pButtonDisableRenderer)->initWithSpriteFrameName(disabled); + break; + default: + break; + } + dynamic_cast(m_pButtonDisableRenderer)->setColor(getColor()); + dynamic_cast(m_pButtonDisableRenderer)->setOpacity(getOpacity()); + } + m_disabledTextureSize = m_pButtonDisableRenderer->getContentSize(); + updateAnchorPoint(); + disabledTextureScaleChangedWithSize(); +} + +void UIButton::setCapInsets(const Rect &capInsets) +{ + setCapInsetsNormalRenderer(capInsets); + setCapInsetsPressedRenderer(capInsets); + setCapInsetsDisabledRenderer(capInsets); +} + +void UIButton::setCapInsetsNormalRenderer(const Rect &capInsets) +{ + m_capInsetsNormal = capInsets; + if (!m_bScale9Enabled) + { + return; + } + dynamic_cast(m_pButtonNormalRenderer)->setCapInsets(capInsets); +} + +void UIButton::setCapInsetsPressedRenderer(const Rect &capInsets) +{ + m_capInsetsPressed = capInsets; + if (!m_bScale9Enabled) + { + return; + } + dynamic_cast(m_pButtonClickedRenderer)->setCapInsets(capInsets); +} + +void UIButton::setCapInsetsDisabledRenderer(const Rect &capInsets) +{ + m_capInsetsDisabled = capInsets; + if (!m_bScale9Enabled) + { + return; + } + dynamic_cast(m_pButtonDisableRenderer)->setCapInsets(capInsets); +} + +void UIButton::onPressStateChangedToNormal() +{ + m_pButtonNormalRenderer->setVisible(true); + m_pButtonClickedRenderer->setVisible(false); + m_pButtonDisableRenderer->setVisible(false); + if (m_bPressedActionEnabled) + { + m_pButtonNormalRenderer->stopAllActions(); + m_pButtonClickedRenderer->stopAllActions(); + m_pButtonDisableRenderer->stopAllActions(); + Action *zoomAction = ScaleTo::create(0.05f, 1.0f); + Action *zoomAction1 = ScaleTo::create(0.05f, 1.0f); + Action *zoomAction2 = ScaleTo::create(0.05f, 1.0f); + m_pButtonNormalRenderer->runAction(zoomAction); + m_pButtonClickedRenderer->runAction(zoomAction1); + m_pButtonDisableRenderer->runAction(zoomAction2); + } +} + +void UIButton::onPressStateChangedToPressed() +{ + m_pButtonNormalRenderer->setVisible(false); + m_pButtonClickedRenderer->setVisible(true); + m_pButtonDisableRenderer->setVisible(false); + if (m_bPressedActionEnabled) + { + m_pButtonNormalRenderer->stopAllActions(); + m_pButtonClickedRenderer->stopAllActions(); + m_pButtonDisableRenderer->stopAllActions(); + Action *zoomAction = ScaleTo::create(0.05f, 1.1f); + Action *zoomAction1 = ScaleTo::create(0.05f, 1.1f); + Action *zoomAction2 = ScaleTo::create(0.05f, 1.1f); + m_pButtonNormalRenderer->runAction(zoomAction); + m_pButtonClickedRenderer->runAction(zoomAction1); + m_pButtonDisableRenderer->runAction(zoomAction2); + } +} + +void UIButton::onPressStateChangedToDisabled() +{ + m_pButtonNormalRenderer->setVisible(false); + m_pButtonClickedRenderer->setVisible(false); + m_pButtonDisableRenderer->setVisible(true); +} + +void UIButton::setFlipX(bool flipX) +{ + m_pTitleRenderer->setFlippedX(flipX); + if (m_bScale9Enabled) + { + return; + } + dynamic_cast(m_pButtonNormalRenderer)->setFlippedX(flipX); + dynamic_cast(m_pButtonClickedRenderer)->setFlippedX(flipX); + dynamic_cast(m_pButtonDisableRenderer)->setFlippedX(flipX); +} + +void UIButton::setFlipY(bool flipY) +{ + m_pTitleRenderer->setFlippedY(flipY); + if (m_bScale9Enabled) + { + return; + } + dynamic_cast(m_pButtonNormalRenderer)->setFlippedY(flipY); + dynamic_cast(m_pButtonClickedRenderer)->setFlippedY(flipY); + dynamic_cast(m_pButtonDisableRenderer)->setFlippedY(flipY); +} + +bool UIButton::isFlipX() +{ + if (m_bScale9Enabled) + { + return false; + } + return dynamic_cast(m_pButtonNormalRenderer)->isFlippedX(); +} + +bool UIButton::isFlipY() +{ + if (m_bScale9Enabled) + { + return false; + } + return dynamic_cast(m_pButtonNormalRenderer)->isFlippedY(); +} + +void UIButton::setAnchorPoint(const Point &pt) +{ + UIWidget::setAnchorPoint(pt); + m_pButtonNormalRenderer->setAnchorPoint(pt); + m_pButtonClickedRenderer->setAnchorPoint(pt); + m_pButtonDisableRenderer->setAnchorPoint(pt); + m_pTitleRenderer->setPosition(Point(m_size.width*(0.5f-m_anchorPoint.x), m_size.height*(0.5f-m_anchorPoint.y))); +} + +void UIButton::setNormalSpriteFrame(SpriteFrame *frame) +{ + if (!frame) + { + return; + } + if (m_bScale9Enabled) + { + dynamic_cast(m_pButtonNormalRenderer)->setSpriteFrame(frame); + } + else + { + dynamic_cast(m_pButtonNormalRenderer)->setDisplayFrame(frame); + } +} + +void UIButton::setPressedSpriteFrame(SpriteFrame *frame) +{ + if (!frame) + { + return; + } + if (m_bScale9Enabled) + { + dynamic_cast(m_pButtonClickedRenderer)->setSpriteFrame(frame); + } + else + { + dynamic_cast(m_pButtonClickedRenderer)->setDisplayFrame(frame); + } +} + +void UIButton::setDisabledSpriteFrame(SpriteFrame *frame) +{ + if (!frame) + { + return; + } + if (m_bScale9Enabled) + { + dynamic_cast(m_pButtonDisableRenderer)->setSpriteFrame(frame); + } + else + { + dynamic_cast(m_pButtonDisableRenderer)->setDisplayFrame(frame); + } +} + +void UIButton::onSizeChanged() +{ + normalTextureScaleChangedWithSize(); + pressedTextureScaleChangedWithSize(); + disabledTextureScaleChangedWithSize(); +} + +const Size& UIButton::getContentSize() const +{ + return m_normalTextureSize; +} + +Node* UIButton::getVirtualRenderer() +{ + if (m_bBright) + { + switch (m_eBrightStyle) + { + case BRIGHT_NORMAL: + return m_pButtonNormalRenderer; + case BRIGHT_HIGHLIGHT: + return m_pButtonClickedRenderer; + default: + return NULL; + } + } + else + { + return m_pButtonDisableRenderer; + } +} + +void UIButton::normalTextureScaleChangedWithSize() +{ + if (m_bIgnoreSize) + { + if (!m_bScale9Enabled) + { + m_pButtonNormalRenderer->setScale(1.0f); + m_size = m_normalTextureSize; + } + } + else + { + if (m_bScale9Enabled) + { + dynamic_cast(m_pButtonNormalRenderer)->setPreferredSize(m_size); + } + else + { + Size textureSize = m_normalTextureSize; + if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) + { + m_pButtonNormalRenderer->setScale(1.0f); + return; + } + float scaleX = m_size.width / textureSize.width; + float scaleY = m_size.height / textureSize.height; + m_pButtonNormalRenderer->setScaleX(scaleX); + m_pButtonNormalRenderer->setScaleY(scaleY); + } + } +} + +void UIButton::pressedTextureScaleChangedWithSize() +{ + if (m_bIgnoreSize) + { + if (!m_bScale9Enabled) + { + m_pButtonClickedRenderer->setScale(1.0f); + } + } + else + { + if (m_bScale9Enabled) + { + dynamic_cast(m_pButtonClickedRenderer)->setPreferredSize(m_size); + } + else + { + Size textureSize = m_pressedTextureSize; + if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) + { + m_pButtonClickedRenderer->setScale(1.0f); + return; + } + float scaleX = m_size.width / m_pressedTextureSize.width; + float scaleY = m_size.height / m_pressedTextureSize.height; + m_pButtonClickedRenderer->setScaleX(scaleX); + m_pButtonClickedRenderer->setScaleY(scaleY); + } + } +} + +void UIButton::disabledTextureScaleChangedWithSize() +{ + if (m_bIgnoreSize) + { + if (!m_bScale9Enabled) + { + m_pButtonDisableRenderer->setScale(1.0f); + } + } + else + { + if (m_bScale9Enabled) + { + dynamic_cast(m_pButtonDisableRenderer)->setPreferredSize(m_size); + } + else + { + Size textureSize = m_disabledTextureSize; + if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) + { + m_pButtonDisableRenderer->setScale(1.0f); + return; + } + float scaleX = m_size.width / m_disabledTextureSize.width; + float scaleY = m_size.height / m_disabledTextureSize.height; + m_pButtonDisableRenderer->setScaleX(scaleX); + m_pButtonDisableRenderer->setScaleY(scaleY); + } + } +} + +void UIButton::setPressedActionEnabled(bool enabled) +{ + m_bPressedActionEnabled = enabled; +} + +void UIButton::setTitleText(const char* text) +{ + m_pTitleRenderer->setString(text); +} + +const char* UIButton::getTitleText() const +{ + return m_pTitleRenderer->getString(); +} + +void UIButton::setTitleColor(const Color3B& color) +{ + m_titleColor = color; + m_pTitleRenderer->setColor(color); +} + +const Color3B& UIButton::getTitleColor() const +{ + return m_pTitleRenderer->getColor(); +} + +void UIButton::setTitleFontSize(float size) +{ + m_pTitleRenderer->setFontSize(size); +} + +float UIButton::getTitleFontSize() const +{ + return m_pTitleRenderer->getFontSize(); +} + +void UIButton::setTitleFontName(const char* fontName) +{ + m_pTitleRenderer->setFontName(fontName); +} + +const char* UIButton::getTitleFontName() const +{ + return m_pTitleRenderer->getFontName(); +} + +void UIButton::setColor(const Color3B &color) +{ + UIWidget::setColor(color); + setTitleColor(m_titleColor); +} + +NS_CC_EXT_END \ No newline at end of file diff --git a/extensions/CocoStudio/GUI/UIWidgets/UIButton.h b/extensions/CocoStudio/GUI/UIWidgets/UIButton.h new file mode 100644 index 0000000000..e0d6994ff8 --- /dev/null +++ b/extensions/CocoStudio/GUI/UIWidgets/UIButton.h @@ -0,0 +1,213 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __UIBUTTON_H__ +#define __UIBUTTON_H__ + +#include "../BaseClasses/UIWidget.h" + +NS_CC_EXT_BEGIN + +class UIButton : public UIWidget +{ +public: + /** + * Default constructor + */ + UIButton(); + + /** + * Default destructor + */ + virtual ~UIButton(); + + /** + * Allocates and initializes. + */ + static UIButton* create(); + + /** + * Load textures for button. + * + * @param normal normal state texture. + * + * @param selected selected state texture. + * + * @param disabled dark state texture. + * + * @param texType @see UI_TEX_TYPE_LOCAL + */ + void loadTextures(const char* normal,const char* selected,const char* disabled,TextureResType texType = UI_TEX_TYPE_LOCAL); + + /** + * Load normal state texture for button. + * + * @param normal normal state texture. + * + * @param texType @see UI_TEX_TYPE_LOCAL + */ + void loadTextureNormal(const char* normal, TextureResType texType = UI_TEX_TYPE_LOCAL); + + /** + * Load selected state texture for button. + * + * @param selected selected state texture. + * + * @param texType @see UI_TEX_TYPE_LOCAL + */ + void loadTexturePressed(const char* selected, TextureResType texType = UI_TEX_TYPE_LOCAL); + + /** + * Load dark state texture for button. + * + * @param disabled dark state texture. + * + * @param texType @see UI_TEX_TYPE_LOCAL + */ + void loadTextureDisabled(const char* disabled, TextureResType texType = UI_TEX_TYPE_LOCAL); + + /** + * Sets capinsets for button, if button is using scale9 renderer. + * + * @param capInsets capinsets for button + */ + void setCapInsets(const Rect &capInsets); + + /** + * Sets capinsets for button, if button is using scale9 renderer. + * + * @param capInsets capinsets for button + */ + void setCapInsetsNormalRenderer(const Rect &capInsets); + + /** + * Sets capinsets for button, if button is using scale9 renderer. + * + * @param capInsets capinsets for button + */ + void setCapInsetsPressedRenderer(const Rect &capInsets); + + /** + * Sets capinsets for button, if button is using scale9 renderer. + * + * @param capInsets capinsets for button + */ + void setCapInsetsDisabledRenderer(const Rect &capInsets); + + //override "setAnchorPoint" of widget. + virtual void setAnchorPoint(const Point &pt); + + /** + * Sets if button is using scale9 renderer. + * + * @param true that using scale9 renderer, false otherwise. + */ + virtual void setScale9Enabled(bool able); + + //override "setFlipX" of widget. + virtual void setFlipX(bool flipX); + + //override "setFlipY" of widget. + virtual void setFlipY(bool flipY); + + //override "isFlipX" of widget. + virtual bool isFlipX(); + + //override "isFlipY" of widget. + virtual bool isFlipY(); + + /** + * Changes if button can be clicked zoom effect. + * + * @param true that can be clicked zoom effect, false otherwise. + */ + void setPressedActionEnabled(bool enabled); + + //override "ignoreContentAdaptWithSize" method of widget. + virtual void ignoreContentAdaptWithSize(bool ignore); + + //override "getContentSize" method of widget. + virtual const Size& getContentSize() const; + + //override "getVirtualRenderer" method of widget. + virtual Node* getVirtualRenderer(); + + /** + * Sets color to widget + * + * It default change the color of widget's children. + * + * @param color + */ + virtual void setColor(const Color3B &color); + + void setTitleText(const char* text); + const char* getTitleText() const; + void setTitleColor(const Color3B& color); + const Color3B& getTitleColor() const; + void setTitleFontSize(float size); + float getTitleFontSize() const; + void setTitleFontName(const char* fontName); + const char* getTitleFontName() const; + + virtual void setNormalSpriteFrame(SpriteFrame* frame); + virtual void setPressedSpriteFrame(SpriteFrame* frame); + virtual void setDisabledSpriteFrame(SpriteFrame* frame); +protected: + virtual bool init(); + virtual void initRenderer(); + virtual void onPressStateChangedToNormal(); + virtual void onPressStateChangedToPressed(); + virtual void onPressStateChangedToDisabled(); + virtual void onSizeChanged(); + + void normalTextureScaleChangedWithSize(); + void pressedTextureScaleChangedWithSize(); + void disabledTextureScaleChangedWithSize(); +protected: + Node* m_pButtonNormalRenderer; + Node* m_pButtonClickedRenderer; + Node* m_pButtonDisableRenderer; + LabelTTF* m_pTitleRenderer; + std::string m_strNormalFileName; + std::string m_strClickedFileName; + std::string m_strDisabledFileName; + bool m_bPrevIgnoreSize; + bool m_bScale9Enabled; + Rect m_capInsetsNormal; + Rect m_capInsetsPressed; + Rect m_capInsetsDisabled; + TextureResType m_eNormalTexType; + TextureResType m_ePressedTexType; + TextureResType m_eDisabledTexType; + Size m_normalTextureSize; + Size m_pressedTextureSize; + Size m_disabledTextureSize; + bool m_bPressedActionEnabled; + Color3B m_titleColor; +}; + +NS_CC_EXT_END + +#endif /* defined(__CocoGUI__UIButton__) */ diff --git a/extensions/CocoStudio/GUI/UIWidgets/UICheckBox.cpp b/extensions/CocoStudio/GUI/UIWidgets/UICheckBox.cpp new file mode 100644 index 0000000000..117ca80545 --- /dev/null +++ b/extensions/CocoStudio/GUI/UIWidgets/UICheckBox.cpp @@ -0,0 +1,459 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "UICheckBox.h" + +NS_CC_EXT_BEGIN + +UICheckBox::UICheckBox(): +m_pBackGroundBoxRenderer(NULL), +m_pBackGroundSelectedBoxRenderer(NULL), +m_pFrontCrossRenderer(NULL), +m_pBackGroundBoxDisabledRenderer(NULL), +m_pFrontCrossDisabledRenderer(NULL), +m_bIsSelected(true), +m_pSelectedStateEventListener(NULL), +m_pfnSelectedStateEventSelector(NULL), +m_eBackGroundTexType(UI_TEX_TYPE_LOCAL), +m_eBackGroundSelectedTexType(UI_TEX_TYPE_LOCAL), +m_eFrontCrossTexType(UI_TEX_TYPE_LOCAL), +m_eBackGroundDisabledTexType(UI_TEX_TYPE_LOCAL), +m_eFrontCrossDisabledTexType(UI_TEX_TYPE_LOCAL) +{ +} + +UICheckBox::~UICheckBox() +{ + +} + +UICheckBox* UICheckBox::create() +{ + UICheckBox* widget = new UICheckBox(); + if (widget && widget->init()) + { + widget->autorelease(); + return widget; + } + CC_SAFE_DELETE(widget); + return NULL; +} + +bool UICheckBox::init() +{ + if (UIWidget::init()) + { + setSelectedState(false); + return true; + } + return false; +} + +void UICheckBox::initRenderer() +{ + UIWidget::initRenderer(); + m_pBackGroundBoxRenderer = CCSprite::create(); + m_pBackGroundSelectedBoxRenderer = CCSprite::create(); + m_pFrontCrossRenderer = CCSprite::create(); + m_pBackGroundBoxDisabledRenderer = CCSprite::create(); + m_pFrontCrossDisabledRenderer = CCSprite::create(); + m_pRenderer->addChild(m_pBackGroundBoxRenderer); + m_pRenderer->addChild(m_pBackGroundSelectedBoxRenderer); + m_pRenderer->addChild(m_pFrontCrossRenderer); + m_pRenderer->addChild(m_pBackGroundBoxDisabledRenderer); + m_pRenderer->addChild(m_pFrontCrossDisabledRenderer); +} + +void UICheckBox::loadTextures(const char *backGround, const char *backGroundSelected, const char *cross,const char* backGroundDisabled,const char* frontCrossDisabled,TextureResType texType) +{ + loadTextureBackGround(backGround,texType); + loadTextureBackGroundSelected(backGroundSelected,texType); + loadTextureFrontCross(cross,texType); + loadTextureBackGroundDisabled(backGroundDisabled,texType); + loadTextureFrontCrossDisabled(frontCrossDisabled,texType); +} + +void UICheckBox::loadTextureBackGround(const char *backGround,TextureResType texType) +{ + if (!backGround || strcmp(backGround, "") == 0) + { + return; + } + m_eBackGroundTexType = texType; + switch (m_eBackGroundTexType) + { + case UI_TEX_TYPE_LOCAL: + m_pBackGroundBoxRenderer->initWithFile(backGround); + break; + case UI_TEX_TYPE_PLIST: + m_pBackGroundBoxRenderer->initWithSpriteFrameName(backGround); + break; + default: + break; + } + m_pBackGroundBoxRenderer->setColor(getColor()); + m_pBackGroundBoxRenderer->setOpacity(getOpacity()); + backGroundTextureScaleChangedWithSize(); +} + +void UICheckBox::loadTextureBackGroundSelected(const char *backGroundSelected,TextureResType texType) +{ + if (!backGroundSelected || strcmp(backGroundSelected, "") == 0) + { + return; + } + m_eBackGroundSelectedTexType = texType; + switch (m_eBackGroundSelectedTexType) + { + case UI_TEX_TYPE_LOCAL: + m_pBackGroundSelectedBoxRenderer->initWithFile(backGroundSelected); + break; + case UI_TEX_TYPE_PLIST: + m_pBackGroundSelectedBoxRenderer->initWithSpriteFrameName(backGroundSelected); + break; + default: + break; + } + m_pBackGroundSelectedBoxRenderer->setColor(getColor()); + m_pBackGroundSelectedBoxRenderer->setOpacity(getOpacity()); + backGroundSelectedTextureScaleChangedWithSize(); +} + +void UICheckBox::loadTextureFrontCross(const char *cross,TextureResType texType) +{ + if (!cross || strcmp(cross, "") == 0) + { + return; + } + m_eFrontCrossTexType = texType; + switch (m_eFrontCrossTexType) + { + case UI_TEX_TYPE_LOCAL: + m_pFrontCrossRenderer->initWithFile(cross); + break; + case UI_TEX_TYPE_PLIST: + m_pFrontCrossRenderer->initWithSpriteFrameName(cross); + break; + default: + break; + } + m_pFrontCrossRenderer->setColor(getColor()); + m_pFrontCrossRenderer->setOpacity(getOpacity()); + frontCrossTextureScaleChangedWithSize(); +} + +void UICheckBox::loadTextureBackGroundDisabled(const char *backGroundDisabled,TextureResType texType) +{ + if (!backGroundDisabled || strcmp(backGroundDisabled, "") == 0) + { + return; + } + m_eBackGroundDisabledTexType = texType; + switch (m_eBackGroundDisabledTexType) + { + case UI_TEX_TYPE_LOCAL: + m_pBackGroundBoxDisabledRenderer->initWithFile(backGroundDisabled); + break; + case UI_TEX_TYPE_PLIST: + m_pBackGroundBoxDisabledRenderer->initWithSpriteFrameName(backGroundDisabled); + break; + default: + break; + } + m_pBackGroundBoxDisabledRenderer->setColor(getColor()); + m_pBackGroundBoxDisabledRenderer->setOpacity(getOpacity()); + backGroundDisabledTextureScaleChangedWithSize(); +} + +void UICheckBox::loadTextureFrontCrossDisabled(const char *frontCrossDisabled,TextureResType texType) +{ + if (!frontCrossDisabled || strcmp(frontCrossDisabled, "") == 0) + { + return; + } + m_eFrontCrossDisabledTexType = texType; + switch (m_eFrontCrossDisabledTexType) + { + case UI_TEX_TYPE_LOCAL: + m_pFrontCrossDisabledRenderer->initWithFile(frontCrossDisabled); + break; + case UI_TEX_TYPE_PLIST: + m_pFrontCrossDisabledRenderer->initWithSpriteFrameName(frontCrossDisabled); + break; + default: + break; + } + m_pFrontCrossDisabledRenderer->setColor(getColor()); + m_pFrontCrossRenderer->setOpacity(getOpacity()); + frontCrossDisabledTextureScaleChangedWithSize(); +} + +void UICheckBox::onTouchEnded(const Point &touchPoint) +{ + if (m_bFocus) + { + releaseUpEvent(); + if (m_bIsSelected){ + setSelectedState(false); + unSelectedEvent(); + } + else + { + setSelectedState(true); + selectedEvent(); + } + } + setFocused(false); + m_pWidgetParent->checkChildInfo(2,this,touchPoint); +} + +void UICheckBox::onPressStateChangedToNormal() +{ + m_pBackGroundBoxRenderer->setVisible(true); + m_pBackGroundSelectedBoxRenderer->setVisible(false); + m_pBackGroundBoxDisabledRenderer->setVisible(false); + m_pFrontCrossDisabledRenderer->setVisible(false); +} + +void UICheckBox::onPressStateChangedToPressed() +{ + m_pBackGroundBoxRenderer->setVisible(false); + m_pBackGroundSelectedBoxRenderer->setVisible(true); + m_pBackGroundBoxDisabledRenderer->setVisible(false); + m_pFrontCrossDisabledRenderer->setVisible(false); +} + +void UICheckBox::onPressStateChangedToDisabled() +{ + m_pBackGroundBoxRenderer->setVisible(false); + m_pBackGroundSelectedBoxRenderer->setVisible(false); + m_pBackGroundBoxDisabledRenderer->setVisible(true); + m_pFrontCrossRenderer->setVisible(false); + if (m_bIsSelected) + { + m_pFrontCrossDisabledRenderer->setVisible(true); + } +} + +void UICheckBox::setSelectedState(bool selected) +{ + if (selected == m_bIsSelected) + { + return; + } + m_bIsSelected = selected; + m_pFrontCrossRenderer->setVisible(m_bIsSelected); +} + +bool UICheckBox::getSelectedState() +{ + return m_bIsSelected; +} + +void UICheckBox::selectedEvent() +{ + if (m_pSelectedStateEventListener && m_pfnSelectedStateEventSelector) + { + (m_pSelectedStateEventListener->*m_pfnSelectedStateEventSelector)(this,CHECKBOX_STATE_EVENT_SELECTED); + } +} + +void UICheckBox::unSelectedEvent() +{ + if (m_pSelectedStateEventListener && m_pfnSelectedStateEventSelector) + { + (m_pSelectedStateEventListener->*m_pfnSelectedStateEventSelector)(this,CHECKBOX_STATE_EVENT_UNSELECTED); + } +} + +void UICheckBox::addSelectedStateEvent(Object *target, SEL_SelectedStateEvent selector) +{ + m_pSelectedStateEventListener = target; + m_pfnSelectedStateEventSelector = selector; +} + +void UICheckBox::setFlipX(bool flipX) +{ + m_pBackGroundBoxRenderer->setFlippedX(flipX); + m_pBackGroundSelectedBoxRenderer->setFlippedX(flipX); + m_pFrontCrossRenderer->setFlippedX(flipX); + m_pBackGroundBoxDisabledRenderer->setFlippedX(flipX); + m_pFrontCrossDisabledRenderer->setFlippedX(flipX); +} + +void UICheckBox::setFlipY(bool flipY) +{ + m_pBackGroundBoxRenderer->setFlippedY(flipY); + m_pBackGroundSelectedBoxRenderer->setFlippedY(flipY); + m_pFrontCrossRenderer->setFlippedY(flipY); + m_pBackGroundBoxDisabledRenderer->setFlippedY(flipY); + m_pFrontCrossDisabledRenderer->setFlippedY(flipY); +} + +bool UICheckBox::isFlipX() +{ + return m_pBackGroundBoxRenderer->isFlippedX(); +} + +bool UICheckBox::isFlipY() +{ + return m_pBackGroundBoxRenderer->isFlippedY(); +} + +void UICheckBox::setAnchorPoint(const Point &pt) +{ + UIWidget::setAnchorPoint(pt); + m_pBackGroundBoxRenderer->setAnchorPoint(pt); + m_pBackGroundSelectedBoxRenderer->setAnchorPoint(pt); + m_pBackGroundBoxDisabledRenderer->setAnchorPoint(pt); + m_pFrontCrossRenderer->setAnchorPoint(pt); + m_pFrontCrossDisabledRenderer->setAnchorPoint(pt); +} + +void UICheckBox::onSizeChanged() +{ + backGroundTextureScaleChangedWithSize(); + backGroundSelectedTextureScaleChangedWithSize(); + frontCrossTextureScaleChangedWithSize(); + backGroundDisabledTextureScaleChangedWithSize(); + frontCrossDisabledTextureScaleChangedWithSize(); +} + +const Size& UICheckBox::getContentSize() const +{ + return m_pBackGroundBoxRenderer->getContentSize(); +} + +Node* UICheckBox::getVirtualRenderer() +{ + return m_pBackGroundBoxRenderer; +} + +void UICheckBox::backGroundTextureScaleChangedWithSize() +{ + if (m_bIgnoreSize) + { + m_pBackGroundBoxRenderer->setScale(1.0f); + m_size = m_pBackGroundBoxRenderer->getContentSize(); + } + else + { + Size textureSize = m_pBackGroundBoxRenderer->getContentSize(); + if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) + { + m_pBackGroundBoxRenderer->setScale(1.0f); + return; + } + float scaleX = m_size.width / textureSize.width; + float scaleY = m_size.height / textureSize.height; + m_pBackGroundBoxRenderer->setScaleX(scaleX); + m_pBackGroundBoxRenderer->setScaleY(scaleY); + } +} + +void UICheckBox::backGroundSelectedTextureScaleChangedWithSize() +{ + if (m_bIgnoreSize) + { + m_pBackGroundSelectedBoxRenderer->setScale(1.0f); + } + else + { + Size textureSize = m_pBackGroundSelectedBoxRenderer->getContentSize(); + if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) + { + m_pBackGroundSelectedBoxRenderer->setScale(1.0f); + return; + } + float scaleX = m_size.width / textureSize.width; + float scaleY = m_size.height / textureSize.height; + m_pBackGroundSelectedBoxRenderer->setScaleX(scaleX); + m_pBackGroundSelectedBoxRenderer->setScaleY(scaleY); + } +} + +void UICheckBox::frontCrossTextureScaleChangedWithSize() +{ + if (m_bIgnoreSize) + { + m_pFrontCrossRenderer->setScale(1.0f); + } + else + { + Size textureSize = m_pFrontCrossRenderer->getContentSize(); + if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) + { + m_pFrontCrossRenderer->setScale(1.0f); + return; + } + float scaleX = m_size.width / textureSize.width; + float scaleY = m_size.height / textureSize.height; + m_pFrontCrossRenderer->setScaleX(scaleX); + m_pFrontCrossRenderer->setScaleY(scaleY); + } +} + +void UICheckBox::backGroundDisabledTextureScaleChangedWithSize() +{ + if (m_bIgnoreSize) + { + m_pBackGroundBoxDisabledRenderer->setScale(1.0f); + } + else + { + Size textureSize = m_pBackGroundBoxDisabledRenderer->getContentSize(); + if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) + { + m_pBackGroundBoxDisabledRenderer->setScale(1.0f); + return; + } + float scaleX = m_size.width / textureSize.width; + float scaleY = m_size.height / textureSize.height; + m_pBackGroundBoxDisabledRenderer->setScaleX(scaleX); + m_pBackGroundBoxDisabledRenderer->setScaleY(scaleY); + } +} + +void UICheckBox::frontCrossDisabledTextureScaleChangedWithSize() +{ + if (m_bIgnoreSize) + { + m_pFrontCrossDisabledRenderer->setScale(1.0f); + } + else + { + Size textureSize = m_pFrontCrossDisabledRenderer->getContentSize(); + if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) + { + m_pFrontCrossDisabledRenderer->setScale(1.0f); + return; + } + float scaleX = m_size.width / textureSize.width; + float scaleY = m_size.height / textureSize.height; + m_pFrontCrossDisabledRenderer->setScaleX(scaleX); + m_pFrontCrossDisabledRenderer->setScaleY(scaleY); + } +} + +NS_CC_EXT_END \ No newline at end of file diff --git a/extensions/CocoStudio/GUI/UIWidgets/UICheckBox.h b/extensions/CocoStudio/GUI/UIWidgets/UICheckBox.h new file mode 100644 index 0000000000..c002ad280f --- /dev/null +++ b/extensions/CocoStudio/GUI/UIWidgets/UICheckBox.h @@ -0,0 +1,194 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __UICHECKBOX_H__ +#define __UICHECKBOX_H__ + +#include "../BaseClasses/UIWidget.h" + +NS_CC_EXT_BEGIN + +typedef enum +{ + CHECKBOX_STATE_EVENT_SELECTED, + CHECKBOX_STATE_EVENT_UNSELECTED +}CheckBoxEventType; + +typedef void (CCObject::*SEL_SelectedStateEvent)(Object*,CheckBoxEventType); +#define checkboxselectedeventselector(_SELECTOR) (cocos2d::extension::SEL_SelectedStateEvent)(&_SELECTOR) + +class UICheckBox : public UIWidget +{ +public: + /** + * Default constructor + */ + UICheckBox(); + + /** + * Default destructor + */ + virtual ~UICheckBox(); + + /** + * Allocates and initializes. + */ + static UICheckBox* create(); + + /** + * Load textures for checkbox. + * + * @param backGround backGround texture. + * + * @param backGroundSelected backGround selected state texture. + * + * @param cross cross texture. + * + * @param frontCrossDisabled cross dark state texture. + * + * @param texType @see UI_TEX_TYPE_LOCAL + */ + void loadTextures(const char* backGround,const char* backGroundSelected,const char* cross,const char* backGroundDisabled,const char* frontCrossDisabled,TextureResType texType = UI_TEX_TYPE_LOCAL); + + /** + * Load backGround texture for checkbox. + * + * @param backGround backGround texture. + * + * @param texType @see UI_TEX_TYPE_LOCAL + */ + void loadTextureBackGround(const char* backGround,TextureResType type = UI_TEX_TYPE_LOCAL); + + /** + * Load backGroundSelected texture for checkbox. + * + * @param backGroundSelected backGround selected state texture. + * + * @param texType @see UI_TEX_TYPE_LOCAL + */ + void loadTextureBackGroundSelected(const char* backGroundSelected,TextureResType texType = UI_TEX_TYPE_LOCAL); + + /** + * Load cross texture for checkbox. + * + * @param cross cross texture. + * + * @param texType @see UI_TEX_TYPE_LOCAL + */ + void loadTextureFrontCross(const char* cross,TextureResType texType = UI_TEX_TYPE_LOCAL); + + /** + * Load backGroundDisabled texture for checkbox. + * + * @param backGroundDisabled backGroundDisabled texture. + * + * @param texType @see UI_TEX_TYPE_LOCAL + */ + void loadTextureBackGroundDisabled(const char* backGroundDisabled,TextureResType texType = UI_TEX_TYPE_LOCAL); + + /** + * Load frontCrossDisabled texture for checkbox. + * + * @param frontCrossDisabled frontCrossDisabled texture. + * + * @param texType @see UI_TEX_TYPE_LOCAL + */ + void loadTextureFrontCrossDisabled(const char* frontCrossDisabled,TextureResType texType = UI_TEX_TYPE_LOCAL); + + /** + * Sets selcted state for checkbox. + * + * @param selected true that checkbox is selected, false otherwise. + */ + void setSelectedState(bool selected); + + /** + * Gets selcted state of checkbox. + * + * @return selected true that checkbox is selected, false otherwise. + */ + bool getSelectedState(); + + //override "setAnchorPoint" method of widget. + virtual void setAnchorPoint(const Point &pt); + + //add a call back function would called when checkbox is selected or unselected. + void addSelectedStateEvent(Object* target,SEL_SelectedStateEvent selector); + + //override "setFlipX" method of widget. + virtual void setFlipX(bool flipX); + + //override "setFlipY" method of widget. + virtual void setFlipY(bool flipY); + + //override "isFlipX" method of widget. + virtual bool isFlipX(); + + //override "isFlipY" method of widget. + virtual bool isFlipY(); + + //override "onTouchEnded" method of widget. + virtual void onTouchEnded(const Point &touchPoint); + + //override "getContentSize" method of widget. + virtual const Size& getContentSize() const; + + //override "getVirtualRenderer" method of widget. + virtual Node* getVirtualRenderer(); + +protected: + virtual bool init(); + virtual void initRenderer(); + virtual void onPressStateChangedToNormal(); + virtual void onPressStateChangedToPressed(); + virtual void onPressStateChangedToDisabled(); + void selectedEvent(); + void unSelectedEvent(); + virtual void onSizeChanged(); + void backGroundTextureScaleChangedWithSize(); + void backGroundSelectedTextureScaleChangedWithSize(); + void frontCrossTextureScaleChangedWithSize(); + void backGroundDisabledTextureScaleChangedWithSize(); + void frontCrossDisabledTextureScaleChangedWithSize(); +protected: + Sprite* m_pBackGroundBoxRenderer; + Sprite* m_pBackGroundSelectedBoxRenderer; + Sprite* m_pFrontCrossRenderer; + Sprite* m_pBackGroundBoxDisabledRenderer; + Sprite* m_pFrontCrossDisabledRenderer; + bool m_bIsSelected; + + Object* m_pSelectedStateEventListener; + SEL_SelectedStateEvent m_pfnSelectedStateEventSelector; + + TextureResType m_eBackGroundTexType; + TextureResType m_eBackGroundSelectedTexType; + TextureResType m_eFrontCrossTexType; + TextureResType m_eBackGroundDisabledTexType; + TextureResType m_eFrontCrossDisabledTexType; +}; + +NS_CC_EXT_END + +#endif /* defined(__CocoGUI__UICheckBox__) */ diff --git a/extensions/CocoStudio/GUI/UIWidgets/UIImageView.cpp b/extensions/CocoStudio/GUI/UIWidgets/UIImageView.cpp new file mode 100644 index 0000000000..20376f3ad8 --- /dev/null +++ b/extensions/CocoStudio/GUI/UIWidgets/UIImageView.cpp @@ -0,0 +1,372 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "UIImageView.h" +#include "../../../GUI/CCControlExtension/CCScale9Sprite.h" + +NS_CC_EXT_BEGIN + +#define DYNAMIC_CAST_CCSPRITE dynamic_cast(m_pImageRenderer) +#define DYNAMIC_CAST_SCALE9SPRITE dynamic_cast(m_pImageRenderer) + +UIImageView::UIImageView(): +m_nViewType(1), +m_nClickCount(0), +m_fClickTimeInterval(0.0), +m_bStartCheckDoubleClick(false), +m_touchRelease(false), +m_bDoubleClickEnabled(false), +m_bScale9Enabled(false), +m_bPrevIgnoreSize(true), +m_capInsets(Rect::ZERO), +m_pImageRenderer(NULL), +m_strTextureFile(""), +m_eImageTexType(UI_TEX_TYPE_LOCAL), +m_imageTextureSize(m_size) +{ + +} + +UIImageView::~UIImageView() +{ + +} + +UIImageView* UIImageView::create() +{ + UIImageView* widget = new UIImageView(); + if (widget && widget->init()) + { + widget->autorelease(); + return widget; + } + CC_SAFE_DELETE(widget); + return NULL; +} + +void UIImageView::initRenderer() +{ + UIWidget::initRenderer(); + m_pImageRenderer = CCSprite::create(); + m_pRenderer->addChild(m_pImageRenderer); +} + +void UIImageView::loadTexture(const char *fileName, TextureResType texType) +{ + if (!fileName || strcmp(fileName, "") == 0) + { + return; + } + m_strTextureFile = fileName; + m_eImageTexType = texType; + switch (m_eImageTexType) + { + case UI_TEX_TYPE_LOCAL: + if (m_bScale9Enabled) + { + DYNAMIC_CAST_SCALE9SPRITE->initWithFile(fileName); + DYNAMIC_CAST_SCALE9SPRITE->setColor(getColor()); + DYNAMIC_CAST_SCALE9SPRITE->setOpacity(getOpacity()); + } + else + { + DYNAMIC_CAST_CCSPRITE->initWithFile(fileName); + DYNAMIC_CAST_CCSPRITE->setColor(getColor()); + DYNAMIC_CAST_CCSPRITE->setOpacity(getOpacity()); + } + break; + case UI_TEX_TYPE_PLIST: + if (m_bScale9Enabled) + { + DYNAMIC_CAST_SCALE9SPRITE->initWithSpriteFrameName(fileName); + DYNAMIC_CAST_SCALE9SPRITE->setColor(getColor()); + DYNAMIC_CAST_SCALE9SPRITE->setOpacity(getOpacity()); + } + else + { + DYNAMIC_CAST_CCSPRITE->initWithSpriteFrameName(fileName); + DYNAMIC_CAST_CCSPRITE->setColor(getColor()); + DYNAMIC_CAST_CCSPRITE->setOpacity(getOpacity()); + } + break; + default: + break; + } + m_imageTextureSize = m_pImageRenderer->getContentSize(); + updateAnchorPoint(); + imageTextureScaleChangedWithSize(); +} + +void UIImageView::setTextureRect(const Rect &rect) +{ + if (m_bScale9Enabled) + { + } + else + { + DYNAMIC_CAST_CCSPRITE->setTextureRect(rect); + } +} + +bool UIImageView::onTouchBegan(const Point &touchPoint) +{ + setFocused(true); + m_touchStartPos.x = touchPoint.x; + m_touchStartPos.y = touchPoint.y; + m_pWidgetParent->checkChildInfo(0,this,touchPoint); + pushDownEvent(); + + if (m_bDoubleClickEnabled) + { + m_fClickTimeInterval = 0; + m_bStartCheckDoubleClick = true; + m_nClickCount++; + m_touchRelease = false; + } + return m_bTouchPassedEnabled; +} + +void UIImageView::onTouchEnded(const Point &touchPoint) +{ + if (m_bDoubleClickEnabled) + { + if (m_nClickCount >= 2) + { + doubleClickEvent(); + m_nClickCount = 0; + m_bStartCheckDoubleClick = false; + } + else + { + m_touchRelease = true; + } + } + else + { + UIWidget::onTouchEnded(touchPoint); + } +} + +void UIImageView::doubleClickEvent() +{ + +} + +void UIImageView::checkDoubleClick(float dt) +{ + if (m_bStartCheckDoubleClick) + { + m_fClickTimeInterval += dt; + if (m_fClickTimeInterval >= 200 && m_nClickCount > 0) + { + m_fClickTimeInterval = 0; + m_nClickCount--; + m_bStartCheckDoubleClick = false; + } + } + else + { + if (m_nClickCount <= 1) + { + if (m_touchRelease) + { + releaseUpEvent(); + m_fClickTimeInterval = 0; + m_nClickCount = 0; + m_touchRelease = false; + } + } + } +} + +void UIImageView::setDoubleClickEnabled(bool able) +{ + if (able == m_bDoubleClickEnabled) + { + return; + } + m_bDoubleClickEnabled = able; + if (able) + { +// COCOUISYSTEM->getUIInputManager()->addCheckedDoubleClickWidget(this); + } + else + { + + } +} + +void UIImageView::setFlipX(bool flipX) +{ + if (m_bScale9Enabled) + { + } + else + { + DYNAMIC_CAST_CCSPRITE->setFlippedX(flipX); + } +} + +void UIImageView::setFlipY(bool flipY) +{ + if (m_bScale9Enabled) + { + } + else + { + DYNAMIC_CAST_CCSPRITE->setFlippedY(flipY); + } +} + +bool UIImageView::isFlipX() +{ + if (m_bScale9Enabled) + { + return false; + } + else + { + return DYNAMIC_CAST_CCSPRITE->isFlippedX(); + } +} + +bool UIImageView::isFlipY() +{ + if (m_bScale9Enabled) + { + return false; + } + else + { + return DYNAMIC_CAST_CCSPRITE->isFlippedY(); + } +} + +void UIImageView::setScale9Enabled(bool able) +{ + if (m_bScale9Enabled == able) + { + return; + } + + + m_bScale9Enabled = able; + m_pRenderer->removeChild(m_pImageRenderer, true); + m_pImageRenderer = NULL; + if (m_bScale9Enabled) + { + m_pImageRenderer = extension::Scale9Sprite::create(); + } + else + { + m_pImageRenderer = CCSprite::create(); + } + loadTexture(m_strTextureFile.c_str(),m_eImageTexType); + m_pRenderer->addChild(m_pImageRenderer); + if (m_bScale9Enabled) + { + bool ignoreBefore = m_bIgnoreSize; + ignoreContentAdaptWithSize(false); + m_bPrevIgnoreSize = ignoreBefore; + } + else + { + ignoreContentAdaptWithSize(m_bPrevIgnoreSize); + } + setCapInsets(m_capInsets); +} + +void UIImageView::ignoreContentAdaptWithSize(bool ignore) +{ + if (!m_bScale9Enabled || (m_bScale9Enabled && !ignore)) + { + UIWidget::ignoreContentAdaptWithSize(ignore); + m_bPrevIgnoreSize = ignore; + } +} + +void UIImageView::setCapInsets(const Rect &capInsets) +{ + m_capInsets = capInsets; + if (!m_bScale9Enabled) + { + return; + } + DYNAMIC_CAST_SCALE9SPRITE->setCapInsets(capInsets); +} + +void UIImageView::setAnchorPoint(const Point &pt) +{ + UIWidget::setAnchorPoint(pt); + m_pImageRenderer->setAnchorPoint(pt); +} + +void UIImageView::onSizeChanged() +{ + imageTextureScaleChangedWithSize(); +} + +const Size& UIImageView::getContentSize() const +{ + return m_imageTextureSize; +} + +Node* UIImageView::getVirtualRenderer() +{ + return m_pImageRenderer; +} + +void UIImageView::imageTextureScaleChangedWithSize() +{ + if (m_bIgnoreSize) + { + if (!m_bScale9Enabled) + { + m_pImageRenderer->setScale(1.0f); + m_size = m_imageTextureSize; + } + } + else + { + if (m_bScale9Enabled) + { + dynamic_cast(m_pImageRenderer)->setPreferredSize(m_size); + } + else + { + Size textureSize = m_pImageRenderer->getContentSize(); + if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) + { + m_pImageRenderer->setScale(1.0f); + return; + } + float scaleX = m_size.width / textureSize.width; + float scaleY = m_size.height / textureSize.height; + m_pImageRenderer->setScaleX(scaleX); + m_pImageRenderer->setScaleY(scaleY); + } + } +} + +NS_CC_EXT_END \ No newline at end of file diff --git a/extensions/CocoStudio/GUI/UIWidgets/UIImageView.h b/extensions/CocoStudio/GUI/UIWidgets/UIImageView.h new file mode 100644 index 0000000000..59501bf889 --- /dev/null +++ b/extensions/CocoStudio/GUI/UIWidgets/UIImageView.h @@ -0,0 +1,132 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __UIIMAGEVIEW_H__ +#define __UIIMAGEVIEW_H__ + +#include "../BaseClasses/UIWidget.h" + +NS_CC_EXT_BEGIN + +class UIImageView : public UIWidget +{ +public: + /** + * Default constructor + */ + UIImageView(); + + /** + * Default destructor + */ + virtual ~UIImageView(); + + /** + * Allocates and initializes. + */ + static UIImageView* create(); + + /** + * Load texture for imageview. + * + * @param fileName file name of texture. + * + * @param texType @see UI_TEX_TYPE_LOCAL + */ + void loadTexture(const char* fileName,TextureResType texType = UI_TEX_TYPE_LOCAL); + + /** + * Updates the texture rect of the UIImageView in points. + * It will call setTextureRect:rotated:untrimmedSize with rotated = NO, and utrimmedSize = rect.size. + */ + void setTextureRect(const Rect& rect); + + /** + * Sets if imageview is using scale9 renderer. + * + * @param true that using scale9 renderer, false otherwise. + */ + void setScale9Enabled(bool able); + + /** + * Sets capinsets for imageview, if imageview is using scale9 renderer. + * + * @param capInsets capinsets for imageview + */ + void setCapInsets(const Rect &capInsets); + + //override "setFlipX" method of widget. + virtual void setFlipX(bool flipX); + + //override "setFlipY" method of widget. + virtual void setFlipY(bool flipY); + + //override "isFlipX" method of widget. + virtual bool isFlipX(); + + //override "isFlipY" method of widget. + virtual bool isFlipY(); + + //override "setAnchorPoint" method of widget. + virtual void setAnchorPoint(const Point &pt); + + //override "onTouchBegan" method of widget. + virtual bool onTouchBegan(const Point &touchPoint); + + //override "onTouchEnded" method of widget. + virtual void onTouchEnded(const Point &touchPoint); + + //override "ignoreContentAdaptWithSize" method of widget. + virtual void ignoreContentAdaptWithSize(bool ignore); + + + + void setDoubleClickEnabled(bool able); + void doubleClickEvent(); + void checkDoubleClick(float dt); + virtual const Size& getContentSize() const; + virtual Node* getVirtualRenderer(); +protected: + virtual void initRenderer(); + virtual void onSizeChanged(); + void imageTextureScaleChangedWithSize(); +protected: + int m_nViewType; + int m_nClickCount; + float m_fClickTimeInterval; + bool m_bStartCheckDoubleClick; + bool m_touchRelease; + bool m_bDoubleClickEnabled; + bool m_bScale9Enabled; + bool m_bPrevIgnoreSize; + Rect m_capInsets; + Node* m_pImageRenderer; + std::string m_strTextureFile; + TextureResType m_eImageTexType; + Size m_imageTextureSize; +}; + +NS_CC_EXT_END + +#endif /* defined(__CocoGUI__UIImageView__) */ diff --git a/extensions/CocoStudio/GUI/UIWidgets/UILabel.cpp b/extensions/CocoStudio/GUI/UIWidgets/UILabel.cpp new file mode 100644 index 0000000000..6e18e6bae8 --- /dev/null +++ b/extensions/CocoStudio/GUI/UIWidgets/UILabel.cpp @@ -0,0 +1,227 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "UILabel.h" + +NS_CC_EXT_BEGIN + +UILabel::UILabel(): +m_bTouchScaleChangeEnabled(false), +m_fNormalScaleValue(1.0f), +m_sFontName("Thonburi"), +m_nFontSize(10), +m_fOnSelectedScaleOffset(0.5), +m_pLabelRenderer(NULL) +{ +} + +UILabel::~UILabel() +{ + +} + +UILabel* UILabel::create() +{ + UILabel* widget = new UILabel(); + if (widget && widget->init()) + { + widget->autorelease(); + return widget; + } + CC_SAFE_DELETE(widget); + return NULL; +} + +bool UILabel::init() +{ + if (UIWidget::init()) + { + return true; + } + return false; +} + +void UILabel::initRenderer() +{ + UIWidget::initRenderer(); + m_pLabelRenderer = CCLabelTTF::create(); + m_pRenderer->addChild(m_pLabelRenderer); +} + +void UILabel::setText(const char* text) +{ + if (!text) + { + return; + } + std::string strText(text); + m_pLabelRenderer->setString(strText.c_str()); + labelScaleChangedWithSize(); +} + +const char* UILabel::getStringValue() +{ + return m_pLabelRenderer->getString(); +} + +int UILabel::getStringLength() +{ + const char* str = m_pLabelRenderer->getString(); + return strlen(str); +} + +void UILabel::setFontSize(int size) +{ + m_pLabelRenderer->setFontSize(size); + labelScaleChangedWithSize(); +} + +void UILabel::setFontName(const char* name) +{ + m_pLabelRenderer->setFontName(name); + labelScaleChangedWithSize(); +} + +void UILabel::setTextAreaSize(const Size &size) +{ + m_pLabelRenderer->setDimensions(size); + labelScaleChangedWithSize(); +} + +void UILabel::setTextHorizontalAlignment(TextHAlignment alignment) +{ + m_pLabelRenderer->setHorizontalAlignment(alignment); + labelScaleChangedWithSize(); +} + +void UILabel::setTextVerticalAlignment(TextVAlignment alignment) +{ + m_pLabelRenderer->setVerticalAlignment(alignment); + labelScaleChangedWithSize(); +} + +void UILabel::setTouchScaleChangeEnabled(bool enable) +{ + m_bTouchScaleChangeEnabled = enable; + m_fNormalScaleValue = getScale(); +} + +bool UILabel::isTouchScaleChangeEnabled() +{ + return m_bTouchScaleChangeEnabled; +} + +void UILabel::onPressStateChangedToNormal() +{ + if (!m_bTouchScaleChangeEnabled) + { + return; + } + clickScale(m_fNormalScaleValue); +} + +void UILabel::onPressStateChangedToPressed() +{ + if (!m_bTouchScaleChangeEnabled) + { + return; + } + clickScale(m_fNormalScaleValue + m_fOnSelectedScaleOffset); +} + +void UILabel::onPressStateChangedToDisabled() +{ + +} + +void UILabel::clickScale(float scale) +{ + m_pRenderer->setScale(scale); +} + +void UILabel::setFlipX(bool flipX) +{ + m_pLabelRenderer->setFlippedX(flipX); +} + +void UILabel::setFlipY(bool flipY) +{ + m_pLabelRenderer->setFlippedY(flipY); +} + +bool UILabel::isFlipX() +{ + return m_pLabelRenderer->isFlippedX(); +} + +bool UILabel::isFlipY() +{ + return m_pLabelRenderer->isFlippedY(); +} + +void UILabel::setAnchorPoint(const Point &pt) +{ + UIWidget::setAnchorPoint(pt); + m_pLabelRenderer->setAnchorPoint(pt); +} + +void UILabel::onSizeChanged() +{ + labelScaleChangedWithSize(); +} + +const Size& UILabel::getContentSize() const +{ + return m_pLabelRenderer->getContentSize(); +} + +Node* UILabel::getVirtualRenderer() +{ + return m_pLabelRenderer; +} + +void UILabel::labelScaleChangedWithSize() +{ + if (m_bIgnoreSize) + { + m_pLabelRenderer->setScale(1.0f); + m_size = m_pLabelRenderer->getContentSize(); + } + else + { + Size textureSize = m_pLabelRenderer->getContentSize(); + if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) + { + m_pLabelRenderer->setScale(1.0f); + return; + } + float scaleX = m_size.width / textureSize.width; + float scaleY = m_size.height / textureSize.height; + m_pLabelRenderer->setScaleX(scaleX); + m_pLabelRenderer->setScaleY(scaleY); + } + +} + +NS_CC_EXT_END \ No newline at end of file diff --git a/extensions/CocoStudio/GUI/UIWidgets/UILabel.h b/extensions/CocoStudio/GUI/UIWidgets/UILabel.h new file mode 100644 index 0000000000..ce816f7344 --- /dev/null +++ b/extensions/CocoStudio/GUI/UIWidgets/UILabel.h @@ -0,0 +1,147 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __UILABEL_H__ +#define __UILABEL_H__ + +#include "../BaseClasses/UIWidget.h" + +NS_CC_EXT_BEGIN + +class UILabel : public UIWidget +{ +public: + /** + * Default constructor + */ + UILabel(); + + /** + * Default destructor + */ + virtual ~UILabel(); + + /** + * Allocates and initializes. + */ + static UILabel* create(); + + /** + * Changes the string value of label. + * + * @param text string value. + */ + void setText(const char* text); + + /** + * Gets the string value of label. + * + * @return text string value. + */ + const char* getStringValue(); + + /** + * Gets the string length of label. + * + * @return string length. + */ + int getStringLength(); + + /** + * Sets the font size of label. + * + * @param font size. + */ + void setFontSize(int size); + + /** + * Sets the font name of label. + * + * @param font name. + */ + void setFontName(const char* name); + + /** + * Sets the touch scale enabled of label. + * + * @param touch scale enabled of label. + */ + void setTouchScaleChangeEnabled(bool enabled); + + /** + * Gets the touch scale enabled of label. + * + * @return touch scale enabled of label. + */ + bool isTouchScaleChangeEnabled(); + + //override "setFlipX" method of widget. + virtual void setFlipX(bool flipX); + + //override "setFlipY" method of widget. + virtual void setFlipY(bool flipY); + + //override "isFlipX" method of widget. + virtual bool isFlipX(); + + //override "isFlipY" method of widget. + virtual bool isFlipY(); + + //override "setAnchorPoint" method of widget. + virtual void setAnchorPoint(const Point &pt); + + //override "getContentSize" method of widget. + virtual const Size& getContentSize() const; + + //override "getVirtualRenderer" method of widget. + virtual Node* getVirtualRenderer(); + + void setTextAreaSize(const Size &size); + void setTextHorizontalAlignment(TextHAlignment alignment); + void setTextVerticalAlignment(TextVAlignment alignment); + + + void setTouchScaleChangeAble(bool able){setTouchScaleChangeEnabled(able);}; + bool getTouchScaleChangeAble(){return isTouchScaleChangeEnabled();}; +protected: + virtual bool init(); + virtual void initRenderer(); + virtual void onPressStateChangedToNormal(); + virtual void onPressStateChangedToPressed(); + virtual void onPressStateChangedToDisabled(); + virtual void onSizeChanged(); + void clickScale(float scale); + void labelScaleChangedWithSize(); +protected: + bool m_bTouchScaleChangeEnabled; + float m_fNormalScaleValue; + std::string m_sFontName; + int m_nFontSize; + float m_fOnSelectedScaleOffset; + LabelTTF* m_pLabelRenderer; +}; + +NS_CC_EXT_END + +#endif /* defined(__CocoGUI__Label__) */ diff --git a/extensions/CocoStudio/GUI/UIWidgets/UILabelAtlas.cpp b/extensions/CocoStudio/GUI/UIWidgets/UILabelAtlas.cpp new file mode 100644 index 0000000000..24013b7668 --- /dev/null +++ b/extensions/CocoStudio/GUI/UIWidgets/UILabelAtlas.cpp @@ -0,0 +1,170 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "UILabelAtlas.h" + +NS_CC_EXT_BEGIN + +UICCLabelAtlas::UICCLabelAtlas() +{ + +} + +UICCLabelAtlas::~UICCLabelAtlas() +{ + +} + +UICCLabelAtlas* UICCLabelAtlas::create() +{ + UICCLabelAtlas *pRet = new UICCLabelAtlas(); + if(pRet) + { + pRet->autorelease(); + return pRet; + } + CC_SAFE_DELETE(pRet); + + return NULL; +} + +void UICCLabelAtlas::setProperty(const char *string, const char *charMapFile, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap) +{ + initWithString(string, charMapFile, itemWidth, itemHeight, startCharMap); +} + +void UICCLabelAtlas::setProperty(const char *string, Texture2D *texture, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap) +{ + initWithString(string, texture, itemWidth, itemHeight, startCharMap); +} + +void UICCLabelAtlas::draw() +{ + if (!_textureAtlas) + { + return; + } + + CCAtlasNode::draw(); +} + +void UICCLabelAtlas::updateDisplayedOpacity(GLubyte opacity) +{ + CCAtlasNode::setOpacity(opacity); +} + + + + +UILabelAtlas::UILabelAtlas(): +m_pLaberAtlasRenderer(NULL) +{ +} + +UILabelAtlas::~UILabelAtlas() +{ + +} + +UILabelAtlas* UILabelAtlas::create() +{ + UILabelAtlas* widget = new UILabelAtlas(); + if (widget && widget->init()) + { + widget->autorelease(); + return widget; + } + CC_SAFE_DELETE(widget); + return NULL; +} + +void UILabelAtlas::initRenderer() +{ + UIWidget::initRenderer(); + m_pLaberAtlasRenderer = UICCLabelAtlas::create(); + m_pRenderer->addChild(m_pLaberAtlasRenderer); +} + +void UILabelAtlas::setProperty(const char *stringValue, const char *charMapFile, int itemWidth, int itemHeight, const char *startCharMap,bool useSpriteFrame) +{ + m_pLaberAtlasRenderer->setProperty(stringValue, charMapFile, itemWidth, itemHeight, (int)(startCharMap[0])); + updateAnchorPoint(); + labelAtlasScaleChangedWithSize(); +} + +void UILabelAtlas::setStringValue(const char *value) +{ + m_pLaberAtlasRenderer->setString(value); + labelAtlasScaleChangedWithSize(); +} + +const char* UILabelAtlas::getStringValue() +{ + return m_pLaberAtlasRenderer->getString(); +} + +void UILabelAtlas::setAnchorPoint(const Point &pt) +{ + UIWidget::setAnchorPoint(pt); + m_pLaberAtlasRenderer->setAnchorPoint(Point(pt.x, pt.y)); +} + +void UILabelAtlas::onSizeChanged() +{ + labelAtlasScaleChangedWithSize(); +} + +const Size& UILabelAtlas::getContentSize() const +{ + return m_pLaberAtlasRenderer->getContentSize(); +} + +Node* UILabelAtlas::getVirtualRenderer() +{ + return m_pLaberAtlasRenderer; +} + +void UILabelAtlas::labelAtlasScaleChangedWithSize() +{ + if (m_bIgnoreSize) + { + m_pLaberAtlasRenderer->setScale(1.0f); + m_size = m_pLaberAtlasRenderer->getContentSize(); + } + else + { + Size textureSize = m_pLaberAtlasRenderer->getContentSize(); + if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) + { + m_pLaberAtlasRenderer->setScale(1.0f); + return; + } + float scaleX = m_size.width / textureSize.width; + float scaleY = m_size.height / textureSize.height; + m_pLaberAtlasRenderer->setScaleX(scaleX); + m_pLaberAtlasRenderer->setScaleY(scaleY); + } +} + +NS_CC_EXT_END \ No newline at end of file diff --git a/extensions/CocoStudio/GUI/UIWidgets/UILabelAtlas.h b/extensions/CocoStudio/GUI/UIWidgets/UILabelAtlas.h new file mode 100644 index 0000000000..a9ee2f5c89 --- /dev/null +++ b/extensions/CocoStudio/GUI/UIWidgets/UILabelAtlas.h @@ -0,0 +1,100 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __UILABELATLAS_H__ +#define __UILABELATLAS_H__ + +#include "../BaseClasses/UIWidget.h" + +NS_CC_EXT_BEGIN + +class UICCLabelAtlas : public LabelAtlas +{ +public: + /** + * Default constructor + */ + UICCLabelAtlas(); + + /** + * Default destructor + */ + virtual ~UICCLabelAtlas(); + + /** + * Allocates and initializes. + */ + static UICCLabelAtlas* create(); + void setProperty(const char *string, const char *charMapFile, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap); + void setProperty(const char *string, Texture2D *texture, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap); + virtual void updateDisplayedOpacity(GLubyte opacity); + virtual void draw(void); +}; + +class UILabelAtlas : public UIWidget +{ +public: + /** + * Default constructor + */ + UILabelAtlas(); + + /** + * Default destructor + */ + virtual ~UILabelAtlas(); + + /** + * Allocates and initializes. + */ + static UILabelAtlas* create(); + + /** initializes the UILabelAtlas with a string, a char map file(the atlas), the width and height of each element and the starting char of the atlas */ + void setProperty(const char* stringValue,const char* charMapFile, int itemWidth, int itemHeight, const char* startCharMap,bool useSpriteFrame = false); + + //set string value for labelatlas. + void setStringValue(const char* value); + + //get string value for labelatlas. + const char* getStringValue(); + + //override "setAnchorPoint" method of widget. + virtual void setAnchorPoint(const Point &pt); + + //override "getContentSize" method of widget. + virtual const Size& getContentSize() const; + + //override "getVirtualRenderer" method of widget. + virtual Node* getVirtualRenderer(); +protected: + virtual void initRenderer(); + virtual void onSizeChanged(); + void labelAtlasScaleChangedWithSize(); +protected: + UICCLabelAtlas* m_pLaberAtlasRenderer; +}; + +NS_CC_EXT_END + +#endif /* defined(__CocoGUI__UILabelAtlas__) */ diff --git a/extensions/CocoStudio/GUI/UIWidgets/UILabelBMFont.cpp b/extensions/CocoStudio/GUI/UIWidgets/UILabelBMFont.cpp new file mode 100644 index 0000000000..a630f78698 --- /dev/null +++ b/extensions/CocoStudio/GUI/UIWidgets/UILabelBMFont.cpp @@ -0,0 +1,129 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "UILabelBMFont.h" + +NS_CC_EXT_BEGIN + +UILabelBMFont::UILabelBMFont(): +m_pLabelBMFontRenderer(NULL), +m_bFntFileHasInit(false) +{ +} + +UILabelBMFont::~UILabelBMFont() +{ + +} + +UILabelBMFont* UILabelBMFont::create() +{ + UILabelBMFont* widget = new UILabelBMFont(); + if (widget && widget->init()) + { + widget->autorelease(); + return widget; + } + CC_SAFE_DELETE(widget); + return NULL; +} + +void UILabelBMFont::initRenderer() +{ + UIWidget::initRenderer(); + m_pLabelBMFontRenderer = CCLabelBMFont::create(); + m_pRenderer->addChild(m_pLabelBMFontRenderer); +} + +void UILabelBMFont::setFntFile(const char *fileName) +{ + if (!fileName || std::strcmp(fileName, "") == 0) + { + return; + } + m_pLabelBMFontRenderer->initWithString("", fileName); + updateAnchorPoint(); + labelBMFontScaleChangedWithSize(); + m_bFntFileHasInit = true; +} + +void UILabelBMFont::setText(const char* value) +{ + if (!value || !m_bFntFileHasInit) + { + return; + } + m_pLabelBMFontRenderer->setString(value); + labelBMFontScaleChangedWithSize(); +} + +const char* UILabelBMFont::getStringValue() +{ + return m_pLabelBMFontRenderer->getString(); +} + +void UILabelBMFont::setAnchorPoint(const Point &pt) +{ + UIWidget::setAnchorPoint(pt); + m_pLabelBMFontRenderer->setAnchorPoint(pt); +} + +void UILabelBMFont::onSizeChanged() +{ + labelBMFontScaleChangedWithSize(); +} + +const Size& UILabelBMFont::getContentSize() const +{ + return m_pLabelBMFontRenderer->getContentSize(); +} + +Node* UILabelBMFont::getVirtualRenderer() +{ + return m_pLabelBMFontRenderer; +} + +void UILabelBMFont::labelBMFontScaleChangedWithSize() +{ + if (m_bIgnoreSize) + { + m_pLabelBMFontRenderer->setScale(1.0f); + m_size = m_pLabelBMFontRenderer->getContentSize(); + } + else + { + Size textureSize = m_pLabelBMFontRenderer->getContentSize(); + if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) + { + m_pLabelBMFontRenderer->setScale(1.0f); + return; + } + float scaleX = m_size.width / textureSize.width; + float scaleY = m_size.height / textureSize.height; + m_pLabelBMFontRenderer->setScaleX(scaleX); + m_pLabelBMFontRenderer->setScaleY(scaleY); + } +} + +NS_CC_EXT_END \ No newline at end of file diff --git a/extensions/CocoStudio/GUI/UIWidgets/UILabelBMFont.h b/extensions/CocoStudio/GUI/UIWidgets/UILabelBMFont.h new file mode 100644 index 0000000000..9be54e08c3 --- /dev/null +++ b/extensions/CocoStudio/GUI/UIWidgets/UILabelBMFont.h @@ -0,0 +1,72 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __UILABELBMFONT_H__ +#define __UILABELBMFONT_H__ + +#include "../BaseClasses/UIWidget.h" + +NS_CC_EXT_BEGIN + +class UILabelBMFont : public UIWidget +{ +public: + /** + * Default constructor + */ + UILabelBMFont(); + + /** + * Default destructor + */ + virtual ~UILabelBMFont(); + + /** + * Allocates and initializes. + */ + static UILabelBMFont* create(); + + /** init a bitmap font atlas with an initial string and the FNT file */ + void setFntFile(const char* fileName); + + /** set string value for labelbmfont*/ + void setText(const char* value); + + /** get string value for labelbmfont*/ + const char* getStringValue(); + virtual void setAnchorPoint(const Point &pt); + virtual const Size& getContentSize() const; + virtual Node* getVirtualRenderer(); +protected: + virtual void initRenderer(); + virtual void onSizeChanged(); + void labelBMFontScaleChangedWithSize(); +protected: + LabelBMFont* m_pLabelBMFontRenderer; + bool m_bFntFileHasInit; +}; + +NS_CC_EXT_END + +#endif /* defined(__UILabelBMFont__) */ diff --git a/extensions/CocoStudio/GUI/UIWidgets/UILoadingBar.cpp b/extensions/CocoStudio/GUI/UIWidgets/UILoadingBar.cpp new file mode 100644 index 0000000000..fe5ecc8e5d --- /dev/null +++ b/extensions/CocoStudio/GUI/UIWidgets/UILoadingBar.cpp @@ -0,0 +1,334 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "UILoadingBar.h" +#include "../../../GUI/CCControlExtension/CCScale9Sprite.h" + +NS_CC_EXT_BEGIN + +#define DYNAMIC_CAST_CCSPRITE dynamic_cast(m_pBarRenderer) + +UILoadingBar::UILoadingBar(): +m_nBarType(LoadingBarTypeLeft), +m_nPercent(100), +m_fTotalLength(0), +m_pBarRenderer(NULL), +m_eRenderBarTexType(UI_TEX_TYPE_LOCAL), +m_barRendererTextureSize(Size::ZERO), +m_bScale9Enabled(false), +m_bPrevIgnoreSize(true), +m_capInsets(Rect::ZERO), +m_strTextureFile("") +{ +} + +UILoadingBar::~UILoadingBar() +{ + +} + +UILoadingBar* UILoadingBar::create() +{ + UILoadingBar* widget = new UILoadingBar(); + if (widget && widget->init()) + { + widget->autorelease(); + return widget; + } + CC_SAFE_DELETE(widget); + return NULL; +} + +void UILoadingBar::initRenderer() +{ + UIWidget::initRenderer(); + m_pBarRenderer = CCSprite::create(); + m_pRenderer->addChild(m_pBarRenderer); + m_pBarRenderer->setAnchorPoint(Point(0.0f,0.5f)); +} + +void UILoadingBar::setDirection(LoadingBarType dir) +{ + if (m_nBarType == dir) + { + return; + } + m_nBarType = dir; + + switch (m_nBarType) + { + case LoadingBarTypeLeft: + m_pBarRenderer->setAnchorPoint(Point(0.0f,0.5f)); + m_pBarRenderer->setPosition(Point(-m_fTotalLength*0.5f,0.0f)); + if (!m_bScale9Enabled) + { + dynamic_cast(m_pBarRenderer)->setFlippedX(false); + } + break; + case LoadingBarTypeRight: + m_pBarRenderer->setAnchorPoint(Point(1.0f,0.5f)); + m_pBarRenderer->setPosition(Point(m_fTotalLength*0.5f,0.0f)); + if (!m_bScale9Enabled) + { + dynamic_cast(m_pBarRenderer)->setFlippedX(true); + } + break; + } +} + +int UILoadingBar::getDirection() +{ + return m_nBarType; +} + +void UILoadingBar::loadTexture(const char* texture,TextureResType texType) +{ + if (!texture || strcmp(texture, "") == 0) + { + return; + } + m_eRenderBarTexType = texType; + m_strTextureFile = texture; + switch (m_eRenderBarTexType) + { + case UI_TEX_TYPE_LOCAL: + if (m_bScale9Enabled) + { + dynamic_cast(m_pBarRenderer)->initWithFile(texture); + } + else + { + dynamic_cast(m_pBarRenderer)->initWithFile(texture); + } + break; + case UI_TEX_TYPE_PLIST: + if (m_bScale9Enabled) + { + dynamic_cast(m_pBarRenderer)->initWithSpriteFrameName(texture); + } + else + { + dynamic_cast(m_pBarRenderer)->initWithSpriteFrameName(texture); + } + break; + default: + break; + } + if (m_bScale9Enabled) + { + dynamic_cast(m_pBarRenderer)->setColor(getColor()); + dynamic_cast(m_pBarRenderer)->setOpacity(getOpacity()); + } + else + { + dynamic_cast(m_pBarRenderer)->setColor(getColor()); + dynamic_cast(m_pBarRenderer)->setOpacity(getOpacity()); + } + m_barRendererTextureSize.width = m_pBarRenderer->getContentSize().width; + m_barRendererTextureSize.height = m_pBarRenderer->getContentSize().height; + + switch (m_nBarType) + { + case LoadingBarTypeLeft: + m_pBarRenderer->setAnchorPoint(Point(0.0f,0.5f)); + if (!m_bScale9Enabled) + { + dynamic_cast(m_pBarRenderer)->setFlippedX(false); + } + break; + case LoadingBarTypeRight: + m_pBarRenderer->setAnchorPoint(Point(1.0f,0.5f)); + if (!m_bScale9Enabled) + { + dynamic_cast(m_pBarRenderer)->setFlippedX(true); + } + break; + } + barRendererScaleChangedWithSize(); +} + +void UILoadingBar::setScale9Enabled(bool enabled) +{ + if (m_bScale9Enabled == enabled) + { + return; + } + m_bScale9Enabled = enabled; + m_pRenderer->removeChild(m_pBarRenderer, true); + m_pBarRenderer = NULL; + if (m_bScale9Enabled) + { + m_pBarRenderer = Scale9Sprite::create(); + } + else + { + m_pBarRenderer = CCSprite::create(); + } + loadTexture(m_strTextureFile.c_str(),m_eRenderBarTexType); + m_pRenderer->addChild(m_pBarRenderer); + if (m_bScale9Enabled) + { + bool ignoreBefore = m_bIgnoreSize; + ignoreContentAdaptWithSize(false); + m_bPrevIgnoreSize = ignoreBefore; + } + else + { + ignoreContentAdaptWithSize(m_bPrevIgnoreSize); + } + setCapInsets(m_capInsets); +} + +void UILoadingBar::setCapInsets(const Rect &capInsets) +{ + m_capInsets = capInsets; + if (!m_bScale9Enabled) + { + return; + } + dynamic_cast(m_pBarRenderer)->setCapInsets(capInsets); +} + +void UILoadingBar::setPercent(int percent) +{ + if ( percent < 0 || percent > 100) + { + return; + } + if (m_fTotalLength <= 0) + { + return; + } + m_nPercent = percent; + float res = m_nPercent/100.0; + + int x = 0, y = 0; + switch (m_eRenderBarTexType) + { + case UI_TEX_TYPE_PLIST: + { + Sprite* barNode = DYNAMIC_CAST_CCSPRITE; + if (barNode) + { + Point to = barNode->getTextureRect().origin; + x = to.x; + y = to.y; + } + break; + } + default: + break; + } + if (m_bScale9Enabled) + { + setScale9Scale(); + } + else + { + dynamic_cast(m_pBarRenderer)->setTextureRect(Rect(x, y, m_barRendererTextureSize.width * res, m_barRendererTextureSize.height)); + } +} + +int UILoadingBar::getPercent() +{ + return m_nPercent; +} + +void UILoadingBar::onSizeChanged() +{ + barRendererScaleChangedWithSize(); +} + +void UILoadingBar::ignoreContentAdaptWithSize(bool ignore) +{ + if (!m_bScale9Enabled || (m_bScale9Enabled && !ignore)) + { + UIWidget::ignoreContentAdaptWithSize(ignore); + m_bPrevIgnoreSize = ignore; + } +} + +const Size& UILoadingBar::getContentSize() const +{ + return m_barRendererTextureSize; +} + +Node* UILoadingBar::getVirtualRenderer() +{ + return m_pBarRenderer; +} + +void UILoadingBar::barRendererScaleChangedWithSize() +{ + if (m_bIgnoreSize) + { + if (!m_bScale9Enabled) + { + m_fTotalLength = m_barRendererTextureSize.width; + m_pBarRenderer->setScale(1.0f); + m_size = m_barRendererTextureSize; + } + } + else + { + m_fTotalLength = m_size.width; + if (m_bScale9Enabled) + { + setScale9Scale(); + } + else + { + + Size textureSize = m_pBarRenderer->getContentSize(); + if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) + { + m_pBarRenderer->setScale(1.0f); + return; + } + float scaleX = m_size.width / textureSize.width; + float scaleY = m_size.height / textureSize.height; + m_pBarRenderer->setScaleX(scaleX); + m_pBarRenderer->setScaleY(scaleY); + } + } + switch (m_nBarType) + { + case LoadingBarTypeLeft: + m_pBarRenderer->setPosition(Point(-m_fTotalLength * 0.5f, 0.0f)); + break; + case LoadingBarTypeRight: + m_pBarRenderer->setPosition(Point(m_fTotalLength * 0.5f, 0.0f)); + break; + default: + break; + } +} + +void UILoadingBar::setScale9Scale() +{ + float width = (float)(m_nPercent) / 100 * m_fTotalLength; + dynamic_cast(m_pBarRenderer)->setPreferredSize(Size(width, m_barRendererTextureSize.height)); +} + +NS_CC_EXT_END \ No newline at end of file diff --git a/extensions/CocoStudio/GUI/UIWidgets/UILoadingBar.h b/extensions/CocoStudio/GUI/UIWidgets/UILoadingBar.h new file mode 100644 index 0000000000..aa7dafd778 --- /dev/null +++ b/extensions/CocoStudio/GUI/UIWidgets/UILoadingBar.h @@ -0,0 +1,140 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __UILOADINGBAR_H__ +#define __UILOADINGBAR_H__ + +#include "../BaseClasses/UIWidget.h" + +NS_CC_EXT_BEGIN + +typedef enum +{ + LoadingBarTypeLeft, + LoadingBarTypeRight +}LoadingBarType; + +class UILoadingBar : public UIWidget +{ +public: + /** + * Default constructor + */ + UILoadingBar(); + + /** + * Default destructor + */ + virtual ~UILoadingBar(); + + /** + * Allocates and initializes. + */ + static UILoadingBar* create(); + + /** + * Changes the progress direction of loadingbar. + * + * @see LoadingBarType LoadingBarTypeLeft means progress left to right, LoadingBarTypeRight otherwise. + * + * @param LoadingBarType + */ + void setDirection(LoadingBarType dir); + + /** + * Gets the progress direction of loadingbar. + * + * @see LoadingBarType LoadingBarTypeLeft means progress left to right, LoadingBarTypeRight otherwise. + * + * @param LoadingBarType + */ + int getDirection(); + + /** + * Load texture for loadingbar. + * + * @param fileName file name of texture. + * + * @param texType @see UI_TEX_TYPE_LOCAL + */ + void loadTexture(const char* texture,TextureResType texType = UI_TEX_TYPE_LOCAL); + + /** + * Changes the progress direction of loadingbar. + * + * @param percent percent value from 1 to 100. + */ + void setPercent(int percent); + + /** + * Gets the progress direction of loadingbar. + * + * @return percent percent value from 1 to 100. + */ + int getPercent(); + + /** + * Sets if loadingbar is using scale9 renderer. + * + * @param true that using scale9 renderer, false otherwise. + */ + void setScale9Enabled(bool enabled); + + /** + * Sets capinsets for loadingbar, if loadingbar is using scale9 renderer. + * + * @param capInsets capinsets for loadingbar + */ + void setCapInsets(const Rect &capInsets); + + //override "ignoreContentAdaptWithSize" method of widget. + virtual void ignoreContentAdaptWithSize(bool ignore); + + //override "getContentSize" method of widget. + virtual const Size& getContentSize() const; + + //override "getVirtualRenderer" method of widget. + virtual Node* getVirtualRenderer(); + +protected: + virtual void initRenderer(); + virtual void onSizeChanged(); + void setScale9Scale(); + void barRendererScaleChangedWithSize(); +protected: + LoadingBarType m_nBarType; + int m_nPercent; + float m_fTotalLength; + Node* m_pBarRenderer; + TextureResType m_eRenderBarTexType; + Size m_barRendererTextureSize; + bool m_bScale9Enabled; + bool m_bPrevIgnoreSize; + Rect m_capInsets; + std::string m_strTextureFile; +}; + +NS_CC_EXT_END + +#endif /* defined(__CocoGUI__UILoadingBar__) */ diff --git a/extensions/CocoStudio/GUI/UIWidgets/UISlider.cpp b/extensions/CocoStudio/GUI/UIWidgets/UISlider.cpp new file mode 100644 index 0000000000..8e12331bfb --- /dev/null +++ b/extensions/CocoStudio/GUI/UIWidgets/UISlider.cpp @@ -0,0 +1,540 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "UISlider.h" +#include "../../../GUI/CCControlExtension/CCScale9Sprite.h" + +NS_CC_EXT_BEGIN + +UISlider::UISlider(): +m_pBarRenderer(NULL), +m_pProgressBarRenderer(NULL), +m_ProgressBarTextureSize(Size::ZERO), +m_pSlidBallNormalRenderer(NULL), +m_pSlidBallPressedRenderer(NULL), +m_pSlidBallDisabledRenderer(NULL), +m_pSlidBallRenderer(NULL), +m_fBarLength(0.0), +m_nPercent(0), +m_fBarNodeScaleValue(1.0), +m_fTouchMoveStartLocation(0.0), +m_bScale9Enabled(false), +m_bPrevIgnoreSize(true), +m_strTextureFile(""), +m_strProgressBarTextureFile(""), +m_strSlidBallNormalTextureFile(""), +m_strSlidBallPressedTextureFile(""), +m_strSlidBallDisabledTextureFile(""), +m_capInsetsBarRenderer(Rect::ZERO), +m_capInsetsProgressBarRenderer(Rect::ZERO), +m_pSlidPercentListener(NULL), +m_pfnSlidPercentSelector(NULL), +m_eBarTexType(UI_TEX_TYPE_LOCAL), +m_eProgressBarTexType(UI_TEX_TYPE_LOCAL), +m_eBallNTexType(UI_TEX_TYPE_LOCAL), +m_eBallPTexType(UI_TEX_TYPE_LOCAL), +m_eBallDTexType(UI_TEX_TYPE_LOCAL) +{ +} + +UISlider::~UISlider() +{ + +} + +UISlider* UISlider::create() +{ + UISlider* widget = new UISlider(); + if (widget && widget->init()) + { + widget->autorelease(); + return widget; + } + CC_SAFE_DELETE(widget); + return NULL; +} + +void UISlider::initRenderer() +{ + UIWidget::initRenderer(); + m_pBarRenderer = CCSprite::create(); + m_pProgressBarRenderer = CCSprite::create(); + m_pProgressBarRenderer->setAnchorPoint(Point(0.0f, 0.5f)); + m_pRenderer->addChild(m_pBarRenderer, -1); + m_pRenderer->addChild(m_pProgressBarRenderer, -1); + m_pSlidBallNormalRenderer = CCSprite::create(); + m_pSlidBallPressedRenderer = CCSprite::create(); + m_pSlidBallPressedRenderer->setVisible(false); + m_pSlidBallDisabledRenderer = CCSprite::create(); + m_pSlidBallDisabledRenderer->setVisible(false); + m_pSlidBallRenderer = CCNode::create(); + m_pSlidBallRenderer->addChild(m_pSlidBallNormalRenderer); + m_pSlidBallRenderer->addChild(m_pSlidBallPressedRenderer); + m_pSlidBallRenderer->addChild(m_pSlidBallDisabledRenderer); + m_pRenderer->addChild(m_pSlidBallRenderer); +} + +void UISlider::loadBarTexture(const char* fileName, TextureResType texType) +{ + if (!fileName || strcmp(fileName, "") == 0) + { + return; + } + m_strTextureFile = fileName; + m_eBarTexType = texType; + switch (m_eBarTexType) + { + case UI_TEX_TYPE_LOCAL: + if (m_bScale9Enabled) + { + dynamic_cast(m_pBarRenderer)->initWithFile(fileName); + } + else + { + dynamic_cast(m_pBarRenderer)->initWithFile(fileName); + } + break; + case UI_TEX_TYPE_PLIST: + if (m_bScale9Enabled) + { + dynamic_cast(m_pBarRenderer)->initWithSpriteFrameName(fileName); + } + else + { + dynamic_cast(m_pBarRenderer)->initWithSpriteFrameName(fileName); + } + break; + default: + break; + } + if (m_bScale9Enabled) + { + dynamic_cast(m_pBarRenderer)->setColor(getColor()); + dynamic_cast(m_pBarRenderer)->setOpacity(getOpacity()); + } + else + { + dynamic_cast(m_pBarRenderer)->setColor(getColor()); + dynamic_cast(m_pBarRenderer)->setOpacity(getOpacity()); + } + barRendererScaleChangedWithSize(); +} + +void UISlider::loadProgressBarTexture(const char *fileName, TextureResType texType) +{ + if (!fileName || strcmp(fileName, "") == 0) + { + return; + } + m_strProgressBarTextureFile = fileName; + m_eProgressBarTexType = texType; + switch (m_eProgressBarTexType) + { + case UI_TEX_TYPE_LOCAL: + if (m_bScale9Enabled) + { + dynamic_cast(m_pProgressBarRenderer)->initWithFile(fileName); + } + else + { + dynamic_cast(m_pProgressBarRenderer)->initWithFile(fileName); + } + break; + case UI_TEX_TYPE_PLIST: + if (m_bScale9Enabled) + { + dynamic_cast(m_pProgressBarRenderer)->initWithSpriteFrameName(fileName); + } + else + { + dynamic_cast(m_pProgressBarRenderer)->initWithSpriteFrameName(fileName); + } + break; + default: + break; + } + if (m_bScale9Enabled) + { + dynamic_cast(m_pProgressBarRenderer)->setColor(getColor()); + dynamic_cast(m_pProgressBarRenderer)->setOpacity(getOpacity()); + } + else + { + dynamic_cast(m_pProgressBarRenderer)->setColor(getColor()); + dynamic_cast(m_pProgressBarRenderer)->setOpacity(getOpacity()); + } + m_pProgressBarRenderer->setAnchorPoint(Point(0.0f, 0.5f)); + m_ProgressBarTextureSize = m_pProgressBarRenderer->getContentSize(); + progressBarRendererScaleChangedWithSize(); +} + +void UISlider::setScale9Enabled(bool able) +{ + if (m_bScale9Enabled == able) + { + return; + } + + m_bScale9Enabled = able; + m_pRenderer->removeChild(m_pBarRenderer, true); + m_pRenderer->removeChild(m_pProgressBarRenderer, true); + m_pBarRenderer = NULL; + m_pProgressBarRenderer = NULL; + if (m_bScale9Enabled) + { + m_pBarRenderer = Scale9Sprite::create(); + m_pProgressBarRenderer = Scale9Sprite::create(); + } + else + { + m_pBarRenderer = CCSprite::create(); + m_pProgressBarRenderer = CCSprite::create(); + } + loadBarTexture(m_strTextureFile.c_str(), m_eBarTexType); + loadProgressBarTexture(m_strProgressBarTextureFile.c_str(), m_eProgressBarTexType); + m_pRenderer->addChild(m_pBarRenderer, -1); + m_pRenderer->addChild(m_pProgressBarRenderer, -1); + if (m_bScale9Enabled) + { + bool ignoreBefore = m_bIgnoreSize; + ignoreContentAdaptWithSize(false); + m_bPrevIgnoreSize = ignoreBefore; + } + else + { + ignoreContentAdaptWithSize(m_bPrevIgnoreSize); + } + setCapInsetsBarRenderer(m_capInsetsBarRenderer); + setCapInsetProgressBarRebderer(m_capInsetsProgressBarRenderer); +} + +void UISlider::ignoreContentAdaptWithSize(bool ignore) +{ + if (!m_bScale9Enabled || (m_bScale9Enabled && !ignore)) + { + UIWidget::ignoreContentAdaptWithSize(ignore); + m_bPrevIgnoreSize = ignore; + } +} + +void UISlider::setCapInsets(const Rect &capInsets) +{ + setCapInsetsBarRenderer(capInsets); + setCapInsetProgressBarRebderer(capInsets); +} + +void UISlider::setCapInsetsBarRenderer(const Rect &capInsets) +{ + m_capInsetsBarRenderer = capInsets; + if (!m_bScale9Enabled) + { + return; + } + dynamic_cast(m_pBarRenderer)->setCapInsets(capInsets); +} + +void UISlider::setCapInsetProgressBarRebderer(const Rect &capInsets) +{ + m_capInsetsProgressBarRenderer = capInsets; + if (!m_bScale9Enabled) + { + return; + } + dynamic_cast(m_pProgressBarRenderer)->setCapInsets(capInsets); +} + +void UISlider::loadSlidBallTextures(const char* normal,const char* pressed,const char* disabled,TextureResType texType) +{ + loadSlidBallTextureNormal(normal, texType); + loadSlidBallTexturePressed(pressed,texType); + loadSlidBallTextureDisabled(disabled,texType); +} + +void UISlider::loadSlidBallTextureNormal(const char* normal,TextureResType texType) +{ + if (!normal || strcmp(normal, "") == 0) + { + return; + } + m_strSlidBallNormalTextureFile = normal; + m_eBallNTexType = texType; + switch (m_eBallNTexType) + { + case UI_TEX_TYPE_LOCAL: + m_pSlidBallNormalRenderer->initWithFile(normal); + break; + case UI_TEX_TYPE_PLIST: + m_pSlidBallNormalRenderer->initWithSpriteFrameName(normal); + break; + default: + break; + } + m_pSlidBallNormalRenderer->setColor(getColor()); + m_pSlidBallNormalRenderer->setOpacity(getOpacity()); +} + +void UISlider::loadSlidBallTexturePressed(const char* pressed,TextureResType texType) +{ + if (!pressed || strcmp(pressed, "") == 0) + { + return; + } + m_strSlidBallPressedTextureFile = pressed; + m_eBallPTexType = texType; + switch (m_eBallPTexType) + { + case UI_TEX_TYPE_LOCAL: + m_pSlidBallPressedRenderer->initWithFile(pressed); + break; + case UI_TEX_TYPE_PLIST: + m_pSlidBallPressedRenderer->initWithSpriteFrameName(pressed); + break; + default: + break; + } + m_pSlidBallPressedRenderer->setColor(getColor()); + m_pSlidBallPressedRenderer->setOpacity(getOpacity()); +} + +void UISlider::loadSlidBallTextureDisabled(const char* disabled,TextureResType texType) +{ + if (!disabled || strcmp(disabled, "") == 0) + { + return; + } + m_strSlidBallDisabledTextureFile = disabled; + m_eBallDTexType = texType; + switch (m_eBallDTexType) + { + case UI_TEX_TYPE_LOCAL: + m_pSlidBallDisabledRenderer->initWithFile(disabled); + break; + case UI_TEX_TYPE_PLIST: + m_pSlidBallDisabledRenderer->initWithSpriteFrameName(disabled); + break; + default: + break; + } + m_pSlidBallDisabledRenderer->setColor(getColor()); + m_pSlidBallDisabledRenderer->setOpacity(getOpacity()); +} + +void UISlider::setPercent(int percent) +{ + if (percent > 100) + { + percent = 100; + } + if (percent < 0) + { + percent = 0; + } + m_nPercent = percent; + float dis = m_fBarLength*(percent/100.0f); + m_pSlidBallRenderer->setPosition(Point(-m_fBarLength/2.0f + dis, 0.0f)); + if (m_bScale9Enabled) + { + dynamic_cast(m_pProgressBarRenderer)->setPreferredSize(Size(dis,m_ProgressBarTextureSize.height)); + } + else + { + int x = 0, y = 0; + switch (m_eProgressBarTexType) + { + case UI_TEX_TYPE_PLIST: + { + Sprite* barNode = dynamic_cast(m_pProgressBarRenderer); + if (barNode) + { + Point to = barNode->getTextureRect().origin; + x = to.x; + y = to.y; + } + break; + } + default: + break; + } + dynamic_cast(m_pProgressBarRenderer)->setTextureRect(Rect(x, y, m_ProgressBarTextureSize.width * (percent/100.0f), m_ProgressBarTextureSize.height)); + } +} + +bool UISlider::onTouchBegan(const Point &touchPoint) +{ + bool pass = UIWidget::onTouchBegan(touchPoint); + Point nsp = m_pRenderer->convertToNodeSpace(touchPoint); + setPercent(getPercentWithBallPos(nsp.x)); + percentChangedEvent(); + return pass; +} + +void UISlider::onTouchMoved(const Point &touchPoint) +{ + Point nsp = m_pRenderer->convertToNodeSpace(touchPoint); + m_pSlidBallRenderer->setPosition(Point(nsp.x,0)); + setPercent(getPercentWithBallPos(nsp.x)); + percentChangedEvent(); +} + +void UISlider::onTouchEnded(const Point &touchPoint) +{ + UIWidget::onTouchEnded(touchPoint); +} + +void UISlider::onTouchCancelled(const Point &touchPoint) +{ + UIWidget::onTouchCancelled(touchPoint); +} + +float UISlider::getPercentWithBallPos(float px) +{ + return (((px-(-m_fBarLength/2.0f))/m_fBarLength)*100.0f); +} + +void UISlider::addPercentEvent(Object *target, SEL_SlidPercentChangedEvent selector) +{ + m_pSlidPercentListener = target; + m_pfnSlidPercentSelector = selector; +} + +void UISlider::percentChangedEvent() +{ + if (m_pSlidPercentListener && m_pfnSlidPercentSelector) + { + (m_pSlidPercentListener->*m_pfnSlidPercentSelector)(this,SLIDER_PERCENTCHANGED); + } +} + +int UISlider::getPercent() +{ + return m_nPercent; +} + +void UISlider::onSizeChanged() +{ + barRendererScaleChangedWithSize(); + progressBarRendererScaleChangedWithSize(); +} + +const Size& UISlider::getContentSize() const +{ + return m_pBarRenderer->getContentSize(); +} + +Node* UISlider::getVirtualRenderer() +{ + return m_pBarRenderer; +} + +void UISlider::barRendererScaleChangedWithSize() +{ + if (m_bIgnoreSize) + { + + m_pBarRenderer->setScale(1.0f); + m_size = m_pBarRenderer->getContentSize(); + m_fBarLength = m_size.width; + } + else + { + m_fBarLength = m_size.width; + if (m_bScale9Enabled) + { + dynamic_cast(m_pBarRenderer)->setPreferredSize(m_size); + } + else + { + Size btextureSize = m_pBarRenderer->getContentSize(); + if (btextureSize.width <= 0.0f || btextureSize.height <= 0.0f) + { + m_pBarRenderer->setScale(1.0f); + return; + } + float bscaleX = m_size.width / btextureSize.width; + float bscaleY = m_size.height / btextureSize.height; + m_pBarRenderer->setScaleX(bscaleX); + m_pBarRenderer->setScaleY(bscaleY); + } + } + setPercent(m_nPercent); +} + +void UISlider::progressBarRendererScaleChangedWithSize() +{ + if (m_bIgnoreSize) + { + if (!m_bScale9Enabled) + { + Size ptextureSize = m_ProgressBarTextureSize; + float pscaleX = m_size.width / ptextureSize.width; + float pscaleY = m_size.height / ptextureSize.height; + m_pProgressBarRenderer->setScaleX(pscaleX); + m_pProgressBarRenderer->setScaleY(pscaleY); + } + } + else + { + if (m_bScale9Enabled) + { + dynamic_cast(m_pProgressBarRenderer)->setPreferredSize(m_size); + } + else + { + Size ptextureSize = m_ProgressBarTextureSize; + if (ptextureSize.width <= 0.0f || ptextureSize.height <= 0.0f) + { + m_pProgressBarRenderer->setScale(1.0f); + return; + } + float pscaleX = m_size.width / ptextureSize.width; + float pscaleY = m_size.height / ptextureSize.height; + m_pProgressBarRenderer->setScaleX(pscaleX); + m_pProgressBarRenderer->setScaleY(pscaleY); + } + } + m_pProgressBarRenderer->setPosition(Point(-m_fBarLength * 0.5f, 0.0f)); + setPercent(m_nPercent); +} + +void UISlider::onPressStateChangedToNormal() +{ + m_pSlidBallNormalRenderer->setVisible(true); + m_pSlidBallPressedRenderer->setVisible(false); + m_pSlidBallDisabledRenderer->setVisible(false); +} + +void UISlider::onPressStateChangedToPressed() +{ + m_pSlidBallNormalRenderer->setVisible(false); + m_pSlidBallPressedRenderer->setVisible(true); + m_pSlidBallDisabledRenderer->setVisible(false); +} + +void UISlider::onPressStateChangedToDisabled() +{ + m_pSlidBallNormalRenderer->setVisible(false); + m_pSlidBallPressedRenderer->setVisible(false); + m_pSlidBallDisabledRenderer->setVisible(true); +} +NS_CC_EXT_END \ No newline at end of file diff --git a/extensions/CocoStudio/GUI/UIWidgets/UISlider.h b/extensions/CocoStudio/GUI/UIWidgets/UISlider.h new file mode 100644 index 0000000000..24b9f03ff3 --- /dev/null +++ b/extensions/CocoStudio/GUI/UIWidgets/UISlider.h @@ -0,0 +1,230 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __UISLIDER_H__ +#define __UISLIDER_H__ + +#include "../BaseClasses/UIWidget.h" + +NS_CC_EXT_BEGIN + +typedef enum +{ + SLIDER_PERCENTCHANGED +}SliderEventType; + +typedef void (CCObject::*SEL_SlidPercentChangedEvent)(Object*,SliderEventType); +#define sliderpercentchangedselector(_SELECTOR) (SEL_SlidPercentChangedEvent)(&_SELECTOR) + +class UISlider : public UIWidget +{ +public: + /** + * Default constructor + */ + UISlider(); + + /** + * Default destructor + */ + virtual ~UISlider(); + + /** + * Allocates and initializes. + */ + static UISlider* create(); + + /** + * Load texture for slider bar. + * + * @param fileName file name of texture. + * + * @param texType @see UI_TEX_TYPE_LOCAL + */ + void loadBarTexture(const char* fileName,TextureResType texType = UI_TEX_TYPE_LOCAL); + + /** + * Sets if slider is using scale9 renderer. + * + * @param true that using scale9 renderer, false otherwise. + */ + void setScale9Enabled(bool able); + + /** + * Sets capinsets for slider, if slider is using scale9 renderer. + * + * @param capInsets capinsets for slider + */ + void setCapInsets(const Rect &capInsets); + + /** + * Sets capinsets for slider, if slider is using scale9 renderer. + * + * @param capInsets capinsets for slider + */ + void setCapInsetsBarRenderer(const Rect &capInsets); + + /** + * Sets capinsets for slider, if slider is using scale9 renderer. + * + * @param capInsets capinsets for slider + */ + void setCapInsetProgressBarRebderer(const Rect &capInsets); + + /** + * Load textures for slider ball. + * + * @param slider ball normal normal state texture. + * + * @param slider ball selected selected state texture. + * + * @param slider ball disabled dark state texture. + * + * @param texType @see UI_TEX_TYPE_LOCAL + */ + void loadSlidBallTextures(const char* normal,const char* pressed,const char* disabled,TextureResType texType = UI_TEX_TYPE_LOCAL); + + /** + * Load normal state texture for slider ball. + * + * @param normal normal state texture. + * + * @param texType @see UI_TEX_TYPE_LOCAL + */ + void loadSlidBallTextureNormal(const char* normal,TextureResType texType = UI_TEX_TYPE_LOCAL); + + /** + * Load selected state texture for slider ball. + * + * @param selected selected state texture. + * + * @param texType @see UI_TEX_TYPE_LOCAL + */ + void loadSlidBallTexturePressed(const char* pressed,TextureResType texType = UI_TEX_TYPE_LOCAL); + + /** + * Load dark state texture for slider ball. + * + * @param disabled dark state texture. + * + * @param texType @see UI_TEX_TYPE_LOCAL + */ + void loadSlidBallTextureDisabled(const char* disabled,TextureResType texType = UI_TEX_TYPE_LOCAL); + + /** + * Load dark state texture for slider progress bar. + * + * @param fileName file path of texture. + * + * @param texType @see UI_TEX_TYPE_LOCAL + */ + void loadProgressBarTexture(const char* fileName, TextureResType texType = UI_TEX_TYPE_LOCAL); + + /** + * Changes the progress direction of slider. + * + * @param percent percent value from 1 to 100. + */ + void setPercent(int percent); + + /** + * Gets the progress direction of slider. + * + * @return percent percent value from 1 to 100. + */ + int getPercent(); + + /** + * Add call back function called when slider's percent has changed to slider. + */ + void addPercentEvent(Object* target,SEL_SlidPercentChangedEvent selector); + + //override "onTouchBegan" method of widget. + virtual bool onTouchBegan(const Point &touchPoint); + + //override "onTouchMoved" method of widget. + virtual void onTouchMoved(const Point &touchPoint); + + //override "onTouchEnded" method of widget. + virtual void onTouchEnded(const Point &touchPoint); + + //override "onTouchCancelled" method of widget. + virtual void onTouchCancelled(const Point &touchPoint); + + //override "getContentSize" method of widget. + virtual const Size& getContentSize() const; + + //override "getVirtualRenderer" method of widget. + virtual Node* getVirtualRenderer(); + + //override "ignoreContentAdaptWithSize" method of widget. + virtual void ignoreContentAdaptWithSize(bool ignore); +protected: + virtual void initRenderer(); + float getPercentWithBallPos(float location); + void percentChangedEvent(); + virtual void onPressStateChangedToNormal(); + virtual void onPressStateChangedToPressed(); + virtual void onPressStateChangedToDisabled(); + virtual void onSizeChanged(); + void barRendererScaleChangedWithSize(); + void progressBarRendererScaleChangedWithSize(); +protected: + Node* m_pBarRenderer; + Node* m_pProgressBarRenderer; + Size m_ProgressBarTextureSize; + + Sprite* m_pSlidBallNormalRenderer; + Sprite* m_pSlidBallPressedRenderer; + Sprite* m_pSlidBallDisabledRenderer; + Node* m_pSlidBallRenderer; + + float m_fBarLength; + int m_nPercent; + + float m_fBarNodeScaleValue; + float m_fTouchMoveStartLocation; + bool m_bScale9Enabled; + bool m_bPrevIgnoreSize; + std::string m_strTextureFile; + std::string m_strProgressBarTextureFile; + std::string m_strSlidBallNormalTextureFile; + std::string m_strSlidBallPressedTextureFile; + std::string m_strSlidBallDisabledTextureFile; + + Rect m_capInsetsBarRenderer; + Rect m_capInsetsProgressBarRenderer; + + Object* m_pSlidPercentListener; + SEL_SlidPercentChangedEvent m_pfnSlidPercentSelector; + TextureResType m_eBarTexType; + TextureResType m_eProgressBarTexType; + TextureResType m_eBallNTexType; + TextureResType m_eBallPTexType; + TextureResType m_eBallDTexType; +}; + +NS_CC_EXT_END + +#endif /* defined(__CocoGUI__UISlider__) */ diff --git a/extensions/CocoStudio/GUI/UIWidgets/UITextField.cpp b/extensions/CocoStudio/GUI/UIWidgets/UITextField.cpp new file mode 100644 index 0000000000..6ec31d2a4f --- /dev/null +++ b/extensions/CocoStudio/GUI/UIWidgets/UITextField.cpp @@ -0,0 +1,587 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "UITextField.h" + +NS_CC_EXT_BEGIN + +UICCTextField::UICCTextField() +: m_bMaxLengthEnabled(false) +, m_nMaxLength(0) +, m_bPasswordEnabled(false) +, m_strPasswordStyleText("*") +, m_bAttachWithIME(false) +, m_bDetachWithIME(false) +, m_bInsertText(false) +, m_bDeleteBackward(false) +{ +} + +UICCTextField::~UICCTextField() +{ +} + +UICCTextField * UICCTextField::create(const char *placeholder, const char *fontName, float fontSize) +{ + UICCTextField *pRet = new UICCTextField(); + + if(pRet && pRet->initWithString("", fontName, fontSize)) + { + pRet->autorelease(); + if (placeholder) + { + pRet->setPlaceHolder(placeholder); + } + return pRet; + } + CC_SAFE_DELETE(pRet); + + return NULL; +} + +void UICCTextField::onEnter() +{ + CCTextFieldTTF::setDelegate(this); +} + + +bool UICCTextField::onTextFieldAttachWithIME(CCTextFieldTTF *pSender) +{ + setAttachWithIME(true); + return false; +} + +bool UICCTextField::onTextFieldInsertText(CCTextFieldTTF *pSender, const char *text, int nLen) +{ + if (nLen == 1 && strcmp(text, "\n") == 0) + { + return false; + } + setInsertText(true); + if (m_bMaxLengthEnabled) + { + if (CCTextFieldTTF::getCharCount() >= m_nMaxLength) + { + return true; + } + } + + return false; +} + +bool UICCTextField::onTextFieldDeleteBackward(CCTextFieldTTF *pSender, const char *delText, int nLen) +{ + setDeleteBackward(true); + return false; +} + +bool UICCTextField::onTextFieldDetachWithIME(CCTextFieldTTF *pSender) +{ + setDetachWithIME(true); + return false; +} + +void UICCTextField::insertText(const char * text, int len) +{ + std::string str_text = text; + int str_len = strlen(CCTextFieldTTF::getString()); + + if (strcmp(text, "\n") != 0) + { + if (m_bMaxLengthEnabled) + { + int multiple = 1; + char value = text[0]; + if (value < 0 || value > 127) + { + multiple = 3; + } + + if (str_len + len > m_nMaxLength * multiple) + { + str_text = str_text.substr(0, m_nMaxLength * multiple); + len = m_nMaxLength * multiple; + /* + int mod = str_len % 3; + int offset = (mod == 0) ? 0 : (3 - mod); + int amount = str_len + offset; + str_text = str_text.substr(0, m_nMaxLength - amount); + // CCLOG("str_test = %s", str_text.c_str()); + */ + } + } + } + CCTextFieldTTF::insertText(str_text.c_str(), len); + + // password + if (m_bPasswordEnabled) + { + if (CCTextFieldTTF::getCharCount() > 0) + { + setPasswordText(_inputText->c_str()); + } + } +} + +void UICCTextField::deleteBackward() +{ + CCTextFieldTTF::deleteBackward(); + + if (CCTextFieldTTF::getCharCount() > 0) + { + // password + if (m_bPasswordEnabled) + { + setPasswordText(_inputText->c_str()); + } + } +} + +void UICCTextField::openIME() +{ + CCTextFieldTTF::attachWithIME(); +} + +void UICCTextField::closeIME() +{ + CCTextFieldTTF::detachWithIME(); +} + +void UICCTextField::setMaxLengthEnabled(bool enable) +{ + m_bMaxLengthEnabled = enable; +} + +bool UICCTextField::isMaxLengthEnabled() +{ + return m_bMaxLengthEnabled; +} + +void UICCTextField::setMaxLength(int length) +{ + m_nMaxLength = length; +} + +int UICCTextField::getMaxLength() +{ + return m_nMaxLength; +} + +int UICCTextField::getCharCount() +{ + return CCTextFieldTTF::getCharCount(); +} + +void UICCTextField::setPasswordEnabled(bool enable) +{ + m_bPasswordEnabled = enable; +} + +bool UICCTextField::isPasswordEnabled() +{ + return m_bPasswordEnabled; +} + +void UICCTextField::setPasswordStyleText(const char* styleText) +{ + if (strlen(styleText) > 1) + { + return; + } + char value = styleText[0]; + if (value < 33 || value > 126) + { + return; + } + m_strPasswordStyleText = styleText; +} + +void UICCTextField::setPasswordText(const char *text) +{ + std::string tempStr; + for (size_t i = 0; i < strlen(text); ++i) + { + tempStr.append(m_strPasswordStyleText); + } + CCLabelTTF::setString(tempStr.c_str()); +} + +void UICCTextField::setAttachWithIME(bool attach) +{ + m_bAttachWithIME = attach; +} + +bool UICCTextField::getAttachWithIME() +{ + return m_bAttachWithIME; +} + +void UICCTextField::setDetachWithIME(bool detach) +{ + m_bDetachWithIME = detach; +} + +bool UICCTextField::getDetachWithIME() +{ + return m_bDetachWithIME; +} + +void UICCTextField::setInsertText(bool insert) +{ + m_bInsertText = insert; +} + +bool UICCTextField::getInsertText() +{ + return m_bInsertText; +} + +void UICCTextField::setDeleteBackward(bool deleteBackward) +{ + m_bDeleteBackward = deleteBackward; +} + +bool UICCTextField::getDeleteBackward() +{ + return m_bDeleteBackward; +} + + + + +UITextField::UITextField(): +m_fTouchWidth(0.0f), +m_fTouchHeight(0.0f), +m_bUseTouchArea(false), +m_pAttachWithIMEListener(NULL), +m_pDetachWithIMEListener(NULL), +m_pInsertTextListener(NULL), +m_pDeleteBackwardListener(NULL), +m_pfnAttachWithIMESelector(NULL), +m_pfnDetachWithIMESelector(NULL), +m_pfnInsertTextSelector(NULL), +m_pfnDeleteBackwardSelector(NULL), +m_pTextFieldRenderer(NULL) +{ +} + +UITextField::~UITextField() +{ +} + +UITextField* UITextField::create() +{ + UITextField* widget = new UITextField(); + if (widget && widget->init()) + { + widget->autorelease(); + return widget; + } + CC_SAFE_DELETE(widget); + return NULL; +} + +bool UITextField::init() +{ + if (UIWidget::init()) + { + setUpdateEnabled(true); + return true; + } + return false; +} + +void UITextField::initRenderer() +{ + UIWidget::initRenderer(); + m_pTextFieldRenderer = UICCTextField::create("input words here", "Thonburi", 20); + m_pRenderer->addChild(m_pTextFieldRenderer); +} + +void UITextField::setTouchSize(const CCSize &size) +{ + m_bUseTouchArea = true; + m_fTouchWidth = size.width; + m_fTouchHeight = size.height; +} + +void UITextField::setText(const char* text) +{ + if (!text) + { + return; + } + std::string strText(text); + m_pTextFieldRenderer->setString(strText.c_str()); + textfieldRendererScaleChangedWithSize(); +} + +void UITextField::setPlaceHolder(const char *value) +{ + m_pTextFieldRenderer->setPlaceHolder(value); + textfieldRendererScaleChangedWithSize(); +} + +void UITextField::setFontSize(int size) +{ + m_pTextFieldRenderer->setFontSize(size); + textfieldRendererScaleChangedWithSize(); +} + +void UITextField::setFontName(const char *name) +{ + m_pTextFieldRenderer->setFontName(name); + textfieldRendererScaleChangedWithSize(); +} + +void UITextField::didNotSelectSelf() +{ + m_pTextFieldRenderer->detachWithIME(); +} + +const char* UITextField::getStringValue() +{ + return m_pTextFieldRenderer->getString(); +} + +bool UITextField::onTouchBegan(const CCPoint &touchPoint) +{ + bool pass = UIWidget::onTouchBegan(touchPoint); + m_pTextFieldRenderer->attachWithIME(); + return pass; +} + +void UITextField::setMaxLengthEnabled(bool enable) +{ + m_pTextFieldRenderer->setMaxLengthEnabled(enable); +} + +bool UITextField::isMaxLengthEnabled() +{ + return m_pTextFieldRenderer->isMaxLengthEnabled(); +} + +void UITextField::setMaxLength(int length) +{ + m_pTextFieldRenderer->setMaxLength(length); +} + +int UITextField::getMaxLength() +{ + return m_pTextFieldRenderer->getMaxLength(); +} + +void UITextField::setPasswordEnabled(bool enable) +{ + m_pTextFieldRenderer->setPasswordEnabled(enable); +} + +bool UITextField::isPasswordEnabled() +{ + return m_pTextFieldRenderer->isPasswordEnabled(); +} + +void UITextField::setPasswordStyleText(const char *styleText) +{ + m_pTextFieldRenderer->setPasswordStyleText(styleText); +} + +void UITextField::update(float dt) +{ + if (getAttachWithIME()) + { + attachWithIMEEvent(); + setAttachWithIME(false); + } + if (getDetachWithIME()) + { + detachWithIMEEvent(); + setDetachWithIME(false); + } + if (getInsertText()) + { + insertTextEvent(); + setInsertText(false); + + textfieldRendererScaleChangedWithSize(); + } + if (getDeleteBackward()) + { + deleteBackwardEvent(); + setDeleteBackward(false); + } +} + +bool UITextField::getAttachWithIME() +{ + return m_pTextFieldRenderer->getAttachWithIME(); +} + +void UITextField::setAttachWithIME(bool attach) +{ + m_pTextFieldRenderer->setAttachWithIME(attach); +} + +bool UITextField::getDetachWithIME() +{ + return m_pTextFieldRenderer->getDetachWithIME(); +} + +void UITextField::setDetachWithIME(bool detach) +{ + m_pTextFieldRenderer->setDetachWithIME(detach); +} + +bool UITextField::getInsertText() +{ + return m_pTextFieldRenderer->getInsertText(); +} + +void UITextField::setInsertText(bool insertText) +{ + m_pTextFieldRenderer->setInsertText(insertText); +} + +bool UITextField::getDeleteBackward() +{ + return m_pTextFieldRenderer->getDeleteBackward(); +} + +void UITextField::setDeleteBackward(bool deleteBackward) +{ + m_pTextFieldRenderer->setDeleteBackward(deleteBackward); +} + +void UITextField::attachWithIMEEvent() +{ + if (m_pAttachWithIMEListener && m_pfnAttachWithIMESelector) + { + (m_pAttachWithIMEListener->*m_pfnAttachWithIMESelector)(this); + } +} + +void UITextField::detachWithIMEEvent() +{ + if (m_pDetachWithIMEListener && m_pfnDetachWithIMESelector) + { + (m_pDetachWithIMEListener->*m_pfnDetachWithIMESelector)(this); + } +} + +void UITextField::insertTextEvent() +{ + if (m_pInsertTextListener && m_pfnInsertTextSelector) + { + (m_pInsertTextListener->*m_pfnInsertTextSelector)(this); + } +} + +void UITextField::deleteBackwardEvent() +{ + if (m_pDeleteBackwardListener && m_pfnDeleteBackwardSelector) + { + (m_pDeleteBackwardListener->*m_pfnDeleteBackwardSelector)(this); + } +} + +void UITextField::addAttachWithIMEEvent(CCObject *target, SEL_TextFieldAttachWithIMEEvent selecor) +{ + m_pAttachWithIMEListener = target; + m_pfnAttachWithIMESelector = selecor; +} + +void UITextField::addDetachWithIMEEvent(CCObject *target, SEL_TextFieldDetachWithIMEEvent selecor) +{ + m_pDetachWithIMEListener = target; + m_pfnDetachWithIMESelector = selecor; +} + +void UITextField::addInsertTextEvent(CCObject *target, SEL_TextFieldInsertTextEvent selecor) +{ + m_pInsertTextListener = target; + m_pfnInsertTextSelector = selecor; +} + +void UITextField::addDeleteBackwardEvent(CCObject *target, SEL_TextFieldDeleteBackwardEvent selecor) +{ + m_pDeleteBackwardListener = target; + m_pfnDeleteBackwardSelector = selecor; +} + +void UITextField::setAnchorPoint(const CCPoint &pt) +{ + UIWidget::setAnchorPoint(pt); + m_pTextFieldRenderer->setAnchorPoint(pt); +} + +void UITextField::setColor(const ccColor3B &color) +{ + UIWidget::setColor(color); + m_pTextFieldRenderer->setColor(color); +} + +void UITextField::setOpacity(int opacity) +{ + UIWidget::setOpacity(opacity); + m_pTextFieldRenderer->setOpacity(opacity); +} + +void UITextField::onSizeChanged() +{ + textfieldRendererScaleChangedWithSize(); +} + +void UITextField::textfieldRendererScaleChangedWithSize() +{ + if (m_bIgnoreSize) + { + m_pTextFieldRenderer->setScale(1.0f); + m_size = getContentSize(); + } + else + { + CCSize textureSize = getContentSize(); + if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) + { + m_pTextFieldRenderer->setScale(1.0f); + return; + } + float scaleX = m_size.width / textureSize.width; + float scaleY = m_size.height / textureSize.height; + m_pTextFieldRenderer->setScaleX(scaleX); + m_pTextFieldRenderer->setScaleY(scaleY); + } +} + +const CCSize& UITextField::getContentSize() const +{ + return m_pTextFieldRenderer->getContentSize(); +} + +CCNode* UITextField::getVirtualRenderer() +{ + return m_pTextFieldRenderer; +} + +NS_CC_EXT_END \ No newline at end of file diff --git a/extensions/CocoStudio/GUI/UIWidgets/UITextField.h b/extensions/CocoStudio/GUI/UIWidgets/UITextField.h new file mode 100644 index 0000000000..71bddcfd2a --- /dev/null +++ b/extensions/CocoStudio/GUI/UIWidgets/UITextField.h @@ -0,0 +1,172 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __UITEXTFIELD_H__ +#define __UITEXTFIELD_H__ + +#include "../BaseClasses/UIWidget.h" + + +NS_CC_EXT_BEGIN + +class UICCTextField: public TextFieldTTF, public TextFieldDelegate, public TouchDelegate +{ +public: + UICCTextField(); + ~UICCTextField(); + + virtual void onEnter(); + + // static + static UICCTextField* create(const char *placeholder, const char *fontName, float fontSize); + + // CCTextFieldDelegate + virtual bool onTextFieldAttachWithIME(TextFieldTTF *pSender); + virtual bool onTextFieldDetachWithIME(TextFieldTTF * pSender); + virtual bool onTextFieldInsertText(TextFieldTTF * pSender, const char * text, int nLen); + virtual bool onTextFieldDeleteBackward(TextFieldTTF * pSender, const char * delText, int nLen); + + void insertText(const char* text, int len); + void deleteBackward(); + + void openIME(); + void closeIME(); + + void setMaxLengthEnabled(bool enable); + bool isMaxLengthEnabled(); + void setMaxLength(int length); + int getMaxLength(); + int getCharCount(); + void setPasswordEnabled(bool enable); + bool isPasswordEnabled(); + void setPasswordStyleText(const char* styleText); + void setPasswordText(const char* text); + void setAttachWithIME(bool attach); + bool getAttachWithIME(); + void setDetachWithIME(bool detach); + bool getDetachWithIME(); + void setInsertText(bool insert); + bool getInsertText(); + void setDeleteBackward(bool deleteBackward); + bool getDeleteBackward(); +protected: + bool m_bMaxLengthEnabled; + int m_nMaxLength; + bool m_bPasswordEnabled; + std::string m_strPasswordStyleText; + bool m_bAttachWithIME; + bool m_bDetachWithIME; + bool m_bInsertText; + bool m_bDeleteBackward; +}; + + +typedef void (Object::*SEL_TextFieldAttachWithIMEEvent)(Object*); +#define coco_TextField_AttachWithIME_selector(_SELECTOR) (SEL_TextFieldAttachWithIMEEvent)(&_SELECTOR) +typedef void (Object::*SEL_TextFieldDetachWithIMEEvent)(Object*); +#define coco_TextField_DetachWithIME_selector(_SELECTOR) (SEL_TextFieldDetachWithIMEEvent)(&_SELECTOR) +typedef void (Object::*SEL_TextFieldInsertTextEvent)(Object*); +#define coco_TextField_InsertText_selector(_SELECTOR) (SEL_TextFieldInsertTextEvent)(&_SELECTOR) +typedef void (Object::*SEL_TextFieldDeleteBackwardEvent)(Object*); +#define coco_TextField_DeleteBackward_selector(_SELECTOR) (SEL_TextFieldDeleteBackwardEvent)(&_SELECTOR) + +//class UITextField : public UIWidget +class UITextField : public UIWidget +{ +public: + UITextField(); + virtual ~UITextField(); + static UITextField* create(); + virtual bool init(); + virtual void initRenderer(); + void setTouchSize(const Size &size); + void setText(const char* text); + void setPlaceHolder(const char* value); + void setFontSize(int size); + void setFontName(const char* name); + virtual void didNotSelectSelf(); + const char* getStringValue(); + virtual bool onTouchBegan(const Point &touchPoint); + void setMaxLengthEnabled(bool enable); + bool isMaxLengthEnabled(); + void setMaxLength(int length); + int getMaxLength(); + void setPasswordEnabled(bool enable); + bool isPasswordEnabled(); + void setPasswordStyleText(const char* styleText); + virtual void update(float dt); + bool getAttachWithIME(); + void setAttachWithIME(bool attach); + bool getDetachWithIME(); + void setDetachWithIME(bool detach); + bool getInsertText(); + void setInsertText(bool insertText); + bool getDeleteBackward(); + void setDeleteBackward(bool deleteBackward); + void addAttachWithIMEEvent(Object* target, SEL_TextFieldAttachWithIMEEvent selecor); + void addDetachWithIMEEvent(Object* target, SEL_TextFieldDetachWithIMEEvent selecor); + void addInsertTextEvent(Object* target, SEL_TextFieldInsertTextEvent selecor); + void addDeleteBackwardEvent(Object* target, SEL_TextFieldDeleteBackwardEvent selecor); + virtual void setAnchorPoint(const Point &pt); + virtual void setColor(const Color3B &color); + virtual void setOpacity(int opacity); + + /*compatibel*/ + /** + * These methods will be removed + */ + void setMaxLengthEnable(bool is){setMaxLengthEnabled(is);}; + void setPasswordEnable(bool is){setPasswordEnabled(is);}; + /************/ + virtual const Size& getContentSize() const; + virtual Node* getVirtualRenderer(); +protected: + // event + void attachWithIMEEvent(); + void detachWithIMEEvent(); + void insertTextEvent(); + void deleteBackwardEvent(); + virtual void onSizeChanged(); + void textfieldRendererScaleChangedWithSize(); +protected: + float m_fTouchWidth; + float m_fTouchHeight; + bool m_bUseTouchArea; + + Object* m_pAttachWithIMEListener; + Object* m_pDetachWithIMEListener; + Object* m_pInsertTextListener; + Object* m_pDeleteBackwardListener; + + SEL_TextFieldAttachWithIMEEvent m_pfnAttachWithIMESelector; + SEL_TextFieldDetachWithIMEEvent m_pfnDetachWithIMESelector; + SEL_TextFieldInsertTextEvent m_pfnInsertTextSelector; + SEL_TextFieldDeleteBackwardEvent m_pfnDeleteBackwardSelector; + + UICCTextField* m_pTextFieldRenderer; +}; + +NS_CC_EXT_END + +#endif /* defined(__CocoGUI__UITextField__) */ diff --git a/extensions/CocoStudio/Reader/CCSGUIReader.cpp b/extensions/CocoStudio/Reader/CCSGUIReader.cpp new file mode 100755 index 0000000000..ca5ffb987c --- /dev/null +++ b/extensions/CocoStudio/Reader/CCSGUIReader.cpp @@ -0,0 +1,1569 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "../GUI/System/CocosGUI.h" +#include "../Json/DictionaryHelper.h" +//#include "../Action/UIActionManager.h" +#include +#include + + +NS_CC_EXT_BEGIN + +static CCSGUIReader* sharedReader = NULL; + +CCSGUIReader::CCSGUIReader(): +m_strFilePath(""), +m_bOlderVersion(false) +{ + +} + +CCSGUIReader::~CCSGUIReader() +{ + +} + +CCSGUIReader* CCSGUIReader::shareReader() +{ + if (!sharedReader) + { + sharedReader = new CCSGUIReader(); + } + return sharedReader; +} + +void CCSGUIReader::purgeCCSGUIReader() +{ + CC_SAFE_DELETE(sharedReader); +} + +int CCSGUIReader::getVersionInteger(const char *str) +{ + /*********temp***********/ + std::string strVersion = str; + int length = strVersion.length(); + if (length < 7) + { + return 0; + } + int pos = strVersion.find_first_of("."); + std::string t = strVersion.substr(0,pos); + strVersion = strVersion.substr(pos+1,strVersion.length()-1); + + pos = strVersion.find_first_of("."); + std::string h = strVersion.substr(0,pos); + strVersion = strVersion.substr(pos+1,strVersion.length()-1); + + pos = strVersion.find_first_of("."); + std::string te = strVersion.substr(0,pos); + strVersion = strVersion.substr(pos+1,strVersion.length()-1); + + pos = strVersion.find_first_of("."); + std::string s = strVersion.substr(0,pos); + + int it = atoi(t.c_str()); + int ih = atoi(h.c_str()); + int ite = atoi(te.c_str()); + int is = atoi(s.c_str()); + + int iVersion = it*1000+ih*100+ite*10+is; + CCLOG("iversion %d",iVersion); + return iVersion; + /************************/ +} + +UIWidget* CCSGUIReader::widgetFromJsonDictionary(cs::JsonDictionary* data) +{ + UIWidget* widget = NULL; + const char* classname = DICTOOL->getStringValue_json(data, "classname"); + cs::JsonDictionary* uiOptions = DICTOOL->getSubDictionary_json(data, "options"); + if (classname && strcmp(classname, "Button") == 0) + { + widget = UIButton::create(); + setPropsForButtonFromJsonDictionary(widget, uiOptions); + } + else if (classname && strcmp(classname, "CheckBox") == 0) + { + widget = UICheckBox::create(); + setPropsForCheckBoxFromJsonDictionary(widget, uiOptions); + } + else if (classname && strcmp(classname, "Label") == 0) + { + widget = UILabel::create(); + setPropsForLabelFromJsonDictionary(widget, uiOptions); + } + else if (classname && strcmp(classname, "LabelAtlas") == 0) + { + widget = UILabelAtlas::create(); + setPropsForLabelAtlasFromJsonDictionary(widget, uiOptions); + } + else if (classname && strcmp(classname, "LoadingBar") == 0) + { + widget = UILoadingBar::create(); + setPropsForLoadingBarFromJsonDictionary(widget, uiOptions); + }else if (classname && strcmp(classname, "ScrollView") == 0){ + widget = UIScrollView::create(); + setPropsForScrollViewFromJsonDictionary(widget, uiOptions); + } + else if (classname && strcmp(classname, "TextArea") == 0) + { + widget = UILabel::create(); + setPropsForTextAreaFromJsonDictionary(widget, uiOptions); + } + else if (classname && strcmp(classname, "TextButton") == 0) + { + widget = UIButton::create(); + setPropsForTextButtonFromJsonDictionary(widget, uiOptions); + } + else if (classname && strcmp(classname, "TextField") == 0) + { + widget = UITextField::create(); + setPropsForTextFieldFromJsonDictionary(widget, uiOptions); + } + else if (classname && strcmp(classname, "ImageView") == 0) + { + widget = UIImageView::create(); + setPropsForImageViewFromJsonDictionary(widget, uiOptions); + } + else if (classname && strcmp(classname, "Panel") == 0) + { + widget = Layout::create(); + setPropsForPanelFromJsonDictionary(widget, uiOptions); + } + else if (classname && strcmp(classname, "Slider") == 0) + { + widget = UISlider::create(); + setPropsForSliderFromJsonDictionary(widget, uiOptions); + } + else if (classname && strcmp(classname, "ListView") == 0) + { +// widget = UIListView::create(); +// setPropsForListViewFromJsonDictionary(widget, uiOptions); + } + else if (classname && strcmp(classname, "PageView") == 0) + { + widget = UIPageView::create(); + setPropsForPageViewFromJsonDictionary(widget, uiOptions); + } + else if (classname && strcmp(classname, "LabelBMFont") == 0) + { + widget = UILabelBMFont::create(); + setPropsForLabelBMFontFromJsonDictionary(widget, uiOptions); + } + else if (classname && strcmp(classname, "DragPanel") == 0) + { + widget = UIDragPanel::create(); + setPropsForDragPanelFromJsonDictionary(widget, uiOptions); + } + + int childrenCount = DICTOOL->getArrayCount_json(data, "children"); + for (int i=0;igetDictionaryFromArray_json(data, "children", i); + UIWidget* child = widgetFromJsonDictionary(subData); + if (child) + { + widget->addChild(child); + } + CC_SAFE_DELETE(subData); + } + + CC_SAFE_DELETE(uiOptions); + return widget; +} + + + +UIWidget* CCSGUIReader::widgetFromJsonFile(const char *fileName) +{ + m_bOlderVersion = false; + const char *des = NULL; + std::string jsonpath; + cs::JsonDictionary *jsonDict = NULL; + jsonpath = CCFileUtils::sharedFileUtils()->fullPathForFilename(fileName); + + unsigned long size = 0; + des = (char*)(CCFileUtils::sharedFileUtils()->getFileData(jsonpath.c_str(),"r" , &size)); + if(NULL == des || strcmp(des, "") == 0) + { + printf("read json file[%s] error!\n", fileName); + return NULL; + } + std::string strDes(des); + jsonDict = new cs::JsonDictionary(); + jsonDict->initWithDescription(strDes.c_str()); + + const char* fileVersion = DICTOOL->getStringValue_json(jsonDict, "version"); + if (!fileVersion || getVersionInteger(fileVersion) < 250) + { + m_bOlderVersion = true; + } + + int texturesCount = DICTOOL->getArrayCount_json(jsonDict, "textures"); + int pos = jsonpath.find_last_of('/'); + m_strFilePath = jsonpath.substr(0,pos+1); + for (int i=0; igetStringValueFromArray_json(jsonDict, "textures", i); + std::string tp = m_strFilePath; + tp.append(file); + CCUIHELPER->addSpriteFrame(tp.c_str()); + } + float fileDesignWidth = DICTOOL->getFloatValue_json(jsonDict, "designWidth"); + float fileDesignHeight = DICTOOL->getFloatValue_json(jsonDict, "designHeight"); + if (fileDesignWidth <= 0 || fileDesignHeight <= 0) { + printf("Read design size error!\n"); + CCSize winSize = CCDirector::sharedDirector()->getWinSize(); + CCUIHELPER->setFileDesignWidth(winSize.width); + CCUIHELPER->setFileDesignHeight(winSize.height); + } + else + { + CCUIHELPER->setFileDesignWidth(fileDesignWidth); + CCUIHELPER->setFileDesignHeight(fileDesignHeight); + } + cs::JsonDictionary* widgetTree = DICTOOL->getSubDictionary_json(jsonDict, "widgetTree"); + UIWidget* widget = widgetFromJsonDictionary(widgetTree); + + /* *********temp********* */ + if (widget->getContentSize().equals(CCSizeZero)) + { + Layout* rootWidget = dynamic_cast(widget); + rootWidget->setSize(CCSizeMake(fileDesignWidth, fileDesignHeight)); + } + /* ********************** */ + +// widget->setFileDesignSize(CCSizeMake(fileDesignWidth, fileDesignHeight)); + cs::JsonDictionary* actions = DICTOOL->getSubDictionary_json(jsonDict, "animation"); + /* *********temp********* */ +// UIActionManager::shareManager()->releaseActions(); + /* ********************** */ + CCLOG("file name == [%s]",fileName); + UIActionManager::shareManager()->initWithDictionary(fileName,actions,widget); + + CC_SAFE_DELETE(widgetTree); + CC_SAFE_DELETE(actions); + CC_SAFE_DELETE(jsonDict); + CC_SAFE_DELETE_ARRAY(des); + return widget; +} + +void CCSGUIReader::setPropsForWidgetFromJsonDictionary(UIWidget*widget,cs::JsonDictionary *options) +{ + bool ignoreSizeExsit = DICTOOL->checkObjectExist_json(options, "ignoreSize"); + if (ignoreSizeExsit) + { + widget->ignoreContentAdaptWithSize(DICTOOL->getBooleanValue_json(options, "ignoreSize")); + } + + float w = DICTOOL->getFloatValue_json(options, "width"); + float h = DICTOOL->getFloatValue_json(options, "height"); + widget->setSize(CCSizeMake(w, h)); + + widget->setTag(DICTOOL->getIntValue_json(options, "tag")); + widget->setActionTag(DICTOOL->getIntValue_json(options, "actiontag")); + widget->setTouchEnabled(DICTOOL->getBooleanValue_json(options, "touchAble")); + const char* name = DICTOOL->getStringValue_json(options, "name"); + const char* widgetName = name?name:"default"; + widget->setName(widgetName); + float x = DICTOOL->getFloatValue_json(options, "x"); + float y = DICTOOL->getFloatValue_json(options, "y"); + widget->setPosition(ccp(x,y)); + bool sx = DICTOOL->checkObjectExist_json(options, "scaleX"); + if (sx) + { + widget->setScaleX(DICTOOL->getFloatValue_json(options, "scaleX")); + } + bool sy = DICTOOL->checkObjectExist_json(options, "scaleY"); + if (sy) + { + widget->setScaleY(DICTOOL->getFloatValue_json(options, "scaleY")); + } + bool rt = DICTOOL->checkObjectExist_json(options, "rotation"); + if (rt) + { + widget->setRotation(DICTOOL->getFloatValue_json(options, "rotation")); + } + bool vb = DICTOOL->checkObjectExist_json(options, "visible"); + if (vb) + { + widget->setVisible(DICTOOL->getBooleanValue_json(options, "visible")); + } +// widget->setUseMergedTexture(DICTOOL->getBooleanValue_json(options, "useMergedTexture")); + int z = DICTOOL->getIntValue_json(options, "ZOrder"); + widget->setZOrder(z); +} + +void CCSGUIReader::setColorPropsForWidgetFromJsonDictionary(UIWidget *widget, cs::JsonDictionary *options) +{ + bool op = DICTOOL->checkObjectExist_json(options, "opacity"); + if (op) + { + widget->setOpacity(DICTOOL->getIntValue_json(options, "opacity")); + } + bool cr = DICTOOL->checkObjectExist_json(options, "colorR"); + bool cg = DICTOOL->checkObjectExist_json(options, "colorG"); + bool cb = DICTOOL->checkObjectExist_json(options, "colorB"); + int colorR = cr ? DICTOOL->getIntValue_json(options, "colorR") : 255; + int colorG = cg ? DICTOOL->getIntValue_json(options, "colorG") : 255; + int colorB = cb ? DICTOOL->getIntValue_json(options, "colorB") : 255; + widget->setColor(ccc3(colorR, colorG, colorB)); + bool apx = DICTOOL->checkObjectExist_json(options, "anchorPointX"); + float apxf = apx ? DICTOOL->getFloatValue_json(options, "anchorPointX") : 0.5f; + bool apy = DICTOOL->checkObjectExist_json(options, "anchorPointY"); + float apyf = apy ? DICTOOL->getFloatValue_json(options, "anchorPointY") : 0.5f; + widget->setAnchorPoint(ccp(apxf, apyf)); + bool flipX = DICTOOL->getBooleanValue_json(options, "flipX"); + bool flipY = DICTOOL->getBooleanValue_json(options, "flipY"); + widget->setFlipX(flipX); + widget->setFlipY(flipY); +} + +void CCSGUIReader::setPropsForButtonFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options) +{ + if (m_bOlderVersion) + { + setPropsForWidgetFromJsonDictionary(widget, options); + UIButton* button = (UIButton*)widget; + bool scale9Enable = DICTOOL->getBooleanValue_json(options, "scale9Enable"); + button->setScale9Enabled(scale9Enable); + + std::string tp_n = m_strFilePath; + std::string tp_p = m_strFilePath; + std::string tp_d = m_strFilePath; + + const char* normalFileName = DICTOOL->getStringValue_json(options, "normal"); + const char* pressedFileName = DICTOOL->getStringValue_json(options, "pressed"); + const char* disabledFileName = DICTOOL->getStringValue_json(options, "disabled"); + + const char* normalFileName_tp = (normalFileName && (strcmp(normalFileName, "") != 0))?tp_n.append(normalFileName).c_str():NULL; + const char* pressedFileName_tp = (pressedFileName && (strcmp(pressedFileName, "") != 0))?tp_p.append(pressedFileName).c_str():NULL; + const char* disabledFileName_tp = (disabledFileName && (strcmp(disabledFileName, "") != 0))?tp_d.append(disabledFileName).c_str():NULL; + bool useMergedTexture = DICTOOL->getBooleanValue_json(options, "useMergedTexture"); + if (scale9Enable) + { + float cx = DICTOOL->getFloatValue_json(options, "capInsetsX"); + float cy = DICTOOL->getFloatValue_json(options, "capInsetsY"); + float cw = DICTOOL->getFloatValue_json(options, "capInsetsWidth"); + float ch = DICTOOL->getFloatValue_json(options, "capInsetsHeight"); + + if (useMergedTexture) + { + button->loadTextures(normalFileName, pressedFileName, disabledFileName,UI_TEX_TYPE_PLIST); + } + else + { + button->loadTextures(normalFileName_tp, pressedFileName_tp, disabledFileName_tp); + } + button->setCapInsets(CCRectMake(cx, cy, cw, ch)); + bool sw = DICTOOL->checkObjectExist_json(options, "scale9Width"); + bool sh = DICTOOL->checkObjectExist_json(options, "scale9Height"); + if (sw && sh) + { + float swf = DICTOOL->getFloatValue_json(options, "scale9Width"); + float shf = DICTOOL->getFloatValue_json(options, "scale9Height"); + button->setSize(CCSizeMake(swf, shf)); + } + } + else + { + if (useMergedTexture) + { + button->loadTextures(normalFileName, pressedFileName, disabledFileName,UI_TEX_TYPE_PLIST); + } + else + { + button->loadTextures(normalFileName_tp, pressedFileName_tp, disabledFileName_tp); + } + } + setColorPropsForWidgetFromJsonDictionary(widget,options); + } + else + { + setPropsForWidgetFromJsonDictionary(widget, options); + UIButton* button = (UIButton*)widget; + bool scale9Enable = DICTOOL->getBooleanValue_json(options, "scale9Enable"); + button->setScale9Enabled(scale9Enable); + + cs::JsonDictionary* normalDic = DICTOOL->getSubDictionary_json(options, "normalData"); + int normalType = DICTOOL->getIntValue_json(normalDic, "resourceType"); + switch (normalType) + { + case 0: + { + std::string tp_n = m_strFilePath; + const char* normalFileName = DICTOOL->getStringValue_json(normalDic, "path"); + const char* normalFileName_tp = (normalFileName && (strcmp(normalFileName, "") != 0))?tp_n.append(normalFileName).c_str():NULL; + button->loadTextureNormal(normalFileName_tp); + break; + } + case 1: + { + const char* normalFileName = DICTOOL->getStringValue_json(normalDic, "path"); + button->loadTextureNormal(normalFileName,UI_TEX_TYPE_PLIST); + break; + } + default: + break; + } + CC_SAFE_DELETE(normalDic); + cs::JsonDictionary* pressedDic = DICTOOL->getSubDictionary_json(options, "pressedData"); + int pressedType = DICTOOL->getIntValue_json(pressedDic, "resourceType"); + switch (pressedType) + { + case 0: + { + std::string tp_p = m_strFilePath; + const char* pressedFileName = DICTOOL->getStringValue_json(pressedDic, "path"); + const char* pressedFileName_tp = (pressedFileName && (strcmp(pressedFileName, "") != 0))?tp_p.append(pressedFileName).c_str():NULL; + button->loadTexturePressed(pressedFileName_tp); + break; + } + case 1: + { + const char* pressedFileName = DICTOOL->getStringValue_json(pressedDic, "path"); + button->loadTexturePressed(pressedFileName,UI_TEX_TYPE_PLIST); + break; + } + default: + break; + } + CC_SAFE_DELETE(pressedDic); + cs::JsonDictionary* disabledDic = DICTOOL->getSubDictionary_json(options, "disabledData"); + int disabledType = DICTOOL->getIntValue_json(disabledDic, "resourceType"); + switch (disabledType) + { + case 0: + { + std::string tp_d = m_strFilePath; + const char* disabledFileName = DICTOOL->getStringValue_json(disabledDic, "path"); + const char* disabledFileName_tp = (disabledFileName && (strcmp(disabledFileName, "") != 0))?tp_d.append(disabledFileName).c_str():NULL; + button->loadTextureDisabled(disabledFileName_tp); + break; + } + case 1: + { + const char* disabledFileName = DICTOOL->getStringValue_json(disabledDic, "path"); + button->loadTextureDisabled(disabledFileName,UI_TEX_TYPE_PLIST); + break; + } + default: + break; + } + CC_SAFE_DELETE(disabledDic); + if (scale9Enable) + { + float cx = DICTOOL->getFloatValue_json(options, "capInsetsX"); + float cy = DICTOOL->getFloatValue_json(options, "capInsetsY"); + float cw = DICTOOL->getFloatValue_json(options, "capInsetsWidth"); + float ch = DICTOOL->getFloatValue_json(options, "capInsetsHeight"); + + button->setCapInsets(CCRectMake(cx, cy, cw, ch)); + bool sw = DICTOOL->checkObjectExist_json(options, "scale9Width"); + bool sh = DICTOOL->checkObjectExist_json(options, "scale9Height"); + if (sw && sh) + { + float swf = DICTOOL->getFloatValue_json(options, "scale9Width"); + float shf = DICTOOL->getFloatValue_json(options, "scale9Height"); + button->setSize(CCSizeMake(swf, shf)); + } + } + setColorPropsForWidgetFromJsonDictionary(widget,options); + } +} + +void CCSGUIReader::setPropsForCheckBoxFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options) +{ + if (m_bOlderVersion) + { + setPropsForWidgetFromJsonDictionary(widget, options); + UICheckBox* checkBox = (UICheckBox*)widget; + const char* backGroundFileName = DICTOOL->getStringValue_json(options, "backGroundBox"); + const char* backGroundSelectedFileName = DICTOOL->getStringValue_json(options, "backGroundBoxSelected"); + const char* frontCrossFileName = DICTOOL->getStringValue_json(options, "frontCross"); + const char* backGroundDisabledFileName = DICTOOL->getStringValue_json(options, "backGroundBoxDisabled"); + const char* frontCrossDisabledFileName = DICTOOL->getStringValue_json(options, "frontCrossDisabled"); + + + std::string tp_b = m_strFilePath; + std::string tp_bs = m_strFilePath; + std::string tp_c = m_strFilePath; + std::string tp_bd = m_strFilePath; + std::string tp_cd = m_strFilePath; + + const char* backGroundFileName_tp = (backGroundFileName && (strcmp(backGroundFileName, "") != 0))?tp_b.append(backGroundFileName).c_str():NULL; + const char* backGroundSelectedFileName_tp = (backGroundSelectedFileName && (strcmp(backGroundSelectedFileName, "") != 0))?tp_bs.append(backGroundSelectedFileName).c_str():NULL; + const char* frontCrossFileName_tp = (frontCrossFileName && (strcmp(frontCrossFileName, "") != 0))?tp_c.append(frontCrossFileName).c_str():NULL; + const char* backGroundDisabledFileName_tp = (backGroundDisabledFileName && (strcmp(backGroundDisabledFileName, "") != 0))?tp_bd.append(backGroundDisabledFileName).c_str():NULL; + const char* frontCrossDisabledFileName_tp = (frontCrossDisabledFileName && (strcmp(frontCrossDisabledFileName, "") != 0))?tp_cd.append(frontCrossDisabledFileName).c_str():NULL; + bool useMergedTexture = DICTOOL->getBooleanValue_json(options, "useMergedTexture"); + + if (useMergedTexture) + { + checkBox->loadTextures(backGroundFileName, backGroundSelectedFileName, frontCrossFileName,backGroundDisabledFileName,frontCrossDisabledFileName,UI_TEX_TYPE_PLIST); + } + else + { + checkBox->loadTextures(backGroundFileName_tp, backGroundSelectedFileName_tp, frontCrossFileName_tp,backGroundDisabledFileName_tp,frontCrossDisabledFileName_tp); + } + + setColorPropsForWidgetFromJsonDictionary(widget,options); + } + else + { + setPropsForWidgetFromJsonDictionary(widget, options); + UICheckBox* checkBox = (UICheckBox*)widget; + + cs::JsonDictionary* backGroundDic = DICTOOL->getSubDictionary_json(options, "backGroundBoxData"); + int backGroundType = DICTOOL->getIntValue_json(backGroundDic, "resourceType"); + switch (backGroundType) + { + case 0: + { + std::string tp_b = m_strFilePath; + const char* backGroundFileName = DICTOOL->getStringValue_json(backGroundDic, "path"); + const char* backGroundFileName_tp = (backGroundFileName && (strcmp(backGroundFileName, "") != 0))?tp_b.append(backGroundFileName).c_str():NULL; + checkBox->loadTextureBackGround(backGroundFileName_tp); + break; + } + case 1: + { + const char* backGroundFileName = DICTOOL->getStringValue_json(backGroundDic, "path"); + checkBox->loadTextureBackGround(backGroundFileName,UI_TEX_TYPE_PLIST); + break; + } + default: + break; + } + CC_SAFE_DELETE(backGroundDic); + + cs::JsonDictionary* backGroundSelectedDic = DICTOOL->getSubDictionary_json(options, "backGroundBoxSelectedData"); + int backGroundSelectedType = DICTOOL->getIntValue_json(backGroundSelectedDic, "resourceType"); + switch (backGroundSelectedType) + { + case 0: + { + std::string tp_bs = m_strFilePath; + const char* backGroundSelectedFileName = DICTOOL->getStringValue_json(backGroundSelectedDic, "path"); + const char* backGroundSelectedFileName_tp = (backGroundSelectedFileName && (strcmp(backGroundSelectedFileName, "") != 0))?tp_bs.append(backGroundSelectedFileName).c_str():NULL; + checkBox->loadTextureBackGroundSelected(backGroundSelectedFileName_tp); + break; + } + case 1: + { + const char* backGroundSelectedFileName = DICTOOL->getStringValue_json(backGroundSelectedDic, "path"); + checkBox->loadTextureBackGroundSelected(backGroundSelectedFileName,UI_TEX_TYPE_PLIST); + break; + } + default: + break; + } + CC_SAFE_DELETE(backGroundSelectedDic); + + cs::JsonDictionary* frontCrossDic = DICTOOL->getSubDictionary_json(options, "frontCrossData"); + int frontCrossType = DICTOOL->getIntValue_json(frontCrossDic, "resourceType"); + switch (frontCrossType) + { + case 0: + { + std::string tp_c = m_strFilePath; + const char* frontCrossFileName = DICTOOL->getStringValue_json(frontCrossDic, "path"); + const char* frontCrossFileName_tp = (frontCrossFileName && (strcmp(frontCrossFileName, "") != 0))?tp_c.append(frontCrossFileName).c_str():NULL; + checkBox->loadTextureFrontCross(frontCrossFileName_tp); + break; + } + case 1: + { + const char* frontCrossFileName = DICTOOL->getStringValue_json(frontCrossDic, "path"); + checkBox->loadTextureFrontCross(frontCrossFileName,UI_TEX_TYPE_PLIST); + break; + } + default: + break; + } + CC_SAFE_DELETE(frontCrossDic); + + cs::JsonDictionary* backGroundDisabledDic = DICTOOL->getSubDictionary_json(options, "backGroundBoxDisabledData"); + int backGroundDisabledType = DICTOOL->getIntValue_json(backGroundDisabledDic, "resourceType"); + switch (backGroundDisabledType) + { + case 0: + { + std::string tp_bd = m_strFilePath; + const char* backGroundDisabledFileName = DICTOOL->getStringValue_json(backGroundDisabledDic, "path"); + const char* backGroundDisabledFileName_tp = (backGroundDisabledFileName && (strcmp(backGroundDisabledFileName, "") != 0))?tp_bd.append(backGroundDisabledFileName).c_str():NULL; + checkBox->loadTextureBackGroundDisabled(backGroundDisabledFileName_tp); + break; + } + case 1: + { + const char* backGroundDisabledFileName = DICTOOL->getStringValue_json(backGroundDisabledDic, "path"); + checkBox->loadTextureBackGroundDisabled(backGroundDisabledFileName,UI_TEX_TYPE_PLIST); + break; + } + default: + break; + } + CC_SAFE_DELETE(backGroundDisabledDic); + + cs::JsonDictionary* frontCrossDisabledDic = DICTOOL->getSubDictionary_json(options, "frontCrossDisabledData"); + int frontCrossDisabledType = DICTOOL->getIntValue_json(frontCrossDisabledDic, "resourceType"); + switch (frontCrossDisabledType) + { + case 0: + { + std::string tp_cd = m_strFilePath; + const char* frontCrossDisabledFileName = DICTOOL->getStringValue_json(options, "path"); + const char* frontCrossDisabledFileName_tp = (frontCrossDisabledFileName && (strcmp(frontCrossDisabledFileName, "") != 0))?tp_cd.append(frontCrossDisabledFileName).c_str():NULL; + checkBox->loadTextureFrontCrossDisabled(frontCrossDisabledFileName_tp); + break; + } + case 1: + { + const char* frontCrossDisabledFileName = DICTOOL->getStringValue_json(options, "path"); + checkBox->loadTextureFrontCrossDisabled(frontCrossDisabledFileName,UI_TEX_TYPE_PLIST); + break; + } + default: + break; + } + CC_SAFE_DELETE(frontCrossDisabledDic); + + setColorPropsForWidgetFromJsonDictionary(widget,options); + } +} + +void CCSGUIReader::setPropsForImageViewFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options) +{ + if (m_bOlderVersion) + { + setPropsForWidgetFromJsonDictionary(widget, options); + + UIImageView* imageView = (UIImageView*)widget; + const char* imageFileName = DICTOOL->getStringValue_json(options, "fileName"); + bool scale9EnableExist = DICTOOL->checkObjectExist_json(options, "scale9Enable"); + bool scale9Enable = false; + if (scale9EnableExist) + { + scale9Enable = DICTOOL->getBooleanValue_json(options, "scale9Enable"); + } + imageView->setScale9Enabled(scale9Enable); + + std::string tp_i = m_strFilePath; + const char* imageFileName_tp = NULL; + if (imageFileName && (strcmp(imageFileName, "") != 0)) + { + imageFileName_tp = tp_i.append(imageFileName).c_str(); + } + + bool useMergedTexture = DICTOOL->getBooleanValue_json(options, "useMergedTexture"); + if (scale9Enable) + { + if (useMergedTexture) + { + imageView->loadTexture(imageFileName,UI_TEX_TYPE_PLIST); + } + else + { + imageView->loadTexture(imageFileName_tp); + } + + bool sw = DICTOOL->checkObjectExist_json(options, "scale9Width"); + bool sh = DICTOOL->checkObjectExist_json(options, "scale9Height"); + if (sw && sh) + { + float swf = DICTOOL->getFloatValue_json(options, "scale9Width"); + float shf = DICTOOL->getFloatValue_json(options, "scale9Height"); + imageView->setSize(CCSizeMake(swf, shf)); + } + + float cx = DICTOOL->getFloatValue_json(options, "capInsetsX"); + float cy = DICTOOL->getFloatValue_json(options, "capInsetsY"); + float cw = DICTOOL->getFloatValue_json(options, "capInsetsWidth"); + float ch = DICTOOL->getFloatValue_json(options, "capInsetsHeight"); + imageView->setCapInsets(CCRectMake(cx, cy, cw, ch)); + + } + else + { + if (useMergedTexture) + { + imageView->loadTexture(imageFileName,UI_TEX_TYPE_PLIST); + } + else + { + imageView->loadTexture(imageFileName_tp); + } + } + setColorPropsForWidgetFromJsonDictionary(widget,options); + } + else + { + setPropsForWidgetFromJsonDictionary(widget, options); + + UIImageView* imageView = (UIImageView*)widget; + + cs::JsonDictionary* imageFileNameDic = DICTOOL->getSubDictionary_json(options, "fileNameData"); + int imageFileNameType = DICTOOL->getIntValue_json(imageFileNameDic, "resourceType"); + switch (imageFileNameType) + { + case 0: + { + std::string tp_i = m_strFilePath; + const char* imageFileName = DICTOOL->getStringValue_json(imageFileNameDic, "path"); + const char* imageFileName_tp = NULL; + if (imageFileName && (strcmp(imageFileName, "") != 0)) + { + imageFileName_tp = tp_i.append(imageFileName).c_str(); + imageView->loadTexture(imageFileName_tp); + } + break; + } + case 1: + { + const char* imageFileName = DICTOOL->getStringValue_json(imageFileNameDic, "path"); + imageView->loadTexture(imageFileName,UI_TEX_TYPE_PLIST); + break; + } + default: + break; + } + CC_SAFE_DELETE(imageFileNameDic); + + bool scale9EnableExist = DICTOOL->checkObjectExist_json(options, "scale9Enable"); + bool scale9Enable = false; + if (scale9EnableExist) + { + scale9Enable = DICTOOL->getBooleanValue_json(options, "scale9Enable"); + } + imageView->setScale9Enabled(scale9Enable); + + + if (scale9Enable) + { + bool sw = DICTOOL->checkObjectExist_json(options, "scale9Width"); + bool sh = DICTOOL->checkObjectExist_json(options, "scale9Height"); + if (sw && sh) + { + float swf = DICTOOL->getFloatValue_json(options, "scale9Width"); + float shf = DICTOOL->getFloatValue_json(options, "scale9Height"); + imageView->setSize(CCSizeMake(swf, shf)); + } + + float cx = DICTOOL->getFloatValue_json(options, "capInsetsX"); + float cy = DICTOOL->getFloatValue_json(options, "capInsetsY"); + float cw = DICTOOL->getFloatValue_json(options, "capInsetsWidth"); + float ch = DICTOOL->getFloatValue_json(options, "capInsetsHeight"); + + imageView->setCapInsets(CCRectMake(cx, cy, cw, ch)); + + } + setColorPropsForWidgetFromJsonDictionary(widget,options); + } +} + +void CCSGUIReader::setPropsForLabelFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options) +{ + setPropsForWidgetFromJsonDictionary(widget, options); + UILabel* label = (UILabel*)widget; + bool touchScaleChangeAble = DICTOOL->getBooleanValue_json(options, "touchScaleEnable"); + label->setTouchScaleChangeAble(touchScaleChangeAble); + const char* text = DICTOOL->getStringValue_json(options, "text"); + label->setText(text); + bool fs = DICTOOL->checkObjectExist_json(options, "fontSize"); + if (fs) + { + label->setFontSize(DICTOOL->getIntValue_json(options, "fontSize")); + } + bool fn = DICTOOL->checkObjectExist_json(options, "fontName"); + if (fn) + { + label->setFontName(DICTOOL->getStringValue_json(options, "fontName")); + } + bool cro = DICTOOL->checkObjectExist_json(options, "colorR"); + bool cgo = DICTOOL->checkObjectExist_json(options, "colorG"); + bool cbo = DICTOOL->checkObjectExist_json(options, "colorB"); + int cr = cro?DICTOOL->getIntValue_json(options, "colorR"):255; + int cg = cgo?DICTOOL->getIntValue_json(options, "colorG"):255; + int cb = cbo?DICTOOL->getIntValue_json(options, "colorB"):255; + ccColor3B tc = ccc3(cr, cg, cb); + label->setColor(tc); + setColorPropsForWidgetFromJsonDictionary(widget,options); +} + +void CCSGUIReader::setPropsForLabelAtlasFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options) +{ + if (m_bOlderVersion) + { + setPropsForWidgetFromJsonDictionary(widget, options); + UILabelAtlas* labelAtlas = (UILabelAtlas*)widget; + bool sv = DICTOOL->checkObjectExist_json(options, "stringValue"); + bool cmf = DICTOOL->checkObjectExist_json(options, "charMapFile"); + bool iw = DICTOOL->checkObjectExist_json(options, "itemWidth"); + bool ih = DICTOOL->checkObjectExist_json(options, "itemHeight"); + bool scm = DICTOOL->checkObjectExist_json(options, "startCharMap"); + if (sv && cmf && iw && ih && scm && (strcmp(DICTOOL->getStringValue_json(options, "charMapFile"), "") != 0)) + { + std::string tp_c = m_strFilePath; + const char* cmf_tp = NULL; + const char* cmft = DICTOOL->getStringValue_json(options, "charMapFile"); + cmf_tp = tp_c.append(cmft).c_str(); + + labelAtlas->setProperty(DICTOOL->getStringValue_json(options, "stringValue"),cmf_tp,DICTOOL->getIntValue_json(options, "itemWidth"),DICTOOL->getIntValue_json(options,"itemHeight"),DICTOOL->getStringValue_json(options, "startCharMap")); + } + setColorPropsForWidgetFromJsonDictionary(widget,options); + } + else + { + setPropsForWidgetFromJsonDictionary(widget, options); + UILabelAtlas* labelAtlas = (UILabelAtlas*)widget; + bool sv = DICTOOL->checkObjectExist_json(options, "stringValue"); + bool cmf = DICTOOL->checkObjectExist_json(options, "charMapFile"); + bool iw = DICTOOL->checkObjectExist_json(options, "itemWidth"); + bool ih = DICTOOL->checkObjectExist_json(options, "itemHeight"); + bool scm = DICTOOL->checkObjectExist_json(options, "startCharMap"); + if (sv && cmf && iw && ih && scm) + { + + cs::JsonDictionary* cmftDic = DICTOOL->getSubDictionary_json(options, "charMapFileData"); + int cmfType = DICTOOL->getIntValue_json(cmftDic, "resourceType"); + switch (cmfType) + { + case 0: + { + std::string tp_c = m_strFilePath; + const char* cmfPath = DICTOOL->getStringValue_json(cmftDic, "path"); + const char* cmf_tp = tp_c.append(cmfPath).c_str(); + labelAtlas->setProperty(DICTOOL->getStringValue_json(options, "stringValue"),cmf_tp,DICTOOL->getIntValue_json(options, "itemWidth"),DICTOOL->getIntValue_json(options,"itemHeight"),DICTOOL->getStringValue_json(options, "startCharMap")); + break; + } + case 1: + CCLOG("Wrong res type of LabelAtlas!"); + break; + default: + break; + } + CC_SAFE_DELETE(cmftDic); + } + setColorPropsForWidgetFromJsonDictionary(widget,options); + } +} + +void CCSGUIReader::setPropsForContainerWidgetFromJsonDictionary(UIWidget *widget, cs::JsonDictionary *options) +{ + setPropsForWidgetFromJsonDictionary(widget, options); + Layout* containerWidget = (Layout*)widget; + if (!dynamic_cast(containerWidget) + && !dynamic_cast(containerWidget) + && !dynamic_cast(containerWidget)) + { + containerWidget->setClippingEnabled(DICTOOL->getBooleanValue_json(options, "clipAble")); + } + setColorPropsForWidgetFromJsonDictionary(widget,options); +} + +void CCSGUIReader::setPropsForPanelFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options) +{ + if (m_bOlderVersion) + { + setPropsForContainerWidgetFromJsonDictionary(widget, options); + Layout* panel = (Layout*)widget; + bool backGroundScale9Enable = DICTOOL->getBooleanValue_json(options, "backGroundScale9Enable"); + panel->setBackGroundImageScale9Enabled(backGroundScale9Enable); + int cr = DICTOOL->getIntValue_json(options, "bgColorR"); + int cg = DICTOOL->getIntValue_json(options, "bgColorG"); + int cb = DICTOOL->getIntValue_json(options, "bgColorB"); + + int scr = DICTOOL->getIntValue_json(options, "bgStartColorR"); + int scg = DICTOOL->getIntValue_json(options, "bgStartColorG"); + int scb = DICTOOL->getIntValue_json(options, "bgStartColorB"); + + int ecr = DICTOOL->getIntValue_json(options, "bgEndColorR"); + int ecg = DICTOOL->getIntValue_json(options, "bgEndColorG"); + int ecb = DICTOOL->getIntValue_json(options, "bgEndColorB"); + + float bgcv1 = DICTOOL->getFloatValue_json(options, "vectorX"); + float bgcv2 = DICTOOL->getFloatValue_json(options, "vectorY"); + panel->setBackGroundColorVector(ccp(bgcv1, bgcv2)); + + int co = DICTOOL->getIntValue_json(options, "bgColorOpacity"); + + int colorType = DICTOOL->getIntValue_json(options, "colorType"); + panel->setBackGroundColorType(LayoutBackGroundColorType(colorType)); +// float w = DICTOOL->getFloatValue_json(options, "width"); +// float h = DICTOOL->getFloatValue_json(options, "height"); + panel->setBackGroundColor(ccc3(scr, scg, scb),ccc3(ecr, ecg, ecb)); + panel->setBackGroundColor(ccc3(cr, cg, cb)); + panel->setBackGroundColorOpacity(co); +// panel->setSize(CCSizeMake(w, h)); + + std::string tp_b = m_strFilePath; + const char* imageFileName = DICTOOL->getStringValue_json(options, "backGroundImage"); + const char* imageFileName_tp = (imageFileName && (strcmp(imageFileName, "") != 0))?tp_b.append(imageFileName).c_str():NULL; + bool useMergedTexture = DICTOOL->getBooleanValue_json(options, "useMergedTexture"); + if (backGroundScale9Enable) + { + float cx = DICTOOL->getFloatValue_json(options, "capInsetsX"); + float cy = DICTOOL->getFloatValue_json(options, "capInsetsY"); + float cw = DICTOOL->getFloatValue_json(options, "capInsetsWidth"); + float ch = DICTOOL->getFloatValue_json(options, "capInsetsHeight"); + if (useMergedTexture) + { + panel->setBackGroundImage(imageFileName,UI_TEX_TYPE_PLIST); + } + else + { + panel->setBackGroundImage(imageFileName_tp); + } + panel->setBackGroundImageCapInsets(CCRectMake(cx, cy, cw, ch)); + } + else + { + + if (useMergedTexture) + { + panel->setBackGroundImage(imageFileName,UI_TEX_TYPE_PLIST); + } + else + { + panel->setBackGroundImage(imageFileName_tp); + } + } + setColorPropsForWidgetFromJsonDictionary(widget,options); + } + else + { + setPropsForContainerWidgetFromJsonDictionary(widget, options); + Layout* panel = (Layout*)widget; + bool backGroundScale9Enable = DICTOOL->getBooleanValue_json(options, "backGroundScale9Enable"); + panel->setBackGroundImageScale9Enabled(backGroundScale9Enable); + int cr = DICTOOL->getIntValue_json(options, "bgColorR"); + int cg = DICTOOL->getIntValue_json(options, "bgColorG"); + int cb = DICTOOL->getIntValue_json(options, "bgColorB"); + + int scr = DICTOOL->getIntValue_json(options, "bgStartColorR"); + int scg = DICTOOL->getIntValue_json(options, "bgStartColorG"); + int scb = DICTOOL->getIntValue_json(options, "bgStartColorB"); + + int ecr = DICTOOL->getIntValue_json(options, "bgEndColorR"); + int ecg = DICTOOL->getIntValue_json(options, "bgEndColorG"); + int ecb = DICTOOL->getIntValue_json(options, "bgEndColorB"); + + float bgcv1 = DICTOOL->getFloatValue_json(options, "vectorX"); + float bgcv2 = DICTOOL->getFloatValue_json(options, "vectorY"); + panel->setBackGroundColorVector(ccp(bgcv1, bgcv2)); + + int co = DICTOOL->getIntValue_json(options, "bgColorOpacity"); + + int colorType = DICTOOL->getIntValue_json(options, "colorType"); + panel->setBackGroundColorType(LayoutBackGroundColorType(colorType)); +// float w = DICTOOL->getFloatValue_json(options, "width"); +// float h = DICTOOL->getFloatValue_json(options, "height"); + panel->setBackGroundColor(ccc3(scr, scg, scb),ccc3(ecr, ecg, ecb)); + panel->setBackGroundColor(ccc3(cr, cg, cb)); + panel->setBackGroundColorOpacity(co); +// panel->setSize(CCSizeMake(w, h)); + + + cs::JsonDictionary* imageFileNameDic = DICTOOL->getSubDictionary_json(options, "backGroundImageData"); + int imageFileNameType = DICTOOL->getIntValue_json(imageFileNameDic, "resourceType"); + switch (imageFileNameType) + { + case 0: + { + std::string tp_b = m_strFilePath; + const char* imageFileName = DICTOOL->getStringValue_json(imageFileNameDic, "path"); + const char* imageFileName_tp = (imageFileName && (strcmp(imageFileName, "") != 0))?tp_b.append(imageFileName).c_str():NULL; + panel->setBackGroundImage(imageFileName_tp); + break; + } + case 1: + { + const char* imageFileName = DICTOOL->getStringValue_json(imageFileNameDic, "path"); + panel->setBackGroundImage(imageFileName,UI_TEX_TYPE_PLIST); + break; + } + default: + break; + } + CC_SAFE_DELETE(imageFileNameDic); + + if (backGroundScale9Enable) + { + float cx = DICTOOL->getFloatValue_json(options, "capInsetsX"); + float cy = DICTOOL->getFloatValue_json(options, "capInsetsY"); + float cw = DICTOOL->getFloatValue_json(options, "capInsetsWidth"); + float ch = DICTOOL->getFloatValue_json(options, "capInsetsHeight"); + panel->setBackGroundImageCapInsets(CCRectMake(cx, cy, cw, ch)); + } + setColorPropsForWidgetFromJsonDictionary(widget,options); + } +} + +void CCSGUIReader::setPropsForScrollViewFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options) +{ + setPropsForPanelFromJsonDictionary(widget, options); + UIScrollView* scrollView = (UIScrollView*)widget; + float innerWidth = DICTOOL->getFloatValue_json(options, "innerWidth"); + float innerHeight = DICTOOL->getFloatValue_json(options, "innerHeight"); + scrollView->setInnerContainerSize(CCSizeMake(innerWidth, innerHeight)); + /* gui mark */ + int direction = DICTOOL->getFloatValue_json(options, "direction"); + scrollView->setDirection((SCROLLVIEW_DIR)direction); + /**/ + setColorPropsForWidgetFromJsonDictionary(widget,options); +} + +void CCSGUIReader::setPropsForSliderFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options) +{ + if (m_bOlderVersion) + { + setPropsForWidgetFromJsonDictionary(widget, options); + UISlider* slider = (UISlider*)widget; + + bool barTextureScale9Enable = DICTOOL->getBooleanValue_json(options, "barTextureScale9Enable"); + slider->setScale9Enabled(barTextureScale9Enable); + bool bt = DICTOOL->checkObjectExist_json(options, "barFileName"); + float barLength = DICTOOL->getFloatValue_json(options, "length"); + bool useMergedTexture = DICTOOL->getBooleanValue_json(options, "useMergedTexture"); + if (bt) + { + if (barTextureScale9Enable) + { + std::string tp_b = m_strFilePath; + const char* imageFileName = DICTOOL->getStringValue_json(options, "barFileName"); + const char* imageFileName_tp = (imageFileName && (strcmp(imageFileName, "") != 0))?tp_b.append(imageFileName).c_str():NULL; + if (useMergedTexture) + { + slider->loadBarTexture(imageFileName,UI_TEX_TYPE_PLIST); + } + else + { + slider->loadBarTexture(imageFileName_tp); + } + slider->setSize(CCSizeMake(barLength, slider->getContentSize().height)); + } + else + { + std::string tp_b = m_strFilePath; + const char* imageFileName = DICTOOL->getStringValue_json(options, "barFileName"); + const char* imageFileName_tp = (imageFileName && (strcmp(imageFileName, "") != 0))?tp_b.append(imageFileName).c_str():NULL; + if (useMergedTexture) + { + slider->loadBarTexture(imageFileName,UI_TEX_TYPE_PLIST); + } + else + { + slider->loadBarTexture(imageFileName_tp); + } + } + } + std::string tp_n = m_strFilePath; + std::string tp_p = m_strFilePath; + std::string tp_d = m_strFilePath; + + const char* normalFileName = DICTOOL->getStringValue_json(options, "ballNormal"); + const char* pressedFileName = DICTOOL->getStringValue_json(options, "ballPressed"); + const char* disabledFileName = DICTOOL->getStringValue_json(options, "ballDisabled"); + + const char* normalFileName_tp = (normalFileName && (strcmp(normalFileName, "") != 0))?tp_n.append(normalFileName).c_str():NULL; + const char* pressedFileName_tp = (pressedFileName && (strcmp(pressedFileName, "") != 0))?tp_p.append(pressedFileName).c_str():NULL; + const char* disabledFileName_tp = (disabledFileName && (strcmp(disabledFileName, "") != 0))?tp_d.append(disabledFileName).c_str():NULL; + if (useMergedTexture) + { + slider->loadSlidBallTextures(normalFileName,pressedFileName,disabledFileName,UI_TEX_TYPE_PLIST); + } + else + { + slider->loadSlidBallTextures(normalFileName_tp,pressedFileName_tp,disabledFileName_tp); + } + slider->setPercent(DICTOOL->getIntValue_json(options, "percent")); + + std::string tp_b = m_strFilePath; + const char* imageFileName = DICTOOL->getStringValue_json(options, "progressBarFileName"); + const char* imageFileName_tp = (imageFileName && (strcmp(imageFileName, "") != 0))?tp_b.append(imageFileName).c_str():NULL; + if (useMergedTexture) + { + slider->loadProgressBarTexture(imageFileName, UI_TEX_TYPE_PLIST); + } + else + { + slider->loadProgressBarTexture(imageFileName_tp); + } + setColorPropsForWidgetFromJsonDictionary(widget,options); + } + else + { + setPropsForWidgetFromJsonDictionary(widget, options); + UISlider* slider = (UISlider*)widget; + + bool barTextureScale9Enable = DICTOOL->getBooleanValue_json(options, "barTextureScale9Enable"); + slider->setScale9Enabled(barTextureScale9Enable); + bool bt = DICTOOL->checkObjectExist_json(options, "barFileName"); + float barLength = DICTOOL->getFloatValue_json(options, "length"); + if (bt) + { + if (barTextureScale9Enable) + { + + cs::JsonDictionary* imageFileNameDic = DICTOOL->getSubDictionary_json(options, "barFileNameData"); + int imageFileType = DICTOOL->getIntValue_json(imageFileNameDic, "resourceType"); + switch (imageFileType) + { + case 0: + { + std::string tp_b = m_strFilePath; + const char* imageFileName = DICTOOL->getStringValue_json(imageFileNameDic, "path"); + const char* imageFileName_tp = (imageFileName && (strcmp(imageFileName, "") != 0))?tp_b.append(imageFileName).c_str():NULL; + slider->loadBarTexture(imageFileName_tp); + break; + } + case 1: + { + const char* imageFileName = DICTOOL->getStringValue_json(imageFileNameDic, "path"); + slider->loadBarTexture(imageFileName,UI_TEX_TYPE_PLIST); + break; + } + default: + break; + } + + slider->setSize(CCSizeMake(barLength, slider->getContentSize().height)); + CC_SAFE_DELETE(imageFileNameDic); + } + else + { + cs::JsonDictionary* imageFileNameDic = DICTOOL->getSubDictionary_json(options, "barFileNameData"); + int imageFileType = DICTOOL->getIntValue_json(imageFileNameDic, "resourceType"); + switch (imageFileType) + { + case 0: + { + std::string tp_b = m_strFilePath; + const char*imageFileName = DICTOOL->getStringValue_json(imageFileNameDic, "path"); + const char* imageFileName_tp = (imageFileName && (strcmp(imageFileName, "") != 0))?tp_b.append(imageFileName).c_str():NULL; + slider->loadBarTexture(imageFileName_tp); + break; + } + case 1: + { + const char*imageFileName = DICTOOL->getStringValue_json(imageFileNameDic, "path"); + slider->loadBarTexture(imageFileName,UI_TEX_TYPE_PLIST); + break; + } + default: + break; + } + CC_SAFE_DELETE(imageFileNameDic); + } + } +// std::string tp_n = m_strFilePath; +// std::string tp_p = m_strFilePath; +// std::string tp_d = m_strFilePath; +// +// const char* normalFileName = DICTOOL->getStringValue_json(options, "ballNormal"); +// const char* pressedFileName = DICTOOL->getStringValue_json(options, "ballPressed"); +// const char* disabledFileName = DICTOOL->getStringValue_json(options, "ballDisabled"); +// +// const char* normalFileName_tp = (normalFileName && (strcmp(normalFileName, "") != 0))?tp_n.append(normalFileName).c_str():NULL; +// const char* pressedFileName_tp = (pressedFileName && (strcmp(pressedFileName, "") != 0))?tp_p.append(pressedFileName).c_str():NULL; +// const char* disabledFileName_tp = (disabledFileName && (strcmp(disabledFileName, "") != 0))?tp_d.append(disabledFileName).c_str():NULL; +// if (useMergedTexture) +// { +// slider->setSlidBallTextures(normalFileName,pressedFileName,disabledFileName,UI_TEX_TYPE_PLIST); +// } +// else +// { +// slider->setSlidBallTextures(normalFileName_tp,pressedFileName_tp,disabledFileName_tp); +// } + + cs::JsonDictionary* normalDic = DICTOOL->getSubDictionary_json(options, "ballNormalData"); + int normalType = DICTOOL->getIntValue_json(normalDic, "resourceType"); + switch (normalType) + { + case 0: + { + std::string tp_n = m_strFilePath; + const char* normalFileName = DICTOOL->getStringValue_json(normalDic, "path"); + const char* normalFileName_tp = (normalFileName && (strcmp(normalFileName, "") != 0))?tp_n.append(normalFileName).c_str():NULL; + slider->loadSlidBallTextureNormal(normalFileName_tp); + break; + } + case 1: + { + const char* normalFileName = DICTOOL->getStringValue_json(normalDic, "path"); + slider->loadSlidBallTextureNormal(normalFileName,UI_TEX_TYPE_PLIST); + break; + } + default: + break; + } + CC_SAFE_DELETE(normalDic); + + cs::JsonDictionary* pressedDic = DICTOOL->getSubDictionary_json(options, "ballPressedData"); + int pressedType = DICTOOL->getIntValue_json(pressedDic, "resourceType"); + switch (pressedType) + { + case 0: + { + std::string tp_p = m_strFilePath; + const char* pressedFileName = DICTOOL->getStringValue_json(pressedDic, "path"); + const char* pressedFileName_tp = (pressedFileName && (strcmp(pressedFileName, "") != 0))?tp_p.append(pressedFileName).c_str():NULL; + slider->loadSlidBallTexturePressed(pressedFileName_tp); + break; + } + case 1: + { + const char* pressedFileName = DICTOOL->getStringValue_json(pressedDic, "path"); + slider->loadSlidBallTexturePressed(pressedFileName,UI_TEX_TYPE_PLIST); + break; + } + default: + break; + } + CC_SAFE_DELETE(pressedDic); + + cs::JsonDictionary* disabledDic = DICTOOL->getSubDictionary_json(options, "ballDisabledData"); + int disabledType = DICTOOL->getIntValue_json(disabledDic, "resourceType"); + switch (disabledType) + { + case 0: + { + std::string tp_d = m_strFilePath; + const char* disabledFileName = DICTOOL->getStringValue_json(disabledDic, "path"); + const char* disabledFileName_tp = (disabledFileName && (strcmp(disabledFileName, "") != 0))?tp_d.append(disabledFileName).c_str():NULL; + slider->loadSlidBallTextureDisabled(disabledFileName_tp); + break; + } + case 1: + { + const char* disabledFileName = DICTOOL->getStringValue_json(disabledDic, "path"); + slider->loadSlidBallTextureDisabled(disabledFileName,UI_TEX_TYPE_PLIST); + break; + } + default: + break; + } + CC_SAFE_DELETE(disabledDic); + + slider->setPercent(DICTOOL->getIntValue_json(options, "percent")); + + cs::JsonDictionary* progressBarDic = DICTOOL->getSubDictionary_json(options, "progressBarData"); + int progressBarType = DICTOOL->getIntValue_json(progressBarDic, "resourceType"); + switch (progressBarType) + { + case 0: + { + std::string tp_b = m_strFilePath; + const char* imageFileName = DICTOOL->getStringValue_json(progressBarDic, "path"); + const char* imageFileName_tp = (imageFileName && (strcmp(imageFileName, "") != 0))?tp_b.append(imageFileName).c_str():NULL; + slider->loadProgressBarTexture(imageFileName_tp); + break; + } + case 1: + { + const char* imageFileName = DICTOOL->getStringValue_json(progressBarDic, "path"); + slider->loadProgressBarTexture(imageFileName,UI_TEX_TYPE_PLIST); + break; + } + default: + break; + } + setColorPropsForWidgetFromJsonDictionary(widget,options); + } +} + +void CCSGUIReader::setPropsForTextAreaFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options) +{ + setPropsForWidgetFromJsonDictionary(widget, options); + UILabel* textArea = (UILabel*)widget; + textArea->setText(DICTOOL->getStringValue_json(options, "text")); + bool fs = DICTOOL->checkObjectExist_json(options, "fontSize"); + if (fs) + { + textArea->setFontSize(DICTOOL->getIntValue_json(options, "fontSize")); + } + int cr = DICTOOL->getIntValue_json(options, "colorR"); + int cg = DICTOOL->getIntValue_json(options, "colorG"); + int cb = DICTOOL->getIntValue_json(options, "colorB"); + textArea->setColor(ccc3(cr, cg, cb)); + textArea->setFontName(DICTOOL->getStringValue_json(options, "fontName")); + bool aw = DICTOOL->checkObjectExist_json(options, "areaWidth"); + bool ah = DICTOOL->checkObjectExist_json(options, "areaHeight"); + if (aw && ah) + { + CCSize size = CCSize(DICTOOL->getFloatValue_json(options, "areaWidth"),DICTOOL->getFloatValue_json(options,"areaHeight")); + textArea->setTextAreaSize(size); + } + bool ha = DICTOOL->checkObjectExist_json(options, "hAlignment"); + if (ha) + { + textArea->setTextHorizontalAlignment((CCTextAlignment)DICTOOL->getIntValue_json(options, "hAlignment")); + } + bool va = DICTOOL->checkObjectExist_json(options, "vAlignment"); + if (va) + { + textArea->setTextVerticalAlignment((CCVerticalTextAlignment)DICTOOL->getIntValue_json(options, "vAlignment")); + } + setColorPropsForWidgetFromJsonDictionary(widget,options); +} + +void CCSGUIReader::setPropsForTextButtonFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options) +{ + setPropsForButtonFromJsonDictionary(widget, options); + + + UIButton* textButton = (UIButton*)widget; + textButton->setTitleText(DICTOOL->getStringValue_json(options, "text")); + bool cr = DICTOOL->checkObjectExist_json(options, "textColorR"); + bool cg = DICTOOL->checkObjectExist_json(options, "textColorG"); + bool cb = DICTOOL->checkObjectExist_json(options, "textColorB"); + int cri = cr?DICTOOL->getIntValue_json(options, "textColorR"):255; + int cgi = cg?DICTOOL->getIntValue_json(options, "textColorG"):255; + int cbi = cb?DICTOOL->getIntValue_json(options, "textColorB"):255; + textButton->setTitleColor(ccc3(cri,cgi,cbi)); + bool fs = DICTOOL->checkObjectExist_json(options, "fontSize"); + if (fs) + { + textButton->setTitleFontSize(DICTOOL->getIntValue_json(options, "fontSize")); + } + bool fn = DICTOOL->checkObjectExist_json(options, "fontName"); + if (fn) + { + textButton->setTitleFontName(DICTOOL->getStringValue_json(options, "fontName")); + } + setColorPropsForWidgetFromJsonDictionary(widget,options); +} + +void CCSGUIReader::setPropsForTextFieldFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options) +{ + setPropsForWidgetFromJsonDictionary(widget, options); + UITextField* textField = (UITextField*)widget; + bool ph = DICTOOL->checkObjectExist_json(options, "placeHolder"); + if (ph) + { + textField->setPlaceHolder(DICTOOL->getStringValue_json(options, "placeHolder")); + } + textField->setText(DICTOOL->getStringValue_json(options, "text")); + bool fs = DICTOOL->checkObjectExist_json(options, "fontSize"); + if (fs) + { + textField->setFontSize(DICTOOL->getIntValue_json(options, "fontSize")); + } + bool fn = DICTOOL->checkObjectExist_json(options, "fontName"); + if (fn) + { + textField->setFontName(DICTOOL->getStringValue_json(options, "fontName")); + } + bool tsw = DICTOOL->checkObjectExist_json(options, "touchSizeWidth"); + bool tsh = DICTOOL->checkObjectExist_json(options, "touchSizeHeight"); + if (tsw && tsh) + { + textField->setTouchSize(CCSizeMake(DICTOOL->getFloatValue_json(options, "touchSizeWidth"), DICTOOL->getFloatValue_json(options,"touchSizeHeight"))); + } + + float dw = DICTOOL->getFloatValue_json(options, "width"); + float dh = DICTOOL->getFloatValue_json(options, "height"); + if (dw > 0.0f || dh > 0.0f) + { + //textField->setSize(CCSizeMake(dw, dh)); + } + bool maxLengthEnable = DICTOOL->getBooleanValue_json(options, "maxLengthEnable"); + textField->setMaxLengthEnable(maxLengthEnable); + + if (maxLengthEnable) + { + int maxLength = DICTOOL->getIntValue_json(options, "maxLength"); + textField->setMaxLength(maxLength); + } + bool passwordEnable = DICTOOL->getBooleanValue_json(options, "passwordEnable"); + textField->setPasswordEnable(passwordEnable); + if (passwordEnable) + { + textField->setPasswordStyleText(DICTOOL->getStringValue_json(options, "passwordStyleText")); + } + setColorPropsForWidgetFromJsonDictionary(widget,options); +} + +void CCSGUIReader::setPropsForLoadingBarFromJsonDictionary(UIWidget *widget, cs::JsonDictionary *options) +{ + if (m_bOlderVersion) + { + setPropsForWidgetFromJsonDictionary(widget, options); + UILoadingBar* loadingBar = (UILoadingBar*)widget; + bool useMergedTexture = DICTOOL->getBooleanValue_json(options, "useMergedTexture"); + std::string tp_b = m_strFilePath; + const char*imageFileName = DICTOOL->getStringValue_json(options, "texture"); + const char* imageFileName_tp = (imageFileName && (strcmp(imageFileName, "") != 0))?tp_b.append(imageFileName).c_str():NULL; + if (useMergedTexture) + { + loadingBar->loadTexture(imageFileName,UI_TEX_TYPE_PLIST); + } + else + { + loadingBar->loadTexture(imageFileName_tp); + } + loadingBar->setDirection(LoadingBarType(DICTOOL->getIntValue_json(options, "direction"))); + loadingBar->setPercent(DICTOOL->getIntValue_json(options, "percent")); + setColorPropsForWidgetFromJsonDictionary(widget,options); + } + else + { + setPropsForWidgetFromJsonDictionary(widget, options); + UILoadingBar* loadingBar = (UILoadingBar*)widget; + + cs::JsonDictionary* imageFileNameDic = DICTOOL->getSubDictionary_json(options, "textureData"); + int imageFileNameType = DICTOOL->getIntValue_json(imageFileNameDic, "resourceType"); + switch (imageFileNameType) + { + case 0: + { + std::string tp_i = m_strFilePath; + const char* imageFileName = DICTOOL->getStringValue_json(imageFileNameDic, "path"); + const char* imageFileName_tp = NULL; + if (imageFileName && (strcmp(imageFileName, "") != 0)) + { + imageFileName_tp = tp_i.append(imageFileName).c_str(); + loadingBar->loadTexture(imageFileName_tp); + } + break; + } + case 1: + { + const char* imageFileName = DICTOOL->getStringValue_json(imageFileNameDic, "path"); + loadingBar->loadTexture(imageFileName,UI_TEX_TYPE_PLIST); + break; + } + default: + break; + } + CC_SAFE_DELETE(imageFileNameDic); + + /* gui mark add load bar scale9 parse */ + bool scale9Enable = DICTOOL->getBooleanValue_json(options, "scale9Enable"); + loadingBar->setScale9Enabled(scale9Enable); + + if (scale9Enable) + { + float cx = DICTOOL->getFloatValue_json(options, "capInsetsX"); + float cy = DICTOOL->getFloatValue_json(options, "capInsetsY"); + float cw = DICTOOL->getFloatValue_json(options, "capInsetsWidth"); + float ch = DICTOOL->getFloatValue_json(options, "capInsetsHeight"); + + loadingBar->setCapInsets(CCRectMake(cx, cy, cw, ch)); + + float width = DICTOOL->getFloatValue_json(options, "width"); + float height = DICTOOL->getFloatValue_json(options, "height"); + loadingBar->setSize(CCSizeMake(width, height)); + } + /**/ + + loadingBar->setDirection(LoadingBarType(DICTOOL->getIntValue_json(options, "direction"))); + loadingBar->setPercent(DICTOOL->getIntValue_json(options, "percent")); + setColorPropsForWidgetFromJsonDictionary(widget,options); + } +} + +void CCSGUIReader::setPropsForListViewFromJsonDictionary(UIWidget *widget, cs::JsonDictionary *options) +{ + setPropsForScrollViewFromJsonDictionary(widget, options); +} + +void CCSGUIReader::setPropsForPageViewFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options) +{ + setPropsForPanelFromJsonDictionary(widget, options); + setColorPropsForWidgetFromJsonDictionary(widget,options); +} + +void CCSGUIReader::setPropsForLabelBMFontFromJsonDictionary(UIWidget *widget, cs::JsonDictionary *options) +{ + if (m_bOlderVersion) + { + setPropsForWidgetFromJsonDictionary(widget, options); + + UILabelBMFont* labelBMFont = (UILabelBMFont*)widget; + + std::string tp_c = m_strFilePath; + const char* cmf_tp = NULL; + const char* cmft = DICTOOL->getStringValue_json(options, "fileName"); + cmf_tp = tp_c.append(cmft).c_str(); + + labelBMFont->setFntFile(cmf_tp); + + const char* text = DICTOOL->getStringValue_json(options, "text"); + labelBMFont->setText(text); + + setColorPropsForWidgetFromJsonDictionary(widget,options); + } + else + { + setPropsForWidgetFromJsonDictionary(widget, options); + + UILabelBMFont* labelBMFont = (UILabelBMFont*)widget; + + cs::JsonDictionary* cmftDic = DICTOOL->getSubDictionary_json(options, "fileNameData"); + int cmfType = DICTOOL->getIntValue_json(cmftDic, "resourceType"); + switch (cmfType) + { + case 0: + { + std::string tp_c = m_strFilePath; + const char* cmfPath = DICTOOL->getStringValue_json(cmftDic, "path"); + const char* cmf_tp = tp_c.append(cmfPath).c_str(); + labelBMFont->setFntFile(cmf_tp); + break; + } + case 1: + CCLOG("Wrong res type of LabelAtlas!"); + break; + default: + break; + } + CC_SAFE_DELETE(cmftDic); + + const char* text = DICTOOL->getStringValue_json(options, "text"); + labelBMFont->setText(text); + + setColorPropsForWidgetFromJsonDictionary(widget,options); + } +} + +void CCSGUIReader::setPropsForDragPanelFromJsonDictionary(UIWidget *widget, cs::JsonDictionary *options) +{ + setPropsForPanelFromJsonDictionary(widget, options); + + UIDragPanel* dragPanel = (UIDragPanel*)widget; + + bool bounceEnable = DICTOOL->getBooleanValue_json(options, "bounceEnable"); + dragPanel->setBounceEnable(bounceEnable); + + float innerWidth = DICTOOL->getFloatValue_json(options, "innerWidth"); + float innerHeight = DICTOOL->getFloatValue_json(options, "innerHeight"); + dragPanel->setInnerContainerSize(CCSizeMake(innerWidth, innerHeight)); + + setColorPropsForWidgetFromJsonDictionary(widget, options); +} + +NS_CC_EXT_END \ No newline at end of file diff --git a/extensions/CocoStudio/Reader/CCSGUIReader.h b/extensions/CocoStudio/Reader/CCSGUIReader.h new file mode 100755 index 0000000000..06867fd6c5 --- /dev/null +++ b/extensions/CocoStudio/Reader/CCSGUIReader.h @@ -0,0 +1,76 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __CCSGUIREADER_H__ +#define __CCSGUIREADER_H__ + +#include "../GUI/BaseClasses/UIWidget.h" +#include "../Json/CSContentJsonDictionary.h" + +NS_CC_EXT_BEGIN + +#define kCCSVersion 1.0 +class CCSGUIReader : CCObject +{ +public: + CCSGUIReader(); + ~CCSGUIReader(); + static CCSGUIReader* shareReader(); + static void purgeCCSGUIReader(); + + UIWidget* widgetFromJsonFile(const char* fileName); + UIWidget* widgetFromJsonDictionary(cs::JsonDictionary* data); + + int getVersionInteger(const char* str); + + void setPropsForWidgetFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options); + void setColorPropsForWidgetFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options); + void setPropsForButtonFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options); + void setPropsForCheckBoxFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options); + void setPropsForImageViewFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options); + void setPropsForLabelFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options); + void setPropsForLabelAtlasFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options); + void setPropsForContainerWidgetFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options); + void setPropsForPanelFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options); + void setPropsForScrollViewFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options); + void setPropsForSliderFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options); + void setPropsForTextAreaFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options); + void setPropsForTextButtonFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options); + void setPropsForTextFieldFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options); + void setPropsForLoadingBarFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options); + void setPropsForImageButtonFromJsonDictionary(UIWidget* widget, cs::JsonDictionary* options); + void setPropsForListViewFromJsonDictionary(UIWidget* widget, cs::JsonDictionary* options); + void setPropsForPageViewFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options); + void setPropsForLabelBMFontFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options); + void setPropsForDragPanelFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options); + +protected: + std::string m_strFilePath; + bool m_bOlderVersion; +}; + +NS_CC_EXT_END + + +#endif /* defined(__CCSGUIReader__) */