DownloadDialog.xaml.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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. #include "util.h"
  14. using namespace SDLPal;
  15. using namespace Platform;
  16. using namespace Platform::Collections;
  17. using namespace Windows::Foundation;
  18. using namespace Windows::Foundation::Collections;
  19. using namespace Windows::Storage;
  20. using namespace Windows::Storage::Compression;
  21. using namespace Windows::Storage::Streams;
  22. using namespace Windows::UI::Core;
  23. using namespace Windows::UI::Popups;
  24. using namespace Windows::UI::Xaml;
  25. using namespace Windows::UI::Xaml::Controls;
  26. using namespace Windows::UI::Xaml::Controls::Primitives;
  27. using namespace Windows::UI::Xaml::Data;
  28. using namespace Windows::UI::Xaml::Input;
  29. using namespace Windows::UI::Xaml::Media;
  30. using namespace Windows::UI::Xaml::Navigation;
  31. using namespace Windows::Web::Http;
  32. // https://go.microsoft.com/fwlink/?LinkId=234238 上介绍了“内容对话框”项模板
  33. static const uint32_t _buffer_size = 65536;
  34. static Platform::String^ const _url = "http://pal5q.baiyou100.com/pal5/download/98xjrq.html";
  35. static const wchar_t _postfix[] = L"/Pal98rqp.zip";
  36. struct zip_file
  37. {
  38. IStream* stream;
  39. HRESULT hr;
  40. ULONG cbBytes;
  41. zip_file(IStream* s) : stream(s), hr(S_OK), cbBytes(0) {}
  42. };
  43. SDLPal::DownloadDialog::DownloadDialog(Windows::ApplicationModel::Resources::ResourceLoader^ ldr, StorageFolder^ folder, IRandomAccessStream^ stream, Platform::String^ msgfile, double w, double h, bool from_url)
  44. : m_stream(stream), m_Closable(false), m_Downloading(false), m_totalBytes(0), m_resLdr(ldr), m_folder(folder), m_width(w), m_height(h), m_msgfile(msgfile)
  45. {
  46. InitializeComponent();
  47. this->MaxWidth = w;
  48. this->MaxHeight = h;
  49. this->PrimaryButtonText = m_resLdr->GetString("ButtonBack");
  50. spProgress->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
  51. if (from_url)
  52. {
  53. wvDownloadPage->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
  54. }
  55. else
  56. {
  57. gridURL->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
  58. }
  59. }
  60. Platform::String^ SDLPal::DownloadDialog::FormatProgress()
  61. {
  62. static auto format = [](wchar_t* buf, double v)->wchar_t* {
  63. if (v <= 1024.0)
  64. swprintf_s(buf, 32, L"%0.0f B", v);
  65. else if (v <= 1048576.0)
  66. swprintf_s(buf, 32, L"%0.2f KB", v / 1024.0);
  67. else if (v <= 1073741824.0)
  68. swprintf_s(buf, 32, L"%0.2f MB", v / 1048576.0);
  69. else
  70. swprintf_s(buf, 32, L"%0.2f GB", v / 1073741824.0);
  71. return buf;
  72. };
  73. wchar_t buf[64], buf1[32], buf2[32];
  74. swprintf_s(buf, L"%s / %s", format(buf1, pbDownload->Value), format(buf2, pbDownload->Maximum));
  75. return ref new Platform::String(buf);
  76. }
  77. void SDLPal::DownloadDialog::DoDownload(Platform::String^ url)
  78. {
  79. this->FullSizeDesired = false;
  80. gridRow1->Height = 0;
  81. wvDownloadPage->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
  82. gridURL->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
  83. spProgress->Visibility = Windows::UI::Xaml::Visibility::Visible;
  84. this->MaxHeight = 128 + 48;
  85. this->Title = m_resLdr->GetString("DialogTitle");
  86. this->PrimaryButtonText = m_resLdr->GetString("ButtonStop");
  87. this->UpdateLayout();
  88. m_Downloading = true;
  89. concurrency::create_task([this, url]() {
  90. Exception^ ex = nullptr;
  91. auto client = ref new HttpClient();
  92. try
  93. {
  94. concurrency::create_task(client->GetAsync(ref new Uri(url), HttpCompletionOption::ResponseHeadersRead)).then(
  95. [this](HttpResponseMessage^ response)->IAsyncOperationWithProgress<IInputStream^, uint64_t>^ {
  96. response->EnsureSuccessStatusCode();
  97. bool determinate = response->Content->Headers->HasKey("Content-Length");
  98. if (determinate)
  99. {
  100. m_totalBytes = wcstoull(response->Content->Headers->Lookup("Content-Length")->Data(), nullptr, 10);
  101. }
  102. this->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, determinate]() {
  103. pbDownload->Maximum = (double)m_totalBytes;
  104. pbDownload->IsIndeterminate = !determinate;
  105. }));
  106. return response->Content->ReadAsInputStreamAsync();
  107. }).then([this, client](IInputStream^ input) {
  108. auto buffer = ref new Buffer(_buffer_size);
  109. uint64_t bytes = 0;
  110. HANDLE hEvent = CreateEventEx(nullptr, nullptr, 0, EVENT_ALL_ACCESS);
  111. for (bool looping = true; looping; )
  112. {
  113. concurrency::create_task(input->ReadAsync(buffer, _buffer_size, InputStreamOptions::None)).then(
  114. [this, &bytes, &looping](IBuffer^ result)->IAsyncOperationWithProgress<uint32_t, uint32_t>^ {
  115. looping = (result->Length == _buffer_size) && !m_Closable;
  116. bytes += result->Length;
  117. this->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, bytes]() {
  118. pbDownload->Value = (double)bytes;
  119. tbProgress->Text = FormatProgress();
  120. UpdateLayout();
  121. }));
  122. return m_stream->WriteAsync(result);
  123. }).then([this](uint32_t)->IAsyncOperation<bool>^ {
  124. return m_stream->FlushAsync();
  125. }).wait();
  126. }
  127. delete buffer;
  128. delete client;
  129. delete input;
  130. this->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, bytes]() {
  131. this->Title = m_resLdr->GetString("Extracting");
  132. pbDownload->Value = 0.0;
  133. UpdateLayout();
  134. }));
  135. m_stream->Seek(0);
  136. Microsoft::WRL::ComPtr<IStream> strm;
  137. HRESULT hr;
  138. if (FAILED(hr = CreateStreamOverRandomAccessStream(m_stream, IID_PPV_ARGS(&strm)))) throw ref new Platform::Exception(hr);
  139. zlib_filefunc_def funcs = {
  140. /* open */ [](voidpf opaque, const char* filename, int mode)->voidpf { return new zip_file((IStream*)opaque); },
  141. /* read */ [](voidpf opaque, voidpf stream, void* buf, uLong size)->uLong {
  142. auto zip = (zip_file*)stream;
  143. return SUCCEEDED(zip->hr = zip->stream->Read(buf, size, &zip->cbBytes)) ? zip->cbBytes : 0;
  144. },
  145. /* write */ [](voidpf opaque, voidpf stream, const void* buf, uLong size)->uLong {
  146. auto zip = (zip_file*)stream;
  147. return SUCCEEDED(zip->hr = zip->stream->Write(buf, size, &zip->cbBytes)) ? zip->cbBytes : 0;
  148. },
  149. /* tell */ [](voidpf opaque, voidpf stream)->long {
  150. auto zip = (zip_file*)stream;
  151. LARGE_INTEGER liPos = { 0 };
  152. ULARGE_INTEGER uliPos;
  153. return SUCCEEDED(zip->hr = zip->stream->Seek(liPos, STREAM_SEEK_CUR, &uliPos)) ? uliPos.LowPart : UNZ_ERRNO;
  154. },
  155. /* seek */ [](voidpf opaque, voidpf stream, uLong offset, int origin)->long {
  156. auto zip = (zip_file*)stream;
  157. LARGE_INTEGER liPos = { offset };
  158. ULARGE_INTEGER uliPos;
  159. return SUCCEEDED(zip->hr = zip->stream->Seek(liPos, origin, &uliPos)) ? 0 : UNZ_ERRNO;
  160. },
  161. /* close */ [](voidpf opaque, voidpf stream)->int { delete (zip_file*)stream; return 0; },
  162. /* error */ [](voidpf opaque, voidpf stream)->int { return reinterpret_cast<zip_file*>(stream)->hr; },
  163. strm.Get()
  164. };
  165. unz_global_info ugi;
  166. char szFilename[65536];
  167. uLong filenum = 0;
  168. bool success = true;
  169. auto uzf = unzOpen2("", &funcs);
  170. unzGetGlobalInfo(uzf, &ugi);
  171. this->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, ugi]() { pbDownload->Maximum = ugi.number_entry; UpdateLayout(); }));
  172. for (auto ret = unzGoToFirstFile(uzf); ret == UNZ_OK; ret = unzGoToNextFile(uzf))
  173. {
  174. unz_file_info ufi;
  175. if (UNZ_OK == unzGetCurrentFileInfo(uzf, &ufi, szFilename, sizeof(szFilename), nullptr, 0, nullptr, 0) &&
  176. UNZ_OK == unzOpenCurrentFile(uzf))
  177. {
  178. std::auto_ptr<uint8_t> buf(new uint8_t[ufi.uncompressed_size]);
  179. auto len = unzReadCurrentFile(uzf, buf.get(), ufi.uncompressed_size);
  180. unzCloseCurrentFile(uzf);
  181. if (len != ufi.uncompressed_size)
  182. {
  183. success = false;
  184. break;
  185. }
  186. auto local = m_folder;
  187. uLong prev = 0;
  188. for (uLong i = 0; i < ufi.size_filename; i++)
  189. {
  190. if (szFilename[i] != '/') continue;
  191. try
  192. {
  193. concurrency::create_task(local->GetFolderAsync(ConvertString(szFilename + prev, i - prev))).then([&local](StorageFolder^ sub) { local = sub; }).wait();
  194. }
  195. catch (Exception^ e)
  196. {
  197. concurrency::create_task(local->CreateFolderAsync(ConvertString(szFilename + prev, i - prev))).then([&local](StorageFolder^ sub) { local = sub; }).wait();
  198. }
  199. prev = i + 1;
  200. }
  201. if (prev < ufi.size_filename)
  202. {
  203. IRandomAccessStream^ stm = nullptr;
  204. StorageFile^ file = nullptr;
  205. auto filename = ConvertString(szFilename + prev, ufi.size_filename - prev);
  206. concurrency::create_task(local->CreateFileAsync(filename, CreationCollisionOption::ReplaceExisting)).then([&](StorageFile^ f)->IAsyncOperation<IRandomAccessStream^>^ {
  207. return (file = f)->OpenAsync(Windows::Storage::FileAccessMode::ReadWrite);
  208. }).then([&](IRandomAccessStream^ s)->IAsyncOperationWithProgress<uint32_t, uint32_t>^ {
  209. return (stm = s)->WriteAsync(NativeBuffer::GetIBuffer(buf.get(), ufi.uncompressed_size));
  210. }).then([&](uint32_t size)->IAsyncOperation<bool>^ {
  211. if (size < ufi.uncompressed_size) throw ref new Exception(E_FAIL);
  212. return stm->FlushAsync();
  213. }).wait();
  214. delete stm;
  215. delete file;
  216. }
  217. }
  218. else
  219. {
  220. success = false;
  221. break;
  222. }
  223. filenum++;
  224. this->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, filenum, &ugi]() {
  225. wchar_t buf[64];
  226. swprintf_s(buf, L"%lu/%lu", filenum, ugi.number_entry);
  227. pbDownload->Value = (double)filenum;
  228. tbProgress->Text = ref new Platform::String(buf);
  229. UpdateLayout();
  230. }));
  231. }
  232. unzClose(uzf);
  233. if (!success) throw ref new Exception(E_FAIL);
  234. }).wait();
  235. }
  236. catch (Exception^ e)
  237. {
  238. ex = e;
  239. }
  240. this->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, ex]() {
  241. if (!m_Closable)
  242. {
  243. String^ string;
  244. if (ex)
  245. {
  246. string = String::Concat(m_resLdr->GetString("MBDownloadError"), ex->Message);
  247. Result = ContentDialogResult::Secondary;
  248. }
  249. else if (PAL_MISSING_REQUIRED(UTIL_CheckResourceFiles(ConvertString(m_folder->Path).c_str(), ConvertString(m_msgfile).c_str())))
  250. {
  251. string = String::Concat(m_resLdr->GetString("MBDownloadError"), m_resLdr->GetString("MBDownloadIncomplete"));
  252. Result = ContentDialogResult::Secondary;
  253. }
  254. else
  255. {
  256. string = m_resLdr->GetString("MBDownloadOK");
  257. Result = ContentDialogResult::None;
  258. }
  259. (ref new MessageDialog(string, m_resLdr->GetString("MBDownloadTitle")))->ShowAsync();
  260. }
  261. m_Downloading = false;
  262. m_Closable = true;
  263. Hide();
  264. }));
  265. });
  266. }
  267. void SDLPal::DownloadDialog::OnPrimaryButtonClick(Windows::UI::Xaml::Controls::ContentDialog^ sender, Windows::UI::Xaml::Controls::ContentDialogButtonClickEventArgs^ args)
  268. {
  269. (ref new MessageDialog(m_resLdr->GetString("MBDownloadCanceled"), m_resLdr->GetString("MBDownloadTitle")))->ShowAsync();
  270. Result = ContentDialogResult::Primary;
  271. m_Closable = true;
  272. }
  273. void SDLPal::DownloadDialog::OnClosing(Windows::UI::Xaml::Controls::ContentDialog^ sender, Windows::UI::Xaml::Controls::ContentDialogClosingEventArgs^ args)
  274. {
  275. args->Cancel = !m_Closable || m_Downloading;
  276. }
  277. void SDLPal::DownloadDialog::OnOpened(Windows::UI::Xaml::Controls::ContentDialog^ sender, Windows::UI::Xaml::Controls::ContentDialogOpenedEventArgs^ args)
  278. {
  279. if (wvDownloadPage->Visibility == Windows::UI::Xaml::Visibility::Visible)
  280. {
  281. this->FullSizeDesired = true;
  282. gridRow1->Height = m_height - 128;
  283. wvDownloadPage->Width = m_width - 48;
  284. wvDownloadPage->Height = m_height - 128;
  285. UpdateLayout();
  286. wvDownloadPage->Navigate(ref new Uri(_url));
  287. }
  288. }
  289. void SDLPal::DownloadDialog::OnNavigateStart(Windows::UI::Xaml::Controls::WebView^ sender, Windows::UI::Xaml::Controls::WebViewNavigationStartingEventArgs^ args)
  290. {
  291. auto url = args->Uri->RawUri;
  292. args->Cancel = (Platform::String::CompareOrdinal(url, _url) != 0);
  293. if (url->Length() >= _countof(_postfix) - 1 && _wcsicmp(url->Data() + url->Length() - (_countof(_postfix) - 1), _postfix) == 0)
  294. {
  295. DoDownload(url);
  296. }
  297. }
  298. void SDLPal::DownloadDialog::OnDOMContentLoaded(Windows::UI::Xaml::Controls::WebView^ sender, Windows::UI::Xaml::Controls::WebViewDOMContentLoadedEventArgs^ args)
  299. {
  300. this->Title = sender->DocumentTitle;
  301. sender->InvokeScriptAsync(ref new String(L"eval"), ref new Vector<String^>(1, ref new String(LR"rs(
  302. var elems = document.getElementsByTagName('a');
  303. for (var i = 0; i < elems.length; i++)
  304. {
  305. if (elems[i].href.indexOf('#') === -1)
  306. {
  307. if (/\/Pal98rqp\.zip$/i.test(elems[i].href))
  308. {
  309. elems[i].target = '';
  310. elems[i].focus();
  311. var r = elems[i].getBoundingClientRect();
  312. var y = (r.top + r.bottom - window.innerHeight) / 2 + window.pageYOffset;
  313. var x = (r.left + r.right - window.innerWidth) / 2 + window.pageXOffset;
  314. window.scroll(x, y);
  315. }
  316. else
  317. {
  318. elems[i].target = '_blank';
  319. }
  320. }
  321. }
  322. )rs")));
  323. }
  324. void SDLPal::DownloadDialog::OnSizeChanged(Platform::Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e)
  325. {
  326. if (wvDownloadPage->Visibility == Windows::UI::Xaml::Visibility::Visible)
  327. {
  328. this->FullSizeDesired = true;
  329. gridRow1->Height = e->NewSize.Height - 128;
  330. wvDownloadPage->Width = e->NewSize.Width - 48;
  331. wvDownloadPage->Height = e->NewSize.Height - 128;
  332. UpdateLayout();
  333. }
  334. }
  335. void SDLPal::DownloadDialog::OnClick(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
  336. {
  337. if (tbURL->Text->Length() > 0)
  338. {
  339. DoDownload(tbURL->Text);
  340. }
  341. }