axmol/cocos/ui/UIEditBox/UIEditBoxImpl-mac.mm

602 lines
17 KiB
Plaintext
Raw Normal View History

2014-08-19 10:28:24 +08:00
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2012 Jozef Pridavok
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.
****************************************************************************/
2014-09-10 07:50:02 +08:00
#include "UIEditBoxImpl-mac.h"
2014-08-19 10:28:24 +08:00
#if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC)
2014-09-10 07:50:02 +08:00
#include "base/CCDirector.h"
2014-08-19 10:28:24 +08:00
#include "UIEditBox.h"
2014-09-24 03:18:24 +08:00
#include "deprecated/CCString.h"
2014-08-19 10:28:24 +08:00
2015-07-17 23:05:42 +08:00
#import <Foundation/Foundation.h>
#import <AppKit/AppKit.h>
2014-08-19 10:28:24 +08:00
#define getEditBoxImplMac() ((cocos2d::ui::EditBoxImplMac *)_editBox)
2014-08-19 10:28:24 +08:00
#pragma mark - internal classes
/** TODO: Missing doc - What does "CustomTextFieldFormatter" do?
*/
@interface CustomTextFieldFormatter : NSFormatter
@property (nonatomic, assign) int maximumLength;
2014-10-10 15:26:33 +08:00
@end
@implementation CustomTextFieldFormatter
- (instancetype)init
{
self = [super init];
if (self) {
_maximumLength = INT_MAX;
2014-10-10 15:26:33 +08:00
}
return self;
}
- (NSString *)stringForObjectValue:(id)object
{
return object;
2014-10-10 15:26:33 +08:00
}
- (BOOL)getObjectValue:(id *)object forString:(NSString *)string errorDescription:(NSString **)error
{
2014-10-10 15:26:33 +08:00
*object = string;
return YES;
}
- (BOOL)isPartialStringValid:(NSString **)partialStringPtr
proposedSelectedRange:(NSRangePointer)proposedSelRangePtr
originalString:(NSString *)origString
originalSelectedRange:(NSRange)origSelRange
errorDescription:(NSString **)error
{
return (*partialStringPtr).length <= self.maximumLength;
2014-10-10 15:26:33 +08:00
}
- (NSAttributedString *)attributedStringForObjectValue:(id)anObject withDefaultAttributes:(NSDictionary *)attributes
{
2014-10-10 15:26:33 +08:00
return nil;
}
@end
2014-08-19 10:28:24 +08:00
#pragma mark - UIEditBox mac implementation
2014-08-19 10:28:24 +08:00
@interface UIEditBoxImplMac : NSObject <NSTextFieldDelegate>
2014-08-19 10:28:24 +08:00
@property (nonatomic, retain) NSTextField* textField;
@property (nonatomic, retain) NSSecureTextField *secureTextField;
@property (nonatomic, retain) NSMutableDictionary *placeholderAttributes;
@property (nonatomic, readonly) NSWindow *window;
2014-08-19 10:28:24 +08:00
@property (nonatomic, readonly, getter = isEditState) BOOL editState;
@property (nonatomic, assign, getter = isSecure) BOOL secure;
@property (nonatomic, assign) void *editBox;
2014-08-19 10:28:24 +08:00
- (instancetype)initWithFrame:(NSRect)frameRect editBox:(void *)editBox;
2014-08-19 10:28:24 +08:00
- (void)doAnimationWhenKeyboardMoveWithDuration:(float)duration distance:(float)distance;
- (void)setPosition:(NSPoint)pos;
- (void)openKeyboard;
- (void)closeKeyboard;
@end
@implementation UIEditBoxImplMac
- (instancetype)initWithFrame:(NSRect)frameRect editBox:(void *)editBox
2014-08-19 10:28:24 +08:00
{
self = [super init];
if (self) {
_editState = NO;
_secure = NO;
2014-08-19 10:28:24 +08:00
self.textField = [[[NSTextField alloc] initWithFrame:frameRect] autorelease];
self.secureTextField = [[[NSSecureTextField alloc] initWithFrame:frameRect] autorelease];
//TODO: need to delete hard code here.
NSFont *font = [NSFont systemFontOfSize:frameRect.size.height*2/3];
_textField.font = font;
_secureTextField.font = font;
2014-08-19 10:28:24 +08:00
[self setupTextField:_textField];
[self setupTextField:_secureTextField];
2014-08-19 10:28:24 +08:00
self.editBox = editBox;
self.placeholderAttributes = [NSMutableDictionary dictionaryWithObjectsAndKeys:
font, NSFontAttributeName,
[NSColor grayColor], NSForegroundColorAttributeName,
nil];
[self.window.contentView addSubview:_textField];
2014-08-19 10:28:24 +08:00
}
return self;
}
- (void)dealloc
2014-08-19 10:28:24 +08:00
{
[_textField resignFirstResponder];
[_textField removeFromSuperview];
[_textField release];
[_secureTextField resignFirstResponder];
[_secureTextField removeFromSuperview];
[_secureTextField release];
[_placeholderAttributes release];
[super dealloc];
2014-08-19 10:28:24 +08:00
}
- (NSWindow *)window
2014-08-19 10:28:24 +08:00
{
auto glview = cocos2d::Director::getInstance()->getOpenGLView();
return glview->getCocoaWindow();
2014-08-19 10:28:24 +08:00
}
- (void)setPosition:(NSPoint)pos
2015-03-02 03:56:18 +08:00
{
NSRect frame = _textField.frame;
frame.origin = pos;
2015-03-02 03:56:18 +08:00
_textField.frame = frame;
_secureTextField.frame = frame;
2015-03-02 03:56:18 +08:00
}
- (void)setupTextField:(NSTextField *)textField
2014-08-19 10:28:24 +08:00
{
textField.textColor = [NSColor whiteColor];
textField.backgroundColor = [NSColor clearColor];
textField.bordered = NO;
textField.hidden = NO;
textField.wantsLayer = YES;
textField.delegate = self;
2014-08-19 10:28:24 +08:00
}
- (void)doAnimationWhenKeyboardMoveWithDuration:(float)duration distance:(float)distance
2014-08-19 10:28:24 +08:00
{
[self.window.contentView doAnimationWhenKeyboardMoveWithDuration:duration distance:distance];
2014-08-19 10:28:24 +08:00
}
- (void)setSecure:(BOOL)secure
2014-08-19 10:28:24 +08:00
{
NSAssert(secure, @"Can only set this flag to true");
2014-08-19 10:28:24 +08:00
_secure = secure;
[_textField.superview addSubview:_secureTextField];
[_textField removeFromSuperview];
2014-08-19 10:28:24 +08:00
}
- (void)openKeyboard
2014-08-19 10:28:24 +08:00
{
2015-07-17 22:15:41 +08:00
NSView *contentView = self.window.contentView;
2015-03-02 03:56:18 +08:00
if (!_secure) {
[contentView addSubview:_textField];
[_textField becomeFirstResponder];
2014-08-19 10:28:24 +08:00
}
else {
[contentView addSubview:_secureTextField];
[_secureTextField becomeFirstResponder];
2014-08-19 10:28:24 +08:00
}
}
- (void)closeKeyboard
2014-08-19 10:28:24 +08:00
{
if ([_textField superview]) {
[_textField resignFirstResponder];
[_textField removeFromSuperview];
2014-08-19 10:28:24 +08:00
}
else {
[_secureTextField resignFirstResponder];
[_secureTextField removeFromSuperview];
2014-08-19 10:28:24 +08:00
}
}
- (BOOL)textFieldShouldReturn:(NSTextField *)sender
{
if (sender == _textField || sender == _secureTextField) {
2014-08-19 10:28:24 +08:00
[sender resignFirstResponder];
}
return NO;
}
- (void)controlTextDidBeginEditing:(NSNotification *)notification
{
_editState = YES;
2014-08-19 10:28:24 +08:00
cocos2d::ui::EditBoxDelegate* pDelegate = getEditBoxImplMac()->getDelegate();
if (pDelegate != NULL)
{
pDelegate->editBoxEditingDidBegin(getEditBoxImplMac()->getEditBox());
}
#if CC_ENABLE_SCRIPT_BINDING
cocos2d::ui::EditBox* pEditBox= getEditBoxImplMac()->getEditBox();
if (NULL != pEditBox && 0 != pEditBox->getScriptEditBoxHandler())
{
cocos2d::CommonScriptData data(pEditBox->getScriptEditBoxHandler(), "began",pEditBox);
cocos2d::ScriptEvent event(cocos2d::kCommonEvent,(void*)&data);
cocos2d::ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&event);
}
#endif
}
- (void)controlTextDidEndEditing:(NSNotification *)notification
{
_editState = NO;
2014-08-19 10:28:24 +08:00
cocos2d::ui::EditBoxDelegate* pDelegate = getEditBoxImplMac()->getDelegate();
if (pDelegate != NULL)
{
pDelegate->editBoxEditingDidEnd(getEditBoxImplMac()->getEditBox());
pDelegate->editBoxReturn(getEditBoxImplMac()->getEditBox());
}
#if CC_ENABLE_SCRIPT_BINDING
cocos2d::ui::EditBox* pEditBox= getEditBoxImplMac()->getEditBox();
if (NULL != pEditBox && 0 != pEditBox->getScriptEditBoxHandler())
{
cocos2d::CommonScriptData data(pEditBox->getScriptEditBoxHandler(), "ended",pEditBox);
cocos2d::ScriptEvent event(cocos2d::kCommonEvent,(void*)&data);
cocos2d::ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&event);
memset(data.eventName, 0, sizeof(data.eventName));
strncpy(data.eventName, "return", sizeof(data.eventName));
event.data = (void*)&data;
cocos2d::ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&event);
}
#endif
}
/**
* Called each time when the text field's text has changed.
*/
- (void)controlTextDidChange:(NSNotification *)notification
{
cocos2d::ui::EditBoxDelegate* pDelegate = getEditBoxImplMac()->getDelegate();
if (pDelegate != NULL)
{
pDelegate->editBoxTextChanged(getEditBoxImplMac()->getEditBox(), getEditBoxImplMac()->getText());
}
#if CC_ENABLE_SCRIPT_BINDING
cocos2d::ui::EditBox* pEditBox= getEditBoxImplMac()->getEditBox();
if (NULL != pEditBox && 0 != pEditBox->getScriptEditBoxHandler())
{
cocos2d::CommonScriptData data(pEditBox->getScriptEditBoxHandler(), "changed",pEditBox);
cocos2d::ScriptEvent event(cocos2d::kCommonEvent,(void*)&data);
cocos2d::ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&event);
}
#endif
}
@end
2014-08-19 10:28:24 +08:00
NS_CC_BEGIN
namespace ui {
EditBoxImpl* __createSystemEditBox(EditBox* pEditBox)
{
return new EditBoxImplMac(pEditBox);
}
EditBoxImplMac::EditBoxImplMac(EditBox* pEditText)
: EditBoxImpl(pEditText)
, _anchorPoint(Vec2(0.5f, 0.5f))
, _maxTextLength(-1)
, _sysEdit(nullptr)
{
//! TODO: Retina on Mac
//! _inRetinaMode = [[CCEAGLView sharedEGLView] contentScaleFactor] == 2.0f ? true : false;
_inRetinaMode = false;
}
EditBoxImplMac::~EditBoxImplMac()
{
[_sysEdit release];
}
void EditBoxImplMac::doAnimationWhenKeyboardMove(float duration, float distance)
{
if ([_sysEdit isEditState] || distance < 0.0f)
[_sysEdit doAnimationWhenKeyboardMoveWithDuration:duration distance:distance];
}
bool EditBoxImplMac::initWithSize(const Size& size)
{
GLView* eglView = Director::getInstance()->getOpenGLView();
NSRect rect = NSMakeRect(0, 0, size.width * eglView->getScaleX(),size.height * eglView->getScaleY());
if (_inRetinaMode) {
rect.size.width /= 2.0f;
rect.size.height /= 2.0f;
}
_sysEdit = [[UIEditBoxImplMac alloc] initWithFrame:rect editBox:this];
if (!_sysEdit)
return false;
return true;
}
NSFont* EditBoxImplMac::constructFont(const char *fontName, int fontSize)
2014-08-19 10:28:24 +08:00
{
NSString * fntName = [NSString stringWithUTF8String:fontName];
2014-08-19 10:28:24 +08:00
float retinaFactor = _inRetinaMode ? 2.0f : 1.0f;
auto glview = cocos2d::Director::getInstance()->getOpenGLView();
float scaleFactor = glview->getScaleX();
if (fontSize == -1)
{
NSRect frameRect = [_sysEdit.textField frame];
fontSize = frameRect.size.height*2/3;
}
else
{
fontSize = fontSize * scaleFactor / retinaFactor;
}
NSFont *textFont = nil;
if (strlen(fontName) == 0)
{
textFont = [NSFont systemFontOfSize:fontSize];
}
else
{
textFont = [NSFont fontWithName:fntName size:fontSize];
}
return textFont;
}
void EditBoxImplMac::setFont(const char* pFontName, int fontSize)
{
NSFont* textFont = constructFont(pFontName, fontSize);
2015-07-17 23:05:42 +08:00
if (textFont != nil) {
[_sysEdit.textField setFont:textFont];
2014-08-19 10:28:24 +08:00
[_sysEdit.secureTextField setFont:textFont];
}
}
void EditBoxImplMac::setPlaceholderFont(const char* pFontName, int fontSize)
{
NSFont *textFont = constructFont(pFontName, fontSize);
2014-08-19 10:28:24 +08:00
if (!textFont) {
2014-08-19 10:28:24 +08:00
CCLOGWARN("Font not found: %s", pFontName);
return;
}
[_sysEdit.placeholderAttributes setObject:textFont forKey:NSFontAttributeName];
2014-08-19 10:28:24 +08:00
/* reload placeholder */
const char *placeholder = [_sysEdit.textField.cell placeholderAttributedString].string.UTF8String;
if (placeholder) {
setPlaceHolder(placeholder);
}
}
2015-03-02 19:31:59 +08:00
void EditBoxImplMac::setFontColor(const Color4B& color)
2014-08-19 10:28:24 +08:00
{
2015-03-02 19:31:59 +08:00
NSColor *newColor = [NSColor colorWithCalibratedRed:color.r / 255.0f green:color.g / 255.0f blue:color.b / 255.0f alpha:color.a / 255.f];
2014-08-19 10:28:24 +08:00
_sysEdit.textField.textColor = newColor;
_sysEdit.secureTextField.textColor = newColor;
}
2015-03-02 19:31:59 +08:00
void EditBoxImplMac::setPlaceholderFontColor(const Color4B& color)
2014-08-19 10:28:24 +08:00
{
2015-03-02 19:31:59 +08:00
NSColor *nsColor = [NSColor colorWithCalibratedRed:color.r/255.f green:color.g / 255.f blue:color.b / 255.f alpha:color.a / 255.f];
2014-08-19 10:28:24 +08:00
[_sysEdit.placeholderAttributes setObject:nsColor forKey:NSForegroundColorAttributeName];
/* reload placeholder */
const char *placeholder = [_sysEdit.textField.cell placeholderAttributedString].string.UTF8String;
if (placeholder) {
setPlaceHolder(placeholder);
}
}
void EditBoxImplMac::setInputMode(EditBox::InputMode inputMode)
{
}
void EditBoxImplMac::setMaxLength(int maxLength)
{
_maxTextLength = maxLength;
2014-10-10 15:26:33 +08:00
id formater = [[[CustomTextFieldFormatter alloc]init] autorelease];
[formater setMaximumLength:maxLength];
[_sysEdit.secureTextField setFormatter:formater];
[_sysEdit.textField setFormatter:formater];
2014-08-19 10:28:24 +08:00
}
int EditBoxImplMac::getMaxLength()
{
return _maxTextLength;
}
void EditBoxImplMac::setInputFlag(EditBox::InputFlag inputFlag)
{
switch (inputFlag)
{
case EditBox::InputFlag::PASSWORD:
2015-03-02 03:56:18 +08:00
_sysEdit.secure = YES;
2014-08-19 10:28:24 +08:00
break;
case EditBox::InputFlag::INITIAL_CAPS_WORD:
CCLOGWARN("INITIAL_CAPS_WORD not implemented");
break;
case EditBox::InputFlag::INITIAL_CAPS_SENTENCE:
CCLOGWARN("INITIAL_CAPS_SENTENCE not implemented");
break;
2015-10-12 12:54:06 +08:00
case EditBox::InputFlag::INITIAL_CAPS_ALL_CHARACTERS:
CCLOGWARN("INITIAL_CAPS_ALL_CHARACTERS not implemented");
2014-08-19 10:28:24 +08:00
break;
case EditBox::InputFlag::SENSITIVE:
CCLOGWARN("SENSITIVE not implemented");
break;
default:
break;
}
}
void EditBoxImplMac::setReturnType(EditBox::KeyboardReturnType returnType)
{
}
bool EditBoxImplMac::isEditing()
{
return [_sysEdit isEditState] ? true : false;
}
void EditBoxImplMac::setText(const char* pText)
{
NSString *string = [NSString stringWithUTF8String:pText];
_sysEdit.textField.stringValue = string;
_sysEdit.secureTextField.stringValue = string;
}
const char* EditBoxImplMac::getText(void)
{
if (_sysEdit.secureTextField.superview) {
return [_sysEdit.secureTextField.stringValue UTF8String];
}
return [_sysEdit.textField.stringValue UTF8String];
}
void EditBoxImplMac::setPlaceHolder(const char* pText)
{
NSAttributedString *as = [[NSAttributedString alloc] initWithString:[NSString stringWithUTF8String:pText]
attributes:_sysEdit.placeholderAttributes];
[[_sysEdit.textField cell] setPlaceholderAttributedString:as];
[[_sysEdit.secureTextField cell] setPlaceholderAttributedString:as];
[as release];
}
NSPoint EditBoxImplMac::convertDesignCoordToScreenCoord(const Vec2& designCoord, bool bInRetinaMode)
{
NSRect frame = [_sysEdit.textField frame];
CGFloat height = frame.size.height;
GLView* eglView = Director::getInstance()->getOpenGLView();
Vec2 visiblePos = Vec2(designCoord.x * eglView->getScaleX(), designCoord.y * eglView->getScaleY());
Vec2 screenGLPos = visiblePos + eglView->getViewPortRect().origin;
//TODO: I don't know why here needs to substract `height`.
NSPoint screenPos = NSMakePoint(screenGLPos.x, screenGLPos.y-height);
if (bInRetinaMode) {
screenPos.x = screenPos.x / 2.0f;
screenPos.y = screenPos.y / 2.0f;
}
CCLOGINFO("[EditBox] pos x = %f, y = %f", screenGLPos.x, screenGLPos.y);
return screenPos;
}
void EditBoxImplMac::updatePosition(float dt)
{
if(nullptr != _sysEdit)
{
adjustTextFieldPosition();
}
}
void EditBoxImplMac::adjustTextFieldPosition()
{
2015-07-17 23:05:42 +08:00
Size contentSize = _editBox->getContentSize();
Rect rect = Rect(0, 0, contentSize.width, contentSize.height);
2014-08-19 10:28:24 +08:00
rect = RectApplyAffineTransform(rect, _editBox->nodeToWorldTransform());
2015-07-17 23:05:42 +08:00
Vec2 designCoord = Vec2(rect.origin.x, rect.origin.y + rect.size.height);
2014-08-19 10:28:24 +08:00
[_sysEdit setPosition:convertDesignCoordToScreenCoord(designCoord, _inRetinaMode)];
}
void EditBoxImplMac::setPosition(const Vec2& pos)
{
_position = pos;
adjustTextFieldPosition();
}
void EditBoxImplMac::setVisible(bool visible)
{
[_sysEdit.textField setHidden:!visible];
[_sysEdit.secureTextField setHidden:!visible];
}
void EditBoxImplMac::setContentSize(const Size& size)
{
_contentSize = size;
CCLOG("[Edit text] content size = (%f, %f)", size.width, size.height);
}
void EditBoxImplMac::setAnchorPoint(const Vec2& anchorPoint)
{
CCLOG("[Edit text] anchor point = (%f, %f)", anchorPoint.x, anchorPoint.y);
2015-07-17 23:05:42 +08:00
_anchorPoint = anchorPoint;
setPosition(_position);
2014-08-19 10:28:24 +08:00
}
void EditBoxImplMac::draw(Renderer *renderer, const Mat4 &transform, uint32_t flags)
2014-08-19 10:28:24 +08:00
{
}
void EditBoxImplMac::openKeyboard()
{
[_sysEdit openKeyboard];
}
void EditBoxImplMac::closeKeyboard()
{
[_sysEdit closeKeyboard];
}
void EditBoxImplMac::onEnter(void)
{
adjustTextFieldPosition();
}
}
NS_CC_END
#endif // #if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC)