1#include "community_icons.h"
2
3#include <base/log.h>
4
5#include <engine/engine.h>
6#include <engine/gfx/image_manipulation.h>
7#include <engine/http.h>
8#include <engine/storage.h>
9
10CCommunityIcons::CAbstractCommunityIconJob::CAbstractCommunityIconJob(CCommunityIcons *pCommunityIcons, const char *pCommunityId, int StorageType) :
11 m_pCommunityIcons(pCommunityIcons),
12 m_StorageType(StorageType)
13{
14 str_copy(dst&: m_aCommunityId, src: pCommunityId);
15 str_format(buffer: m_aPath, buffer_size: sizeof(m_aPath), format: "communityicons/%s.png", pCommunityId);
16}
17
18CCommunityIcons::CCommunityIconDownloadJob::CCommunityIconDownloadJob(CCommunityIcons *pCommunityIcons, const char *pCommunityId, const char *pUrl, const SHA256_DIGEST &Sha256) :
19 CAbstractCommunityIconJob(pCommunityIcons, pCommunityId, IStorage::TYPE_SAVE)
20{
21 m_pHttpRequest = CreateHttpRequest(pUrl);
22 m_pHttpRequest->WriteToFile(pStorage: pCommunityIcons->Storage(), pDest: m_aPath, StorageType: IStorage::TYPE_SAVE);
23 m_pHttpRequest->ExpectSha256(Sha256);
24 m_pHttpRequest->Timeout(Timeout: CTimeout{.m_ConnectTimeoutMs: 0, .m_TimeoutMs: 0, .m_LowSpeedLimit: 0, .m_LowSpeedTime: 0});
25 m_pHttpRequest->SkipByFileTime(SkipByFileTime: false); // Always re-download.
26 m_pHttpRequest->LogProgress(LogProgress: HTTPLOG::FAILURE);
27}
28
29void CCommunityIcons::CCommunityIconLoadJob::Run()
30{
31 m_Success = m_pCommunityIcons->LoadFile(pPath: m_aPath, DirType: m_StorageType, Info&: m_ImageInfo, InfoGrayscale&: m_ImageInfoGrayscale, Sha256&: m_Sha256);
32}
33
34CCommunityIcons::CCommunityIconLoadJob::CCommunityIconLoadJob(CCommunityIcons *pCommunityIcons, const char *pCommunityId, int StorageType) :
35 CAbstractCommunityIconJob(pCommunityIcons, pCommunityId, StorageType)
36{
37 Abortable(Abortable: true);
38}
39
40CCommunityIcons::CCommunityIconLoadJob::~CCommunityIconLoadJob()
41{
42 m_ImageInfo.Free();
43 m_ImageInfoGrayscale.Free();
44}
45
46int CCommunityIcons::FileScan(const char *pName, int IsDir, int DirType, void *pUser)
47{
48 const char *pExtension = ".png";
49 CCommunityIcons *pSelf = static_cast<CCommunityIcons *>(pUser);
50 if(IsDir || !str_endswith(str: pName, suffix: pExtension) || str_length(str: pName) - str_length(str: pExtension) >= (int)CServerInfo::MAX_COMMUNITY_ID_LENGTH)
51 return 0;
52
53 char aCommunityId[CServerInfo::MAX_COMMUNITY_ID_LENGTH];
54 str_truncate(dst: aCommunityId, dst_size: sizeof(aCommunityId), src: pName, truncation_len: str_length(str: pName) - str_length(str: pExtension));
55
56 std::shared_ptr<CCommunityIconLoadJob> pJob = std::make_shared<CCommunityIconLoadJob>(args&: pSelf, args&: aCommunityId, args&: DirType);
57 pSelf->Engine()->AddJob(pJob);
58 pSelf->m_CommunityIconLoadJobs.push_back(x: pJob);
59 return 0;
60}
61
62const CCommunityIcon *CCommunityIcons::Find(const char *pCommunityId)
63{
64 auto Icon = std::find_if(first: m_vCommunityIcons.begin(), last: m_vCommunityIcons.end(), pred: [pCommunityId](const CCommunityIcon &Element) {
65 return str_comp(a: Element.m_aCommunityId, b: pCommunityId) == 0;
66 });
67 return Icon == m_vCommunityIcons.end() ? nullptr : &(*Icon);
68}
69
70bool CCommunityIcons::LoadFile(const char *pPath, int DirType, CImageInfo &Info, CImageInfo &InfoGrayscale, SHA256_DIGEST &Sha256)
71{
72 if(!Graphics()->LoadPng(Image&: Info, pFilename: pPath, StorageType: DirType))
73 {
74 log_error("menus/browser", "Failed to load community icon from '%s'", pPath);
75 return false;
76 }
77 if(Info.m_Format != CImageInfo::FORMAT_RGBA)
78 {
79 Info.Free();
80 log_error("menus/browser", "Failed to load community icon from '%s': must be an RGBA image", pPath);
81 return false;
82 }
83 if(!Storage()->CalculateHashes(pFilename: pPath, Type: DirType, pSha256: &Sha256))
84 {
85 Info.Free();
86 log_error("menus/browser", "Failed to load community icon from '%s': could not calculate hash", pPath);
87 return false;
88 }
89 InfoGrayscale = Info.DeepCopy();
90 ConvertToGrayscale(Image: InfoGrayscale);
91 return true;
92}
93
94void CCommunityIcons::LoadFinish(const char *pCommunityId, CImageInfo &Info, CImageInfo &InfoGrayscale, const SHA256_DIGEST &Sha256)
95{
96 CCommunityIcon CommunityIcon;
97 str_copy(dst&: CommunityIcon.m_aCommunityId, src: pCommunityId);
98 CommunityIcon.m_Sha256 = Sha256;
99 CommunityIcon.m_OrgTexture = Graphics()->LoadTextureRawMove(Image&: Info, Flags: 0, pTexName: pCommunityId);
100 CommunityIcon.m_GreyTexture = Graphics()->LoadTextureRawMove(Image&: InfoGrayscale, Flags: 0, pTexName: pCommunityId);
101
102 auto ExistingIcon = std::find_if(first: m_vCommunityIcons.begin(), last: m_vCommunityIcons.end(), pred: [pCommunityId](const CCommunityIcon &Element) {
103 return str_comp(a: Element.m_aCommunityId, b: pCommunityId) == 0;
104 });
105 if(ExistingIcon == m_vCommunityIcons.end())
106 {
107 m_vCommunityIcons.push_back(x: CommunityIcon);
108 }
109 else
110 {
111 Graphics()->UnloadTexture(pIndex: &ExistingIcon->m_OrgTexture);
112 Graphics()->UnloadTexture(pIndex: &ExistingIcon->m_GreyTexture);
113 *ExistingIcon = CommunityIcon;
114 }
115
116 log_trace("menus/browser", "Loaded community icon '%s'", pCommunityId);
117}
118
119void CCommunityIcons::Render(const CCommunityIcon *pIcon, CUIRect Rect, bool Active)
120{
121 Rect.VMargin(Cut: Rect.w / 2.0f - Rect.h, pOtherRect: &Rect);
122
123 Graphics()->WrapClamp();
124 Graphics()->TextureSet(Texture: Active ? pIcon->m_OrgTexture : pIcon->m_GreyTexture);
125 Graphics()->QuadsBegin();
126 Graphics()->SetColor(r: 1.0f, g: 1.0f, b: 1.0f, a: Active ? 1.0f : 0.5f);
127 IGraphics::CQuadItem QuadItem(Rect.x, Rect.y, Rect.w, Rect.h);
128 Graphics()->QuadsDrawTL(pArray: &QuadItem, Num: 1);
129 Graphics()->QuadsEnd();
130 Graphics()->WrapNormal();
131}
132
133void CCommunityIcons::Load()
134{
135 m_vCommunityIcons.clear();
136 Storage()->ListDirectory(Type: IStorage::TYPE_ALL, pPath: "communityicons", pfnCallback: FileScan, pUser: this);
137}
138
139void CCommunityIcons::Shutdown()
140{
141 m_CommunityIconLoadJobs.clear();
142 m_CommunityIconDownloadJobs.clear();
143}
144
145void CCommunityIcons::Update()
146{
147 // Update load jobs (icon is loaded from existing file)
148 if(!m_CommunityIconLoadJobs.empty())
149 {
150 std::shared_ptr<CCommunityIconLoadJob> pJob = m_CommunityIconLoadJobs.front();
151 if(pJob->Done())
152 {
153 if(pJob->State() == IJob::STATE_DONE && pJob->Success())
154 {
155 LoadFinish(pCommunityId: pJob->CommunityId(), Info&: pJob->ImageInfo(), InfoGrayscale&: pJob->ImageInfoGrayscale(), Sha256: pJob->Sha256());
156 }
157 m_CommunityIconLoadJobs.pop_front();
158 }
159
160 // Don't start download jobs until all load jobs are done
161 if(!m_CommunityIconLoadJobs.empty())
162 return;
163 }
164
165 // Update download jobs (icon is downloaded and loaded from new file)
166 if(!m_CommunityIconDownloadJobs.empty())
167 {
168 std::shared_ptr<CCommunityIconDownloadJob> pJob = m_CommunityIconDownloadJobs.front();
169 if(pJob->HttpRequest()->Done())
170 {
171 if(pJob->HttpRequest()->State() == EHttpState::DONE)
172 {
173 std::shared_ptr<CCommunityIconLoadJob> pLoadJob = std::make_shared<CCommunityIconLoadJob>(args: this, args: pJob->CommunityId(), args: IStorage::TYPE_SAVE);
174 Engine()->AddJob(pJob: pLoadJob);
175 m_CommunityIconLoadJobs.push_back(x: pLoadJob);
176 }
177 m_CommunityIconDownloadJobs.pop_front();
178 }
179 }
180
181 // Rescan for changed communities only when necessary
182 if(!ServerBrowser()->DDNetInfoAvailable() || m_CommunityIconsInfoSha256 == ServerBrowser()->DDNetInfoSha256().value())
183 return;
184 m_CommunityIconsInfoSha256 = ServerBrowser()->DDNetInfoSha256();
185
186 // Remove icons for removed communities
187 auto RemovalIterator = m_vCommunityIcons.begin();
188 while(RemovalIterator != m_vCommunityIcons.end())
189 {
190 if(ServerBrowser()->Community(pCommunityId: RemovalIterator->m_aCommunityId) == nullptr)
191 {
192 Graphics()->UnloadTexture(pIndex: &RemovalIterator->m_OrgTexture);
193 Graphics()->UnloadTexture(pIndex: &RemovalIterator->m_GreyTexture);
194 RemovalIterator = m_vCommunityIcons.erase(position: RemovalIterator);
195 }
196 else
197 {
198 ++RemovalIterator;
199 }
200 }
201
202 // Find added and updated community icons
203 for(const auto &Community : ServerBrowser()->Communities())
204 {
205 if(!Community.IconSha256().has_value())
206 continue;
207 const char *pCommunityId = Community.Id();
208 auto ExistingIcon = std::find_if(first: m_vCommunityIcons.begin(), last: m_vCommunityIcons.end(), pred: [pCommunityId](const auto &Element) {
209 return str_comp(Element.m_aCommunityId, pCommunityId) == 0;
210 });
211 auto ExistingDownload = std::find_if(first: m_CommunityIconDownloadJobs.begin(), last: m_CommunityIconDownloadJobs.end(), pred: [pCommunityId](const auto &Element) {
212 return str_comp(Element->CommunityId(), pCommunityId) == 0;
213 });
214 if(ExistingDownload == m_CommunityIconDownloadJobs.end() && (ExistingIcon == m_vCommunityIcons.end() || ExistingIcon->m_Sha256 != Community.IconSha256().value()))
215 {
216 std::shared_ptr<CCommunityIconDownloadJob> pJob = std::make_shared<CCommunityIconDownloadJob>(args: this, args&: pCommunityId, args: Community.IconUrl(), args: Community.IconSha256().value());
217 Http()->Run(pRequest: pJob->HttpRequest());
218 m_CommunityIconDownloadJobs.push_back(x: pJob);
219 }
220 }
221}
222