EditBox-ios.mm 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. /****************************************************************************
  2. Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
  3. http://www.cocos2d-x.org
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in
  11. all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. THE SOFTWARE.
  19. ****************************************************************************/
  20. #include "EditBox.h"
  21. #include "platform/CCApplication.h"
  22. #include "platform/ios/CCEAGLView-ios.h"
  23. #include "cocos/scripting/js-bindings/jswrapper/SeApi.h"
  24. #include "cocos/scripting/js-bindings/manual/jsb_global.h"
  25. #import <UIKit/UITextField.h>
  26. #import <UIKit/UITextView.h>
  27. #define TEXT_LINE_HEIGHT 40
  28. #define TEXT_VIEW_MAX_LINE_SHOWN 3
  29. #define BUTTON_HIGHT (TEXT_LINE_HEIGHT - 2)
  30. #define BUTTON_WIDTH 60
  31. #define TO_TEXT_VIEW(textinput) ((UITextView*)textinput)
  32. #define TO_TEXT_FIELD(textinput) ((UITextField*)textinput)
  33. /*************************************************************************
  34. Inner class declarations.
  35. ************************************************************************/
  36. // MARK: class declaration
  37. @interface ButtonHandler : NSObject
  38. -(IBAction) buttonTapped:(UIButton *)button;
  39. @end
  40. @interface KeyboardEventHandler : NSObject
  41. -(void)keyboardWillShow: (NSNotification*) notification;
  42. -(void)keyboardWillHide: (NSNotification*) notification;
  43. @end
  44. @interface TextFieldDelegate : NSObject<UITextFieldDelegate>
  45. - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
  46. - (void)textFieldDidChange:(UITextField *)textField;
  47. - (BOOL)textFieldShouldReturn:(UITextField *)textField;
  48. @end
  49. @interface TextViewDelegate : NSObject<UITextViewDelegate>
  50. - (BOOL) textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text;
  51. - (void) textViewDidChange:(UITextView *)textView;
  52. @end
  53. /*************************************************************************
  54. Global variables and functions.
  55. ************************************************************************/
  56. // MARK: global variables and functions
  57. namespace
  58. {
  59. bool g_isMultiline = false;
  60. bool g_confirmHold = false;
  61. int g_maxLength = INT_MAX;
  62. KeyboardEventHandler* g_keyboardHandler = nil;
  63. // "#1fa014", a color of dark green, was used for confirm button background
  64. static UIColor* g_darkGreen = [UIColor colorWithRed:31/255.0 green:160/255.0 blue:20/255.0 alpha:0.8];
  65. UITextField* g_textField = nil;
  66. TextFieldDelegate* g_textFieldDelegate = nil;
  67. UIButton* g_textFieldConfirmButton = nil;
  68. ButtonHandler* g_textFieldConfirmButtonHandler = nil;
  69. UITextView* g_textView = nil;
  70. TextViewDelegate* g_textViewDelegate = nil;
  71. UIButton* g_textViewConfirmButton = nil;
  72. ButtonHandler* g_textViewConfirmButtonHander = nil;
  73. UIView* getCurrentView()
  74. {
  75. if (g_isMultiline)
  76. return g_textView;
  77. else
  78. return g_textField;
  79. }
  80. NSString* getCurrentText()
  81. {
  82. if (g_isMultiline)
  83. return g_textView.text;
  84. else
  85. return g_textField.text;
  86. }
  87. void setText(NSString* text)
  88. {
  89. if (g_isMultiline)
  90. g_textView.text = text;
  91. else
  92. g_textField.text = text;
  93. }
  94. se::Value textInputCallback;
  95. void getTextInputCallback()
  96. {
  97. if (! textInputCallback.isUndefined())
  98. return;
  99. auto global = se::ScriptEngine::getInstance()->getGlobalObject();
  100. se::Value jsbVal;
  101. if (global->getProperty("jsb", &jsbVal) && jsbVal.isObject())
  102. {
  103. jsbVal.toObject()->getProperty("onTextInput", &textInputCallback);
  104. // free globle se::Value before ScriptEngine clean up
  105. se::ScriptEngine::getInstance()->addBeforeCleanupHook([](){
  106. textInputCallback.setUndefined();
  107. });
  108. }
  109. }
  110. void callJSFunc(const std::string& type, const std::string& text)
  111. {
  112. getTextInputCallback();
  113. se::AutoHandleScope scope;
  114. se::ValueArray args;
  115. args.push_back(se::Value(type));
  116. args.push_back(se::Value(text));
  117. textInputCallback.toObject()->call(args, nullptr);
  118. }
  119. int getTextInputHeight()
  120. {
  121. if (g_isMultiline)
  122. return TEXT_LINE_HEIGHT * TEXT_VIEW_MAX_LINE_SHOWN;
  123. else
  124. return TEXT_LINE_HEIGHT;
  125. }
  126. void createButton(UIButton** button, ButtonHandler** buttonHandler, const CGRect& viewRect, const std::string& title)
  127. {
  128. ButtonHandler *btnHandler = [[ButtonHandler alloc] init];
  129. UIButton* btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  130. [btn addTarget:btnHandler action:@selector(buttonTapped:)
  131. forControlEvents:UIControlEventTouchUpInside];
  132. btn.frame = CGRectMake(0, 0, BUTTON_WIDTH, BUTTON_HIGHT);
  133. btn.backgroundColor = g_darkGreen;
  134. [btn setTitle: [NSString stringWithUTF8String:title.c_str()]
  135. forState:UIControlStateNormal];
  136. [btn setTitleColor: [UIColor whiteColor]
  137. forState:UIControlStateNormal];
  138. *button = btn;
  139. *buttonHandler = btnHandler;
  140. }
  141. void setTexFiledKeyboardType(UITextField* textField, const std::string& inputType)
  142. {
  143. if (0 == inputType.compare("password"))
  144. {
  145. textField.secureTextEntry = TRUE;
  146. textField.keyboardType = UIKeyboardTypeDefault;
  147. }
  148. else
  149. {
  150. textField.secureTextEntry = FALSE;
  151. if (0 == inputType.compare("email"))
  152. textField.keyboardType = UIKeyboardTypeEmailAddress;
  153. else if (0 == inputType.compare("number"))
  154. textField.keyboardType = UIKeyboardTypeDecimalPad;
  155. else if (0 == inputType.compare("url"))
  156. textField.keyboardType = UIKeyboardTypeURL;
  157. else if (0 == inputType.compare("text"))
  158. textField.keyboardType = UIKeyboardTypeDefault;
  159. }
  160. }
  161. void setTextFieldReturnType(UITextField* textField, const std::string& returnType)
  162. {
  163. if (0 == returnType.compare("done"))
  164. textField.returnKeyType = UIReturnKeyDone;
  165. else if (0 == returnType.compare("next"))
  166. textField.returnKeyType = UIReturnKeyNext;
  167. else if (0 == returnType.compare("search"))
  168. textField.returnKeyType = UIReturnKeySearch;
  169. else if (0 == returnType.compare("go"))
  170. textField.returnKeyType = UIReturnKeyGo;
  171. else if (0 == returnType.compare("send"))
  172. textField.returnKeyType = UIReturnKeySend;
  173. }
  174. NSString* getConfirmButtonTitle(const std::string& returnType)
  175. {
  176. NSString* titleKey = [NSString stringWithUTF8String: returnType.c_str()];
  177. return NSLocalizedString(titleKey, nil); // get i18n string to be the title
  178. }
  179. void initTextField(const CGRect& rect, const cocos2d::EditBox::ShowInfo& showInfo)
  180. {
  181. if (! g_textField)
  182. {
  183. g_textField = [[UITextField alloc] initWithFrame:rect];
  184. g_textField.textColor = [UIColor blackColor];
  185. g_textField.backgroundColor = [UIColor whiteColor];
  186. [g_textField setBorderStyle:UITextBorderStyleLine];
  187. g_textField.backgroundColor = [UIColor whiteColor];
  188. g_textFieldDelegate = [[TextFieldDelegate alloc] init];
  189. g_textField.delegate = g_textFieldDelegate;
  190. // Assign the overlay button to a stored text field
  191. createButton(&g_textFieldConfirmButton, &g_textFieldConfirmButtonHandler, rect, showInfo.confirmType);
  192. g_textField.rightView = g_textFieldConfirmButton;
  193. g_textField.rightViewMode = UITextFieldViewModeAlways;
  194. [g_textField addTarget:g_textFieldDelegate action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  195. }
  196. g_textField.frame = rect;
  197. setTextFieldReturnType(g_textField, showInfo.confirmType);
  198. setTexFiledKeyboardType(g_textField, showInfo.inputType);
  199. g_textField.text = [NSString stringWithUTF8String: showInfo.defaultValue.c_str()];
  200. [g_textFieldConfirmButton setTitle:getConfirmButtonTitle(showInfo.confirmType) forState:UIControlStateNormal];
  201. }
  202. void initTextView(const CGRect& viewRect, const CGRect& btnRect, const cocos2d::EditBox::ShowInfo& showInfo)
  203. {
  204. if (!g_textView)
  205. {
  206. g_textView = [[UITextView alloc] initWithFrame:btnRect];
  207. g_textView.textColor = [UIColor blackColor];
  208. g_textView.backgroundColor = [UIColor whiteColor];
  209. g_textViewDelegate = [[TextViewDelegate alloc] init];
  210. g_textView.delegate = g_textViewDelegate;
  211. createButton(&g_textViewConfirmButton, &g_textViewConfirmButtonHander, btnRect, showInfo.confirmType);
  212. g_textViewConfirmButton.frame = CGRectMake(viewRect.size.width - BUTTON_WIDTH, 0, BUTTON_WIDTH, BUTTON_HIGHT);
  213. [g_textView addSubview:g_textViewConfirmButton];
  214. }
  215. g_textView.frame = btnRect;
  216. g_textView.text = [NSString stringWithUTF8String: showInfo.defaultValue.c_str()];
  217. [g_textViewConfirmButton setTitle:getConfirmButtonTitle(showInfo.confirmType) forState:UIControlStateNormal];
  218. }
  219. CGRect getSafeAreaRect()
  220. {
  221. UIView* view = (UIView*)cocos2d::Application::getInstance()->getView();
  222. CGRect viewRect = view.frame;
  223. // safeAreaInsets is avaible since iOS 11.
  224. if (@available(iOS 11.0, *))
  225. {
  226. auto safeAreaInsets = view.safeAreaInsets;
  227. viewRect.origin.x += safeAreaInsets.left;
  228. viewRect.size.width -= safeAreaInsets.left;
  229. }
  230. return viewRect;
  231. }
  232. void addTextInput(const cocos2d::EditBox::ShowInfo& showInfo)
  233. {
  234. auto safeAreaRect = getSafeAreaRect();
  235. int height = getTextInputHeight();
  236. CGRect rect = CGRectMake(safeAreaRect.origin.x,
  237. safeAreaRect.size.height - height,
  238. safeAreaRect.size.width,
  239. height);
  240. if (showInfo.isMultiline)
  241. initTextView(safeAreaRect, rect, showInfo);
  242. else
  243. initTextField(rect, showInfo);
  244. UIView* textInput = getCurrentView();
  245. UIView* view = (UIView*)cocos2d::Application::getInstance()->getView();
  246. [view addSubview:textInput];
  247. [textInput becomeFirstResponder];
  248. }
  249. void addKeyboardEventLisnters()
  250. {
  251. if (!g_keyboardHandler)
  252. g_keyboardHandler = [[KeyboardEventHandler alloc] init];
  253. [[NSNotificationCenter defaultCenter] addObserver:g_keyboardHandler
  254. selector:@selector(keyboardWillShow:)
  255. name:UIKeyboardWillShowNotification
  256. object:nil];
  257. [[NSNotificationCenter defaultCenter] addObserver:g_keyboardHandler
  258. selector:@selector(keyboardWillHide:)
  259. name:UIKeyboardWillHideNotification
  260. object:nil];
  261. }
  262. void removeKeyboardEventLisnters()
  263. {
  264. if (!g_keyboardHandler)
  265. return;
  266. [[NSNotificationCenter defaultCenter] removeObserver:g_keyboardHandler];
  267. }
  268. }
  269. /*************************************************************************
  270. Class implementations.
  271. ************************************************************************/
  272. // MARK: class implementation
  273. @implementation KeyboardEventHandler
  274. -(void)keyboardWillShow: (NSNotification*) notification
  275. {
  276. UIView* textView = getCurrentView();
  277. if (!textView)
  278. return;
  279. NSDictionary* keyboardInfo = [notification userInfo];
  280. NSValue* keyboardFrame = [keyboardInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
  281. CGSize kbSize = [keyboardFrame CGRectValue].size;
  282. int textHeight = getTextInputHeight();
  283. CGRect screenRect = getSafeAreaRect();
  284. textView.frame = CGRectMake(screenRect.origin.x,
  285. screenRect.size.height - textHeight - kbSize.height,
  286. screenRect.size.width,
  287. textHeight);
  288. }
  289. -(void)keyboardWillHide: (NSNotification*) notification
  290. {
  291. cocos2d::EditBox::complete();
  292. cocos2d::EditBox::hide();
  293. }
  294. @end
  295. @implementation TextFieldDelegate
  296. - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
  297. {
  298. // REFINE: check length limit before text changed
  299. return YES;
  300. }
  301. - (void)textFieldDidChange:(UITextField *)textField
  302. {
  303. if (textField.markedTextRange != nil)
  304. return;
  305. // check length limit after text changed, a little rude
  306. if (textField.text.length > g_maxLength) {
  307. NSRange rangeIndex = [textField.text rangeOfComposedCharacterSequenceAtIndex:g_maxLength];
  308. textField.text = [textField.text substringToIndex:rangeIndex.location];
  309. }
  310. callJSFunc("input", [textField.text UTF8String]);
  311. }
  312. -(BOOL) textFieldShouldReturn:(UITextField *)textField
  313. {
  314. cocos2d::EditBox::complete();
  315. return YES;
  316. }
  317. @end
  318. @implementation ButtonHandler
  319. -(IBAction) buttonTapped:(UIButton *)button
  320. {
  321. const std::string text([getCurrentText() UTF8String]);
  322. callJSFunc("confirm", text);
  323. if (!g_confirmHold)
  324. cocos2d::EditBox::complete();
  325. }
  326. @end
  327. @implementation TextViewDelegate
  328. - (BOOL) textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
  329. {
  330. // REFINE: check length limit before text changed
  331. return YES;
  332. }
  333. - (void)textViewDidChange:(UITextView *)textView
  334. {
  335. if (textView.markedTextRange != nil)
  336. return;
  337. // check length limit after text changed, a little rude
  338. if (textView.text.length > g_maxLength)
  339. textView.text = [textView.text substringToIndex:g_maxLength];
  340. callJSFunc("input", [textView.text UTF8String]);
  341. }
  342. @end
  343. /*************************************************************************
  344. Implementation of EditBox.
  345. ************************************************************************/
  346. // MARK: EditBox
  347. NS_CC_BEGIN
  348. void EditBox::show(const cocos2d::EditBox::ShowInfo& showInfo)
  349. {
  350. // Should initialize them at first.
  351. g_maxLength = showInfo.maxLength;
  352. g_isMultiline = showInfo.isMultiline;
  353. g_confirmHold = showInfo.confirmHold;
  354. [(CCEAGLView*)cocos2d::Application::getInstance()->getView() setPreventTouchEvent:true];
  355. addKeyboardEventLisnters();
  356. addTextInput(showInfo);
  357. }
  358. void EditBox::hide()
  359. {
  360. removeKeyboardEventLisnters();
  361. UIView* view = getCurrentView();
  362. if (view)
  363. {
  364. [view removeFromSuperview];
  365. [view resignFirstResponder];
  366. }
  367. [(CCEAGLView*)cocos2d::Application::getInstance()->getView() setPreventTouchEvent:false];
  368. }
  369. void EditBox::updateRect(int x, int y, int width, int height)
  370. {
  371. // not supported ...
  372. }
  373. void EditBox::complete()
  374. {
  375. NSString* text = getCurrentText();
  376. callJSFunc("complete", [text UTF8String]);
  377. EditBox::hide();
  378. }
  379. NS_CC_END