UIWebViewImpl-ios.mm 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. /****************************************************************************
  2. Copyright (c) 2014-2016 Chukong Technologies Inc.
  3. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
  4. http://www.cocos2d-x.org
  5. Permission is hereby granted, free of charge, to any person obtaining a copy
  6. of this software and associated documentation files (the "Software"), to deal
  7. in the Software without restriction, including without limitation the rights
  8. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the Software is
  10. furnished to do so, subject to the following conditions:
  11. The above copyright notice and this permission notice shall be included in
  12. all copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. THE SOFTWARE.
  20. ****************************************************************************/
  21. #include "platform/CCPlatformConfig.h"
  22. // Webview not available on tvOS
  23. #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) && !defined(CC_TARGET_OS_TVOS)
  24. #include "ui/UIWebViewImpl-ios.h"
  25. #include "renderer/CCRenderer.h"
  26. #include "base/CCDirector.h"
  27. #include "platform/CCGLView.h"
  28. #include "platform/ios/CCEAGLView-ios.h"
  29. #include "platform/CCFileUtils.h"
  30. #include "ui/UIWebView.h"
  31. #import <JavaScriptCore/JavaScriptCore.h>
  32. static std::string getFixedBaseUrl(const std::string& baseUrl)
  33. {
  34. std::string fixedBaseUrl;
  35. if (baseUrl.empty() || baseUrl.at(0) != '/') {
  36. fixedBaseUrl = [[[NSBundle mainBundle] resourcePath] UTF8String];
  37. fixedBaseUrl += "/";
  38. fixedBaseUrl += baseUrl;
  39. }
  40. else {
  41. fixedBaseUrl = baseUrl;
  42. }
  43. size_t pos = 0;
  44. while ((pos = fixedBaseUrl.find(" ")) != std::string::npos) {
  45. fixedBaseUrl.replace(pos, 1, "%20");
  46. }
  47. if (fixedBaseUrl.at(fixedBaseUrl.length() - 1) != '/') {
  48. fixedBaseUrl += "/";
  49. }
  50. return fixedBaseUrl;
  51. }
  52. @interface UIWebViewWrapper : NSObject
  53. @property (nonatomic) std::function<bool(std::string url)> shouldStartLoading;
  54. @property (nonatomic) std::function<void(std::string url)> didFinishLoading;
  55. @property (nonatomic) std::function<void(std::string url)> didFailLoading;
  56. @property (nonatomic) std::function<void(std::string url)> onJsCallback;
  57. @property(nonatomic, readonly, getter=canGoBack) BOOL canGoBack;
  58. @property(nonatomic, readonly, getter=canGoForward) BOOL canGoForward;
  59. + (instancetype)newWebViewWrapper;
  60. - (void)setVisible:(bool)visible;
  61. - (void)setBounces:(bool)bounces;
  62. - (void)setOpacityWebView:(float)opacity;
  63. - (float)getOpacityWebView;
  64. - (void)setBackgroundTransparent;
  65. - (void)setFrameWithX:(float)x y:(float)y width:(float)width height:(float)height;
  66. - (void)setJavascriptInterfaceScheme:(const std::string &)scheme;
  67. - (void)loadData:(const std::string &)data MIMEType:(const std::string &)MIMEType textEncodingName:(const std::string &)encodingName baseURL:(const std::string &)baseURL;
  68. - (void)loadHTMLString:(const std::string &)string baseURL:(const std::string &)baseURL;
  69. - (void)loadUrl:(const std::string &)urlString cleanCachedData:(BOOL) needCleanCachedData;
  70. - (void)loadFile:(const std::string &)filePath;
  71. - (void)postUrl:(const std::string &)url data:(const std::string &)data;
  72. - (void)stopLoading;
  73. - (void)reload;
  74. - (void)evaluateJS:(const std::string &)js;
  75. - (void)goBack;
  76. - (void)goForward;
  77. - (void)OpenApp:(const std::string &)js;
  78. - (void)setScalesPageToFit:(const bool)scalesPageToFit;
  79. @end
  80. @interface UIWebViewWrapper () <UIWebViewDelegate>
  81. @property(nonatomic, retain) UIWebView *uiWebView;
  82. @property(nonatomic) JSContext* jsContext;
  83. @property(nonatomic, copy) NSString *jsScheme;
  84. @end
  85. @implementation UIWebViewWrapper {
  86. }
  87. + (instancetype) newWebViewWrapper {
  88. return [[self alloc] init];
  89. }
  90. - (instancetype)init {
  91. self = [super init];
  92. if (self) {
  93. self.uiWebView = nil;
  94. self.shouldStartLoading = nullptr;
  95. self.didFinishLoading = nullptr;
  96. self.didFailLoading = nullptr;
  97. }
  98. return self;
  99. }
  100. - (void)dealloc {
  101. self.uiWebView.delegate = nil;
  102. [self.uiWebView removeFromSuperview];
  103. [self.uiWebView release];
  104. self.uiWebView = nil;
  105. self.jsScheme = nil;
  106. [super dealloc];
  107. }
  108. - (void)setupWebView {
  109. if (!self.uiWebView) {
  110. self.uiWebView = [[UIWebView alloc] init];
  111. self.uiWebView.delegate = self;
  112. self.uiWebView.scrollView.bounces = NO;
  113. }
  114. if (!self.uiWebView.superview) {
  115. auto view = cocos2d::Director::getInstance()->getOpenGLView();
  116. auto eaglview = (CCEAGLView *) view->getEAGLView();
  117. [eaglview addSubview:self.uiWebView];
  118. }
  119. }
  120. - (void)setVisible:(bool)visible {
  121. if (!self.uiWebView) {[self setupWebView];}
  122. self.uiWebView.hidden = !visible;
  123. }
  124. - (void)setBounces:(bool)bounces {
  125. self.uiWebView.scrollView.bounces = bounces;
  126. }
  127. - (void)setOpacityWebView:(float)opacity {
  128. if (!self.uiWebView) {[self setupWebView];}
  129. self.uiWebView.alpha=opacity;
  130. [self.uiWebView setOpaque:NO];
  131. }
  132. -(float) getOpacityWebView{
  133. return self.uiWebView.alpha;
  134. }
  135. -(void) setBackgroundTransparent{
  136. if (!self.uiWebView) {[self setupWebView];}
  137. [self.uiWebView setOpaque:NO];
  138. [self.uiWebView setBackgroundColor:[UIColor clearColor]];
  139. }
  140. - (void)setFrameWithX:(float)x y:(float)y width:(float)width height:(float)height {
  141. if (!self.uiWebView) {[self setupWebView];}
  142. CGRect newFrame = CGRectMake(x, y, width, height);
  143. if (!CGRectEqualToRect(self.uiWebView.frame, newFrame)) {
  144. self.uiWebView.frame = CGRectMake(x, y, width, height);
  145. }
  146. }
  147. - (void)setJavascriptInterfaceScheme:(const std::string &)scheme {
  148. self.jsScheme = @(scheme.c_str());
  149. }
  150. - (void)loadData:(const std::string &)data MIMEType:(const std::string &)MIMEType textEncodingName:(const std::string &)encodingName baseURL:(const std::string &)baseURL {
  151. [self.uiWebView loadData:[NSData dataWithBytes:data.c_str() length:data.length()]
  152. MIMEType:@(MIMEType.c_str())
  153. textEncodingName:@(encodingName.c_str())
  154. baseURL:[NSURL URLWithString:@(getFixedBaseUrl(baseURL).c_str())]];
  155. }
  156. - (void)loadHTMLString:(const std::string &)string baseURL:(const std::string &)baseURL {
  157. if (!self.uiWebView) {[self setupWebView];}
  158. [self.uiWebView loadHTMLString:@(string.c_str()) baseURL:[NSURL URLWithString:@(getFixedBaseUrl(baseURL).c_str())]];
  159. }
  160. - (void)loadUrl:(const std::string &)urlString cleanCachedData:(BOOL) needCleanCachedData {
  161. if (!self.uiWebView) {[self setupWebView];}
  162. NSURL *url = [NSURL URLWithString:@(urlString.c_str())];
  163. NSURLRequest *request = nil;
  164. if (needCleanCachedData)
  165. request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
  166. else
  167. request = [NSURLRequest requestWithURL:url];
  168. [self.uiWebView loadRequest:request];
  169. }
  170. - (void)loadFile:(const std::string &)filePath {
  171. if (!self.uiWebView) {[self setupWebView];}
  172. NSURL *url = [NSURL fileURLWithPath:@(filePath.c_str())];
  173. NSURLRequest *request = [NSURLRequest requestWithURL:url];
  174. [self.uiWebView loadRequest:request];
  175. }
  176. - (void)postUrl:(const std::string &)url data:(const std::string &)data{
  177. if (!self.uiWebView) {[self setupWebView];}
  178. NSURL *url2 = [NSURL URLWithString: @(url.c_str())];
  179. NSString *body = [[NSString alloc] initWithUTF8String:data.c_str()];
  180. NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url2];
  181. [request setHTTPMethod: @"POST"];
  182. [request setHTTPBody: [body dataUsingEncoding: NSUTF8StringEncoding]];
  183. [self.uiWebView loadRequest: request];
  184. }
  185. - (void)stopLoading {
  186. [self.uiWebView stopLoading];
  187. }
  188. - (void)reload {
  189. [self.uiWebView reload];
  190. }
  191. - (BOOL)canGoForward {
  192. return self.uiWebView.canGoForward;
  193. }
  194. - (BOOL)canGoBack {
  195. return self.uiWebView.canGoBack;
  196. }
  197. - (void)goBack {
  198. [self.uiWebView goBack];
  199. }
  200. - (void)goForward {
  201. [self.uiWebView goForward];
  202. }
  203. -(void)OpenApp:(const std::string &)js
  204. {
  205. NSLog(@"OpenApp %@",js.c_str());
  206. }
  207. - (void)evaluateJS:(const std::string &)js {
  208. if (!self.uiWebView) {[self setupWebView];}
  209. [self.uiWebView stringByEvaluatingJavaScriptFromString:@(js.c_str())];
  210. }
  211. - (void)setScalesPageToFit:(const bool)scalesPageToFit {
  212. if (!self.uiWebView) {[self setupWebView];}
  213. self.uiWebView.scalesPageToFit = scalesPageToFit;
  214. }
  215. #pragma mark - UIWebViewDelegate
  216. - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
  217. NSString *url = [[request URL] absoluteString];
  218. if ([[[request URL] scheme] isEqualToString:self.jsScheme]) {
  219. self.onJsCallback([url UTF8String]);
  220. return NO;
  221. }
  222. if (self.shouldStartLoading && url) {
  223. return self.shouldStartLoading([url UTF8String]);
  224. }
  225. return YES;
  226. }
  227. - (void)webViewDidFinishLoad:(UIWebView *)webView {
  228. if (self.didFinishLoading) {
  229. NSString *url = [[webView.request URL] absoluteString];
  230. self.didFinishLoading([url UTF8String]);
  231. }
  232. _jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
  233. _jsContext[@"OpenAppEx"] = ^(NSString* str) {
  234. NSArray *args = [JSContext currentArguments];
  235. dispatch_async(dispatch_get_main_queue(), ^{
  236. self.onJsCallback([str UTF8String]);
  237. });
  238. };
  239. _jsContext.exceptionHandler = ^(JSContext *context, JSValue *exceptionValue) {
  240. context.exception = exceptionValue;
  241. NSLog(@"Òì³£ÐÅÏ¢£º%@", exceptionValue);
  242. };
  243. }
  244. - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
  245. if (self.didFailLoading) {
  246. NSString *url = error.userInfo[NSURLErrorFailingURLStringErrorKey];
  247. if (url) {
  248. self.didFailLoading([url UTF8String]);
  249. }
  250. }
  251. }
  252. @end
  253. namespace cocos2d {
  254. namespace experimental {
  255. namespace ui{
  256. WebViewImpl::WebViewImpl(WebView *webView)
  257. : _uiWebViewWrapper([UIWebViewWrapper newWebViewWrapper]),
  258. _webView(webView) {
  259. _uiWebViewWrapper.shouldStartLoading = [this](std::string url) {
  260. if (this->_webView->_onShouldStartLoading) {
  261. return this->_webView->_onShouldStartLoading(this->_webView, url);
  262. }
  263. return true;
  264. };
  265. _uiWebViewWrapper.didFinishLoading = [this](std::string url) {
  266. if (this->_webView->_onDidFinishLoading) {
  267. this->_webView->_onDidFinishLoading(this->_webView, url);
  268. }
  269. };
  270. _uiWebViewWrapper.didFailLoading = [this](std::string url) {
  271. if (this->_webView->_onDidFailLoading) {
  272. this->_webView->_onDidFailLoading(this->_webView, url);
  273. }
  274. };
  275. _uiWebViewWrapper.onJsCallback = [this](std::string url) {
  276. if (this->_webView->_onJSCallback) {
  277. this->_webView->_onJSCallback(this->_webView, url);
  278. }
  279. };
  280. }
  281. WebViewImpl::~WebViewImpl(){
  282. [_uiWebViewWrapper release];
  283. _uiWebViewWrapper = nullptr;
  284. }
  285. void WebViewImpl::setJavascriptInterfaceScheme(const std::string &scheme) {
  286. [_uiWebViewWrapper setJavascriptInterfaceScheme:scheme];
  287. }
  288. void WebViewImpl::loadData(const Data &data,
  289. const std::string &MIMEType,
  290. const std::string &encoding,
  291. const std::string &baseURL) {
  292. std::string dataString(reinterpret_cast<char *>(data.getBytes()), static_cast<unsigned int>(data.getSize()));
  293. [_uiWebViewWrapper loadData:dataString MIMEType:MIMEType textEncodingName:encoding baseURL:baseURL];
  294. }
  295. void WebViewImpl::loadHTMLString(const std::string &string, const std::string &baseURL) {
  296. [_uiWebViewWrapper loadHTMLString:string baseURL:baseURL];
  297. }
  298. void WebViewImpl::loadURL(const std::string &url) {
  299. this->loadURL(url, false);
  300. }
  301. void WebViewImpl::loadURL(const std::string &url, bool cleanCachedData) {
  302. [_uiWebViewWrapper loadUrl:url cleanCachedData:cleanCachedData];
  303. }
  304. void WebViewImpl::loadFile(const std::string &fileName) {
  305. auto fullPath = cocos2d::FileUtils::getInstance()->fullPathForFilename(fileName);
  306. [_uiWebViewWrapper loadFile:fullPath];
  307. }
  308. void WebViewImpl::PostURL(const std::string &url, const std::string &data)
  309. {
  310. [_uiWebViewWrapper postUrl:url data:data];
  311. }
  312. void WebViewImpl::stopLoading() {
  313. [_uiWebViewWrapper stopLoading];
  314. }
  315. void WebViewImpl::reload() {
  316. [_uiWebViewWrapper reload];
  317. }
  318. bool WebViewImpl::canGoBack() {
  319. return _uiWebViewWrapper.canGoBack;
  320. }
  321. bool WebViewImpl::canGoForward() {
  322. return _uiWebViewWrapper.canGoForward;
  323. }
  324. void WebViewImpl::goBack() {
  325. [_uiWebViewWrapper goBack];
  326. }
  327. void WebViewImpl::goForward() {
  328. [_uiWebViewWrapper goForward];
  329. }
  330. void WebViewImpl::evaluateJS(const std::string &js) {
  331. [_uiWebViewWrapper evaluateJS:js];
  332. }
  333. void WebViewImpl::setBounces(bool bounces) {
  334. [_uiWebViewWrapper setBounces:bounces];
  335. }
  336. void WebViewImpl::setScalesPageToFit(const bool scalesPageToFit) {
  337. [_uiWebViewWrapper setScalesPageToFit:scalesPageToFit];
  338. }
  339. void WebViewImpl::draw(cocos2d::Renderer *renderer, cocos2d::Mat4 const &transform, uint32_t flags) {
  340. if (flags & cocos2d::Node::FLAGS_TRANSFORM_DIRTY) {
  341. auto director = cocos2d::Director::getInstance();
  342. auto glView = director->getOpenGLView();
  343. auto frameSize = glView->getFrameSize();
  344. auto scaleFactor = [static_cast<CCEAGLView *>(glView->getEAGLView()) contentScaleFactor];
  345. auto winSize = director->getWinSize();
  346. auto leftBottom = this->_webView->convertToWorldSpace(cocos2d::Vec2::ZERO);
  347. auto rightTop = this->_webView->convertToWorldSpace(cocos2d::Vec2(this->_webView->getContentSize().width, this->_webView->getContentSize().height));
  348. auto x = (frameSize.width / 2 + (leftBottom.x - winSize.width / 2) * glView->getScaleX()) / scaleFactor;
  349. auto y = (frameSize.height / 2 - (rightTop.y - winSize.height / 2) * glView->getScaleY()) / scaleFactor;
  350. auto width = (rightTop.x - leftBottom.x) * glView->getScaleX() / scaleFactor;
  351. auto height = (rightTop.y - leftBottom.y) * glView->getScaleY() / scaleFactor;
  352. [_uiWebViewWrapper setFrameWithX:x
  353. y:y
  354. width:width
  355. height:height];
  356. }
  357. }
  358. void WebViewImpl::setVisible(bool visible){
  359. [_uiWebViewWrapper setVisible:visible];
  360. }
  361. void WebViewImpl::setOpacityWebView(float opacity){
  362. [_uiWebViewWrapper setOpacityWebView: opacity];
  363. }
  364. float WebViewImpl::getOpacityWebView() const{
  365. return [_uiWebViewWrapper getOpacityWebView];
  366. }
  367. void WebViewImpl::setBackgroundTransparent(){
  368. [_uiWebViewWrapper setBackgroundTransparent];
  369. }
  370. } // namespace ui
  371. } // namespace experimental
  372. } //namespace cocos2d
  373. #endif // CC_TARGET_PLATFORM == CC_PLATFORM_IOS