libaria2wx.cc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. /* <!-- copyright */
  2. /*
  3. * aria2 - The high speed download utility
  4. *
  5. * Copyright (C) 2013 Tatsuhiro Tsujikawa
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. *
  21. * In addition, as a special exception, the copyright holders give
  22. * permission to link the code of portions of this program with the
  23. * OpenSSL library under certain conditions as described in each
  24. * individual source file, and distribute linked combinations
  25. * including the two.
  26. * You must obey the GNU General Public License in all respects
  27. * for all of the code used other than OpenSSL. If you modify
  28. * file(s) with this exception, you may extend this exception to your
  29. * version of the file(s), but you are not obligated to do so. If you
  30. * do not wish to do so, delete this exception statement from your
  31. * version. If you delete this exception statement from all source
  32. * files in the program, then also delete it here.
  33. */
  34. /* copyright --> */
  35. //
  36. // Multi-threaded GUI program example for libaria2. The downloads can
  37. // be added using Download -> Add URI menu. The progress is shown in
  38. // the main window.
  39. //
  40. // Compile and link like this:
  41. // $ g++ -O2 -Wall -g -std=c++11 `wx-config --cflags` -o libaria2wx
  42. // libaria2wx.cc `wx-config --libs` -laria2 -pthread
  43. #include <iostream>
  44. #include <chrono>
  45. #include <thread>
  46. #include <mutex>
  47. #include <queue>
  48. #include <wx/wx.h>
  49. #include <aria2/aria2.h>
  50. // Interface to send message to downloader thread from UI thread
  51. struct Job {
  52. virtual ~Job(){};
  53. virtual void execute(aria2::Session* session) = 0;
  54. };
  55. class MainFrame;
  56. // Interface to report back to UI thread from downloader thread
  57. struct Notification {
  58. virtual ~Notification(){};
  59. virtual void notify(MainFrame* frame) = 0;
  60. };
  61. // std::queue<T> wrapper synchronized by mutex. In this example
  62. // program, only one thread consumes from the queue, so separating
  63. // empty() and pop() is not a problem.
  64. template <typename T> class SynchronizedQueue {
  65. public:
  66. SynchronizedQueue() {}
  67. ~SynchronizedQueue() {}
  68. void push(std::unique_ptr<T>&& t)
  69. {
  70. std::lock_guard<std::mutex> l(m_);
  71. q_.push(std::move(t));
  72. }
  73. std::unique_ptr<T> pop()
  74. {
  75. std::lock_guard<std::mutex> l(m_);
  76. std::unique_ptr<T> t = std::move(q_.front());
  77. q_.pop();
  78. return t;
  79. }
  80. bool empty()
  81. {
  82. std::lock_guard<std::mutex> l(m_);
  83. return q_.empty();
  84. }
  85. private:
  86. std::queue<std::unique_ptr<T>> q_;
  87. std::mutex m_;
  88. };
  89. typedef SynchronizedQueue<Job> JobQueue;
  90. typedef SynchronizedQueue<Notification> NotifyQueue;
  91. // Job to shutdown downloader thread
  92. struct ShutdownJob : public Job {
  93. ShutdownJob(bool force) : force(force) {}
  94. virtual void execute(aria2::Session* session)
  95. {
  96. aria2::shutdown(session, force);
  97. }
  98. bool force;
  99. };
  100. // Job to send URI to download and options to downloader thread
  101. struct AddUriJob : public Job {
  102. AddUriJob(std::vector<std::string>&& uris, aria2::KeyVals&& options)
  103. : uris(uris), options(options)
  104. {
  105. }
  106. virtual void execute(aria2::Session* session)
  107. {
  108. // TODO check return value
  109. aria2::addUri(session, 0, uris, options);
  110. }
  111. std::vector<std::string> uris;
  112. aria2::KeyVals options;
  113. };
  114. int downloaderJob(JobQueue& jobq, NotifyQueue& notifyq);
  115. // This struct is used to report download progress for active
  116. // downloads from downloader thread to UI thread.
  117. struct DownloadStatus {
  118. aria2::A2Gid gid;
  119. int64_t totalLength;
  120. int64_t completedLength;
  121. int downloadSpeed;
  122. int uploadSpeed;
  123. std::string filename;
  124. };
  125. class Aria2App : public wxApp {
  126. public:
  127. virtual bool OnInit();
  128. virtual int OnExit();
  129. };
  130. class MainFrame : public wxFrame {
  131. public:
  132. MainFrame(const wxString& title);
  133. void OnQuit(wxCommandEvent& event);
  134. void OnAbout(wxCommandEvent& event);
  135. void OnCloseWindow(wxCloseEvent& event);
  136. void OnTimer(wxTimerEvent& event);
  137. void OnAddUri(wxCommandEvent& event);
  138. void UpdateActiveStatus(const std::vector<DownloadStatus>& v);
  139. private:
  140. wxTextCtrl* text_;
  141. wxTimer timer_;
  142. JobQueue jobq_;
  143. NotifyQueue notifyq_;
  144. std::thread downloaderThread_;
  145. DECLARE_EVENT_TABLE()
  146. };
  147. enum { TIMER_ID = 1 };
  148. enum { MI_ADD_URI = 1 };
  149. BEGIN_EVENT_TABLE(MainFrame, wxFrame)
  150. EVT_CLOSE(MainFrame::OnCloseWindow)
  151. EVT_TIMER(TIMER_ID, MainFrame::OnTimer)
  152. EVT_MENU(MI_ADD_URI, MainFrame::OnAddUri)
  153. END_EVENT_TABLE()
  154. class AddUriDialog : public wxDialog {
  155. public:
  156. AddUriDialog(wxWindow* parent);
  157. void OnButton(wxCommandEvent& event);
  158. wxString GetUri();
  159. wxString GetOption();
  160. private:
  161. wxTextCtrl* uriText_;
  162. wxTextCtrl* optionText_;
  163. wxButton* okBtn_;
  164. wxButton* cancelBtn_;
  165. DECLARE_EVENT_TABLE()
  166. };
  167. BEGIN_EVENT_TABLE(AddUriDialog, wxDialog)
  168. EVT_BUTTON(wxID_ANY, AddUriDialog::OnButton)
  169. END_EVENT_TABLE()
  170. IMPLEMENT_APP(Aria2App)
  171. bool Aria2App::OnInit()
  172. {
  173. if (!wxApp::OnInit())
  174. return false;
  175. aria2::libraryInit();
  176. MainFrame* frame = new MainFrame(wxT("libaria2 GUI example"));
  177. frame->Show(true);
  178. return true;
  179. }
  180. int Aria2App::OnExit()
  181. {
  182. aria2::libraryDeinit();
  183. return wxApp::OnExit();
  184. }
  185. MainFrame::MainFrame(const wxString& title)
  186. : wxFrame(nullptr, wxID_ANY, title, wxDefaultPosition, wxSize(640, 400)),
  187. timer_(this, TIMER_ID),
  188. downloaderThread_(downloaderJob, std::ref(jobq_), std::ref(notifyq_))
  189. {
  190. wxMenu* downloadMenu = new wxMenu;
  191. downloadMenu->Append(MI_ADD_URI, wxT("&Add URI"), wxT("Add URI to download"));
  192. wxMenuBar* menuBar = new wxMenuBar();
  193. menuBar->Append(downloadMenu, wxT("&Download"));
  194. SetMenuBar(menuBar);
  195. // Show active downloads in textual manner
  196. wxPanel* panel = new wxPanel(this, wxID_ANY);
  197. wxBoxSizer* box = new wxBoxSizer(wxVERTICAL);
  198. box->Add(new wxStaticText(panel, wxID_ANY, wxT("Active Download(s)")));
  199. text_ = new wxTextCtrl(panel, wxID_ANY, wxT(""), wxDefaultPosition,
  200. wxDefaultSize, wxTE_MULTILINE | wxTE_READONLY);
  201. box->Add(text_, wxSizerFlags().Expand().Proportion(1));
  202. panel->SetSizer(box);
  203. // Finally start time here
  204. timer_.Start(900);
  205. }
  206. void MainFrame::OnAddUri(wxCommandEvent& WXUNUSED(event))
  207. {
  208. AddUriDialog dlg(this);
  209. int ret = dlg.ShowModal();
  210. if (ret == 0) {
  211. if (dlg.GetUri().IsEmpty()) {
  212. return;
  213. }
  214. std::vector<std::string> uris = {std::string(dlg.GetUri().mb_str())};
  215. std::string optstr(dlg.GetOption().mb_str());
  216. aria2::KeyVals options;
  217. int keyfirst = 0;
  218. for (int i = 0; i < (int)optstr.size(); ++i) {
  219. if (optstr[i] == '\n') {
  220. keyfirst = i + 1;
  221. }
  222. else if (optstr[i] == '=') {
  223. int j;
  224. for (j = i + 1; j < (int)optstr.size(); ++j) {
  225. if (optstr[j] == '\n') {
  226. break;
  227. }
  228. }
  229. if (i - keyfirst > 0) {
  230. options.push_back(
  231. std::make_pair(optstr.substr(keyfirst, i - keyfirst),
  232. optstr.substr(i + 1, j - i - 1)));
  233. }
  234. keyfirst = j + 1;
  235. i = j;
  236. }
  237. }
  238. jobq_.push(std::unique_ptr<Job>(
  239. new AddUriJob(std::move(uris), std::move(options))));
  240. }
  241. }
  242. void MainFrame::OnCloseWindow(wxCloseEvent& WXUNUSED(event))
  243. {
  244. // On exit, we have to shutdown downloader thread and wait for it to
  245. // join. This is needed to execute graceful shutdown sequence of
  246. // aria2 session.
  247. jobq_.push(std::unique_ptr<Job>(new ShutdownJob(true)));
  248. downloaderThread_.join();
  249. Destroy();
  250. }
  251. void MainFrame::OnTimer(wxTimerEvent& event)
  252. {
  253. while (!notifyq_.empty()) {
  254. std::unique_ptr<Notification> nt = notifyq_.pop();
  255. nt->notify(this);
  256. }
  257. }
  258. template <typename T> std::string abbrevsize(T size)
  259. {
  260. if (size >= 1024 * 1024 * 1024) {
  261. return std::to_string(size / 1024 / 1024 / 1024) + "G";
  262. }
  263. else if (size >= 1024 * 1024) {
  264. return std::to_string(size / 1024 / 1024) + "M";
  265. }
  266. else if (size >= 1024) {
  267. return std::to_string(size / 1024) + "K";
  268. }
  269. else {
  270. return std::to_string(size);
  271. }
  272. }
  273. wxString towxs(const std::string& s) { return wxString(s.c_str(), wxConvUTF8); }
  274. void MainFrame::UpdateActiveStatus(const std::vector<DownloadStatus>& v)
  275. {
  276. text_->Clear();
  277. for (auto& a : v) {
  278. *text_ << wxT("[") << towxs(aria2::gidToHex(a.gid)) << wxT("] ")
  279. << towxs(abbrevsize(a.completedLength)) << wxT("/")
  280. << towxs(abbrevsize(a.totalLength)) << wxT("(")
  281. << (a.totalLength != 0 ? a.completedLength * 100 / a.totalLength : 0)
  282. << wxT("%)") << wxT(" D:") << towxs(abbrevsize(a.downloadSpeed))
  283. << wxT(" U:") << towxs(abbrevsize(a.uploadSpeed)) << wxT("\n")
  284. << wxT("File:") << towxs(a.filename) << wxT("\n");
  285. }
  286. }
  287. AddUriDialog::AddUriDialog(wxWindow* parent)
  288. : wxDialog(parent, wxID_ANY, wxT("Add URI"), wxDefaultPosition,
  289. wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER)
  290. {
  291. wxPanel* panel = new wxPanel(this, wxID_ANY);
  292. wxBoxSizer* box = new wxBoxSizer(wxVERTICAL);
  293. // URI text input
  294. box->Add(new wxStaticText(panel, wxID_ANY, wxT("URI")));
  295. uriText_ = new wxTextCtrl(panel, wxID_ANY);
  296. box->Add(uriText_, wxSizerFlags().Align(wxGROW));
  297. // Option multi text input
  298. box->Add(new wxStaticText(
  299. panel, wxID_ANY, wxT("Options (key=value pair per line, e.g. dir=/tmp")));
  300. optionText_ = new wxTextCtrl(panel, wxID_ANY, wxT(""), wxDefaultPosition,
  301. wxDefaultSize, wxTE_MULTILINE);
  302. box->Add(optionText_, wxSizerFlags().Align(wxGROW));
  303. // buttons
  304. wxPanel* btnpanel = new wxPanel(panel, wxID_ANY);
  305. box->Add(btnpanel);
  306. wxBoxSizer* btnbox = new wxBoxSizer(wxHORIZONTAL);
  307. // OK button
  308. okBtn_ = new wxButton(btnpanel, wxID_ANY, wxT("OK"));
  309. btnbox->Add(okBtn_);
  310. // Cancel button
  311. cancelBtn_ = new wxButton(btnpanel, wxID_ANY, wxT("Cancel"));
  312. btnbox->Add(cancelBtn_);
  313. panel->SetSizer(box);
  314. btnpanel->SetSizer(btnbox);
  315. }
  316. void AddUriDialog::OnButton(wxCommandEvent& event)
  317. {
  318. int ret = -1;
  319. if (event.GetEventObject() == okBtn_) {
  320. ret = 0;
  321. }
  322. EndModal(ret);
  323. }
  324. wxString AddUriDialog::GetUri() { return uriText_->GetValue(); }
  325. wxString AddUriDialog::GetOption() { return optionText_->GetValue(); }
  326. struct DownloadStatusNotification : public Notification {
  327. DownloadStatusNotification(std::vector<DownloadStatus>&& v) : v(v) {}
  328. virtual void notify(MainFrame* frame) { frame->UpdateActiveStatus(v); }
  329. std::vector<DownloadStatus> v;
  330. };
  331. struct ShutdownNotification : public Notification {
  332. ShutdownNotification() {}
  333. virtual void notify(MainFrame* frame) { frame->Close(); }
  334. };
  335. int downloaderJob(JobQueue& jobq, NotifyQueue& notifyq)
  336. {
  337. // session is actually singleton: 1 session per process
  338. aria2::Session* session;
  339. // Use default configuration
  340. aria2::SessionConfig config;
  341. config.keepRunning = true;
  342. session = aria2::sessionNew(aria2::KeyVals(), config);
  343. auto start = std::chrono::steady_clock::now();
  344. for (;;) {
  345. int rv = aria2::run(session, aria2::RUN_ONCE);
  346. if (rv != 1) {
  347. break;
  348. }
  349. auto now = std::chrono::steady_clock::now();
  350. auto count = std::chrono::duration_cast<std::chrono::milliseconds>(
  351. now - start).count();
  352. while (!jobq.empty()) {
  353. std::unique_ptr<Job> job = jobq.pop();
  354. job->execute(session);
  355. }
  356. if (count >= 900) {
  357. start = now;
  358. std::vector<aria2::A2Gid> gids = aria2::getActiveDownload(session);
  359. std::vector<DownloadStatus> v;
  360. for (auto gid : gids) {
  361. aria2::DownloadHandle* dh = aria2::getDownloadHandle(session, gid);
  362. if (dh) {
  363. DownloadStatus st;
  364. st.gid = gid;
  365. st.totalLength = dh->getTotalLength();
  366. st.completedLength = dh->getCompletedLength();
  367. st.downloadSpeed = dh->getDownloadSpeed();
  368. st.uploadSpeed = dh->getUploadSpeed();
  369. if (dh->getNumFiles() > 0) {
  370. aria2::FileData file = dh->getFile(1);
  371. st.filename = file.path;
  372. }
  373. v.push_back(std::move(st));
  374. aria2::deleteDownloadHandle(dh);
  375. }
  376. }
  377. notifyq.push(std::unique_ptr<Notification>(
  378. new DownloadStatusNotification(std::move(v))));
  379. }
  380. }
  381. int rv = aria2::sessionFinal(session);
  382. // Report back to the UI thread that this thread is going to
  383. // exit. This is needed when user pressed ctrl-C in the terminal.
  384. notifyq.push(std::unique_ptr<Notification>(new ShutdownNotification()));
  385. return rv;
  386. }