-
Notifications
You must be signed in to change notification settings - Fork 123
/
main.cpp
1250 lines (1048 loc) · 40 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*! \file main.cpp
* \brief HNTerm - browse Hacker News in the terminal
*
* warning : ugly code below
*
*/
#include "imtui/imtui.h"
#ifdef __EMSCRIPTEN__
#include "imtui/imtui-impl-emscripten.h"
#include <emscripten.h>
#include <emscripten/html5.h>
#else
#include "imtui/imtui-impl-ncurses.h"
#define EMSCRIPTEN_KEEPALIVE
#endif
#include "imtui-common.h"
#include <map>
#include <atomic>
#include <vector>
#include <string>
#include <mutex>
#include <thread>
#include <variant>
#include <functional>
#ifdef __EMSCRIPTEN__
#define ENABLE_API_CACHE 0
#else
#define ENABLE_API_CACHE 0
#endif
// tmp
#include <fstream>
std::mutex g_mutex;
std::atomic<bool> g_keepRunning = true;
uint64_t g_totalBytesDownloaded = 0;
int g_nfetches = 0;
int g_nextUpdate = 0;
char g_curURI[512];
ImTui::TScreen screen;
extern bool hnInit();
extern void hnFree();
extern int openInBrowser(std::string uri);
extern std::string getJSONForURI_impl(std::string uri);
extern std::string getJSONForURI_cache(std::string uri);
namespace {
inline uint64_t t_s() {
#ifdef __EMSCRIPTEN__
return emscripten_date_now()*0.001f;
#else
return std::chrono::duration_cast<std::chrono::seconds>(std::chrono::high_resolution_clock::now().time_since_epoch()).count(); // duh ..
#endif
}
std::map<std::string, std::string> parseCmdArguments(int argc, char ** argv) {
int last = argc;
std::map<std::string, std::string> res;
for (int i = 1; i < last; ++i) {
res[argv[i]] = "";
if (argv[i][0] == '-') {
if (strlen(argv[i]) > 1) {
res[std::string(1, argv[i][1])] = strlen(argv[i]) > 2 ? argv[i] + 2 : "";
}
}
}
return res;
}
void replaceAll(std::string & s, const std::string & search, const std::string & replace) {
for (size_t pos = 0; ; pos += replace.length()) {
pos = s.find(search, pos);
if (pos == std::string::npos) break;
s.erase(pos, search.length());
s.insert(pos, replace);
}
}
inline std::string timeSince(uint64_t t) {
auto delta = t_s() - t;
if (delta < 60) return std::to_string(delta) + " seconds";
if (delta < 3600) return std::to_string(delta/60) + " minutes";
if (delta < 24*3600) return std::to_string(delta/3600) + " hours";
return std::to_string(delta/24/3600) + " days";
}
void requestJSONForURI(std::string uri) {
{
std::lock_guard<std::mutex> lock(g_mutex);
++g_nfetches;
snprintf(g_curURI, 512, "%s", uri.c_str());
}
getJSONForURI_impl(uri);
}
std::string getJSONForURI(std::string uri) {
#ifndef __EMSCRIPTEN__
{
std::lock_guard<std::mutex> lock(g_mutex);
++g_nfetches;
snprintf(g_curURI, 512, "%s", uri.c_str());
}
std::string fname = "cache-" + uri;
for (auto & ch : fname) {
if ((ch >= 'a' && ch <= 'z') ||
(ch >= 'A' && ch <= 'Z') ||
(ch >= '0' && ch <= '9')) {
continue;
}
ch = '-';
}
if (ENABLE_API_CACHE) {
std::ifstream fin(fname);
if (fin.is_open() && fin.good()) {
//printf("%s\n", uri.c_str());
std::string str((std::istreambuf_iterator<char>(fin)), std::istreambuf_iterator<char>());
fin.close();
return str;
}
}
auto response_string = getJSONForURI_impl(uri);
if (ENABLE_API_CACHE) {
std::ofstream fout(fname);
fout.write(response_string.c_str(), response_string.size());
fout.close();
}
#else
auto response_string = getJSONForURI_cache(uri);
if (response_string == "") return "";
#endif
{
std::lock_guard<std::mutex> lock(g_mutex);
g_totalBytesDownloaded += response_string.size();
}
return response_string;
}
}
namespace HN {
using URI = std::string;
using ItemId = int;
using ItemIds = std::vector<ItemId>;
using ItemData = std::map<std::string, std::string>;
static const std::string kCmdPrefix = "curl -s -k ";
static const URI kAPIItem = "https://hacker-news.firebaseio.com/v0/item/";
static const URI kAPITopStories = "https://hacker-news.firebaseio.com/v0/topstories.json";
static const URI kAPINewStories = "https://hacker-news.firebaseio.com/v0/newstories.json";
//static const URI kAPIBestStories = "https://hacker-news.firebaseio.com/v0/beststories.json";
static const URI kAPIAskStories = "https://hacker-news.firebaseio.com/v0/askstories.json";
static const URI kAPIShowStories = "https://hacker-news.firebaseio.com/v0/showstories.json";
static const URI kAPIJobStories = "https://hacker-news.firebaseio.com/v0/jobstories.json";
static const URI kAPIUpdates = "https://hacker-news.firebaseio.com/v0/updates.json";
struct Story {
std::string by = "";
int descendants = 0;
ItemId id = 0;
ItemIds kids;
int score = 0;
uint64_t time = 0;
std::string text = "";
std::string title = "";
std::string url = "";
std::string domain = "";
};
struct Comment {
std::string by = "";
ItemId id = 0;
ItemIds kids;
ItemId parent = 0;
std::string text = "";
uint64_t time = 0;
};
struct Job {};
struct Poll {};
struct PollOpt {};
enum class ItemType : int {
Unknown,
Story,
Comment,
Job,
Poll,
PollOpt,
};
struct Item {
ItemType type = ItemType::Unknown;
bool needUpdate = true;
bool needRequest = true;
std::variant<Story, Comment> data;
};
ItemIds parseJSONIntArray(const std::string json) {
ItemIds res;
if (json[0] != '[') return res;
int n = json.size();
int curid = 0;
for (int i = 1; i < n; ++i) {
if (json[i] == ' ') continue;
if (json[i] == ',') {
res.push_back(curid);
curid = 0;
continue;
}
if (json[i] == ']') {
res.push_back(curid);
break;
}
curid = 10*curid + json[i] - 48;
}
return res;
}
ItemData parseJSONMap(const std::string json) {
ItemData res;
if (json[0] != '{') return res;
bool hasKey = false;
bool inToken = false;
std::string strKey = "";
std::string strVal = "";
int n = json.size();
for (int i = 1; i < n; ++i) {
if (!inToken) {
if (json[i] == ' ') continue;
if (json[i] == '"' && json[i-1] != '\\') {
inToken = true;
continue;
}
} else {
if (json[i] == '"' && json[i-1] != '\\') {
if (hasKey == false) {
hasKey = true;
++i;
while (json[i] == ' ') ++i;
++i; // :
while (json[i] == ' ') ++i;
if (json[i] == '[') {
while (json[i] != ']') {
strVal += json[i++];
}
strVal += ']';
hasKey = false;
res[strKey] = strVal;
strKey = "";
strVal = "";
} else if (json[i] != '\"') {
while (json[i] != ',' && json[i] != '}') {
strVal += json[i++];
}
hasKey = false;
res[strKey] = strVal;
strKey = "";
strVal = "";
} else {
inToken = true;
continue;
}
} else {
hasKey = false;
res[strKey] = strVal;
strKey = "";
strVal = "";
}
inToken = false;
continue;
}
if (hasKey == false) {
strKey += json[i];
} else {
strVal += json[i];
}
}
}
return res;
}
std::string parseHTML(std::string str) {
::replaceAll(str, "<p>", "\n");
std::string res;
bool inTag = false;
for (auto & ch : str) {
if (ch == '<') {
inTag = true;
} else if (ch == '>') {
inTag = false;
} else {
if (inTag == false) {
res += ch;
}
}
}
::replaceAll(res, "/", "/");
::replaceAll(res, "'", "'");
::replaceAll(res, ">", ">");
::replaceAll(res, "–", "-");
::replaceAll(res, "“", "\"");
::replaceAll(res, "”", "\"");
::replaceAll(res, "‘", "'");
::replaceAll(res, "’", "'");
::replaceAll(res, "„", "'");
::replaceAll(res, """, "\"");
return res;
}
URI getItemURI(ItemId id) {
return kAPIItem + std::to_string(id) + ".json";
}
ItemData getItemDataFromJSON(std::string json) {
return parseJSONMap(json);
}
ItemType getItemType(const ItemData & itemData) {
if (itemData.find("type") == itemData.end()) return ItemType::Unknown;
auto strType = itemData.at("type");
if (strType == "story") return ItemType::Story;
if (strType == "comment") return ItemType::Comment;
if (strType == "job") return ItemType::Job;
if (strType == "poll") return ItemType::Poll;
if (strType == "pollopt") return ItemType::PollOpt;
return ItemType::Unknown;
}
void parseStory(const ItemData & data, Story & res) {
try {
res.by = data.at("by");
} catch (...) {
res.by = "[deleted]";
}
try {
res.descendants = std::stoi(data.at("descendants"));
} catch (...) {
res.descendants = 0;
}
res.id = std::stoi(data.at("id"));
try {
res.kids = parseJSONIntArray(data.at("kids"));
} catch (...) {
res.kids.clear();
}
res.score = std::stoi(data.at("score"));
res.time = std::stoll(data.at("time"));
try {
res.text = parseHTML(data.at("text"));
} catch (...) {
res.text = "";
}
try {
res.title = parseHTML(data.at("title"));
} catch (...) {
res.title = "";
}
try {
res.url = data.at("url");
res.domain = "";
int slash = 0;
for (auto & ch : res.url) {
if (ch == '/') {
++slash;
continue;
}
if (slash > 2) break;
if (slash > 1) res.domain += ch;
}
} catch (...) {
res.url = "";
res.domain = "";
}
}
void parseComment(const ItemData & data, Comment & res) {
try {
res.by = data.at("by");
} catch (...) {
res.by = "[deleted]";
}
res.id = std::stoi(data.at("id"));
try {
res.kids = parseJSONIntArray(data.at("kids"));
} catch (...) {
res.kids.clear();
}
res.parent = std::stoi(data.at("parent"));
try {
res.text = parseHTML(data.at("text"));
} catch (...) {
res.text = "";
}
res.time = std::stoll(data.at("time"));
}
ItemIds getStoriesIds(URI uri) {
std::string json = getJSONForURI(uri);
return parseJSONIntArray(json);
}
ItemIds getChangedItemsIds() {
std::string json = getJSONForURI(HN::kAPIUpdates);
auto data = parseJSONMap(json);
return parseJSONIntArray(data["items"]);
}
struct State {
bool timeout(uint64_t now, uint64_t last) {
return now - last > 30;
}
bool update(const ItemIds & toRefresh) {
auto now = ::t_s();
bool hasChange = false;
#ifdef __EMSCRIPTEN__
if (timeout(now, lastStoriesPoll_s)) {
::requestJSONForURI(HN::kAPITopStories);
//::requestJSONForURI(HN::kAPIBestStories);
::requestJSONForURI(HN::kAPIShowStories);
::requestJSONForURI(HN::kAPIAskStories);
::requestJSONForURI(HN::kAPINewStories);
lastStoriesPoll_s = ::t_s();
} else {
{
std::lock_guard<std::mutex> lock(g_mutex);
g_nextUpdate = lastStoriesPoll_s + 30 - now;
}
}
if (timeout(now, lastUpdatePoll_s)) {
::requestJSONForURI(HN::kAPIUpdates);
lastUpdatePoll_s = ::t_s();
}
#endif
#ifdef __EMSCRIPTEN__
{
#else
if (timeout(now, lastStoriesPoll_s)) {
#endif
{
auto ids = HN::getStoriesIds(HN::kAPITopStories);
if (ids.empty() == false) {
idsTop = std::move(ids);
hasChange = true;
}
}
//{
// auto ids = HN::getStoriesIds(HN::kAPIBestStories);
// if (ids.empty() == false) {
// idsBest = std::move(ids);
// hasChange = true;
// }
//}
{
auto ids = HN::getStoriesIds(HN::kAPIShowStories);
if (ids.empty() == false) {
idsShow = std::move(ids);
hasChange = true;
}
}
{
auto ids = HN::getStoriesIds(HN::kAPIAskStories);
if (ids.empty() == false) {
idsAsk = std::move(ids);
hasChange = true;
}
}
{
auto ids = HN::getStoriesIds(HN::kAPINewStories);
if (ids.empty() == false) {
idsNew = std::move(ids);
hasChange = true;
}
}
#ifndef __EMSCRIPTEN__
lastStoriesPoll_s = ::t_s();
} else {
{
std::lock_guard<std::mutex> lock(g_mutex);
g_nextUpdate = lastStoriesPoll_s + 30 - now;
}
#endif
}
#ifdef __EMSCRIPTEN__
{
#else
if (timeout(now, lastUpdatePoll_s)) {
#endif
auto ids = HN::getChangedItemsIds();
for (auto id : ids) {
if (items.find(id) == items.end()) continue;
items[id].needUpdate = true;
items[id].needRequest = true;
}
#ifndef __EMSCRIPTEN__
lastUpdatePoll_s = ::t_s();
#endif
}
#ifdef __EMSCRIPTEN__
for (auto id : toRefresh) {
if (items[id].needRequest == false) continue;
::requestJSONForURI(getItemURI(id));
items[id].needRequest = false;
}
#endif
for (auto id : toRefresh) {
if (items[id].needUpdate == false) continue;
const auto json = getJSONForURI(getItemURI(id));
if (json == "") continue;
const auto data = getItemDataFromJSON(json);
const auto type = getItemType(data);
auto & item = items[id];
switch (type) {
case ItemType::Unknown:
{
}
break;
case ItemType::Story:
{
if (std::holds_alternative<Story>(item.data) == false) {
item.data = Story();
}
Story & story = std::get<Story>(item.data);
if (item.needUpdate) {
hasChange = true;
parseStory(data, story);
item.needUpdate = false;
}
}
break;
case ItemType::Comment:
{
if (std::holds_alternative<Comment>(item.data) == false) {
item.data = Comment();
}
Comment & story = std::get<Comment>(item.data);
if (item.needUpdate) {
hasChange = true;
parseComment(data, story);
item.needUpdate = false;
}
}
break;
case ItemType::Job:
{
// temp
hasChange = true;
item.needUpdate = false;
}
break;
case ItemType::Poll:
{
// temp
hasChange = true;
item.needUpdate = false;
}
break;
case ItemType::PollOpt:
{
// temp
hasChange = true;
item.needUpdate = false;
}
break;
};
break;
}
return hasChange;
}
ItemIds idsTop;
//ItemIds idsBest;
ItemIds idsShow;
ItemIds idsAsk;
ItemIds idsNew;
std::map<ItemId, Item> items;
uint64_t lastUpdatePoll_s = 0;
uint64_t lastStoriesPoll_s = 0;
};
}
namespace UI {
enum class WindowContent : int {
Top,
//Best,
Show,
Ask,
New,
Count,
};
std::map<WindowContent, std::string> kContentStr = {
{ WindowContent::Top, "Top" },
//{ WindowContent::Best, "Best" },
{ WindowContent::Show, "Show" },
{ WindowContent::Ask, "Ask" },
{ WindowContent::New, "New" },
};
struct WindowData {
WindowContent content;
bool showComments = false;
HN::ItemId selectedStoryId = 0;
int hoveredStoryId = 0;
int hoveredCommentId = 0;
};
struct State {
int hoveredWindowId = 0;
int maxStories = 10;
int statusWindowHeight = 4;
#ifdef __EMSCRIPTEN__
bool showHelpWelcome = true;
#else
bool showHelpWelcome = false;
#endif
bool showHelpModal = false;
bool showStatusWindow = true;
int nWindows = 2;
std::map<int, bool> collapsed;
std::array<WindowData, 3> windows { {
{
WindowContent::Top,
false,
0, 0, 0,
},
{
WindowContent::Show,
false,
0, 0, 0,
},
{
WindowContent::New,
false,
0, 0, 0,
},
} };
};
}
std::mutex mutex;
std::thread workerHN;
VSync vsync;
bool stateHNUpdated = false;
HN::State stateHNBG;
HN::State stateHNBuf;
HN::State stateHNFG;
HN::ItemIds toRefreshBG;
HN::ItemIds toRefreshBuf;
HN::ItemIds toRefreshFG;
UI::State stateUI;
void updateHN() {
{
std::lock_guard<std::mutex> lock(mutex);
toRefreshBG = toRefreshBuf;
}
bool needUpdate = stateHNBG.update(toRefreshBG);
if (needUpdate) {
{
std::lock_guard<std::mutex> lock(mutex);
stateHNUpdated = true;
stateHNBuf = stateHNBG;
}
}
}
extern "C" {
EMSCRIPTEN_KEEPALIVE
void get_screen(char * buffer) {
int nx = screen.data[0].size();
int ny = screen.data.size();
int idx = 0;
for (int y = 0; y < ny; ++y) {
for (int x = 0; x < nx; ++x) {
buffer[idx] = screen.data[y][x].c; ++idx;
buffer[idx] = screen.data[y][x].f; ++idx;
buffer[idx] = screen.data[y][x].b; ++idx;
}
}
}
EMSCRIPTEN_KEEPALIVE
void set_screen_size(int nx, int ny) {
ImGui::GetIO().DisplaySize.x = nx;
ImGui::GetIO().DisplaySize.y = ny;
}
EMSCRIPTEN_KEEPALIVE
bool render_frame() {
#ifdef __EMSCRIPTEN__
updateHN();
#endif
{
std::lock_guard<std::mutex> lock(mutex);
if (stateHNUpdated) {
stateHNUpdated = false;
stateHNFG = stateHNBuf;
}
}
toRefreshFG.clear();
#ifdef __EMSCRIPTEN__
ImTui_ImplEmscripten_NewFrame(screen);
#else
ImTui_ImplNcurses_NewFrame(screen);
#endif
ImTui_ImplText_NewFrame();
#ifndef __EMSCRIPTEN__
ImGui::GetIO().DeltaTime = vsync.delta_s();
#endif
if (ImGui::GetIO().DisplaySize.x < 50) {
stateUI.nWindows = 1;
}
ImGui::NewFrame();
for (int windowId = 0; windowId < stateUI.nWindows; ++windowId) {
const auto & items = stateHNFG.items;
auto & window = stateUI.windows[windowId];
{
auto wSize = ImGui::GetIO().DisplaySize;
wSize.x /= stateUI.nWindows;
if (stateUI.showStatusWindow) {
wSize.y -= stateUI.statusWindowHeight;
}
wSize.x = int(wSize.x);
ImGui::SetNextWindowPos(ImVec2(wSize.x*windowId, 0), ImGuiCond_Always);
if (windowId < stateUI.nWindows - 1) {
wSize.x -= 1.1;
}
ImGui::SetNextWindowSize(wSize, ImGuiCond_Always);
}
std::string title = "[Y] Hacker News (" + UI::kContentStr[window.content] + ")##" + std::to_string(windowId);
ImGui::Begin(title.c_str(), nullptr,
ImGuiWindowFlags_NoCollapse |
ImGuiWindowFlags_NoResize |
ImGuiWindowFlags_NoMove |
ImGuiWindowFlags_NoScrollbar);
ImGui::Text("%s", "");
if (window.showComments == false) {
const auto & storyIds =
(window.content == UI::WindowContent::Top) ? stateHNFG.idsTop :
(window.content == UI::WindowContent::Show) ? stateHNFG.idsShow :
(window.content == UI::WindowContent::New) ? stateHNFG.idsNew :
stateHNFG.idsTop;
int nShow = std::min(stateUI.maxStories, (int) storyIds.size());
for (int i = 0; i < nShow; ++i) {
const auto & id = storyIds[i];
toRefreshFG.push_back(id);
if (items.find(id) == items.end() || std::holds_alternative<HN::Story>(items.at(id).data) == false) {
continue;
}
const auto & item = items.at(id);
const HN::Story & story = std::get<HN::Story>(item.data);
if (windowId == stateUI.hoveredWindowId && i == window.hoveredStoryId) {
auto col0 = ImGui::GetStyleColorVec4(ImGuiCol_Text);
auto col1 = ImGui::GetStyleColorVec4(ImGuiCol_WindowBg);
ImGui::PushStyleColor(ImGuiCol_Text, col1);
ImGui::PushStyleColor(ImGuiCol_TextDisabled, col0);
auto p0 = ImGui::GetCursorScreenPos();
p0.x += 1;
auto p1 = p0;
p1.x += ImGui::CalcTextSize(story.title.c_str()).x + 4;
ImGui::GetWindowDrawList()->AddRectFilled(p0, p1, ImGui::GetColorU32(col0));
if (ImGui::IsKeyPressed('o', false) || ImGui::IsKeyPressed('O', false)) {
openInBrowser(story.url);
}
}
bool isHovered = false;
ImGui::Text("%2d.", i + 1);
isHovered |= ImGui::IsItemHovered();
ImGui::SameLine();
ImGui::PushTextWrapPos(ImGui::GetContentRegionAvailWidth());
ImGui::Text("%s", story.title.c_str());
isHovered |= ImGui::IsItemHovered();
ImGui::PopTextWrapPos();
ImGui::SameLine();
if (windowId == stateUI.hoveredWindowId && i == window.hoveredStoryId) {
ImGui::PopStyleColor(2);
}
ImGui::TextDisabled(" (%s)", story.domain.c_str());
ImGui::TextDisabled(" %d points by %s %s ago | %d comments", story.score, story.by.c_str(), ::timeSince(story.time).c_str(), story.descendants);
isHovered |= ImGui::IsItemHovered();
if (isHovered) {
stateUI.hoveredWindowId = windowId;
window.hoveredStoryId = i;
}
if (ImGui::GetCursorScreenPos().y > ImGui::GetWindowSize().y) {
stateUI.maxStories = i;
} else {
if ((i == stateUI.maxStories - 1) && (ImGui::GetCursorScreenPos().y + 2 < ImGui::GetWindowSize().y)) {
++stateUI.maxStories;
}
}
}
if (windowId == stateUI.hoveredWindowId) {
if (ImGui::IsMouseDoubleClicked(0) ||
ImGui::IsKeyPressed(ImGui::GetIO().KeyMap[ImGuiKey_Enter], false)) {
if (stateUI.showHelpModal == false) {
window.showComments = true;
window.selectedStoryId = storyIds[window.hoveredStoryId];
}
}
if (ImGui::IsKeyPressed('k', true) ||
ImGui::IsKeyPressed(ImGui::GetIO().KeyMap[ImGuiKey_UpArrow], true)) {
window.hoveredStoryId = std::max(0, window.hoveredStoryId - 1);
}
if (ImGui::IsKeyPressed('j', true) ||
ImGui::IsKeyPressed(ImGui::GetIO().KeyMap[ImGuiKey_DownArrow], true)) {
window.hoveredStoryId = std::min(stateUI.maxStories - 1, window.hoveredStoryId + 1);
}
if (ImGui::IsKeyPressed('g', true)) {
window.hoveredStoryId = 0;
}
if (ImGui::IsKeyPressed('G', true)) {
window.hoveredStoryId = stateUI.maxStories - 1;
}
if (ImGui::IsKeyPressed(ImGui::GetIO().KeyMap[ImGuiKey_Tab])) {
stateUI.windows[stateUI.hoveredWindowId].content =
(UI::WindowContent) ((int(stateUI.windows[stateUI.hoveredWindowId].content) + 1)%int(UI::WindowContent::Count));
}
}
} else {
const auto & story = std::get<HN::Story>(items.at(window.selectedStoryId).data);
toRefreshFG.push_back(story.id);
ImGui::Text("%s", story.title.c_str());
ImGui::TextDisabled("%d points by %s %s ago | %d comments", story.score, story.by.c_str(), ::timeSince(story.time).c_str(), story.descendants);
if (story.text.empty() == false) {
ImGui::PushTextWrapPos(ImGui::GetContentRegionAvailWidth());
ImGui::Text("%s", story.text.c_str());
ImGui::PopTextWrapPos();
}
ImGui::Text("%s", "");
int curCommentId = 0;
std::function<void(const HN::ItemIds & commentIds, int indent)> renderComments;
renderComments = [&](const HN::ItemIds & commentIds, int indent) {
const int nComments = commentIds.size();
for (int i = 0; i < nComments; ++i) {
const auto & id = commentIds[i];
toRefreshFG.push_back(commentIds[i]);
if (items.find(id) == items.end() || std::holds_alternative<HN::Comment>(items.at(id).data) == false) {
continue;
}
const auto & item = items.at(id);
const auto & comment = std::get<HN::Comment>(item.data);
static char header[128];
snprintf(header, 128, "%*s %s %s ago [%s]", indent, "", comment.by.c_str(), ::timeSince(comment.time).c_str(), stateUI.collapsed[id] ? "+" : "-");
if (windowId == stateUI.hoveredWindowId && curCommentId == window.hoveredCommentId) {
auto col0 = ImGui::GetStyleColorVec4(ImGuiCol_Text);
ImGui::PushStyleColor(ImGuiCol_TextDisabled, ImVec4(1.0f, 1.0f, 1.0f, 1.0f));
auto p0 = ImGui::GetCursorScreenPos();
p0.x += 1 + indent;
auto p1 = p0;
p1.x += ImGui::CalcTextSize(header).x - indent;
ImGui::GetWindowDrawList()->AddRectFilled(p0, p1, ImGui::GetColorU32(col0));
if (ImGui::GetCursorScreenPos().y < 4) {
ImGui::SetScrollHereY(0.0f);
}
}
bool isHovered = false;
ImGui::TextDisabled("%s", header);
isHovered |= ImGui::IsItemHovered();
if (windowId == stateUI.hoveredWindowId && curCommentId == window.hoveredCommentId) {
ImGui::PopStyleColor(1);
}
if (stateUI.collapsed[id] == false ) {
ImGui::PushTextWrapPos(ImGui::GetContentRegionAvailWidth());
ImGui::Text("%*s", indent, "");
ImGui::SameLine();
ImGui::Text("%s", comment.text.c_str());
isHovered |= ImGui::IsItemHovered();
ImGui::PopTextWrapPos();
}
if (windowId == stateUI.hoveredWindowId && curCommentId == window.hoveredCommentId) {
if (ImGui::GetCursorScreenPos().y > ImGui::GetWindowSize().y + 4) {
ImGui::SetScrollHereY(1.0f);
}
if (ImGui::IsMouseDoubleClicked(0) ||
ImGui::IsKeyPressed(ImGui::GetIO().KeyMap[ImGuiKey_Enter], false)) {
stateUI.collapsed[id] = !stateUI.collapsed[id];
}