libaria2wx.cc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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 libaria2wx.cc `wx-config --libs` -laria2 -pthread
  42. #include <iostream>
  43. #include <chrono>
  44. #include <thread>
  45. #include <mutex>
  46. #include <queue>
  47. #include <wx/wx.h>
  48. #include <aria2/aria2.h>
  49. // Interface to send message to downloader thread from UI thread
  50. struct Job {
  51. virtual ~Job() {};
  52. virtual void execute(aria2::Session* session) = 0;
  53. };
  54. class MainFrame;
  55. // Interface to report back to UI thread from downloader thread
  56. struct Notification {
  57. virtual ~Notification() {};
  58. virtual void notify(MainFrame* frame) = 0;
  59. };
  60. // std::queue<T> wrapper synchronized by mutex. In this example
  61. // program, only one thread consumes from the queue, so separating
  62. // empty() and pop() is not a problem.
  63. template<typename T>
  64. 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. virtual void execute(aria2::Session* session)
  106. {
  107. // TODO check return value
  108. aria2::addUri(session, 0, uris, options);
  109. }
  110. std::vector<std::string> uris;
  111. aria2::KeyVals options;
  112. };
  113. int downloaderJob(JobQueue& jobq, NotifyQueue& notifyq);
  114. // This struct is used to report download progress for active
  115. // downloads from downloader thread to UI thread.
  116. struct DownloadStatus {
  117. aria2::A2Gid gid;
  118. int64_t totalLength;
  119. int64_t completedLength;
  120. int downloadSpeed;
  121. int uploadSpeed;
  122. std::string filename;
  123. };
  124. class Aria2App : public wxApp {
  125. public:
  126. virtual bool OnInit();
  127. virtual int OnExit();
  128. };
  129. class MainFrame : public wxFrame {
  130. public:
  131. MainFrame(const wxString& title);
  132. void OnQuit(wxCommandEvent& event);
  133. void OnAbout(wxCommandEvent& event);
  134. void OnCloseWindow(wxCloseEvent& event);
  135. void OnTimer(wxTimerEvent& event);
  136. void OnAddUri(wxCommandEvent& event);
  137. void UpdateActiveStatus(const std::vector<DownloadStatus>& v);
  138. private:
  139. wxTextCtrl* text_;
  140. wxTimer timer_;
  141. JobQueue jobq_;
  142. NotifyQueue notifyq_;
  143. std::thread downloaderThread_;
  144. DECLARE_EVENT_TABLE()
  145. };
  146. enum {
  147. TIMER_ID = 1
  148. };
  149. enum {
  150. MI_ADD_URI = 1
  151. };
  152. BEGIN_EVENT_TABLE(MainFrame, wxFrame)
  153. EVT_CLOSE(MainFrame::OnCloseWindow)
  154. EVT_TIMER(TIMER_ID, MainFrame::OnTimer)
  155. EVT_MENU(MI_ADD_URI, MainFrame::OnAddUri)
  156. END_EVENT_TABLE()
  157. class AddUriDialog : public wxDialog {
  158. public:
  159. AddUriDialog(wxWindow* parent);
  160. void OnButton(wxCommandEvent& event);
  161. wxString GetUri();
  162. wxString GetOption();
  163. private:
  164. wxTextCtrl* uriText_;
  165. wxTextCtrl* optionText_;
  166. wxButton* okBtn_;
  167. wxButton* cancelBtn_;
  168. DECLARE_EVENT_TABLE()
  169. };
  170. BEGIN_EVENT_TABLE(AddUriDialog, wxDialog)
  171. EVT_BUTTON(wxID_ANY, AddUriDialog::OnButton)
  172. END_EVENT_TABLE()
  173. IMPLEMENT_APP(Aria2App)
  174. bool Aria2App::OnInit()
  175. {
  176. if(!wxApp::OnInit()) return false;
  177. aria2::libraryInit();
  178. MainFrame* frame = new MainFrame(wxT("libaria2 GUI example"));
  179. frame->Show(true);
  180. return true;
  181. }
  182. int Aria2App::OnExit()
  183. {
  184. aria2::libraryDeinit();
  185. return wxApp::OnExit();
  186. }
  187. MainFrame::MainFrame(const wxString& title)
  188. : wxFrame(nullptr, wxID_ANY, title, wxDefaultPosition,
  189. wxSize(640, 400)),
  190. timer_(this, TIMER_ID),
  191. downloaderThread_(downloaderJob, std::ref(jobq_), std::ref(notifyq_))
  192. {
  193. wxMenu* downloadMenu = new wxMenu;
  194. downloadMenu->Append(MI_ADD_URI, wxT("&Add URI"),
  195. wxT("Add URI to download"));
  196. wxMenuBar* menuBar = new wxMenuBar();
  197. menuBar->Append(downloadMenu, wxT("&Download"));
  198. SetMenuBar(menuBar);
  199. // Show active downloads in textual manner
  200. wxPanel* panel = new wxPanel(this, wxID_ANY);
  201. wxBoxSizer* box = new wxBoxSizer(wxVERTICAL);
  202. box->Add(new wxStaticText(panel, wxID_ANY, wxT("Active Download(s)")));
  203. text_ = new wxTextCtrl(panel, wxID_ANY, wxT(""), wxDefaultPosition,
  204. wxDefaultSize, wxTE_MULTILINE | wxTE_READONLY);
  205. box->Add(text_, wxSizerFlags().Expand().Proportion(1));
  206. panel->SetSizer(box);
  207. // Finally start time here
  208. timer_.Start(900);
  209. }
  210. void MainFrame::OnAddUri(wxCommandEvent& WXUNUSED(event))
  211. {
  212. AddUriDialog dlg(this);
  213. int ret = dlg.ShowModal();
  214. if(ret == 0) {
  215. if(dlg.GetUri().IsEmpty()) {
  216. return;
  217. }
  218. std::vector<std::string> uris = { std::string(dlg.GetUri().mb_str()) };
  219. std::string optstr(dlg.GetOption().mb_str());
  220. aria2::KeyVals options;
  221. int keyfirst = 0;
  222. for(int i = 0; i < (int)optstr.size(); ++i) {
  223. if(optstr[i] == '\n') {
  224. keyfirst = i+1;
  225. } else if(optstr[i] == '=') {
  226. int j;
  227. for(j = i+1; j < (int)optstr.size(); ++j) {
  228. if(optstr[j] == '\n') {
  229. break;
  230. }
  231. }
  232. if(i - keyfirst > 0) {
  233. options.push_back
  234. (std::make_pair(optstr.substr(keyfirst, i - keyfirst),
  235. optstr.substr(i + 1, j - i - 1)));
  236. }
  237. keyfirst = j + 1;
  238. i = j;
  239. }
  240. }
  241. jobq_.push(std::unique_ptr<Job>(new AddUriJob(std::move(uris),
  242. std::move(options))));
  243. }
  244. }
  245. void MainFrame::OnCloseWindow(wxCloseEvent& WXUNUSED(event))
  246. {
  247. // On exit, we have to shutdown downloader thread and wait for it to
  248. // join. This is needed to execute graceful shutdown sequence of
  249. // aria2 session.
  250. jobq_.push(std::unique_ptr<Job>(new ShutdownJob(true)));
  251. downloaderThread_.join();
  252. Destroy();
  253. }
  254. void MainFrame::OnTimer(wxTimerEvent& event)
  255. {
  256. while(!notifyq_.empty()) {
  257. std::unique_ptr<Notification> nt = notifyq_.pop();
  258. nt->notify(this);
  259. }
  260. }
  261. template<typename T>
  262. std::string abbrevsize(T size)
  263. {
  264. if(size >= 1024*1024*1024) {
  265. return std::to_string(size/1024/1024/1024)+"G";
  266. } else if(size >= 1024*1024) {
  267. return std::to_string(size/1024/1024)+"M";
  268. } else if(size >= 1024) {
  269. return std::to_string(size/1024)+"K";
  270. } else {
  271. return std::to_string(size);
  272. }
  273. }
  274. wxString towxs(const std::string& s)
  275. {
  276. return wxString(s.c_str(), wxConvUTF8);
  277. }
  278. void MainFrame::UpdateActiveStatus(const std::vector<DownloadStatus>& v)
  279. {
  280. text_->Clear();
  281. for(auto& a : v) {
  282. *text_ << wxT("[")
  283. << towxs(aria2::gidToHex(a.gid))
  284. << wxT("] ")
  285. << towxs(abbrevsize(a.completedLength))
  286. << wxT("/")
  287. << towxs(abbrevsize(a.totalLength))
  288. << wxT("(")
  289. << (a.totalLength != 0 ? a.completedLength*100/a.totalLength : 0)
  290. << wxT("%)")
  291. << wxT(" D:")
  292. << towxs(abbrevsize(a.downloadSpeed))
  293. << wxT(" U:")
  294. << towxs(abbrevsize(a.uploadSpeed))
  295. << wxT("\n")
  296. << wxT("File:") << towxs(a.filename) << wxT("\n");
  297. }
  298. }
  299. AddUriDialog::AddUriDialog(wxWindow* parent)
  300. : wxDialog(parent, wxID_ANY, wxT("Add URI"), wxDefaultPosition,
  301. wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER)
  302. {
  303. wxPanel* panel = new wxPanel(this, wxID_ANY);
  304. wxBoxSizer* box = new wxBoxSizer(wxVERTICAL);
  305. // URI text input
  306. box->Add(new wxStaticText(panel, wxID_ANY, wxT("URI")));
  307. uriText_ = new wxTextCtrl(panel, wxID_ANY);
  308. box->Add(uriText_, wxSizerFlags().Align(wxGROW));
  309. // Option multi text input
  310. box->Add(new wxStaticText
  311. (panel, wxID_ANY,
  312. wxT("Options (key=value pair per line, e.g. dir=/tmp")));
  313. optionText_ = new wxTextCtrl(panel, wxID_ANY, wxT(""), wxDefaultPosition,
  314. wxDefaultSize, wxTE_MULTILINE);
  315. box->Add(optionText_, wxSizerFlags().Align(wxGROW));
  316. // buttons
  317. wxPanel* btnpanel = new wxPanel(panel, wxID_ANY);
  318. box->Add(btnpanel);
  319. wxBoxSizer* btnbox = new wxBoxSizer(wxHORIZONTAL);
  320. // OK button
  321. okBtn_ = new wxButton(btnpanel, wxID_ANY, wxT("OK"));
  322. btnbox->Add(okBtn_);
  323. // Cancel button
  324. cancelBtn_ = new wxButton(btnpanel, wxID_ANY, wxT("Cancel"));
  325. btnbox->Add(cancelBtn_);
  326. panel->SetSizer(box);
  327. btnpanel->SetSizer(btnbox);
  328. }
  329. void AddUriDialog::OnButton(wxCommandEvent& event)
  330. {
  331. int ret = -1;
  332. if(event.GetEventObject() == okBtn_) {
  333. ret = 0;
  334. }
  335. EndModal(ret);
  336. }
  337. wxString AddUriDialog::GetUri()
  338. {
  339. return uriText_->GetValue();
  340. }
  341. wxString AddUriDialog::GetOption()
  342. {
  343. return optionText_->GetValue();
  344. }
  345. struct DownloadStatusNotification : public Notification {
  346. DownloadStatusNotification(std::vector<DownloadStatus>&& v)
  347. : v(v) {}
  348. virtual void notify(MainFrame* frame)
  349. {
  350. frame->UpdateActiveStatus(v);
  351. }
  352. std::vector<DownloadStatus> v;
  353. };
  354. struct ShutdownNotification : public Notification {
  355. ShutdownNotification() {}
  356. virtual void notify(MainFrame* frame)
  357. {
  358. frame->Close();
  359. }
  360. };
  361. int downloaderJob(JobQueue& jobq, NotifyQueue& notifyq)
  362. {
  363. // session is actually singleton: 1 session per process
  364. aria2::Session* session;
  365. // Use default configuration
  366. aria2::SessionConfig config;
  367. config.keepRunning = true;
  368. session = aria2::sessionNew(aria2::KeyVals(), config);
  369. auto start = std::chrono::steady_clock::now();
  370. for(;;) {
  371. int rv = aria2::run(session, aria2::RUN_ONCE);
  372. if(rv != 1) {
  373. break;
  374. }
  375. auto now = std::chrono::steady_clock::now();
  376. auto count = std::chrono::duration_cast<std::chrono::milliseconds>
  377. (now - start).count();
  378. while(!jobq.empty()) {
  379. std::unique_ptr<Job> job = jobq.pop();
  380. job->execute(session);
  381. }
  382. if(count >= 900) {
  383. start = now;
  384. std::vector<aria2::A2Gid> gids = aria2::getActiveDownload(session);
  385. std::vector<DownloadStatus> v;
  386. for(auto gid : gids) {
  387. aria2::DownloadHandle* dh = aria2::getDownloadHandle(session, gid);
  388. if(dh) {
  389. DownloadStatus st;
  390. st.gid = gid;
  391. st.totalLength = dh->getTotalLength();
  392. st.completedLength = dh->getCompletedLength();
  393. st.downloadSpeed = dh->getDownloadSpeed();
  394. st.uploadSpeed = dh->getUploadSpeed();
  395. if(dh->getNumFiles() > 0) {
  396. aria2::FileData file = dh->getFile(1);
  397. st.filename = file.path;
  398. }
  399. v.push_back(std::move(st));
  400. aria2::deleteDownloadHandle(dh);
  401. }
  402. }
  403. notifyq.push(std::unique_ptr<Notification>
  404. (new DownloadStatusNotification(std::move(v))));
  405. }
  406. }
  407. int rv = aria2::sessionFinal(session);
  408. // Report back to the UI thread that this thread is going to
  409. // exit. This is needed when user pressed ctrl-C in the terminal.
  410. notifyq.push(std::unique_ptr<Notification>(new ShutdownNotification()));
  411. return rv;
  412. }