DownloadDialog.xaml.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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), m_FromURL(from_url)
  45. {
  46. InitializeComponent();
  47. this->MaxWidth = w;
  48. this->MaxHeight = h;
  49. this->PrimaryButtonText = m_resLdr->GetString("ButtonBack");
  50. pbDownload->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
  51. tbProgress->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
  52. wvDownloadPage->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
  53. gridURL->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
  54. }
  55. Platform::String^ SDLPal::DownloadDialog::FormatProgress()
  56. {
  57. static auto format = [](wchar_t* buf, double v)->wchar_t* {
  58. if (v <= 1024.0)
  59. swprintf_s(buf, 32, L"%0.0f B", v);
  60. else if (v <= 1048576.0)
  61. swprintf_s(buf, 32, L"%0.2f KB", v / 1024.0);
  62. else if (v <= 1073741824.0)
  63. swprintf_s(buf, 32, L"%0.2f MB", v / 1048576.0);
  64. else
  65. swprintf_s(buf, 32, L"%0.2f GB", v / 1073741824.0);
  66. return buf;
  67. };
  68. wchar_t buf[64], buf1[32], buf2[32];
  69. swprintf_s(buf, L"%s / %s", format(buf1, pbDownload->Value), format(buf2, pbDownload->Maximum));
  70. return ref new Platform::String(buf);
  71. }
  72. void SDLPal::DownloadDialog::DoDownload(Platform::String^ url)
  73. {
  74. wvDownloadPage->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
  75. gridURL->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
  76. pbDownload->Visibility = Windows::UI::Xaml::Visibility::Visible;
  77. tbProgress->Visibility = Windows::UI::Xaml::Visibility::Visible;
  78. this->FullSizeDesired = false;
  79. this->MaxHeight = 232;
  80. this->Title = m_resLdr->GetString("DialogTitle");
  81. this->PrimaryButtonText = m_resLdr->GetString("ButtonStop");
  82. this->UpdateLayout();
  83. m_Downloading = true;
  84. concurrency::create_task([this, url]() {
  85. Exception^ ex = nullptr;
  86. auto client = ref new HttpClient();
  87. try
  88. {
  89. concurrency::create_task(client->GetAsync(ref new Uri(url), HttpCompletionOption::ResponseHeadersRead)).then(
  90. [this](HttpResponseMessage^ response)->IAsyncOperationWithProgress<IInputStream^, uint64_t>^ {
  91. response->EnsureSuccessStatusCode();
  92. bool determinate = response->Content->Headers->HasKey("Content-Length");
  93. if (determinate)
  94. {
  95. m_totalBytes = wcstoull(response->Content->Headers->Lookup("Content-Length")->Data(), nullptr, 10);
  96. }
  97. this->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, determinate]() {
  98. pbDownload->Maximum = (double)m_totalBytes;
  99. pbDownload->IsIndeterminate = !determinate;
  100. }));
  101. return response->Content->ReadAsInputStreamAsync();
  102. }).then([this, client](IInputStream^ input) {
  103. auto buffer = ref new Buffer(_buffer_size);
  104. uint64_t bytes = 0;
  105. HANDLE hEvent = CreateEventEx(nullptr, nullptr, 0, EVENT_ALL_ACCESS);
  106. for (bool looping = true; looping; )
  107. {
  108. concurrency::create_task(input->ReadAsync(buffer, _buffer_size, InputStreamOptions::None)).then(
  109. [this, &bytes, &looping](IBuffer^ result)->IAsyncOperationWithProgress<uint32_t, uint32_t>^ {
  110. looping = (result->Length == _buffer_size) && !m_Closable;
  111. bytes += result->Length;
  112. this->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, bytes]() {
  113. pbDownload->Value = (double)bytes;
  114. tbProgress->Text = FormatProgress();
  115. UpdateLayout();
  116. }));
  117. return m_stream->WriteAsync(result);
  118. }).then([this](uint32_t)->IAsyncOperation<bool>^ {
  119. return m_stream->FlushAsync();
  120. }).wait();
  121. }
  122. delete buffer;
  123. delete client;
  124. delete input;
  125. this->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, bytes]() {
  126. this->Title = m_resLdr->GetString("Extracting");
  127. pbDownload->Value = 0.0;
  128. UpdateLayout();
  129. }));
  130. m_stream->Seek(0);
  131. Microsoft::WRL::ComPtr<IStream> strm;
  132. HRESULT hr;
  133. if (FAILED(hr = CreateStreamOverRandomAccessStream(m_stream, IID_PPV_ARGS(&strm)))) throw ref new Platform::Exception(hr);
  134. zlib_filefunc_def funcs = {
  135. /* open */ [](voidpf opaque, const char* filename, int mode)->voidpf { return new zip_file((IStream*)opaque); },
  136. /* read */ [](voidpf opaque, voidpf stream, void* buf, uLong size)->uLong {
  137. auto zip = (zip_file*)stream;
  138. return SUCCEEDED(zip->hr = zip->stream->Read(buf, size, &zip->cbBytes)) ? zip->cbBytes : 0;
  139. },
  140. /* write */ [](voidpf opaque, voidpf stream, const void* buf, uLong size)->uLong {
  141. auto zip = (zip_file*)stream;
  142. return SUCCEEDED(zip->hr = zip->stream->Write(buf, size, &zip->cbBytes)) ? zip->cbBytes : 0;
  143. },
  144. /* tell */ [](voidpf opaque, voidpf stream)->long {
  145. auto zip = (zip_file*)stream;
  146. LARGE_INTEGER liPos = { 0 };
  147. ULARGE_INTEGER uliPos;
  148. return SUCCEEDED(zip->hr = zip->stream->Seek(liPos, STREAM_SEEK_CUR, &uliPos)) ? uliPos.LowPart : UNZ_ERRNO;
  149. },
  150. /* seek */ [](voidpf opaque, voidpf stream, uLong offset, int origin)->long {
  151. auto zip = (zip_file*)stream;
  152. LARGE_INTEGER liPos = { offset };
  153. ULARGE_INTEGER uliPos;
  154. return SUCCEEDED(zip->hr = zip->stream->Seek(liPos, origin, &uliPos)) ? 0 : UNZ_ERRNO;
  155. },
  156. /* close */ [](voidpf opaque, voidpf stream)->int { delete (zip_file*)stream; return 0; },
  157. /* error */ [](voidpf opaque, voidpf stream)->int { return reinterpret_cast<zip_file*>(stream)->hr; },
  158. strm.Get()
  159. };
  160. unz_global_info ugi;
  161. char szFilename[65536];
  162. uLong filenum = 0;
  163. bool success = true;
  164. auto uzf = unzOpen2("", &funcs);
  165. unzGetGlobalInfo(uzf, &ugi);
  166. this->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, ugi]() { pbDownload->Maximum = ugi.number_entry; UpdateLayout(); }));
  167. for (auto ret = unzGoToFirstFile(uzf); ret == UNZ_OK; ret = unzGoToNextFile(uzf))
  168. {
  169. unz_file_info ufi;
  170. if (UNZ_OK == unzGetCurrentFileInfo(uzf, &ufi, szFilename, sizeof(szFilename), nullptr, 0, nullptr, 0) &&
  171. UNZ_OK == unzOpenCurrentFile(uzf))
  172. {
  173. std::auto_ptr<uint8_t> buf(new uint8_t[ufi.uncompressed_size]);
  174. auto len = unzReadCurrentFile(uzf, buf.get(), ufi.uncompressed_size);
  175. unzCloseCurrentFile(uzf);
  176. if (len != ufi.uncompressed_size)
  177. {
  178. success = false;
  179. break;
  180. }
  181. auto local = m_folder;
  182. uLong prev = 0;
  183. for (uLong i = 0; i < ufi.size_filename; i++)
  184. {
  185. if (szFilename[i] != '/') continue;
  186. try
  187. {
  188. concurrency::create_task(local->GetFolderAsync(ConvertString(szFilename + prev, i - prev))).then([&local](StorageFolder^ sub) { local = sub; }).wait();
  189. }
  190. catch (Exception^ e)
  191. {
  192. concurrency::create_task(local->CreateFolderAsync(ConvertString(szFilename + prev, i - prev))).then([&local](StorageFolder^ sub) { local = sub; }).wait();
  193. }
  194. prev = i + 1;
  195. }
  196. if (prev < ufi.size_filename)
  197. {
  198. IRandomAccessStream^ stm = nullptr;
  199. StorageFile^ file = nullptr;
  200. auto filename = ConvertString(szFilename + prev, ufi.size_filename - prev);
  201. concurrency::create_task(local->CreateFileAsync(filename, CreationCollisionOption::ReplaceExisting)).then([&](StorageFile^ f)->IAsyncOperation<IRandomAccessStream^>^ {
  202. return (file = f)->OpenAsync(Windows::Storage::FileAccessMode::ReadWrite);
  203. }).then([&](IRandomAccessStream^ s)->IAsyncOperationWithProgress<uint32_t, uint32_t>^ {
  204. return (stm = s)->WriteAsync(NativeBuffer::GetIBuffer(buf.get(), ufi.uncompressed_size));
  205. }).then([&](uint32_t size)->IAsyncOperation<bool>^ {
  206. if (size < ufi.uncompressed_size) throw ref new Exception(E_FAIL);
  207. return stm->FlushAsync();
  208. }).wait();
  209. delete stm;
  210. delete file;
  211. }
  212. }
  213. else
  214. {
  215. success = false;
  216. break;
  217. }
  218. filenum++;
  219. this->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, filenum, &ugi]() {
  220. wchar_t buf[64];
  221. swprintf_s(buf, L"%lu/%lu", filenum, ugi.number_entry);
  222. pbDownload->Value = (double)filenum;
  223. tbProgress->Text = ref new Platform::String(buf);
  224. UpdateLayout();
  225. }));
  226. }
  227. unzClose(uzf);
  228. if (!success) throw ref new Exception(E_FAIL);
  229. }).wait();
  230. }
  231. catch (Exception^ e)
  232. {
  233. ex = e;
  234. }
  235. this->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, ex]() {
  236. if (!m_Closable)
  237. {
  238. String^ string;
  239. if (ex)
  240. {
  241. string = String::Concat(m_resLdr->GetString("MBDownloadError"), ex->Message);
  242. Result = ContentDialogResult::Secondary;
  243. }
  244. else if (PAL_MISSING_REQUIRED(UTIL_CheckResourceFiles(ConvertString(m_folder->Path).c_str(), ConvertString(m_msgfile).c_str())))
  245. {
  246. string = String::Concat(m_resLdr->GetString("MBDownloadError"), m_resLdr->GetString("MBDownloadIncomplete"));
  247. Result = ContentDialogResult::Secondary;
  248. }
  249. else
  250. {
  251. string = m_resLdr->GetString("MBDownloadOK");
  252. Result = ContentDialogResult::None;
  253. }
  254. (ref new MessageDialog(string, m_resLdr->GetString("MBDownloadTitle")))->ShowAsync();
  255. }
  256. m_Downloading = false;
  257. m_Closable = true;
  258. Hide();
  259. }));
  260. });
  261. }
  262. void SDLPal::DownloadDialog::OnPrimaryButtonClick(Windows::UI::Xaml::Controls::ContentDialog^ sender, Windows::UI::Xaml::Controls::ContentDialogButtonClickEventArgs^ args)
  263. {
  264. (ref new MessageDialog(m_resLdr->GetString("MBDownloadCanceled"), m_resLdr->GetString("MBDownloadTitle")))->ShowAsync();
  265. Result = ContentDialogResult::Primary;
  266. m_Closable = true;
  267. }
  268. void SDLPal::DownloadDialog::OnClosing(Windows::UI::Xaml::Controls::ContentDialog^ sender, Windows::UI::Xaml::Controls::ContentDialogClosingEventArgs^ args)
  269. {
  270. args->Cancel = !m_Closable || m_Downloading;
  271. }
  272. void SDLPal::DownloadDialog::OnOpened(Windows::UI::Xaml::Controls::ContentDialog^ sender, Windows::UI::Xaml::Controls::ContentDialogOpenedEventArgs^ args)
  273. {
  274. if (m_FromURL)
  275. {
  276. gridURL->Visibility = Windows::UI::Xaml::Visibility::Visible;
  277. UpdateLayout();
  278. }
  279. else
  280. {
  281. wvDownloadPage->Visibility = Windows::UI::Xaml::Visibility::Visible;
  282. this->FullSizeDesired = true;
  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. wvDownloadPage->Width = e->NewSize.Width - 48;
  329. wvDownloadPage->Height = e->NewSize.Height - 128;
  330. UpdateLayout();
  331. }
  332. }
  333. void SDLPal::DownloadDialog::OnClick(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
  334. {
  335. if (tbURL->Text->Length() > 0)
  336. {
  337. DoDownload(tbURL->Text);
  338. }
  339. }