UIEditBoxImpl-winrt.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. ///****************************************************************************
  2. //Copyright (c) 2014 cocos2d-x.org
  3. //
  4. //http://www.cocos2d-x.org
  5. //
  6. //* Portions Copyright (c) Microsoft Open Technologies, Inc.
  7. //* All Rights Reserved
  8. //
  9. //Permission is hereby granted, free of charge, to any person obtaining a copy
  10. //of this software and associated documentation files (the "Software"), to deal
  11. //in the Software without restriction, including without limitation the rights
  12. //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. //copies of the Software, and to permit persons to whom the Software is
  14. //furnished to do so, subject to the following conditions:
  15. //
  16. //The above copyright notice and this permission notice shall be included in
  17. //all copies or substantial portions of the Software.
  18. //
  19. //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. //THE SOFTWARE.
  26. //****************************************************************************/
  27. #include "platform/CCPlatformConfig.h"
  28. #if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8 || CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
  29. #include "ui/UIEditBox/UIEditBoxImpl-winrt.h"
  30. #include "platform/winrt/CCWinRTUtils.h"
  31. #include "platform/winrt/CCGLViewImpl-winrt.h"
  32. #include "2d/CCFontFreeType.h"
  33. #if defined(WINAPI_FAMILY) && WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
  34. #define XAML_TOP_PADDING 10.0f
  35. #else
  36. #define XAML_TOP_PADDING 0.0f
  37. #endif
  38. namespace cocos2d {
  39. namespace ui {
  40. Platform::String^ EDIT_BOX_XAML_NAME = L"cocos2d_editbox";
  41. Platform::String^ CANVAS_XAML_NAME = L"cocos2d_canvas";
  42. EditBoxImpl* __createSystemEditBox(EditBox* pEditBox)
  43. {
  44. return new UIEditBoxImplWinrt(pEditBox);
  45. }
  46. EditBoxWinRT::EditBoxWinRT(Windows::Foundation::EventHandler<Platform::String^>^ beginHandler,
  47. Windows::Foundation::EventHandler<Platform::String^>^ changeHandler,
  48. Windows::Foundation::EventHandler<cocos2d::EndEventArgs^>^ endHandler) :
  49. _beginHandler(beginHandler),
  50. _changeHandler(changeHandler),
  51. _endHandler(endHandler),
  52. _color(Windows::UI::Colors::White),
  53. _alignment(),
  54. _initialText(L""),
  55. _fontFamily(L"Segoe UI"),
  56. _fontSize(12),
  57. _password(false),
  58. _isEditing(false),
  59. _multiline(false),
  60. _maxLength(0 /* unlimited */)
  61. {
  62. m_dispatcher = cocos2d::GLViewImpl::sharedOpenGLView()->getDispatcher();
  63. m_panel = cocos2d::GLViewImpl::sharedOpenGLView()->getPanel();
  64. }
  65. void EditBoxWinRT::closeKeyboard()
  66. {
  67. m_dispatcher.Get()->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([this]() {
  68. removeTextBox();
  69. _textBox = nullptr;
  70. auto canvas = static_cast<Canvas^>(findXamlElement(m_panel.Get(), CANVAS_XAML_NAME));
  71. canvas->Visibility = Visibility::Collapsed;
  72. }));
  73. }
  74. Windows::UI::Xaml::Controls::Control^ EditBoxWinRT::createPasswordBox()
  75. {
  76. auto passwordBox = ref new PasswordBox;
  77. passwordBox->BorderThickness = 0;
  78. passwordBox->Name = EDIT_BOX_XAML_NAME;
  79. passwordBox->Width = _size.Width;
  80. passwordBox->Height = _size.Height;
  81. passwordBox->Foreground = ref new Media::SolidColorBrush(_color);
  82. passwordBox->FontSize = _fontSize;
  83. passwordBox->FontFamily = ref new Media::FontFamily(_fontFamily);
  84. passwordBox->MaxLength = _maxLength;
  85. passwordBox->Password = _initialText;
  86. _changeToken = passwordBox->PasswordChanged += ref new Windows::UI::Xaml::RoutedEventHandler(this, &cocos2d::ui::EditBoxWinRT::onPasswordChanged);
  87. return passwordBox;
  88. }
  89. Windows::UI::Xaml::Controls::Control^ EditBoxWinRT::createTextBox()
  90. {
  91. auto textBox = ref new TextBox;
  92. textBox->BorderThickness = 0;
  93. textBox->Name = EDIT_BOX_XAML_NAME;
  94. textBox->Width = _size.Width;
  95. textBox->Height = _size.Height;
  96. textBox->Foreground = ref new Media::SolidColorBrush(_color);
  97. textBox->FontSize = _fontSize;
  98. textBox->FontFamily = ref new Media::FontFamily(_fontFamily);
  99. textBox->MaxLength = _maxLength;
  100. textBox->AcceptsReturn = _multiline;
  101. textBox->TextWrapping = _multiline ? TextWrapping::Wrap : TextWrapping::NoWrap;
  102. textBox->Text = _initialText;
  103. setInputScope(textBox);
  104. _setTextHorizontalAlignment(textBox);
  105. _changeToken = textBox->TextChanged += ref new Windows::UI::Xaml::Controls::TextChangedEventHandler(this, &cocos2d::ui::EditBoxWinRT::onTextChanged);
  106. return textBox;
  107. }
  108. void EditBoxWinRT::onPasswordChanged(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ args)
  109. {
  110. onTextChanged(sender, nullptr);
  111. }
  112. void EditBoxWinRT::onTextChanged(Platform::Object ^sender, Windows::UI::Xaml::Controls::TextChangedEventArgs ^e)
  113. {
  114. Platform::String^ text = L"";
  115. if (_password) {
  116. text = static_cast<PasswordBox^>(_textBox)->Password;
  117. }
  118. else {
  119. text = static_cast<TextBox^>(_textBox)->Text;
  120. }
  121. std::shared_ptr<cocos2d::InputEvent> inputEvent(new UIEditBoxEvent(this, text, _changeHandler));
  122. cocos2d::GLViewImpl::sharedOpenGLView()->QueueEvent(inputEvent);
  123. }
  124. void EditBoxWinRT::onKeyDown(Platform::Object^ sender, Windows::UI::Xaml::Input::KeyRoutedEventArgs^ args)
  125. {
  126. if (args->Key == Windows::System::VirtualKey::Enter && !_multiline) {
  127. onLostFocus(nullptr, args);
  128. }
  129. else if (args->Key == Windows::System::VirtualKey::Tab) {
  130. onLostFocus(nullptr, args);
  131. }
  132. }
  133. void EditBoxWinRT::onGotFocus(Platform::Object ^sender, Windows::UI::Xaml::RoutedEventArgs ^args)
  134. {
  135. Concurrency::critical_section::scoped_lock lock(_critical_section);
  136. std::shared_ptr<cocos2d::InputEvent> inputEvent(new UIEditBoxEvent(this, nullptr, _beginHandler));
  137. cocos2d::GLViewImpl::sharedOpenGLView()->QueueEvent(inputEvent);
  138. _isEditing = true;
  139. }
  140. void EditBoxWinRT::onLostFocus(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs ^args)
  141. {
  142. EditBoxDelegate::EditBoxEndAction action = EditBoxDelegate::EditBoxEndAction::UNKNOWN;
  143. Windows::UI::Xaml::Input::KeyRoutedEventArgs^ keyArgs = dynamic_cast<Windows::UI::Xaml::Input::KeyRoutedEventArgs^>(args);
  144. if (keyArgs) {
  145. if (keyArgs->Key == Windows::System::VirtualKey::Enter && !_multiline) {
  146. action = EditBoxDelegate::EditBoxEndAction::RETURN;
  147. }
  148. else if (keyArgs->Key == Windows::System::VirtualKey::Tab) {
  149. action = EditBoxDelegate::EditBoxEndAction::TAB_TO_NEXT;
  150. }
  151. }
  152. _isEditing = false;
  153. Concurrency::critical_section::scoped_lock lock(_critical_section);
  154. Platform::String^ text = L"";
  155. if (_password) {
  156. text = static_cast<PasswordBox^>(_textBox)->Password;
  157. static_cast<PasswordBox^>(_textBox)->PasswordChanged -= _changeToken;
  158. }
  159. else {
  160. text = static_cast<TextBox^>(_textBox)->Text;
  161. static_cast<TextBox^>(_textBox)->TextChanged -= _changeToken;
  162. }
  163. std::shared_ptr<cocos2d::InputEvent> inputEvent(new UIEditBoxEndEvent(this, text, static_cast<int>(action), _endHandler));
  164. cocos2d::GLViewImpl::sharedOpenGLView()->QueueEvent(inputEvent);
  165. _textBox->LostFocus -= _unfocusToken;
  166. _textBox->GotFocus -= _focusToken;
  167. _textBox->KeyDown -= _keydownToken;
  168. closeKeyboard();
  169. }
  170. bool EditBoxWinRT::isEditing() {
  171. return _isEditing;
  172. }
  173. void EditBoxWinRT::openKeyboard()
  174. {
  175. m_dispatcher.Get()->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([this]() {
  176. removeTextBox();
  177. Canvas^ canvas = static_cast<Canvas^>(findXamlElement(m_panel.Get(), CANVAS_XAML_NAME));
  178. if (_password) {
  179. _textBox = createPasswordBox();
  180. }
  181. else {
  182. _textBox = createTextBox();
  183. }
  184. // Position the text box
  185. canvas->SetLeft(_textBox, _rect.X);
  186. canvas->SetTop(_textBox, _rect.Y - XAML_TOP_PADDING);
  187. // Finally, insert it into the XAML scene hierarchy and make the containing canvas visible
  188. canvas->Children->InsertAt(0, _textBox);
  189. canvas->Background = ref new Media::SolidColorBrush();
  190. canvas->Visibility = Visibility::Visible;
  191. _keydownToken = _textBox->KeyDown += ref new Windows::UI::Xaml::Input::KeyEventHandler(this, &cocos2d::ui::EditBoxWinRT::onKeyDown);
  192. _focusToken = _textBox->GotFocus += ref new Windows::UI::Xaml::RoutedEventHandler(this, &cocos2d::ui::EditBoxWinRT::onGotFocus);
  193. _unfocusToken = _textBox->LostFocus += ref new Windows::UI::Xaml::RoutedEventHandler(this, &cocos2d::ui::EditBoxWinRT::onLostFocus);
  194. _textBox->Focus(FocusState::Programmatic);
  195. if (_password) {
  196. static_cast<PasswordBox^>(_textBox)->SelectAll();
  197. }
  198. else {
  199. static_cast<TextBox^>(_textBox)->Select(_initialText->Length(), 0);
  200. }
  201. auto inputPane = Windows::UI::ViewManagement::InputPane::GetForCurrentView();
  202. }));
  203. }
  204. void EditBoxWinRT::setFontColor(Windows::UI::Color color)
  205. {
  206. _color = color;
  207. }
  208. void EditBoxWinRT::setFontFamily(Platform::String^ fontFamily)
  209. {
  210. _fontFamily = fontFamily;
  211. }
  212. void EditBoxWinRT::setFontSize(int fontSize)
  213. {
  214. _fontSize = fontSize;
  215. }
  216. void EditBoxWinRT::removeTextBox()
  217. {
  218. auto canvas = findXamlElement(m_panel.Get(), CANVAS_XAML_NAME);
  219. auto box = findXamlElement(canvas, EDIT_BOX_XAML_NAME);
  220. removeXamlElement(canvas, box);
  221. _isEditing = false;
  222. }
  223. void EditBoxWinRT::setInputFlag(int inputFlags) {
  224. _password = false;
  225. switch ((EditBox::InputFlag)inputFlags) {
  226. case EditBox::InputFlag::PASSWORD:
  227. _password = true;
  228. break;
  229. default:
  230. CCLOG("Warning: cannot set INITIAL_CAPS_* input flags for WinRT edit boxes");
  231. }
  232. }
  233. void EditBoxWinRT::setInputMode(int inputMode) {
  234. _multiline = (EditBox::InputMode)inputMode == EditBox::InputMode::ANY;
  235. _inputMode = inputMode;
  236. }
  237. void EditBoxWinRT::setTextHorizontalAlignment(int alignment) {
  238. _alignment = alignment;
  239. }
  240. void EditBoxWinRT::setMaxLength(int maxLength) {
  241. _maxLength = maxLength;
  242. }
  243. void EditBoxWinRT::_setTextHorizontalAlignment(TextBox^ textBox)
  244. {
  245. switch (_alignment) {
  246. default:
  247. case 0:
  248. textBox->TextAlignment = TextAlignment::Left;
  249. break;
  250. case 1:
  251. textBox->TextAlignment = TextAlignment::Center;
  252. break;
  253. case 2:
  254. textBox->TextAlignment = TextAlignment::Right;
  255. break;
  256. }
  257. }
  258. void EditBoxWinRT::setInputScope(TextBox^ textBox)
  259. {
  260. InputScope^ inputScope = ref new InputScope;
  261. InputScopeName^ name = ref new InputScopeName;
  262. switch ((EditBox::InputMode)_inputMode) {
  263. case EditBox::InputMode::SINGLE_LINE:
  264. case EditBox::InputMode::ANY:
  265. name->NameValue = InputScopeNameValue::Default;
  266. break;
  267. case EditBox::InputMode::EMAIL_ADDRESS:
  268. name->NameValue = InputScopeNameValue::EmailSmtpAddress;
  269. break;
  270. case EditBox::InputMode::DECIMAL:
  271. case EditBox::InputMode::NUMERIC:
  272. name->NameValue = InputScopeNameValue::Number;
  273. break;
  274. case EditBox::InputMode::PHONE_NUMBER:
  275. name->NameValue = InputScopeNameValue::TelephoneNumber;
  276. break;
  277. case EditBox::InputMode::URL:
  278. name->NameValue = InputScopeNameValue::Url;
  279. break;
  280. }
  281. textBox->InputScope = nullptr;
  282. inputScope->Names->Append(name);
  283. textBox->InputScope = inputScope;
  284. }
  285. void EditBoxWinRT::setPosition(Windows::Foundation::Rect rect)
  286. {
  287. _rect = rect;
  288. }
  289. void EditBoxWinRT::setSize(Windows::Foundation::Size size)
  290. {
  291. _size = size;
  292. }
  293. void EditBoxWinRT::setText(Platform::String^ text)
  294. {
  295. _initialText = text;
  296. // If already editing
  297. if (_isEditing) {
  298. m_dispatcher.Get()->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([this]() {
  299. auto textBox = static_cast<TextBox^>(_textBox);
  300. unsigned int currentStart = textBox->SelectionStart;
  301. bool cursorAtEnd = currentStart == textBox->Text->Length();
  302. textBox->Text = _initialText;
  303. if (cursorAtEnd || currentStart > textBox->Text->Length()) {
  304. currentStart = textBox->Text->Length();
  305. }
  306. textBox->Select(currentStart, 0);
  307. }));
  308. }
  309. }
  310. void EditBoxWinRT::setVisible(bool visible)
  311. {
  312. _visible = visible;
  313. // If already editing
  314. m_dispatcher.Get()->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([this]() {
  315. Canvas^ canvas = static_cast<Canvas^>(findXamlElement(m_panel.Get(), CANVAS_XAML_NAME));
  316. canvas->Visibility = _visible ? Visibility::Visible : Visibility::Collapsed;
  317. }));
  318. }
  319. UIEditBoxImplWinrt::UIEditBoxImplWinrt(EditBox* pEditText) : EditBoxImplCommon(pEditText)
  320. {
  321. auto beginHandler = ref new Windows::Foundation::EventHandler<Platform::String^>([this](Platform::Object^ sender, Platform::String^ arg) {
  322. this->editBoxEditingDidBegin();
  323. });
  324. auto changeHandler = ref new Windows::Foundation::EventHandler<Platform::String^>([this](Platform::Object^ sender, Platform::String^ arg) {
  325. auto text = PlatformStringToString(arg);
  326. this->editBoxEditingChanged(text);
  327. });
  328. auto endHandler = ref new Windows::Foundation::EventHandler<cocos2d::EndEventArgs^>([this](Platform::Object^ sender, cocos2d::EndEventArgs^ arg) {
  329. auto text = PlatformStringToString(arg->GetText());
  330. auto action = arg->GetAction();
  331. this->editBoxEditingDidEnd(text, static_cast<cocos2d::ui::EditBoxDelegate::EditBoxEndAction>(action));
  332. this->onEndEditing(text);
  333. });
  334. _system_control = ref new EditBoxWinRT(beginHandler, changeHandler, endHandler);
  335. }
  336. void UIEditBoxImplWinrt::setNativeFont(const char* pFontName, int fontSize)
  337. {
  338. // fontSize
  339. _fontSize = fontSize;
  340. auto transform = _editBox->getNodeToWorldTransform();
  341. cocos2d::Vec3 scale;
  342. transform.getScale(&scale);
  343. _system_control->setFontSize(_fontSize * cocos2d::Director::getInstance()->getOpenGLView()->getScaleY() /** scale.y*/);
  344. // fontFamily
  345. auto font = cocos2d::FontFreeType::create(pFontName, fontSize, cocos2d::GlyphCollection::DYNAMIC, nullptr);
  346. if (font != nullptr) {
  347. std::string fontName = "ms-appx:///Assets/Resources/" + std::string(pFontName) +'#' + font->getFontFamily();
  348. _system_control->setFontFamily(PlatformStringFromString(fontName));
  349. }
  350. }
  351. void UIEditBoxImplWinrt::setNativeFontColor(const Color4B& color)
  352. {
  353. Windows::UI::Color win_color = { 0xFF, color.r, color.g, color.b };
  354. _system_control->setFontColor(win_color);
  355. }
  356. void UIEditBoxImplWinrt::setNativeInputMode(EditBox::InputMode inputMode)
  357. {
  358. _system_control->setInputMode((int)inputMode);
  359. }
  360. void UIEditBoxImplWinrt::setNativeInputFlag(EditBox::InputFlag inputFlag)
  361. {
  362. _system_control->setInputFlag((int)inputFlag);
  363. }
  364. void UIEditBoxImplWinrt::setNativeTextHorizontalAlignment(cocos2d::TextHAlignment alignment)
  365. {
  366. _system_control->setTextHorizontalAlignment((int)alignment);
  367. }
  368. void UIEditBoxImplWinrt::setNativeText(const char* pText)
  369. {
  370. _system_control->setText(PlatformStringFromString(pText));
  371. }
  372. void UIEditBoxImplWinrt::setNativeVisible(bool visible)
  373. {
  374. _system_control->setVisible(visible);
  375. }
  376. void UIEditBoxImplWinrt::updateNativeFrame(const Rect& rect)
  377. {
  378. }
  379. void UIEditBoxImplWinrt::nativeOpenKeyboard()
  380. {
  381. // Update the text
  382. _system_control->setText(PlatformStringFromString(getText()));
  383. // Size
  384. auto glView = cocos2d::Director::getInstance()->getOpenGLView();
  385. auto transform = _editBox->getNodeToWorldTransform();
  386. cocos2d::Vec3 scale;
  387. transform.getScale(&scale);
  388. Windows::Foundation::Size xamlSize = { _editBox->getContentSize().width * glView->getScaleX() * scale.x, _editBox->getContentSize().height * glView->getScaleY() * scale.y };
  389. _system_control->setSize(xamlSize);
  390. _system_control->setFontSize(_fontSize * cocos2d::Director::getInstance()->getOpenGLView()->getScaleY() /** scale.y*/);
  391. // Position
  392. auto directorInstance = cocos2d::Director::getInstance();
  393. auto frameSize = glView->getFrameSize();
  394. auto winSize = directorInstance->getWinSize();
  395. auto leftBottom = _editBox->convertToWorldSpace(cocos2d::Point::ZERO);
  396. auto rightTop = _editBox->convertToWorldSpace(cocos2d::Point(_editBox->getContentSize().width, _editBox->getContentSize().height));
  397. Windows::Foundation::Rect rect;
  398. rect.X = frameSize.width / 2 + (leftBottom.x - winSize.width / 2) * glView->getScaleX();
  399. rect.Y = frameSize.height / 2 - (rightTop.y - winSize.height / 2) * glView->getScaleY();
  400. rect.Width = (rightTop.x - leftBottom.x) * glView->getScaleX();
  401. rect.Height = (rightTop.y - leftBottom.y) * glView->getScaleY();
  402. _system_control->setPosition(rect);
  403. // .. and open
  404. _system_control->openKeyboard();
  405. }
  406. void UIEditBoxImplWinrt::nativeCloseKeyboard()
  407. {
  408. _system_control->closeKeyboard();
  409. }
  410. void UIEditBoxImplWinrt::setNativeMaxLength(int maxLength)
  411. {
  412. _system_control->setMaxLength(maxLength);
  413. }
  414. cocos2d::Vec2 UIEditBoxImplWinrt::convertDesignCoordToXamlCoord(const cocos2d::Vec2& designCoord)
  415. {
  416. auto glView = cocos2d::Director::getInstance()->getOpenGLView();
  417. float viewH = glView->getFrameSize().height;
  418. Vec2 visiblePos = Vec2(designCoord.x * glView->getScaleX(), designCoord.y * glView->getScaleY());
  419. Vec2 screenGLPos = visiblePos + glView->getViewPortRect().origin;
  420. Vec2 xamlPos(screenGLPos.x, viewH - screenGLPos.y);
  421. return xamlPos;
  422. }
  423. } // namespace ui
  424. } // namespace cocos2d
  425. #endif // (CC_TARGET_PLATFORM == CC_PLATFORM_WP8 || CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)