DownloadDialog.xaml.cpp 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. //
  2. // DownloadDialog.xaml.cpp
  3. // DownloadDialog 类的实现
  4. //
  5. #include "pch.h"
  6. #include <wrl.h>
  7. #include <shcore.h>
  8. #include "DownloadDialog.xaml.h"
  9. #include "AsyncHelper.h"
  10. #include "NativeBuffer.h"
  11. #include "StringHelper.h"
  12. #include "minizip/unzip.h"
  13. using namespace SDLPal;
  14. using namespace Platform;
  15. using namespace Windows::Foundation;
  16. using namespace Windows::Foundation::Collections;
  17. using namespace Windows::Storage;
  18. using namespace Windows::Storage::Compression;
  19. using namespace Windows::Storage::Streams;
  20. using namespace Windows::UI::Core;
  21. using namespace Windows::UI::Popups;
  22. using namespace Windows::UI::Xaml;
  23. using namespace Windows::UI::Xaml::Controls;
  24. using namespace Windows::UI::Xaml::Controls::Primitives;
  25. using namespace Windows::UI::Xaml::Data;
  26. using namespace Windows::UI::Xaml::Input;
  27. using namespace Windows::UI::Xaml::Media;
  28. using namespace Windows::UI::Xaml::Navigation;
  29. using namespace Windows::Web::Http;
  30. // https://go.microsoft.com/fwlink/?LinkId=234238 上介绍了“内容对话框”项模板
  31. static const uint32_t _buffer_size = 65536;
  32. struct zip_file
  33. {
  34. IStream* stream;
  35. HRESULT hr;
  36. ULONG cbBytes;
  37. zip_file(IStream* s) : stream(s), hr(S_OK), cbBytes(0) {}
  38. };
  39. SDLPal::DownloadDialog::DownloadDialog(Platform::String^ link, Windows::ApplicationModel::Resources::ResourceLoader^ ldr, Windows::Storage::StorageFolder^ folder, Windows::Storage::Streams::IRandomAccessStream^ stream)
  40. : m_link(link), m_stream(stream), m_Closable(false), m_InitialPhase(true), m_totalBytes(0), m_resLdr(ldr), m_folder(folder)
  41. {
  42. InitializeComponent();
  43. this->IsSecondaryButtonEnabled = false;
  44. }
  45. Platform::String^ SDLPal::DownloadDialog::FormatProgress()
  46. {
  47. static auto format = [](wchar_t* buf, double v)->wchar_t* {
  48. if (v <= 1024.0)
  49. swprintf_s(buf, 32, L"%0.0f B", v);
  50. else if (v <= 1048576.0)
  51. swprintf_s(buf, 32, L"%0.2f KB", v / 1024.0);
  52. else if (v <= 1073741824.0)
  53. swprintf_s(buf, 32, L"%0.2f MB", v / 1048576.0);
  54. else
  55. swprintf_s(buf, 32, L"%0.2f GB", v / 1073741824.0);
  56. return buf;
  57. };
  58. wchar_t buf[64], buf1[32], buf2[32];
  59. swprintf_s(buf, L"%s / %s", format(buf1, pbDownload->Value), format(buf2, pbDownload->Maximum));
  60. return ref new Platform::String(buf);
  61. }
  62. void SDLPal::DownloadDialog::OnPrimaryButtonClick(Windows::UI::Xaml::Controls::ContentDialog^ sender, Windows::UI::Xaml::Controls::ContentDialogButtonClickEventArgs^ args)
  63. {
  64. m_Closable = true;
  65. }
  66. void SDLPal::DownloadDialog::OnClosing(Windows::UI::Xaml::Controls::ContentDialog^ sender, Windows::UI::Xaml::Controls::ContentDialogClosingEventArgs^ args)
  67. {
  68. args->Cancel = !m_Closable;
  69. }
  70. void SDLPal::DownloadDialog::OnOpened(Windows::UI::Xaml::Controls::ContentDialog^ sender, Windows::UI::Xaml::Controls::ContentDialogOpenedEventArgs^ args)
  71. {
  72. concurrency::create_task([this]() {
  73. Exception^ ex = nullptr;
  74. auto client = ref new HttpClient();
  75. try
  76. {
  77. concurrency::create_task(client->GetAsync(ref new Uri(m_link), HttpCompletionOption::ResponseHeadersRead)).then(
  78. [this](HttpResponseMessage^ response)->IAsyncOperationWithProgress<IInputStream^, uint64_t>^ {
  79. response->EnsureSuccessStatusCode();
  80. bool determinate = response->Content->Headers->HasKey("Content-Length");
  81. if (determinate)
  82. {
  83. m_totalBytes = wcstoull(response->Content->Headers->Lookup("Content-Length")->Data(), nullptr, 10);
  84. }
  85. this->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, determinate]() {
  86. pbDownload->Maximum = (double)m_totalBytes;
  87. pbDownload->IsIndeterminate = !determinate;
  88. }));
  89. return response->Content->ReadAsInputStreamAsync();
  90. }).then([this, client](IInputStream^ input) {
  91. auto buffer = ref new Buffer(_buffer_size);
  92. uint64_t bytes = 0;
  93. HANDLE hEvent = CreateEventEx(nullptr, nullptr, 0, EVENT_ALL_ACCESS);
  94. for (bool looping = true; looping; )
  95. {
  96. concurrency::create_task(input->ReadAsync(buffer, _buffer_size, InputStreamOptions::None)).then(
  97. [this, &bytes, &looping](IBuffer^ result)->IAsyncOperationWithProgress<uint32_t, uint32_t>^ {
  98. looping = (result->Length == _buffer_size) && !m_Closable;
  99. bytes += result->Length;
  100. this->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, bytes]() {
  101. pbDownload->Value = (double)bytes;
  102. tbProgress->Text = FormatProgress();
  103. UpdateLayout();
  104. }));
  105. return m_stream->WriteAsync(result);
  106. }).then([this](uint32_t)->IAsyncOperation<bool>^ {
  107. return m_stream->FlushAsync();
  108. }).wait();
  109. }
  110. delete buffer;
  111. delete client;
  112. delete input;
  113. this->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, bytes]() {
  114. this->Title = m_resLdr->GetString("Extracting");
  115. pbDownload->Value = 0.0;
  116. UpdateLayout();
  117. }));
  118. m_stream->Seek(0);
  119. Microsoft::WRL::ComPtr<IStream> strm;
  120. HRESULT hr;
  121. if (FAILED(hr = CreateStreamOverRandomAccessStream(m_stream, IID_PPV_ARGS(&strm)))) throw ref new Platform::Exception(hr);
  122. zlib_filefunc_def funcs = {
  123. /* open */ [](voidpf opaque, const char* filename, int mode)->voidpf { return new zip_file((IStream*)opaque); },
  124. /* read */ [](voidpf opaque, voidpf stream, void* buf, uLong size)->uLong {
  125. auto zip = (zip_file*)stream;
  126. return SUCCEEDED(zip->hr = zip->stream->Read(buf, size, &zip->cbBytes)) ? zip->cbBytes : 0;
  127. },
  128. /* write */ [](voidpf opaque, voidpf stream, const void* buf, uLong size)->uLong {
  129. auto zip = (zip_file*)stream;
  130. return SUCCEEDED(zip->hr = zip->stream->Write(buf, size, &zip->cbBytes)) ? zip->cbBytes : 0;
  131. },
  132. /* tell */ [](voidpf opaque, voidpf stream)->long {
  133. auto zip = (zip_file*)stream;
  134. LARGE_INTEGER liPos = { 0 };
  135. ULARGE_INTEGER uliPos;
  136. return SUCCEEDED(zip->hr = zip->stream->Seek(liPos, STREAM_SEEK_CUR, &uliPos)) ? uliPos.LowPart : UNZ_ERRNO;
  137. },
  138. /* seek */ [](voidpf opaque, voidpf stream, uLong offset, int origin)->long {
  139. auto zip = (zip_file*)stream;
  140. LARGE_INTEGER liPos = { offset };
  141. ULARGE_INTEGER uliPos;
  142. return SUCCEEDED(zip->hr = zip->stream->Seek(liPos, origin, &uliPos)) ? 0 : UNZ_ERRNO;
  143. },
  144. /* close */ [](voidpf opaque, voidpf stream)->int { delete (zip_file*)stream; return 0; },
  145. /* error */ [](voidpf opaque, voidpf stream)->int { return reinterpret_cast<zip_file*>(stream)->hr; },
  146. strm.Get()
  147. };
  148. unz_global_info ugi;
  149. char szFilename[65536];
  150. uLong filenum = 0;
  151. bool success = true;
  152. auto uzf = unzOpen2("", &funcs);
  153. unzGetGlobalInfo(uzf, &ugi);
  154. this->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, ugi]() { pbDownload->Maximum = ugi.number_entry; UpdateLayout(); }));
  155. for (auto ret = unzGoToFirstFile(uzf); ret == UNZ_OK; ret = unzGoToNextFile(uzf))
  156. {
  157. unz_file_info ufi;
  158. if (UNZ_OK == unzGetCurrentFileInfo(uzf, &ufi, szFilename, sizeof(szFilename), nullptr, 0, nullptr, 0) &&
  159. UNZ_OK == unzOpenCurrentFile(uzf))
  160. {
  161. std::auto_ptr<uint8_t> buf(new uint8_t[ufi.uncompressed_size]);
  162. auto len = unzReadCurrentFile(uzf, buf.get(), ufi.uncompressed_size);
  163. unzCloseCurrentFile(uzf);
  164. if (len != ufi.uncompressed_size)
  165. {
  166. success = false;
  167. break;
  168. }
  169. auto local = m_folder;
  170. uLong prev = 0;
  171. for (uLong i = 0; i < ufi.size_filename; i++)
  172. {
  173. if (szFilename[i] != '/') continue;
  174. try
  175. {
  176. concurrency::create_task(local->GetFolderAsync(ConvertString(szFilename + prev, i - prev))).then([&local](StorageFolder^ sub) { local = sub; }).wait();
  177. }
  178. catch (Exception^ e)
  179. {
  180. concurrency::create_task(local->CreateFolderAsync(ConvertString(szFilename + prev, i - prev))).then([&local](StorageFolder^ sub) { local = sub; }).wait();
  181. }
  182. prev = i + 1;
  183. }
  184. if (prev < ufi.size_filename)
  185. {
  186. IRandomAccessStream^ stm = nullptr;
  187. StorageFile^ file = nullptr;
  188. auto filename = ConvertString(szFilename + prev, ufi.size_filename - prev);
  189. concurrency::create_task(local->CreateFileAsync(filename, CreationCollisionOption::ReplaceExisting)).then([&](StorageFile^ f)->IAsyncOperation<IRandomAccessStream^>^ {
  190. return (file = f)->OpenAsync(Windows::Storage::FileAccessMode::ReadWrite);
  191. }).then([&](IRandomAccessStream^ s)->IAsyncOperationWithProgress<uint32_t, uint32_t>^ {
  192. return (stm = s)->WriteAsync(NativeBuffer::GetIBuffer(buf.get(), ufi.uncompressed_size));
  193. }).then([&](uint32_t size)->IAsyncOperation<bool>^ {
  194. if (size < ufi.uncompressed_size) throw ref new Exception(E_FAIL);
  195. return stm->FlushAsync();
  196. }).wait();
  197. delete stm;
  198. delete file;
  199. }
  200. }
  201. else
  202. {
  203. success = false;
  204. break;
  205. }
  206. filenum++;
  207. this->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, filenum, &ugi]() {
  208. wchar_t buf[64];
  209. swprintf_s(buf, L"%lu/%lu", filenum, ugi.number_entry);
  210. pbDownload->Value = (double)filenum;
  211. tbProgress->Text = ref new Platform::String(buf);
  212. UpdateLayout();
  213. }));
  214. }
  215. unzClose(uzf);
  216. if (!success) throw ref new Exception(E_FAIL);
  217. }).wait();
  218. }
  219. catch (Exception^ e)
  220. {
  221. ex = e;
  222. }
  223. this->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, ex]() {
  224. Platform::String^ string;
  225. if (m_Closable)
  226. string = m_resLdr->GetString("MBDownloadCanceled");
  227. else if (ex)
  228. string = String::Concat(m_resLdr->GetString("MBDownloadError"), ex->Message);
  229. else
  230. string = m_resLdr->GetString("MBDownloadOK");
  231. (ref new MessageDialog(string, m_resLdr->GetString("MBDownloadTitle")))->ShowAsync();
  232. m_Closable = true;
  233. Hide();
  234. }));
  235. });
  236. }