1 | // Aseprite |
2 | // Copyright (C) 2021 Igara Studio S.A. |
3 | // Copyright (C) 2001-2018 David Capello |
4 | // |
5 | // This program is distributed under the terms of |
6 | // the End-User License Agreement for Aseprite. |
7 | |
8 | #ifndef APP_JOB_H_INCLUDED |
9 | #define APP_JOB_H_INCLUDED |
10 | #pragma once |
11 | |
12 | #include "ui/alert.h" |
13 | #include "ui/timer.h" |
14 | |
15 | #include <atomic> |
16 | #include <exception> |
17 | #include <mutex> |
18 | #include <thread> |
19 | |
20 | namespace app { |
21 | |
22 | class Job { |
23 | public: |
24 | static int runningJobs(); |
25 | |
26 | Job(const char* jobName); |
27 | virtual ~Job(); |
28 | |
29 | // Starts the job calling onJob() event in another thread and |
30 | // monitoring the progress with onMonitorTick() event. |
31 | void startJob(); |
32 | |
33 | void waitJob(); |
34 | |
35 | // The onJob() can use this function to report progress of the |
36 | // background job being done. 1.0 is completed. |
37 | void jobProgress(double f); |
38 | |
39 | // Returns true if the job was canceled by the user (in case he |
40 | // pressed a "Cancel" button in the GUI). The onJob() thread should |
41 | // check this variable periodically to stop working. |
42 | bool isCanceled(); |
43 | |
44 | protected: |
45 | |
46 | // This member function is called from another dedicated thread |
47 | // outside the GUI one, so you can do some image processing here. |
48 | // Remember that you cannot use any GUI element in this handler. |
49 | virtual void onJob() = 0; |
50 | |
51 | // Called each 1000 msecs by the GUI queue processing. |
52 | // It is executed from the main GUI thread. |
53 | virtual void onMonitoringTick(); |
54 | |
55 | private: |
56 | void done(); |
57 | |
58 | static void thread_proc(Job* self); |
59 | static void monitor_proc(void* data); |
60 | static void monitor_free(void* data); |
61 | |
62 | std::thread m_thread; |
63 | std::unique_ptr<ui::Timer> m_timer; |
64 | std::mutex m_mutex; |
65 | ui::AlertPtr m_alert_window; |
66 | std::atomic<double> m_last_progress; |
67 | bool m_done_flag; |
68 | bool m_canceled_flag; |
69 | std::exception_ptr m_error; |
70 | |
71 | // these methods are privated and not defined |
72 | Job(); |
73 | Job(const Job&); |
74 | Job& operator==(const Job&); |
75 | |
76 | }; |
77 | |
78 | } // namespace app |
79 | |
80 | #endif |
81 | |