|
2 | 2 | #define CPP_TRACER_H
|
3 | 3 |
|
4 | 4 | #include <string>
|
| 5 | +#include <cstdlib> |
5 | 6 | #include <fstream>
|
6 | 7 | #include <nlohmann/json.hpp>
|
| 8 | +#include <curl/curl.h> |
7 | 9 |
|
8 | 10 | #define MAX_TRACES 1000000
|
9 | 11 | #define MAX_TRACERS 100
|
@@ -43,10 +45,52 @@ class Tracer {
|
43 | 45 | }
|
44 | 46 |
|
45 | 47 | public:
|
| 48 | + static size_t writeFunction(void *ptr, size_t size, size_t nmemb, std::string *data) { |
| 49 | + data->append((char *) ptr, size * nmemb); |
| 50 | + return size * nmemb; |
| 51 | + } |
| 52 | + |
46 | 53 | static void onExit() {
|
47 |
| - std::ofstream fout("traces.json"); |
48 |
| - fout << traces.dump(); |
49 |
| - fout.close(); |
| 54 | + string content = traces.dump(); |
| 55 | + if (std::getenv("ALGORITHM_VISUALIZER")) { |
| 56 | + std::ofstream fout("traces.json"); |
| 57 | + fout << content; |
| 58 | + fout.close(); |
| 59 | + } else { |
| 60 | + auto curl = curl_easy_init(); |
| 61 | + if (curl) { |
| 62 | + string params = "content=" + content; |
| 63 | + |
| 64 | + curl_easy_setopt(curl, CURLOPT_URL, "https://algorithm-visualizer.org/api/visualizations"); |
| 65 | + curl_easy_setopt(curl, CURLOPT_POSTFIELDS, params.c_str()); |
| 66 | + curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1L); |
| 67 | + curl_easy_setopt(curl, CURLOPT_TCP_KEEPALIVE, 1L); |
| 68 | + |
| 69 | + string header; |
| 70 | + string response; |
| 71 | + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeFunction); |
| 72 | + curl_easy_setopt(curl, CURLOPT_HEADERDATA, &header); |
| 73 | + curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); |
| 74 | + |
| 75 | + curl_easy_perform(curl); |
| 76 | + long response_code; |
| 77 | + curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code); |
| 78 | + |
| 79 | + curl_easy_cleanup(curl); |
| 80 | + curl = NULL; |
| 81 | + |
| 82 | + if (response_code == 200) { |
| 83 | +#ifdef linux |
| 84 | + string command = "xdg-open " + response; |
| 85 | +#elif _WIN32 |
| 86 | + string command = "start " + response; |
| 87 | +#else |
| 88 | + string command = "open " + response; |
| 89 | +#endif |
| 90 | + system(command.c_str()); |
| 91 | + } |
| 92 | + } |
| 93 | + } |
50 | 94 | }
|
51 | 95 | };
|
52 | 96 |
|
|
0 commit comments