CCWinRTUtils.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. /****************************************************************************
  2. Copyright (c) 2010-2013 cocos2d-x.org
  3. Copyright (c) Microsoft Open Technologies, Inc.
  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/winrt/CCWinRTUtils.h"
  22. #include <wrl/client.h>
  23. #include <wrl/wrappers/corewrappers.h>
  24. #include <ppl.h>
  25. #include <ppltasks.h>
  26. #include <sstream>
  27. #include "base/ccMacros.h"
  28. #include "platform/CCPlatformMacros.h"
  29. #include "platform/CCFileUtils.h"
  30. #include "base/CCUserDefault.h"
  31. using namespace Windows::UI::Xaml;
  32. using namespace Windows::UI::Xaml::Controls;
  33. NS_CC_BEGIN
  34. using namespace Windows::Graphics::Display;
  35. using namespace Windows::Storage;
  36. using namespace concurrency;
  37. using namespace Platform;
  38. using namespace Windows::Storage;
  39. using namespace Windows::Storage::Pickers;
  40. using namespace Windows::Storage::Streams;
  41. using namespace Windows::Networking::Connectivity;
  42. bool isWindowsPhone()
  43. {
  44. #if _MSC_VER >= 1900
  45. if (Windows::Foundation::Metadata::ApiInformation::IsTypePresent("Windows.Phone.UI.Input.HardwareButtons"))
  46. return true;
  47. else
  48. return false;
  49. #elif (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP)
  50. return true;
  51. #else
  52. return false;
  53. #endif
  54. }
  55. CC_DEPRECATED_ATTRIBUTE std::wstring CC_DLL CCUtf8ToUnicode(const char * pszUtf8Str, unsigned len /*= -1*/)
  56. {
  57. if (len == -1)
  58. {
  59. return StringUtf8ToWideChar(pszUtf8Str);
  60. }
  61. else
  62. {
  63. std::wstring ret;
  64. do
  65. {
  66. if (!pszUtf8Str || !len) break;
  67. // get UTF16 string length
  68. int wLen = MultiByteToWideChar(CP_UTF8, 0, pszUtf8Str, len, 0, 0);
  69. if (0 == wLen || 0xFFFD == wLen) break;
  70. // convert string
  71. wchar_t * pwszStr = new wchar_t[wLen + 1];
  72. if (!pwszStr) break;
  73. pwszStr[wLen] = 0;
  74. MultiByteToWideChar(CP_UTF8, 0, pszUtf8Str, len, pwszStr, wLen + 1);
  75. ret = pwszStr;
  76. CC_SAFE_DELETE_ARRAY(pwszStr);
  77. } while (0);
  78. return ret;
  79. }
  80. }
  81. CC_DEPRECATED_ATTRIBUTE std::string CC_DLL CCUnicodeToUtf8(const wchar_t* pwszStr)
  82. {
  83. return StringWideCharToUtf8(pwszStr);
  84. }
  85. std::wstring StringUtf8ToWideChar(const std::string& strUtf8)
  86. {
  87. std::wstring ret;
  88. if (!strUtf8.empty())
  89. {
  90. int nNum = MultiByteToWideChar(CP_UTF8, 0, strUtf8.c_str(), -1, nullptr, 0);
  91. if (nNum)
  92. {
  93. WCHAR* wideCharString = new WCHAR[nNum + 1];
  94. wideCharString[0] = 0;
  95. nNum = MultiByteToWideChar(CP_UTF8, 0, strUtf8.c_str(), -1, wideCharString, nNum + 1);
  96. ret = wideCharString;
  97. delete[] wideCharString;
  98. }
  99. else
  100. {
  101. CCLOG("Wrong convert to WideChar code:0x%x", GetLastError());
  102. }
  103. }
  104. return ret;
  105. }
  106. std::string StringWideCharToUtf8(const std::wstring& strWideChar)
  107. {
  108. std::string ret;
  109. if (!strWideChar.empty())
  110. {
  111. int nNum = WideCharToMultiByte(CP_UTF8, 0, strWideChar.c_str(), -1, nullptr, 0, nullptr, FALSE);
  112. if (nNum)
  113. {
  114. char* utf8String = new char[nNum + 1];
  115. utf8String[0] = 0;
  116. nNum = WideCharToMultiByte(CP_UTF8, 0, strWideChar.c_str(), -1, utf8String, nNum + 1, nullptr, FALSE);
  117. ret = utf8String;
  118. delete[] utf8String;
  119. }
  120. else
  121. {
  122. CCLOG("Wrong convert to Utf8 code:0x%x", GetLastError());
  123. }
  124. }
  125. return ret;
  126. }
  127. std::string PlatformStringToString(Platform::String^ s) {
  128. return StringWideCharToUtf8(std::wstring(s->Data()));
  129. }
  130. Platform::String^ PlatformStringFromString(const std::string& s)
  131. {
  132. std::wstring ws = StringUtf8ToWideChar(s);
  133. return ref new Platform::String(ws.data(), static_cast<unsigned int>(ws.length()));
  134. }
  135. #if 0
  136. // Method to convert a length in device-independent pixels (DIPs) to a length in physical pixels.
  137. float ConvertDipsToPixels(float dips)
  138. {
  139. static const float dipsPerInch = 96.0f;
  140. return floor(dips * DisplayProperties::LogicalDpi / dipsPerInch + 0.5f); // Round to nearest integer.
  141. }
  142. float getScaledDPIValue(float v) {
  143. auto dipFactor = DisplayProperties::LogicalDpi / 96.0f;
  144. return v * dipFactor;
  145. }
  146. #endif
  147. void CC_DLL CCLogIPAddresses()
  148. {
  149. auto hostnames = NetworkInformation::GetHostNames();
  150. int length = hostnames->Size;
  151. for(int i = 0; i < length; i++)
  152. {
  153. auto hn = hostnames->GetAt(i);
  154. if (hn->IPInformation != nullptr)
  155. {
  156. std::string s = PlatformStringToString(hn->DisplayName);
  157. log("IP Address: %s:", s.c_str());
  158. }
  159. }
  160. }
  161. std::string CC_DLL getDeviceIPAddresses()
  162. {
  163. std::stringstream result;
  164. auto hostnames = NetworkInformation::GetHostNames();
  165. int length = hostnames->Size;
  166. for(int i = 0; i < length; i++)
  167. {
  168. auto hn = hostnames->GetAt(i);
  169. if (hn->IPInformation != nullptr)
  170. {
  171. result << PlatformStringToString(hn->DisplayName) << std::endl;
  172. }
  173. }
  174. return result.str();
  175. }
  176. Platform::Object^ findXamlElement(Platform::Object^ parent, Platform::String^ name)
  177. {
  178. if (parent == nullptr || name == nullptr || name->Length() == 0)
  179. {
  180. return nullptr;
  181. }
  182. FrameworkElement^ element = dynamic_cast<FrameworkElement^>(parent);
  183. if (element == nullptr)
  184. {
  185. return nullptr;
  186. }
  187. if (element->Name == name)
  188. {
  189. return element;
  190. }
  191. Panel^ panel = dynamic_cast<Panel^>(element);
  192. if (panel == nullptr)
  193. {
  194. return nullptr;
  195. }
  196. int count = panel->Children->Size;
  197. for (int i = 0; i < count; i++)
  198. {
  199. auto result = findXamlElement(panel->Children->GetAt(i), name);
  200. if (result != nullptr)
  201. {
  202. return result;
  203. }
  204. }
  205. return nullptr;
  206. }
  207. bool removeXamlElement(Platform::Object^ parent, Platform::Object^ element)
  208. {
  209. Panel^ panel = dynamic_cast<Panel^>(parent);
  210. if (panel == nullptr)
  211. {
  212. return false;
  213. }
  214. UIElement^ uiElement = dynamic_cast<UIElement^>(element);
  215. if (uiElement == nullptr)
  216. {
  217. return false;
  218. }
  219. unsigned int index;
  220. if (!panel->Children->IndexOf(uiElement, &index))
  221. {
  222. return false;
  223. }
  224. panel->Children->RemoveAt(index);
  225. return true;
  226. }
  227. bool replaceXamlElement(Platform::Object^ parent, Platform::Object^ add, Platform::Object^ remove)
  228. {
  229. Panel^ panel = dynamic_cast<Panel^>(parent);
  230. if (panel == nullptr)
  231. {
  232. return false;
  233. }
  234. UIElement^ addElement = dynamic_cast<UIElement^>(add);
  235. if (addElement == nullptr)
  236. {
  237. return false;
  238. }
  239. UIElement^ removeElement = dynamic_cast<UIElement^>(remove);
  240. if (removeElement == nullptr)
  241. {
  242. return false;
  243. }
  244. unsigned int index;
  245. if (!panel->Children->IndexOf(removeElement, &index))
  246. {
  247. return false;
  248. }
  249. panel->Children->RemoveAt(index);
  250. panel->Children->InsertAt(index, addElement);
  251. return true;
  252. }
  253. // Function that reads from a binary file asynchronously.
  254. Concurrency::task<Platform::Array<byte>^> ReadDataAsync(Platform::String^ path)
  255. {
  256. using namespace Windows::Storage;
  257. using namespace Concurrency;
  258. return create_task(StorageFile::GetFileFromPathAsync(path)).then([&](StorageFile^ f)
  259. {
  260. return FileIO::ReadBufferAsync(f);
  261. }).then([] (Streams::IBuffer^ fileBuffer) -> Platform::Array<byte>^
  262. {
  263. auto fileData = ref new Platform::Array<byte>(fileBuffer->Length);
  264. Streams::DataReader::FromBuffer(fileBuffer)->ReadBytes(fileData);
  265. return fileData;
  266. });
  267. }
  268. std::string computeHashForFile(const std::string& filePath)
  269. {
  270. std::string ret = filePath;
  271. size_t pos = ret.find_last_of('/');
  272. if (pos != std::string::npos) {
  273. ret = ret.substr(pos);
  274. }
  275. pos = ret.find_last_of('.');
  276. if (pos != std::string::npos) {
  277. ret = ret.substr(0, pos);
  278. }
  279. CREATEFILE2_EXTENDED_PARAMETERS extParams = { 0 };
  280. extParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
  281. extParams.dwFileFlags = FILE_FLAG_RANDOM_ACCESS;
  282. extParams.dwSecurityQosFlags = SECURITY_ANONYMOUS;
  283. extParams.dwSize = sizeof(extParams);
  284. extParams.hTemplateFile = nullptr;
  285. extParams.lpSecurityAttributes = nullptr;
  286. Microsoft::WRL::Wrappers::FileHandle file(CreateFile2(std::wstring(filePath.begin(), filePath.end()).c_str(), GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, &extParams));
  287. if (file.Get() != INVALID_HANDLE_VALUE) {
  288. FILE_BASIC_INFO fInfo = { 0 };
  289. if (GetFileInformationByHandleEx(file.Get(), FileBasicInfo, &fInfo, sizeof(FILE_BASIC_INFO))) {
  290. std::stringstream ss;
  291. ss << ret << "_";
  292. ss << fInfo.CreationTime.QuadPart;
  293. ss << fInfo.ChangeTime.QuadPart;
  294. ret = ss.str();
  295. }
  296. }
  297. return ret;
  298. }
  299. bool createMappedCacheFile(const std::string& srcFilePath, std::string& cacheFilePath, const std::string& ext /* = "" */)
  300. {
  301. bool ret = false;
  302. auto folderPath = FileUtils::getInstance()->getWritablePath();
  303. cacheFilePath = folderPath + computeHashForFile(srcFilePath) + ext;
  304. std::string prevFile = UserDefault::getInstance()->getStringForKey(srcFilePath.c_str());
  305. if (prevFile == cacheFilePath) {
  306. ret = FileUtils::getInstance()->isFileExist(cacheFilePath);
  307. }
  308. else {
  309. FileUtils::getInstance()->removeFile(prevFile);
  310. }
  311. UserDefault::getInstance()->setStringForKey(srcFilePath.c_str(), cacheFilePath);
  312. return ret;
  313. }
  314. void destroyMappedCacheFile(const std::string& key)
  315. {
  316. std::string value = UserDefault::getInstance()->getStringForKey(key.c_str());
  317. if (!value.empty()) {
  318. FileUtils::getInstance()->removeFile(value);
  319. }
  320. UserDefault::getInstance()->setStringForKey(key.c_str(), "");
  321. }
  322. NS_CC_END