PuzzleSDK
DownloaderTest.cpp
浏览该文件的文档.
1/****************************************************************************
2 Copyright (c) 2012 cocos2d-x.org
3 Copyright (c) 2013-2016 Chukong Technologies Inc.
4 Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
5
6 http://www.cocos2d-x.org
7
8 Permission is hereby granted, free of charge, to any person obtaining a copy
9 of this software and associated documentation files (the "Software"), to deal
10 in the Software without restriction, including without limitation the rights
11 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 copies of the Software, and to permit persons to whom the Software is
13 furnished to do so, subject to the following conditions:
14
15 The above copyright notice and this permission notice shall be included in
16 all copies or substantial portions of the Software.
17
18 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24 THE SOFTWARE.
25 ****************************************************************************/
26
27#include "DownloaderTest.h"
28
29#include "../testResource.h"
30
31#include "ui/UILoadingBar.h"
32#include "ui/UIButton.h"
33#include "network/CCDownloader.h"
34
36
37static const char* sURLList[] =
38{
39 "https://www.cocos2d-x.org/attachments/802/cocos2dx_landscape.png",
40 "https://cocos2d-x.org/images/logo.png",
41 "https://www.cocos2d-x.org/attachments/1503/no_exist.txt", // try to download no exist file
42 "https://github.com/openssl/openssl/archive/OpenSSL_1_1_1a.zip",
43};
44const static int sListSize = (sizeof(sURLList)/sizeof(sURLList[0]));
45static const char* sNameList[sListSize] =
46{
47 "cocos2dx_landscape.png",
48 "logo.png",
49 "inexist file",
50 "big file",
51};
52
53struct DownloaderTest : public TestCase
54{
56
57 virtual std::string title() const override { return "Downloader Test"; }
58
59 std::unique_ptr<network::Downloader> downloader;
60
62 {
63 downloader.reset(new network::Downloader());
64 }
65
66 enum {
72 };
73
74 Node* createDownloadView(const char *name, const cocos2d::ui::Button::ccWidgetClickCallback &callback)
75 {
76 Size viewSize(220, 120);
77 float margin = 5;
78
79 // create background
80 auto bg = ui::Scale9Sprite::createWithSpriteFrameName("button_actived.png");
81 bg->setContentSize(viewSize);
82
83 // add a title on the top
84 auto title = Label::createWithTTF(name,"fonts/arial.ttf",16);
85 title->setTag(TAG_TITLE);
86 title->setAnchorPoint(Vec2(0.5f, 1.0f));
87 title->setPosition(viewSize.width / 2, viewSize.height - margin);
88 bg->addChild(title, 10);
89
90 // add a button on the bottom
91 auto btn = ui::Button::create("cocosui/animationbuttonnormal.png",
92 "cocosui/animationbuttonpressed.png");
93 btn->setTag(TAG_BUTTON);
94 btn->setTitleText("Download");
95 btn->setAnchorPoint(Vec2(0.5f, 0.0f));
96 btn->setPosition(Vec2(viewSize.width / 2, margin));
97 btn->addClickEventListener(callback);
98 bg->addChild(btn, 10);
99
100 // add a progress bar
101 auto bar = ui::LoadingBar::create("ccs-res/cocosui/sliderProgress.png");
102 bar->setTag(TAG_PROGRESS_BAR);
103 bar->ignoreContentAdaptWithSize(false);
104 bar->setAnchorPoint(Vec2(0.5f, 0.0f));
105 bar->setContentSize(Size(viewSize.width - margin * 2, btn->getContentSize().height));
106 bar->setPosition(btn->getPosition());
107 bar->setVisible(false);
108 bg->addChild(bar, 10);
109
110 // add a status label
111 auto label = Label::createWithTTF("","fonts/arial.ttf",14);
112 label->setTag(TAG_STATUS);
113 label->setAnchorPoint(Vec2(0.5f, 0.5f));
114 label->setPosition(Vec2(viewSize.width / 2, viewSize.height / 2));
115 label->setContentSize(Size(viewSize.width, 0.0f));
116 label->setAlignment(TextHAlignment::CENTER, TextVAlignment::CENTER);
117 label->setDimensions(viewSize.width, viewSize.height);
118 bg->addChild(label, 20);
119
120 return bg;
121 }
122
123 virtual void onEnter() override
124 {
126 _restartTestItem->setVisible(true);
127
128 SpriteFrameCache::getInstance()->addSpriteFramesWithFile(s_s9s_ui_plist);
129
130 // add four download view in test case
131 Node* topRightView = createDownloadView(sNameList[0], [this](Ref*)
132 {
133 auto view = this->getChildByName(sNameList[0]);
134 auto sprite = view->getChildByTag(TAG_SPRITE);
135 if (sprite)
136 {
137 sprite->removeFromParentAndCleanup(true);
138 }
139 auto btn = (ui::Button*)view->getChildByTag(TAG_BUTTON);
140 btn->setEnabled(false);
141 btn->setVisible(false);
142 auto bar = (ui::LoadingBar*)view->getChildByTag(TAG_PROGRESS_BAR);
143 bar->setPercent(0);
144 bar->setVisible(true);
145 this->downloader->createDownloadDataTask(sURLList[0], sNameList[0]);
146 });
147 topRightView->setName(sNameList[0]);
148 topRightView->setAnchorPoint(Vec2(0, 0));
149 topRightView->setPosition(VisibleRect::center());
150 this->addChild(topRightView);
151
152 Node* topLeftView = createDownloadView(sNameList[1], [this](Ref*)
153 {
154 auto view = this->getChildByName(sNameList[1]);
155 auto sprite = view->getChildByTag(TAG_SPRITE);
156 if (sprite)
157 {
158 sprite->removeFromParentAndCleanup(true);
159 }
160 auto btn = (ui::Button*)view->getChildByTag(TAG_BUTTON);
161 btn->setEnabled(false);
162 btn->setVisible(false);
163 auto bar = (ui::LoadingBar*)view->getChildByTag(TAG_PROGRESS_BAR);
164 bar->setPercent(0);
165 bar->setVisible(true);
166 bar->setEnabled(true);
167 this->downloader->createDownloadDataTask(sURLList[1], sNameList[1]);
168 });
169 topLeftView->setName(sNameList[1]);
170 topLeftView->setAnchorPoint(Vec2(1.0f, 0.0f));
171 topLeftView->setPosition(VisibleRect::center());
172 this->addChild(topLeftView);
173
174 Node* bottomLeftView = createDownloadView(sNameList[2], [this](Ref*)
175 {
176 auto view = this->getChildByName(sNameList[2]);
177 auto sprite = view->getChildByTag(TAG_SPRITE);
178 if (sprite)
179 {
180 sprite->removeFromParentAndCleanup(true);
181 }
182 auto btn = (ui::Button*)view->getChildByTag(TAG_BUTTON);
183 btn->setEnabled(false);
184 btn->setVisible(false);
185 auto bar = (ui::LoadingBar*)view->getChildByTag(TAG_PROGRESS_BAR);
186 bar->setPercent(0);
187 bar->setVisible(true);
188 bar->setEnabled(true);
189 auto path = FileUtils::getInstance()->getWritablePath() + "CppTests/DownloaderTest/" + sNameList[2];
190 this->downloader->createDownloadFileTask(sURLList[2], path, sNameList[2]);
191 });
192 bottomLeftView->setName(sNameList[2]);
193 bottomLeftView->setAnchorPoint(Vec2(1, 1));
194 bottomLeftView->setPosition(VisibleRect::center());
195 this->addChild(bottomLeftView);
196
197 Node* bottomRightView = createDownloadView(sNameList[3], [this](Ref*)
198 {
199 auto view = this->getChildByName(sNameList[3]);
200 auto btn = (ui::Button*)view->getChildByTag(TAG_BUTTON);
201 btn->setEnabled(false);
202 btn->setVisible(false);
203 auto bar = (ui::LoadingBar*)view->getChildByTag(TAG_PROGRESS_BAR);
204 bar->setPercent(0);
205 bar->setVisible(true);
206 bar->setEnabled(true);
207 auto path = FileUtils::getInstance()->getWritablePath() + "CppTests/DownloaderTest/" + sNameList[3];
208 this->downloader->createDownloadFileTask(sURLList[3], path, sNameList[3]);
209 });
210 bottomRightView->setName(sNameList[3]);
211 bottomRightView->setAnchorPoint(Vec2(0, 1));
212 bottomRightView->setPosition(VisibleRect::center());
213 this->addChild(bottomRightView);
214
215 // define progress callback
216 downloader->onTaskProgress = [this](const network::DownloadTask& task,
217 int64_t bytesReceived,
218 int64_t totalBytesReceived,
219 int64_t totalBytesExpected)
220 {
221 Node* view = this->getChildByName(task.identifier);
222 auto bar = (ui::LoadingBar*)view->getChildByTag(TAG_PROGRESS_BAR);
223 float percent = float(totalBytesReceived * 100) / totalBytesExpected;
224 bar->setPercent(percent);
225 char buf[32];
226 sprintf(buf, "%.1f%%[total %d KB]", percent, int(totalBytesExpected/1024));
227 auto status = (Label*)view->getChildByTag(TAG_STATUS);
228 status->setString(buf);
229 };
230
231 // define success callback
232 downloader->onDataTaskSuccess = [this](const cocos2d::network::DownloadTask& task,
233 std::vector<unsigned char>& data)
234 {
235 // create texture from data
236 Texture2D* texture = nullptr;
237 do
238 {
239 Image img;
240 if (false == img.initWithImageData(data.data(), data.size()))
241 {
242 break;
243 }
244
245 texture = new Texture2D();
246 if (false == texture->initWithImage(&img))
247 {
248 break;
249 }
250 auto sprite = Sprite::createWithTexture(texture);
251 auto view = this->getChildByName(task.identifier);
252 auto viewSize = view->getContentSize();
253 sprite->setPosition(viewSize.width / 2, viewSize.height / 2);
254 auto spriteSize = sprite->getContentSize();
255 float scale = MIN((viewSize.height - 20) / spriteSize.height, (viewSize.width - 20) / spriteSize.width);
256 sprite->setScale(scale);
257 view->addChild(sprite, 5, TAG_SPRITE);
258
259 auto btn = (ui::Button*)view->getChildByTag(TAG_BUTTON);
260 btn->setEnabled(true);
261 btn->setVisible(true);
262 auto bar = (ui::LoadingBar*)view->getChildByTag(TAG_PROGRESS_BAR);
263 bar->setVisible(false);
264 } while (0);
265 CC_SAFE_RELEASE(texture);
266 };
267
268 downloader->onFileTaskSuccess = [this](const cocos2d::network::DownloadTask& task)
269 {
270 Texture2D* texture = nullptr;
271 do
272 {
273 auto view = this->getChildByName(task.identifier);
274 if (std::string::npos == task.storagePath.find(".png"))
275 {
276 // download big file success
277 char buf[32];
278 sprintf(buf, "Download [%s] success.", task.identifier.c_str());
279 auto status = (Label*)view->getChildByTag(TAG_STATUS);
280 status->setString(buf);
281 break;
282 }
283 // create sprite from file
284 auto sprite = Sprite::create(task.storagePath);
285 auto viewSize = view->getContentSize();
286 sprite->setPosition(viewSize.width / 2, viewSize.height / 2);
287 auto spriteSize = sprite->getContentSize();
288 float scale = MIN((viewSize.height - 20) / spriteSize.height, (viewSize.width - 20) / spriteSize.width);
289 sprite->setScale(scale);
290 view->addChild(sprite, 5, TAG_SPRITE);
291
292 auto btn = (ui::Button*)view->getChildByTag(TAG_BUTTON);
293 btn->setEnabled(true);
294 btn->setVisible(true);
295 auto bar = (ui::LoadingBar*)view->getChildByTag(TAG_PROGRESS_BAR);
296 bar->setVisible(false);
297 } while (0);
298 CC_SAFE_RELEASE(texture);
299 };
300
301 // define failed callback
302 downloader->onTaskError = [this](const cocos2d::network::DownloadTask& task,
303 int errorCode,
304 int errorCodeInternal,
305 const std::string& errorStr)
306 {
307 log("Failed to download : %s, identifier(%s) error code(%d), internal error code(%d) desc(%s)"
308 , task.requestURL.c_str()
309 , task.identifier.c_str()
310 , errorCode
311 , errorCodeInternal
312 , errorStr.c_str());
313 auto view = this->getChildByName(task.identifier);
314 auto status = (Label*)view->getChildByTag(TAG_STATUS);
315 status->setString(errorStr.length() ? errorStr : "Download failed.");
316
317 auto btn = (ui::Button*)view->getChildByTag(TAG_BUTTON);
318 btn->setEnabled(true);
319 btn->setVisible(true);
320 };
321 }
322};
323
325{
327
328 virtual std::string title() const override { return "Downloader Multi Task"; }
329 virtual std::string subtitle() const override { return "see the console output"; }
330
331 std::unique_ptr<network::Downloader> downloader;
332
334 {
335 // countOfMaxProcessingTasks 32
336 network::DownloaderHints hints = {32, 60, ".going"};
337 downloader.reset(new network::Downloader(hints));
338 }
339
340 virtual void onEnter() override
341 {
343 char path[256];
344 char name[64];
345 // add 64 download task at same time.
346 for(int i=0; i< 64;i++){
347 sprintf(name, "%d_%s", i, sNameList[0]);
348 sprintf(path, "%sCppTests/DownloaderTest/%s", FileUtils::getInstance()->getWritablePath().c_str(), name);
349 log("downloader task create: %s", name);
350 this->downloader->createDownloadFileTask(sURLList[0], path, name);
351 }
352
353 downloader->onFileTaskSuccess = ([] (const network::DownloadTask& task) {
354 log("downloader task success: %s", task.identifier.c_str());
355 });
356
357 downloader->onTaskError = ([] (const network::DownloadTask& task, int errorCode, int errorCodeInternal, const std::string& errorStr) {
358 log("downloader task failed : %s, identifier(%s) error code(%d), internal error code(%d) desc(%s)"
359 , task.requestURL.c_str()
360 , task.identifier.c_str()
361 , errorCode
362 , errorCodeInternal
363 , errorStr.c_str());
364 });
365 }
366};
367
368DownloaderTests::DownloaderTests()
369{
372};
#define ADD_TEST_CASE(__className__)
Definition: BaseTest.h:211
static const char * sNameList[sListSize]
static const int sListSize
USING_NS_CC
static const char * sURLList[]
cocos2d::MenuItemImage * _restartTestItem
Definition: BaseTest.h:103
virtual void onEnter() override
Definition: BaseTest.cpp:430
static cocos2d::Vec2 center()
Definition: VisibleRect.cpp:69
virtual void onEnter() override
std::unique_ptr< network::Downloader > downloader
virtual std::string title() const override
CREATE_FUNC(DownloaderMultiTask)
virtual std::string subtitle() const override
virtual void onEnter() override
virtual std::string title() const override
std::unique_ptr< network::Downloader > downloader
CREATE_FUNC(DownloaderTest)
Node * createDownloadView(const char *name, const cocos2d::ui::Button::ccWidgetClickCallback &callback)
static const char s_s9s_ui_plist[]
Definition: testResource.h:70