UIEditBox.h 23.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
/****************************************************************************
 Copyright (c) 2010-2012 cocos2d-x.org
 Copyright (c) 2012 James Chen
 Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
 
 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 __UIEDITTEXT_H__
#define __UIEDITTEXT_H__

#include "base/CCIMEDelegate.h"
#include "ui/GUIDefine.h"
#include "ui/UIWidget.h"
#include "ui/UIScale9Sprite.h"

NS_CC_BEGIN

/**
 * @addtogroup ui
 * @{
 */
namespace ui {

    class EditBox;
    class EditBoxImpl;

    /**
     *@brief Editbox delegate class.
     * It's useful when you want to do some customization during Editbox input event
     *
     * @js NA
     * @lua NA
     */
    class CC_GUI_DLL EditBoxDelegate
    {
    public:

        /**
         * Reason for ending edit (for platforms where it is known)
         */
        enum class EditBoxEndAction {
            UNKNOWN,
            TAB_TO_NEXT,
            TAB_TO_PREVIOUS,
            RETURN
        };

        virtual ~EditBoxDelegate() {}

        /**
         * This method is called when an edit box gains focus after keyboard is shown.
         * @param editBox The edit box object that generated the event.
         */
        virtual void editBoxEditingDidBegin(EditBox* /*editBox*/) {}

        /**
         * This method is called when the edit box text was changed.
         * @param editBox The edit box object that generated the event.
         * @param text The new text.
         */
        virtual void editBoxTextChanged(EditBox* /*editBox*/, const std::string& /*text*/) {}

        /**
         * This method is called when the return button was pressed or the outside area of keyboard was touched.
         * @param editBox The edit box object that generated the event.
         */
        virtual void editBoxReturn(EditBox* editBox) = 0;

        /**
         * This method is called when an edit box loses focus after keyboard is hidden.
         * @param editBox The edit box object that generated the event.
         * @param type The reason why editing ended.
         */
        virtual void editBoxEditingDidEndWithAction(EditBox* /*editBox*/, EditBoxEndAction /*action*/) {}
    };

    /**
     * @brief Class for edit box.
     *
     * You can use this widget to gather small amounts of text from the user.
     *
     */
    class CC_GUI_DLL EditBox
        : public Widget
        , public IMEDelegate
    {
    public:

        /**
         * The popup keyboard return type.
         */
        enum class KeyboardReturnType
        {
            DEFAULT,
            DONE,
            SEND,
            SEARCH,
            GO,
            NEXT
        };

        /**
         * @brief The EditBox::InputMode defines the type of text that the user is allowed
         * to enter.
         */
        enum class InputMode
        {
            /**
             * The user is allowed to enter any text, including line breaks.
             */
            ANY,

            /**
             * The user is allowed to enter an e-mail address.
             */
            EMAIL_ADDRESS,

            /**
             * The user is allowed to enter an integer value.
             */
            NUMERIC,

            /**
             * The user is allowed to enter a phone number.
             */
            PHONE_NUMBER,

            /**
             * The user is allowed to enter a URL.
             */
            URL,

            /**
             * The user is allowed to enter a real number value.
             * This extends kEditBoxInputModeNumeric by allowing a decimal point.
             */
            DECIMAL,

            /**
             * The user is allowed to enter any text, except for line breaks.
             */
            SINGLE_LINE,
        };

        /**
         * @brief The EditBox::InputFlag defines how the input text is displayed/formatted.
         */
        enum class InputFlag
        {
            /**
             * Indicates that the text entered is confidential data that should be
             * obscured whenever possible. This implies EDIT_BOX_INPUT_FLAG_SENSITIVE.
             */
            PASSWORD,

            /**
             * Indicates that the text entered is sensitive data that the
             * implementation must never store into a dictionary or table for use
             * in predictive, auto-completing, or other accelerated input schemes.
             * A credit card number is an example of sensitive data.
             */
            SENSITIVE,

            /**
             * This flag is a hint to the implementation that during text editing,
             * the initial letter of each word should be capitalized.
             */
            INITIAL_CAPS_WORD,

            /**
             * This flag is a hint to the implementation that during text editing,
             * the initial letter of each sentence should be capitalized.
             */
            INITIAL_CAPS_SENTENCE,

            /**
             * Capitalize all characters automatically.
             */
            INITIAL_CAPS_ALL_CHARACTERS,

            /**
             * Lowercase all characters automatically.
             */
            LOWERCASE_ALL_CHARACTERS
        };

        /**
         * create a edit box with size.
         * @return An autorelease pointer of EditBox, you don't need to release it only if you retain it again.
         */
        static EditBox* create(const Size& size,
                               Scale9Sprite* normalSprite,
                               Scale9Sprite* pressedSprite = nullptr,
                               Scale9Sprite* disabledSprite = nullptr);

        /**
         * create a edit box with size.
         * @return An autorelease pointer of EditBox, you don't need to release it only if you retain it again.
         */
        static EditBox* create(const Size& size,
                               const std::string& normalImage,
                               TextureResType texType);

        /**
         * create a edit box with size.
         * @return An autorelease pointer of EditBox, you don't need to release it only if you retain it again.
         */
        static EditBox* create(const Size& size,
                               const std::string& normalImage,
                               const std::string& pressedImage = "",
                               const std::string& disabledImage = "",
                               TextureResType texType = TextureResType::LOCAL);

        /**
         * Constructor.
         * @js ctor
         * @lua new
         */
        EditBox();

        /**
         * Destructor.
         * @js NA
         * @lua NA
         */
        virtual ~EditBox();

        /**
         * Init edit box with specified size. This method should be invoked right after constructor.
         * @param size The size of edit box.
         * @param normal9SpriteBg  background image of edit box.
         * @param texType the resource type, the default value is TextureResType::LOCAL
         * @return Whether initialization is successfully or not.
         */
        bool initWithSizeAndBackgroundSprite(const Size& size,
                                             const std::string& normal9SpriteBg,
                                             TextureResType texType = TextureResType::LOCAL);

        /**
         * Init edit box with specified size. This method should be invoked right after constructor.
         * @param size The size of edit box.
         * @param normal9SpriteBg  background image of edit box.
         * @return Whether initialization is successfully or not.
         */
        bool initWithSizeAndBackgroundSprite(const Size& size, Scale9Sprite* normal9SpriteBg);

        /**
         * Init edit box with specified size. This method should be invoked right after constructor.
         * @param size The size of edit box.
         * @param normalSprite  normal state image of edit box.
         * @param pressedSprite  pressed state image of edit box.
         * @param disabledSprite  disabled state image of edit box.
         * @return Whether initialization is successfully or not.
         */
        bool initWithSizeAndBackgroundSprite(const Size& size, Scale9Sprite* normalSprite, Scale9Sprite* pressedSprite, Scale9Sprite* disabledSprite);

        /**
         * Init edit box with specified size. This method should be invoked right after constructor.
         * @param size The size of edit box.
         * @param normalImage  normal state texture name.
         * @param pressedImage  pressed state texture name.
         * @param disabledImage  disabled state texture name.
         * @return Whether initialization is successfully or not.
         */
        bool initWithSizeAndTexture(const Size& size,
                                    const std::string& normalImage,
                                    const std::string& pressedImage = "",
                                    const std::string& disabledImage = "",
                                    TextureResType texType = TextureResType::LOCAL);

        /**
         * Load textures for edit box.
         *
         * @param normal    normal state texture name.
         * @param pressed    pressed state texture name.
         * @param disabled    disabled state texture name.
         * @param texType    @see `TextureResType`
         */
        void loadTextures(const std::string& normal,
                          const std::string& pressed,
                          const std::string& disabled = "",
                          TextureResType texType = TextureResType::LOCAL);

        /**
         * Load normal state texture for edit box.
         *
         * @param normal    normal state texture.
         * @param texType    @see `TextureResType`
         */
        void loadTextureNormal(const std::string& normal, TextureResType texType = TextureResType::LOCAL);

        /**
         * Load pressed state texture for edit box.
         *
         * @param pressed    pressed state texture.
         * @param texType    @see `TextureResType`
         */
        void loadTexturePressed(const std::string& pressed, TextureResType texType = TextureResType::LOCAL);

        /**
         * Load disabled state texture for edit box.
         *
         * @param disabled    dark state texture.
         * @param texType    @see `TextureResType`
         */
        void loadTextureDisabled(const std::string& disabled, TextureResType texType = TextureResType::LOCAL);

        /**
         * Sets capInsets for edit box.
         *
         * @param capInsets    capInset in Rect.
         */
        void setCapInsets(const Rect &capInsets);

        /**
         * Sets capInsets for edit box, only the normal state scale9 renderer will be affected.
         *
         * @param capInsets    capInsets in Rect.
         */
        void setCapInsetsNormalRenderer(const Rect &capInsets);

        /**
         * Return the capInsets of normal state scale9sprite.
         * @return The normal scale9 renderer capInsets.
         */
        const Rect& getCapInsetsNormalRenderer() const;

        /**
         * Sets capInsets for edit box, only the pressed state scale9 renderer will be affected.
         *
         * @param capInsets    capInsets in Rect
         */
        void setCapInsetsPressedRenderer(const Rect &capInsets);

        /**
         * Return the capInsets of pressed state scale9sprite.
         * @return The pressed scale9 renderer capInsets.
         */
        const Rect& getCapInsetsPressedRenderer() const;

        /**
         * Sets capInsets for edit box, only the disabled state scale9 renderer will be affected.
         *
         * @param capInsets  capInsets in Rect.
         */
        void setCapInsetsDisabledRenderer(const Rect &capInsets);

        /**
         * Return the capInsets of disabled state scale9sprite.
         * @return The disabled scale9 renderer capInsets.
         */
        const Rect& getCapInsetsDisabledRenderer() const;

        /**
         * Gets/Sets the delegate for edit box.
         * @lua NA
         */
        void setDelegate(EditBoxDelegate* delegate);

        /**
         * @js NA
         * @lua NA
         */
        EditBoxDelegate* getDelegate();

#if CC_ENABLE_SCRIPT_BINDING
        /**
         * Registers a script function that will be called for EditBox events.
         *
         * This handler will be removed automatically after onExit() called.
         * @code
         * -- lua sample
         * local function editboxEventHandler(eventType)
         *     if eventType == "began" then
         *         -- triggered when an edit box gains focus after keyboard is shown
         *     elseif eventType == "ended" then
         *         -- triggered when an edit box loses focus after keyboard is hidden.
         *     elseif eventType == "changed" then
         *         -- triggered when the edit box text was changed.
         *     elseif eventType == "return" then
         *         -- triggered when the return button was pressed or the outside area of keyboard was touched.
         *     end
         * end
         *
         * local editbox = EditBox:create(Size(...), Scale9Sprite:create(...))
         * editbox = registerScriptEditBoxHandler(editboxEventHandler)
         * @endcode
         *
         * @param handler A number that indicates a lua function.
         * @js NA
         * @lua NA
         */
        void registerScriptEditBoxHandler(int handler);

        /**
         * Unregisters a script function that will be called for EditBox events.
         * @js NA
         * @lua NA
         */
        void unregisterScriptEditBoxHandler();
        /**
         * get a script Handler
         * @js NA
         * @lua NA
         */
        int  getScriptEditBoxHandler(){ return _scriptEditBoxHandler ;}

#endif // #if CC_ENABLE_SCRIPT_BINDING

        /**
         * Set the text entered in the edit box.
         * @param pText The given text.
         */
        void setText(const char* pText);

        /**
         * Get the text entered in the edit box.
         * @return The text entered in the edit box.
         */
        const char* getText() const;

        /**
         * Set the font. Only system font is allowed.
         * @param pFontName The font name.
         * @param fontSize The font size.
         */
        void setFont(const char* pFontName, int fontSize);

        /**
         * Set the font name. Only system font is allowed.
         * @param pFontName The font name.
         */
        void setFontName(const char* pFontName);

        /**
         * Get the font name.
         * @return The font name.
         */
        const char* getFontName() const;

        /**
         * Set the font size.
         * @param fontSize The font size.
         */
        void setFontSize(int fontSize);

        /**
         * Get the font size.
         * @return The font size.
         */
        int getFontSize() const;

        /**
         * Set the font color of the widget's text.
         */
        void setFontColor(const Color3B& color);
        void setFontColor(const Color4B& color);

        /**
         * Get the font color of the widget's text.
         */
        const Color4B& getFontColor() const;

        /**
         * Set the placeholder's font. Only system font is allowed.
         * @param pFontName The font name.
         * @param fontSize The font size.
         */
        void setPlaceholderFont(const char* pFontName, int fontSize);

        /**
         * Set the placeholder's font name. only system font is allowed.
         * @param pFontName The font name.
         */
        void setPlaceholderFontName(const char* pFontName);

        /**
         * Get the placeholder's font name. only system font is allowed.
         * @return The font name.
         */
        const char* getPlaceholderFontName() const;

        /**
         * Set the placeholder's font size.
         * @param fontSize The font size.
         */
        void setPlaceholderFontSize(int fontSize);

        /**
         * Get the placeholder's font size.
         * @return The font size.
         */
        int getPlaceholderFontSize() const;

        /**
         * Set the font color of the placeholder text when the edit box is empty.
         */
        void setPlaceholderFontColor(const Color3B& color);

        /**
         * Set the font color of the placeholder text when the edit box is empty.
         */
        void setPlaceholderFontColor(const Color4B& color);

        /**
         * Get the font color of the placeholder text when the edit box is empty.
         */
        const Color4B& getPlaceholderFontColor() const;

        /**
         * Set a text in the edit box that acts as a placeholder when an
         * edit box is empty.
         * @param pText The given text.
         */
        void setPlaceHolder(const char* pText);

        /**
         * Get a text in the edit box that acts as a placeholder when an
         * edit box is empty.
         */
        const char* getPlaceHolder() const;

        /**
         * Set the input mode of the edit box.
         * @param inputMode One of the EditBox::InputMode constants.
         */
        void setInputMode(InputMode inputMode);

        /**
         * Get the input mode of the edit box.
         * @return One of the EditBox::InputMode constants.
         */
        InputMode getInputMode() const;

        /**
         * Sets the maximum input length of the edit box.
         * Setting this value enables multiline input mode by default.
         * Available on Android, iOS and Windows Phone.
         *
         * @param maxLength The maximum length.
         */
        void setMaxLength(int maxLength);

        /**
         * Gets the maximum input length of the edit box.
         *
         * @return Maximum input length.
         */
        int getMaxLength();

        /**
         * Set the input flags that are to be applied to the edit box.
         * @param inputFlag One of the EditBox::InputFlag constants.
         */
        void setInputFlag(InputFlag inputFlag);

        /**
         * Get the input flags that are to be applied to the edit box.
         * @return One of the EditBox::InputFlag constants.
         */
        InputFlag getInputFlag() const;

        /**
         * Set the return type that are to be applied to the edit box.
         * @param returnType One of the EditBox::KeyboardReturnType constants.
         */
        void setReturnType(KeyboardReturnType returnType);

        /**
         * Get the return type that are to be applied to the edit box.
         * @return One of the EditBox::KeyboardReturnType constants.
         */
        KeyboardReturnType getReturnType() const;

        /**
         * Set the text horizontal alignment.
         */
        void setTextHorizontalAlignment(TextHAlignment alignment);

        /**
         * Get the text horizontal alignment.
         */
        TextHAlignment getTextHorizontalAlignment() const;

        /* override functions */
        virtual void setPosition(const Vec2& pos) override;
        virtual void setVisible(bool visible) override;
        virtual void setContentSize(const Size& size) override;
        virtual void setAnchorPoint(const Vec2& anchorPoint) override;

        /**
         * Returns the "class name" of widget.
         */
        virtual std::string getDescription() const override;

        /**
         * @js NA
         * @lua NA
         */
        virtual void draw(Renderer *renderer, const Mat4 &parentTransform, uint32_t parentFlags) override;
        /**
         * @js NA
         * @lua NA
         */
        virtual void onEnter() override;
        /**
         * @js NA
         * @lua NA
         */
        virtual void onExit() override;
        /**
         * @js NA
         * @lua NA
         */
        virtual void keyboardWillShow(IMEKeyboardNotificationInfo& info) override;
        /**
         * @js NA
         * @lua NA
         */
        virtual void keyboardDidShow(IMEKeyboardNotificationInfo& info) override;
        /**
         * @js NA
         * @lua NA
         */
        virtual void keyboardWillHide(IMEKeyboardNotificationInfo& info) override;
        /**
         * @js NA
         * @lua NA
         */
        virtual void keyboardDidHide(IMEKeyboardNotificationInfo& info) override;

        void openKeyboard() const;

    protected:
        virtual void releaseUpEvent() override;

        virtual void initRenderer() override;
        virtual void onPressStateChangedToNormal() override;
        virtual void onPressStateChangedToPressed() override;
        virtual void onPressStateChangedToDisabled() override;
        virtual void onSizeChanged() override;

        void loadTextureNormal(SpriteFrame* normalSpriteFrame);
        void setupNormalTexture(bool textureLoaded);
        void loadTexturePressed(SpriteFrame* pressedSpriteFrame);
        void setupPressedTexture(bool textureLoaded);
        void loadTextureDisabled(SpriteFrame* disabledSpriteFrame);
        void setupDisabledTexture(bool textureLoaded);

        void normalTextureScaleChangedWithSize();
        void pressedTextureScaleChangedWithSize();
        void disabledTextureScaleChangedWithSize();

        virtual void adaptRenderers() override;

    protected:
        void updatePosition(float dt);

        Scale9Sprite* _normalRenderer = nullptr;
        Scale9Sprite* _pressedRenderer = nullptr;
        Scale9Sprite* _disabledRenderer = nullptr;

        Rect _capInsetsNormal;
        Rect _capInsetsPressed;
        Rect _capInsetsDisabled;

        Size _normalTextureSize;
        Size _pressedTextureSize;
        Size _disabledTextureSize;

        bool _normalTextureLoaded = false;
        bool _pressedTextureLoaded = false;
        bool _disabledTextureLoaded = false;
        bool _normalTextureAdaptDirty = true;
        bool _pressedTextureAdaptDirty = true;
        bool _disabledTextureAdaptDirty = true;

        std::string _normalFileName;
        std::string _pressedFileName;
        std::string _disabledFileName;
        TextureResType _normalTexType = TextureResType::LOCAL;
        TextureResType _pressedTexType = TextureResType::LOCAL;
        TextureResType _disabledTexType = TextureResType::LOCAL;

        EditBoxImpl*      _editBoxImpl = nullptr;
        EditBoxDelegate*  _delegate = nullptr;

        float _adjustHeight = 0.f;
#if CC_ENABLE_SCRIPT_BINDING
        int   _scriptEditBoxHandler = 0;
#endif
    };
}

// end of ui group
/// @}
NS_CC_END

#endif /* __UIEDITTEXT_H__ */