1/*
2 * LegacyClonk
3 *
4 * Copyright (c) RedWolf Design
5 * Copyright (c) 2005, Sven2
6 * Copyright (c) 2017-2022, The LegacyClonk Team and contributors
7 *
8 * Distributed under the terms of the ISC license; see accompanying file
9 * "COPYING" for details.
10 *
11 * "Clonk" is a registered trademark of Matthes Bender, used with permission.
12 * See accompanying file "TRADEMARK" for details.
13 *
14 * To redistribute this file separately, substitute the full license texts
15 * for the above references.
16 */
17
18// Startup screen for non-parameterized engine start: Scenario selection dialog
19
20#include <C4StartupScenSelDlg.h>
21
22#include <C4Network2Dialogs.h>
23#include <C4StartupMainDlg.h>
24#include <C4StartupNetDlg.h>
25#include "C4GuiEdit.h"
26#include "C4GuiListBox.h"
27#include "C4GuiResource.h"
28#include "C4GuiTabular.h"
29#include "StdMarkup.h"
30#include <C4ComponentHost.h>
31#include <C4Components.h>
32#include <C4RTF.h>
33#include <C4Wrappers.h>
34#include <C4Log.h>
35#include <C4Game.h>
36#include <C4GameDialogs.h>
37#include <C4FileSelDlg.h>
38#include "C4TextEncoding.h"
39
40#include <format>
41
42// singleton
43C4StartupScenSelDlg *C4StartupScenSelDlg::pInstance = nullptr;
44
45// Map folder data
46
47void C4MapFolderData::Scenario::CompileFunc(StdCompiler *pComp)
48{
49 pComp->Value(rStruct: mkNamingAdapt(rValue&: sFilename, szName: "File", rDefault: StdStrBuf()));
50 pComp->Value(rStruct: mkNamingAdapt(rValue&: sBaseImage, szName: "BaseImage", rDefault: StdStrBuf()));
51 pComp->Value(rStruct: mkNamingAdapt(rValue&: sOverlayImage, szName: "OverlayImage", rDefault: StdStrBuf()));
52 pComp->Value(rStruct: mkNamingAdapt(rValue&: singleClick, szName: "SingleClick", rDefault: false));
53 pComp->Value(rStruct: mkNamingAdapt(rValue&: rcOverlayPos, szName: "Area", rDefault: C4Rect()));
54 pComp->Value(rStruct: mkNamingAdapt(rValue&: sTitle, szName: "Title", rDefault: StdStrBuf()));
55 pComp->Value(rStruct: mkNamingAdapt(rValue&: iTitleFontSize, szName: "TitleFontSize", rDefault: 20));
56 pComp->Value(rStruct: mkNamingAdapt(rValue&: dwTitleInactClr, szName: "TitleColorInactive", rDefault: 0x7fffffffu));
57 pComp->Value(rStruct: mkNamingAdapt(rValue&: dwTitleActClr, szName: "TitleColorActive", rDefault: 0x0fffffffu));
58 pComp->Value(rStruct: mkNamingAdapt(rValue&: iTitleOffX, szName: "TitleOffX", rDefault: 0));
59 pComp->Value(rStruct: mkNamingAdapt(rValue&: iTitleOffY, szName: "TitleOffY", rDefault: 0));
60 pComp->Value(rStruct: mkNamingAdapt(rValue&: byTitleAlign, szName: "TitleAlign", rDefault: ACenter));
61 pComp->Value(rStruct: mkNamingAdapt(rValue&: fTitleBookFont, szName: "TitleUseBookFont", rDefault: true));
62 pComp->Value(rStruct: mkNamingAdapt(rValue&: fImgDump, szName: "ImageDump", rDefault: false)); // developer help
63}
64
65void C4MapFolderData::AccessGfx::CompileFunc(StdCompiler *pComp)
66{
67 pComp->Value(rStruct: mkNamingAdapt(rValue&: sPassword, szName: "Access", rDefault: StdStrBuf()));
68 pComp->Value(rStruct: mkNamingAdapt(rValue&: sOverlayImage, szName: "OverlayImage", rDefault: StdStrBuf()));
69 pComp->Value(rStruct: mkNamingAdapt(rValue&: rcOverlayPos, szName: "Area", rDefault: C4Rect()));
70}
71
72C4MapFolderData::MapPic::MapPic(const C4GUI::FLOAT_RECT &rcfBounds, const C4Facet &rfct) : C4GUI::Picture(C4Rect(rcfBounds), false), rcfBounds(rcfBounds)
73{
74 SetFacet(rfct);
75 SetToolTip(LoadResStr(id: C4ResStrTableKey::IDS_MSG_MAP_DESC));
76}
77
78void C4MapFolderData::MapPic::MouseInput(C4GUI::CMouse &rMouse, int32_t iButton, int32_t iX, int32_t iY, uint32_t dwKeyParam)
79{
80 typedef C4GUI::Picture Parent;
81 Parent::MouseInput(rMouse, iButton, iX, iY, dwKeyParam);
82 // input: mouse movement or buttons - deselect everything if clicked
83 if (iButton == C4MC_Button_LeftDown && C4StartupScenSelDlg::pInstance)
84 {
85 C4StartupScenSelDlg::pInstance->DeselectAll();
86 }
87}
88
89void C4MapFolderData::MapPic::DrawElement(C4FacetEx &cgo)
90{
91 // get drawing bounds
92 float x0 = rcfBounds.left + cgo.TargetX, y0 = rcfBounds.top + cgo.TargetY;
93 // draw the image
94 GetFacet().DrawXFloat(sfcTarget: cgo.Surface, fX: x0, fY: y0, fWdt: rcfBounds.right - rcfBounds.left, fHgt: rcfBounds.bottom - rcfBounds.top);
95}
96
97void C4MapFolderData::Clear()
98{
99 fCoordinatesAdjusted = false;
100 fctBackgroundPicture.Clear();
101 pScenarioFolder = nullptr;
102 pSelectedEntry = nullptr;
103 pSelectionInfoBox = nullptr;
104 rcScenInfoArea.Set(iX: 0, iY: 0, iWdt: 0, iHgt: 0);
105 MinResX = MinResY = 0;
106 fUseFullscreenMap = false;
107 int i;
108 for (i = 0; i < iScenCount; ++i) delete ppScenList[i];
109 iScenCount = 0;
110 delete[] ppScenList; ppScenList = nullptr;
111 for (i = 0; i < iAccessGfxCount; ++i) delete ppAccessGfxList[i];
112 iAccessGfxCount = 0;
113 delete[] ppAccessGfxList; ppAccessGfxList = nullptr;
114 pMainDlg = nullptr;
115}
116
117bool C4MapFolderData::Load(C4Group &hGroup, C4ScenarioListLoader::Folder *pScenLoaderFolder)
118{
119 // clear previous
120 Clear();
121 // load localization info
122 C4LangStringTable LangTable;
123 bool fHasLangTable = !!LangTable.LoadEx(szName: "StringTbl", hGroup, C4CFN_ScriptStringTbl, szLanguage: Config.General.LanguageEx);
124 // load core data
125 StdStrBuf Buf;
126 if (!hGroup.LoadEntryString(C4CFN_MapFolderData, Buf)) return false;
127 if (fHasLangTable) LangTable.ReplaceStrings(rBuf&: Buf);
128 if (!CompileFromBuf_LogWarn<StdCompilerINIRead>(TargetStruct: mkNamingAdapt(rValue&: *this, szName: "FolderMap"), SrcBuf: Buf, C4CFN_MapFolderData)) return false;
129 // check resolution requirement
130 if (MinResX && MinResX > C4GUI::GetScreenWdt()) return false;
131 if (MinResY && MinResY > C4GUI::GetScreenHgt()) return false;
132 // load images
133 if (!fctBackgroundPicture.Load(hGroup, C4CFN_MapFolderBG))
134 {
135 DebugLog(level: spdlog::level::err, fmt: "C4MapFolderData::Load({}): Could not load background graphic \"{}\"", args: hGroup.GetName(), C4CFN_MapFolderBG);
136 return false;
137 }
138 int i;
139 for (i = 0; i < iScenCount; ++i)
140 {
141 // init scenario entry stuff
142 Scenario *pScen = ppScenList[i];
143 pScen->pScenEntry = pScenLoaderFolder->FindEntryByName(szFilename: pScen->sFilename.getData());
144 pScen->pBtn = nullptr;
145 pScen->sTitle.Replace(szOld: "TITLE", szNew: pScen->pScenEntry ? pScen->pScenEntry->GetName().getData() : "<c ff0000>ERROR</c>" /* scenario not loaded; title cannot be referenced */);
146 // developer image dump
147 if (pScen->fImgDump)
148 {
149 C4FacetExSurface fctDump; bool fSuccess = false;
150 if (fctDump.Create(iWdt: pScen->rcOverlayPos.Wdt, iHgt: pScen->rcOverlayPos.Hgt, iWdt2: C4FCT_Full, iHgt2: C4FCT_Full))
151 {
152 lpDDraw->Blit(sfcSource: fctBackgroundPicture.Surface,
153 fx: static_cast<float>(pScen->rcOverlayPos.x), fy: static_cast<float>(pScen->rcOverlayPos.y),
154 fwdt: static_cast<float>(pScen->rcOverlayPos.Wdt), fhgt: static_cast<float>(pScen->rcOverlayPos.Hgt),
155 sfcTarget: fctDump.Surface,
156 tx: 0, ty: 0,
157 twdt: fctDump.Wdt, thgt: fctDump.Hgt);
158 fSuccess = fctDump.Surface->SavePNG(szFilename: pScen->sBaseImage.getData(), fSaveAlpha: true, fApplyGamma: false, fSaveOverlayOnly: false);
159 }
160 if (!fSuccess)
161 DebugLog(level: spdlog::level::err, fmt: "C4MapFolderData::Load({}): Could not dump graphic \"{}\"", args: hGroup.GetName(), args: pScen->sBaseImage.getData());
162 continue;
163 }
164 // load images
165 if (pScen->sBaseImage.getLength() > 0) if (!pScen->fctBase.Load(hGroup, szName: pScen->sBaseImage.getData()))
166 {
167 DebugLog(level: spdlog::level::err, fmt: "C4MapFolderData::Load({}): Could not load base graphic \"{}\"", args: hGroup.GetName(), args: pScen->sBaseImage.getData());
168 return false;
169 }
170 }
171 for (i = 0; i < iScenCount; ++i)
172 {
173 Scenario *pScen = ppScenList[i];
174 if (pScen->sOverlayImage.getLength() > 0) if (!pScen->fctOverlay.Load(hGroup, szName: pScen->sOverlayImage.getData()))
175 {
176 DebugLog(level: spdlog::level::err, fmt: "C4MapFolderData::Load({}): Could not load graphic \"{}\"", args: hGroup.GetName(), args: pScen->sOverlayImage.getData());
177 return false;
178 }
179 }
180 for (i = 0; i < iAccessGfxCount; ++i)
181 {
182 AccessGfx *pGfx = ppAccessGfxList[i];
183 if (pGfx->sOverlayImage.getLength() > 0) if (!pGfx->fctOverlay.Load(hGroup, szName: pGfx->sOverlayImage.getData()))
184 {
185 DebugLog(level: spdlog::level::err, fmt: "C4MapFolderData::Load({}): Could not load graphic \"{}\"", args: hGroup.GetName(), args: pGfx->sOverlayImage.getData());
186 return false;
187 }
188 }
189 // all loaded
190 pScenarioFolder = pScenLoaderFolder;
191 return true;
192}
193
194void C4MapFolderData::CompileFunc(StdCompiler *pComp)
195{
196 // core values
197 pComp->Value(rStruct: mkNamingAdapt(rValue&: rcScenInfoArea, szName: "ScenInfoArea", rDefault: C4Rect(0, 0, 0, 0)));
198 pComp->Value(rStruct: mkNamingAdapt(rValue&: MinResX, szName: "MinResX", rDefault: 0));
199 pComp->Value(rStruct: mkNamingAdapt(rValue&: MinResY, szName: "MinResY", rDefault: 0));
200 pComp->Value(rStruct: mkNamingAdapt(rValue&: fUseFullscreenMap, szName: "FullscreenBG", rDefault: false));
201 pComp->Value(rStruct: mkNamingAdapt(rValue&: hideTitle, szName: "HideTitle", rDefault: false));
202 // compile scenario list
203 int32_t iOldScenCount = iScenCount;
204 pComp->Value(rStruct: mkNamingCountAdapt(iCount&: iScenCount, szName: "Scenario"));
205 if (pComp->isCompiler())
206 {
207 while (iOldScenCount--) delete ppScenList[iOldScenCount];
208 delete[] ppScenList;
209 if (iScenCount)
210 {
211 ppScenList = new Scenario *[iScenCount]{};
212 }
213 else
214 ppScenList = nullptr;
215 }
216 if (iScenCount)
217 {
218 mkPtrAdaptNoNull(rpObj&: *ppScenList);
219 pComp->Value(rStruct: mkNamingAdapt(rValue: mkArrayAdaptMapS(array: ppScenList, size: iScenCount, map: mkPtrAdaptNoNull<Scenario>), szName: "Scenario"));
220 }
221 // compile access gfx list
222 int32_t iOldAccesGfxCount = iAccessGfxCount;
223 pComp->Value(rStruct: mkNamingCountAdapt(iCount&: iAccessGfxCount, szName: "AccessGfx"));
224 if (pComp->isCompiler())
225 {
226 while (iOldAccesGfxCount--) delete ppAccessGfxList[iOldAccesGfxCount];
227 delete[] ppAccessGfxList;
228 if (iAccessGfxCount)
229 {
230 ppAccessGfxList = new AccessGfx *[iAccessGfxCount]{};
231 }
232 else
233 ppAccessGfxList = nullptr;
234 }
235 if (iAccessGfxCount)
236 {
237 mkPtrAdaptNoNull(rpObj&: *ppAccessGfxList);
238 pComp->Value(rStruct: mkNamingAdapt(rValue: mkArrayAdaptMapS(array: ppAccessGfxList, size: iAccessGfxCount, map: mkPtrAdaptNoNull<AccessGfx>), szName: "AccessGfx"));
239 }
240}
241
242void C4MapFolderData::ConvertFacet2ScreenCoord(const C4Rect &rc, C4GUI::FLOAT_RECT *pfrc, float fBGZoomX, float fBGZoomY, int iOffX, int iOffY)
243{
244 pfrc->left = (fBGZoomX * rc.x) + iOffX;
245 pfrc->top = (fBGZoomY * rc.y) + iOffY;
246 pfrc->right = pfrc->left + (fBGZoomX * rc.Wdt);
247 pfrc->bottom = pfrc->top + (fBGZoomY * rc.Hgt);
248}
249
250void C4MapFolderData::ConvertFacet2ScreenCoord(int32_t *piValue, float fBGZoom, int iOff)
251{
252 *piValue = int32_t(floorf(x: fBGZoom * *piValue + 0.5f)) + iOff;
253}
254
255void C4MapFolderData::ConvertFacet2ScreenCoord(C4Rect &rcMapArea, bool fAspect)
256{
257 if (!fctBackgroundPicture.Wdt || !fctBackgroundPicture.Hgt) return; // invalid BG - should not happen
258 // get zoom of background image
259 float fBGZoomX = 1.0f, fBGZoomY = 1.0f; int iOffX = 0, iOffY = 0;
260 if (fAspect)
261 {
262 if (fctBackgroundPicture.Wdt * rcMapArea.Hgt > rcMapArea.Wdt * fctBackgroundPicture.Hgt)
263 {
264 // background image is limited by width
265 fBGZoomX = fBGZoomY = static_cast<float>(rcMapArea.Wdt) / fctBackgroundPicture.Wdt;
266 iOffY = std::max<int>(a: 0, b: static_cast<int>(rcMapArea.Hgt - (fBGZoomX * fctBackgroundPicture.Hgt))) / 2;
267 }
268 else
269 {
270 // background image is limited by height
271 fBGZoomX = fBGZoomY = static_cast<float>(rcMapArea.Hgt) / fctBackgroundPicture.Hgt;
272 iOffX = std::max<int>(a: 0, b: static_cast<int>(rcMapArea.Wdt - (fBGZoomY * fctBackgroundPicture.Wdt))) / 2;
273 }
274 }
275 else
276 {
277 // do not keep aspect: Independent X and Y zoom
278 fBGZoomX = static_cast<float>(rcMapArea.Wdt) / fctBackgroundPicture.Wdt;
279 fBGZoomY = static_cast<float>(rcMapArea.Hgt) / fctBackgroundPicture.Hgt;
280 }
281 iOffX -= rcMapArea.x; iOffY -= rcMapArea.y;
282 C4Rect rcBG; rcBG.Set(iX: 0, iY: 0, iWdt: fctBackgroundPicture.Wdt, iHgt: fctBackgroundPicture.Hgt);
283 ConvertFacet2ScreenCoord(rc: rcBG, pfrc: &rcfBG, fBGZoomX, fBGZoomY, iOffX, iOffY);
284 // default for scenario info area: 1/3rd of right area
285 if (!rcScenInfoArea.Wdt)
286 rcScenInfoArea.Set(iX: static_cast<int32_t>(fctBackgroundPicture.Wdt * 2 / 3), iY: static_cast<int32_t>(fctBackgroundPicture.Hgt / 16), iWdt: static_cast<int32_t>(fctBackgroundPicture.Wdt / 3), iHgt: static_cast<int32_t>(fctBackgroundPicture.Hgt * 7 / 8));
287 // assume all facet coordinates are referring to background image zoom; convert them to screen coordinates by applying zoom and offset
288 C4GUI::FLOAT_RECT rcfScenInfoArea;
289 ConvertFacet2ScreenCoord(rc: rcScenInfoArea, pfrc: &rcfScenInfoArea, fBGZoomX, fBGZoomY, iOffX, iOffY);
290 rcScenInfoArea.x = static_cast<int32_t>(rcfScenInfoArea.left); rcScenInfoArea.y = static_cast<int32_t>(rcfScenInfoArea.top);
291 rcScenInfoArea.Wdt = static_cast<int32_t>(rcfScenInfoArea.right - rcfScenInfoArea.left);
292 rcScenInfoArea.Hgt = static_cast<int32_t>(rcfScenInfoArea.bottom - rcfScenInfoArea.top);
293 int i;
294 for (i = 0; i < iScenCount; ++i)
295 {
296 Scenario *pScen = ppScenList[i];
297 ConvertFacet2ScreenCoord(rc: pScen->rcOverlayPos, pfrc: &(pScen->rcfOverlayPos), fBGZoomX, fBGZoomY, iOffX, iOffY);
298 // title sizes
299 ConvertFacet2ScreenCoord(piValue: &(pScen->iTitleFontSize), fBGZoom: fBGZoomY, iOff: 0);
300 // title position: Relative to title rect; so do not add offset here
301 ConvertFacet2ScreenCoord(piValue: &(pScen->iTitleOffX), fBGZoom: fBGZoomX, iOff: 0);
302 ConvertFacet2ScreenCoord(piValue: &(pScen->iTitleOffY), fBGZoom: fBGZoomY, iOff: 0);
303 }
304 for (i = 0; i < iAccessGfxCount; ++i) ConvertFacet2ScreenCoord(rc: ppAccessGfxList[i]->rcOverlayPos, pfrc: &(ppAccessGfxList[i]->rcfOverlayPos), fBGZoomX, fBGZoomY, iOffX, iOffY);
305 // done
306 fCoordinatesAdjusted = true;
307}
308
309void C4MapFolderData::CreateGUIElements(C4StartupScenSelDlg *pMainDlg, C4GUI::Window &rContainer)
310{
311 this->pMainDlg = pMainDlg;
312
313 if (hideTitle)
314 {
315 this->pMainDlg->HideTitle(hide: true);
316 }
317
318 // convert all coordinates to match the container sizes
319 // do this only once; assume container won't change between loads
320 if (!fCoordinatesAdjusted)
321 if (!fUseFullscreenMap)
322 ConvertFacet2ScreenCoord(rcMapArea&: rContainer.GetClientRect(), fAspect: true);
323 else
324 {
325 C4Rect rcMapRect = pMainDlg->GetBounds();
326 rContainer.ClientPos2ScreenPos(riX&: rcMapRect.x, riY&: rcMapRect.y);
327 ConvertFacet2ScreenCoord(rcMapArea&: rcMapRect, fAspect: false);
328 }
329 // empty any previous stuff in container
330 while (rContainer.GetFirst()) delete rContainer.GetFirst();
331 // create background image
332 if (!fUseFullscreenMap)
333 rContainer.AddElement(pChild: new MapPic(rcfBG, fctBackgroundPicture));
334 else
335 {
336 pMainDlg->SetBackground(&fctBackgroundPicture);
337 }
338 // create mission access overlays
339 int i;
340 for (i = 0; i < iAccessGfxCount; ++i)
341 {
342 AccessGfx *pGfx = ppAccessGfxList[i];
343 const char *szPassword = pGfx->sPassword.getData();
344 if (!szPassword || !*szPassword || SIsModule(szList: Config.General.MissionAccess, szString: szPassword))
345 {
346 // ACCESS TO GFX GRANTED: draw it
347 rContainer.AddElement(pChild: new MapPic(pGfx->rcfOverlayPos, pGfx->fctOverlay));
348 }
349 }
350 // create buttons for scenarios
351 C4GUI::Button *pBtnFirst = nullptr;
352 for (i = 0; i < iScenCount; ++i)
353 {
354 Scenario *pScen = ppScenList[i];
355 if (pScen->pScenEntry && !pScen->pScenEntry->HasMissionAccess())
356 {
357 // no access to this scenario: Do not create a button at all; not even base image. The scenario is "invisible".
358 }
359 else
360 {
361 C4GUI::CallbackButtonEx<C4StartupScenSelDlg, C4GUI::FacetButton> *pBtn = new C4GUI::CallbackButtonEx<C4StartupScenSelDlg, C4GUI::FacetButton>
362 (pScen->fctBase, pScen->fctOverlay, pScen->rcfOverlayPos, 0, pMainDlg, &C4StartupScenSelDlg::OnButtonScenario);
363 ppScenList[i]->pBtn = pBtn;
364 if (pScen->pScenEntry)
365 pBtn->SetToolTip(LoadResStr(id: C4ResStrTableKey::IDS_MSG_MAP_STARTSCEN, args: pScen->pScenEntry->GetName().getData()).c_str());
366 if (pScen->sTitle.getLength() > 0)
367 {
368 pBtn->SetText(pScen->sTitle.getData());
369 pBtn->SetTextColors(dwClrInact: InvertRGBAAlpha(dwFromClr: pScen->dwTitleInactClr), dwClrAct: InvertRGBAAlpha(dwFromClr: pScen->dwTitleActClr));
370 pBtn->SetTextPos(iOffX: pScen->iTitleOffX, iOffY: pScen->iTitleOffY, byAlign: pScen->byTitleAlign);
371 CStdFont *pUseFont; float fFontZoom = 1.0f;
372 if (pScen->fTitleBookFont)
373 pUseFont = &(C4Startup::Get()->Graphics.GetBlackFontByHeight(iHgt: pScen->iTitleFontSize, pfZoom: &fFontZoom));
374 else
375 pUseFont = &(C4GUI::GetRes()->GetFontByHeight(iHgt: pScen->iTitleFontSize, pfZoom: &fFontZoom));
376 if (Inside<float>(ival: fFontZoom, lbound: 0.8f, rbound: 1.25f)) fFontZoom = 1.0f; // some tolerance for font zoom
377 pBtn->SetTextFont(pFont: pUseFont, fFontZoom);
378 }
379 rContainer.AddElement(pChild: pBtn);
380 if (!pBtnFirst) pBtnFirst = pBtn;
381 }
382 }
383 // create scenario info listbox
384 pSelectionInfoBox = new C4GUI::TextWindow(rcScenInfoArea,
385 C4StartupScenSel_TitlePictureWdt + 2 * C4StartupScenSel_TitleOverlayMargin, C4StartupScenSel_TitlePictureHgt + 2 * C4StartupScenSel_TitleOverlayMargin,
386 C4StartupScenSel_TitlePicturePadding, 100, 4096, nullptr, true, &C4Startup::Get()->Graphics.fctScenSelTitleOverlay, C4StartupScenSel_TitleOverlayMargin);
387 pSelectionInfoBox->SetDecoration(fDrawBG: false, fDrawFrame: false, pToGfx: &C4Startup::Get()->Graphics.sfctBookScroll, fAutoScroll: true);
388 rContainer.AddElement(pChild: pSelectionInfoBox);
389}
390
391bool C4MapFolderData::OnButtonScenario(C4GUI::Control *pEl)
392{
393 // get associated scenario entry
394 int i;
395 for (i = 0; i < iScenCount; ++i)
396 if (pEl == ppScenList[i]->pBtn)
397 break;
398 if (i == iScenCount) return false;
399 // select the associated entry
400 pSelectedEntry = ppScenList[i]->pScenEntry;
401 return ppScenList[i]->singleClick;
402}
403
404void C4MapFolderData::ResetSelection()
405{
406 pSelectedEntry = nullptr;
407}
408
409// Scenario list loader
410
411// Entry
412
413C4ScenarioListLoader::Entry::Entry(Folder *pParent) : pNext(nullptr), pParent(pParent), fBaseLoaded(false), fExLoaded(false)
414{
415 // ctor: Put into parent tree node
416 if (pParent)
417 {
418 pNext = pParent->pFirst;
419 pParent->pFirst = this;
420 }
421 iIconIndex = -1;
422 iDifficulty = 0;
423 iFolderIndex = 0;
424}
425
426C4ScenarioListLoader::Entry::~Entry()
427{
428 // dtor: unlink from parent list (MUST be in there)
429 if (pParent)
430 {
431 Entry **ppCheck = &(pParent->pFirst);
432 while (*ppCheck != this)
433 {
434 ppCheck = &(*ppCheck)->pNext;
435 }
436 *ppCheck = pNext;
437 }
438}
439
440bool C4ScenarioListLoader::Entry::Load(C4Group *pFromGrp, const StdStrBuf *psFilename, bool fLoadEx)
441{
442 // nothing to do if already loaded
443 if (fBaseLoaded && (fExLoaded || !fLoadEx)) return true;
444 C4Group Group;
445 // group specified: Load as child
446 if (pFromGrp)
447 {
448 assert(psFilename);
449 if (!Group.OpenAsChild(pMother: pFromGrp, szEntryName: psFilename->getData())) return false;
450 // set FN by complete entry name
451 this->sFilename.Take(Buf2: Group.GetFullName());
452 }
453 else
454 {
455 // set FN by complete entry name
456 if (psFilename) this->sFilename.Copy(Buf2: *psFilename);
457 // no parent group: Direct load from filename
458 if (!Group.Open(szGroupName: sFilename.getData())) return false;
459 }
460 // okay; load standard stuff from group
461 bool fNameLoaded = false, fIconLoaded = false;
462 if (fBaseLoaded)
463 {
464 fNameLoaded = fIconLoaded = true;
465 }
466 else
467 {
468 // Set default name as filename without extension
469 sName.Copy(pnData: GetFilename(path: sFilename.getData()));
470 char *szBuf = sName.GrabPointer();
471 RemoveExtension(szFileName: szBuf);
472 sName.Take(pnData: szBuf);
473
474 std::string converted{TextEncodingConverter.SystemToClonk(input: {sName.getData(), sName.getLength()})};
475 sName.Copy(pnData: converted.c_str(), iChars: converted.size());
476 // load entry specific stuff that's in the front of the group
477 if (!LoadCustomPre(rGrp&: Group))
478 return false;
479 // Load entry name
480 C4ComponentHost DefNames;
481 if (DefNames.LoadEx(szName: "Title", hGroup&: Group, C4CFN_Title, szLanguage: Config.General.LanguageEx))
482 if (DefNames.GetLanguageString(szLanguage: Config.General.LanguageEx, rTarget&: sName))
483 fNameLoaded = true;
484 DefNames.Close();
485 // load entry icon
486 if (Group.FindEntry(C4CFN_IconPNG) && fctIcon.Load(hGroup&: Group, C4CFN_IconPNG))
487 fIconLoaded = true;
488 else
489 {
490 C4FacetExSurface fctTemp;
491 if (Group.FindEntry(C4CFN_ScenarioIcon) && fctTemp.Load(hGroup&: Group, C4CFN_ScenarioIcon, iWdt: C4FCT_Full, iHgt: C4FCT_Full, fOwnPal: true))
492 {
493 // old style icon: Blit it on a pieace of paper
494 fctTemp.Surface->Lock();
495 for (int y = 0; y < fctTemp.Hgt; ++y)
496 for (int x = 0; x < fctTemp.Wdt; ++x)
497 {
498 uint32_t dwPix = fctTemp.Surface->GetPixDw(iX: x, iY: y, fApplyModulation: false);
499 // transparency has some tolerance...
500 if (Inside<uint8_t>(ival: dwPix & 0xff, lbound: 0xb8, rbound: 0xff))
501 if (Inside<uint8_t>(ival: (dwPix >> 0x08) & 0xff, lbound: 0x00, rbound: 0x0f))
502 if (Inside<uint8_t>(ival: (dwPix >> 0x10) & 0xff, lbound: 0xb8, rbound: 0xff))
503 fctTemp.Surface->SetPixDw(iX: x, iY: y, dwCol: 0xffffffff);
504 }
505 fctTemp.Surface->Unlock();
506 int iIconSize = C4Startup::Get()->Graphics.fctScenSelIcons.Hgt;
507 fctIcon.Create(iWdt: iIconSize, iHgt: iIconSize, iWdt2: C4FCT_Full, iHgt2: C4FCT_Full);
508 C4Startup::Get()->Graphics.fctScenSelIcons.GetPhase(iPhaseX: C4StartupScenSel_DefaultIcon_OldIconBG).Draw(cgo&: fctIcon);
509 fctTemp.Draw(sfcTarget: fctIcon.Surface, iX: (fctIcon.Wdt - fctTemp.Wdt) / 2, iY: (fctIcon.Hgt - fctTemp.Hgt) / 2);
510 fctTemp.Clear();
511 fIconLoaded = true;
512 }
513 }
514 // load any entryx-type-specific custom data (e.g. fallbacks for scenario title, and icon)
515 if (!LoadCustom(rGrp&: Group, fNameLoaded, fIconLoaded)) return false;
516 // store maker
517 sMaker.Copy(pnData: Group.GetMaker());
518 fBaseLoaded = true;
519 }
520 // load extended stuff: title picture
521 if (fLoadEx && !fExLoaded)
522 {
523 // load desc
524 C4ComponentHost DefDesc;
525 if (DefDesc.LoadEx(szName: "Desc", hGroup&: Group, C4CFN_ScenarioDesc, szLanguage: Config.General.LanguageEx))
526 {
527 C4RTFFile rtf;
528 rtf.Load(sContents: StdBuf::MakeRef(pData: DefDesc.GetData(), iSize: SLen(sptr: DefDesc.GetData())));
529 sDesc.Take(Buf2: rtf.GetPlainText());
530 }
531 DefDesc.Close();
532 // load title
533 if (!fctTitle.Load(hGroup&: Group, C4CFN_ScenarioTitlePNG, iWdt: C4FCT_Full, iHgt: C4FCT_Full, fOwnPal: false, fNoErrIfNotFound: true))
534 fctTitle.Load(hGroup&: Group, C4CFN_ScenarioTitle, iWdt: C4FCT_Full, iHgt: C4FCT_Full, fOwnPal: true, fNoErrIfNotFound: true);
535 fExLoaded = true;
536 // load author
537 if (Group.IsPacked())
538 {
539 const char *strSecAuthors = "RedWolf Design;Clonk History Project;GWE-Team"; // Now hardcoded...
540 if (SIsModule(szList: strSecAuthors, szString: Group.GetMaker()) && Group.LoadEntryString(C4CFN_Author, Buf&: sAuthor))
541 {
542 // OK; custom author by txt
543 }
544 else
545 // defeault author by group
546 sAuthor.Copy(pnData: Group.GetMaker());
547 }
548 else
549 {
550 // unpacked groups do not have an author
551 sAuthor.Clear();
552 }
553 // load version
554 Group.LoadEntryString(C4CFN_Version, Buf&: sVersion);
555 }
556 // done, success
557 return true;
558}
559
560// helper func: Recursive check whether a directory contains a .c4s or .c4f file
561bool DirContainsScenarios(const char *szDir)
562{
563 // create iterator on free store to avoid stack overflow with deeply recursed folders
564 DirectoryIterator *pIter = new DirectoryIterator(szDir);
565 const char *szChildFilename;
566 for (; szChildFilename = **pIter; ++*pIter)
567 {
568 // Ignore directory navigation entries and CVS folders
569 if (!*szChildFilename || *GetFilename(path: szChildFilename) == '.') continue;
570 if (SEqualNoCase(szStr1: GetFilename(path: szChildFilename), szStr2: "CVS")) continue;
571 if (WildcardMatch(C4CFN_ScenarioFiles, szFName2: szChildFilename) || WildcardMatch(C4CFN_FolderFiles, szFName2: szChildFilename)) break;
572 if (DirectoryExists(szFileName: szChildFilename))
573 if (DirContainsScenarios(szDir: szChildFilename))
574 break;
575 }
576 delete pIter;
577 // return true if loop was broken, in which case a matching entry was found
578 return !!szChildFilename;
579}
580
581C4ScenarioListLoader::Entry *C4ScenarioListLoader::Entry::CreateEntryForFile(const StdStrBuf &sFilename, Folder *pParent)
582{
583 // determine entry type by file type
584 const char *szFilename = sFilename.getData();
585 if (!szFilename || !*szFilename) return nullptr;
586 if (WildcardMatch(C4CFN_ScenarioFiles, szFName2: sFilename.getData())) return new Scenario(pParent);
587 if (WildcardMatch(C4CFN_FolderFiles, szFName2: sFilename.getData())) return new SubFolder(pParent);
588 // regular, open folder (C4Group-packed folders without extensions are not regarded, because they could contain anything!)
589 const char *szExt = GetExtension(fname: szFilename);
590 if ((!szExt || !*szExt) && DirectoryExists(szFileName: sFilename.getData()))
591 {
592 // open folders only if they contain a scenario or folder
593 if (DirContainsScenarios(szDir: szFilename))
594 return new RegularFolder(pParent);
595 }
596 // type not recognized
597 return nullptr;
598}
599
600bool C4ScenarioListLoader::Entry::RenameTo(const char *szNewName)
601{
602 // change name+filename
603 // some name sanity validation
604 if (!szNewName || !*szNewName) return false;
605 if (SEqual(szStr1: szNewName, szStr2: sName.getData())) return true;
606 char fn[_MAX_PATH + 1];
607 SCopy(szSource: szNewName, sTarget: fn, _MAX_PATH);
608 // generate new file name
609 MakeFilenameFromTitle(szTitle: fn);
610 if (!*fn) return false;
611 const char *szExt = GetDefaultExtension();
612 if (szExt) { SAppend(szSource: ".", szTarget: fn, _MAX_PATH); SAppend(szSource: szExt, szTarget: fn, _MAX_PATH); }
613 char fullfn[_MAX_PATH + 1];
614 SCopy(szSource: sFilename.getData(), sTarget: fullfn, _MAX_PATH);
615 char *fullfn_fn = GetFilename(path: fullfn);
616 SCopy(szSource: fn, sTarget: fullfn_fn, _MAX_PATH - (fullfn_fn - fullfn));
617 StdStrBuf strErr(LoadResStr(id: C4ResStrTableKey::IDS_FAIL_RENAME));
618 // check if a rename is due
619 if (!ItemIdentical(szFilename1: sFilename.getData(), szFilename2: fullfn))
620 {
621 // check for duplicate filename
622 if (ItemExists(szItemName: fullfn))
623 {
624 const std::string msg{LoadResStr(id: C4ResStrTableKey::IDS_ERR_FILEEXISTS, args&: fullfn)};
625 Game.pGUI->ShowMessageModal(szMessage: msg.c_str(), szCaption: strErr.getData(), dwButtons: C4GUI::MessageDialog::btnOK, icoIcon: C4GUI::Ico_Error);
626 return false;
627 }
628 // OK; then rename
629 if (!C4Group_MoveItem(szSource: sFilename.getData(), szTarget: fullfn, fNoSort: true))
630 {
631 const std::string msg{LoadResStr(id: C4ResStrTableKey::IDS_ERR_RENAMEFILE, args: sFilename.getData(), args&: fullfn)};
632 Game.pGUI->ShowMessageModal(szMessage: msg.c_str(), szCaption: strErr.getData(), dwButtons: C4GUI::MessageDialog::btnOK, icoIcon: C4GUI::Ico_Error);
633 return false;
634 }
635 sFilename.Copy(pnData: fullfn);
636 }
637 // update real name in group, if this is a group
638 if (C4Group_IsGroup(szFilename: fullfn))
639 {
640 C4Group Grp;
641 if (!Grp.Open(szGroupName: fullfn))
642 {
643 const std::string msg{LoadResStr(id: C4ResStrTableKey::IDS_ERR_OPENFILE, args: sFilename.getData(), args: Grp.GetError())};
644 Game.pGUI->ShowMessageModal(szMessage: msg.c_str(), szCaption: strErr.getData(), dwButtons: C4GUI::MessageDialog::btnOK, icoIcon: C4GUI::Ico_Error);
645 return false;
646 }
647 if (!Grp.Delete(C4CFN_Title))
648 {
649 const std::string msg{LoadResStr(id: C4ResStrTableKey::IDS_ERR_DELOLDTITLE, args: sFilename.getData(), args: Grp.GetError())};
650 Game.pGUI->ShowMessageModal(szMessage: msg.c_str(), szCaption: strErr.getData(), dwButtons: C4GUI::MessageDialog::btnOK, icoIcon: C4GUI::Ico_Error);
651 return false;
652 }
653 if (!SetTitleInGroup(rGrp&: Grp, szNewTitle: szNewName)) return false;
654 if (!Grp.Close())
655 {
656 const std::string msg{LoadResStr(id: C4ResStrTableKey::IDS_ERR_WRITENEWTITLE, args: sFilename.getData(), args: Grp.GetError())};
657 Game.pGUI->ShowMessageModal(szMessage: msg.c_str(), szCaption: strErr.getData(), dwButtons: C4GUI::MessageDialog::btnOK, icoIcon: C4GUI::Ico_Error);
658 return false;
659 }
660 }
661 // update title
662 sName.Copy(pnData: szNewName);
663 // done
664 return true;
665}
666
667bool C4ScenarioListLoader::Entry::SetTitleInGroup(C4Group &rGrp, const char *szNewTitle)
668{
669 // default for group files: Create a title text file and set the title in there
670 // no title needed if filename is sufficient - except for scenarios, where a Scenario.txt could overwrite the title
671 if (!IsScenario())
672 {
673 StdStrBuf sNameByFile; sNameByFile.Copy(pnData: GetFilename(path: sFilename.getData()));
674 char *szBuf = sNameByFile.GrabPointer();
675 RemoveExtension(szFileName: szBuf);
676 sNameByFile.Take(pnData: szBuf);
677 if (SEqual(szStr1: szNewTitle, szStr2: sNameByFile.getData())) return true;
678 }
679 // okay, make a title
680 StdStrBuf title{std::format(fmt: "{:2}:{}", args: +Config.General.Language, args&: szNewTitle).c_str()};
681 if (!rGrp.Add(C4CFN_WriteTitle, pBuffer&: title, fChild: false, fHoldBuffer: true))
682 {
683 const std::string msg{LoadResStr(id: C4ResStrTableKey::IDS_ERR_ERRORADDINGNEWTITLEFORFIL, args: sFilename.getData(), args: rGrp.GetError())};
684 Game.pGUI->ShowMessageModal(szMessage: msg.c_str(), szCaption: LoadResStr(id: C4ResStrTableKey::IDS_FAIL_RENAME), dwButtons: C4GUI::MessageDialog::btnOK, icoIcon: C4GUI::Ico_Error);
685 return false;
686 }
687 return true;
688}
689
690// Scenario
691
692bool C4ScenarioListLoader::Scenario::LoadCustomPre(C4Group &rGrp)
693{
694 // load scenario core first
695 StdStrBuf sFileContents;
696 if (!rGrp.LoadEntryString(C4CFN_ScenarioCore, Buf&: sFileContents)) return false;
697 if (!CompileFromBuf_LogWarn<StdCompilerINIRead>(TargetStruct: mkParAdapt(rObj&: C4S, rPar: false), SrcBuf: sFileContents, szName: (rGrp.GetFullName() + DirSep C4CFN_ScenarioCore).getData()))
698 return false;
699 return true;
700}
701
702bool C4ScenarioListLoader::Scenario::LoadCustom(C4Group &rGrp, bool fNameLoaded, bool fIconLoaded)
703{
704 // icon fallback: Standard scenario icon
705 if (!fIconLoaded)
706 {
707 iIconIndex = C4S.Head.Icon;
708 int32_t iIcon = C4S.Head.Icon;
709 if (!Inside<int32_t>(ival: iIcon, lbound: 0, rbound: C4StartupScenSel_IconCount - 1)) iIcon = C4StartupScenSel_DefaultIcon_Scenario;
710 fctIcon.Set(C4Startup::Get()->Graphics.fctScenSelIcons.GetSection(iSection: iIcon));
711 }
712 // scenario name fallback to core
713 if (!fNameLoaded)
714 sName.Copy(pnData: C4S.Head.Title);
715 // difficulty: Set only for regular rounds (not savegame or record) to avoid bogus sorting
716 if (!C4S.Head.SaveGame && !C4S.Head.Replay)
717 iDifficulty = C4S.Head.Difficulty;
718 else
719 iDifficulty = 0;
720
721 // minimum required player count
722 iMinPlrCount = C4S.GetMinPlayer();
723 return true;
724}
725
726bool C4ScenarioListLoader::Scenario::Start()
727{
728 // gogo!
729 if (!(C4StartupScenSelDlg::pInstance)) return false;
730 return (C4StartupScenSelDlg::pInstance)->StartScenario(pStartScen: this);
731}
732
733bool C4ScenarioListLoader::Scenario::CanOpen(StdStrBuf &sErrOut)
734{
735 // safety
736 C4StartupScenSelDlg *pDlg = C4StartupScenSelDlg::pInstance;
737 if (!pDlg) return false;
738 // check mission access
739 if (C4S.Head.MissionAccess[0] && !SIsModule(szList: Config.General.MissionAccess, szString: C4S.Head.MissionAccess))
740 {
741 sErrOut.Copy(pnData: LoadResStr(id: C4ResStrTableKey::IDS_PRC_NOMISSIONACCESS));
742 return false;
743 }
744 // replay
745 if (C4S.Head.Replay)
746 {
747 // replays can currently not be launched in network mode
748 if (pDlg->IsNetworkStart())
749 {
750 sErrOut.Copy(pnData: LoadResStr(id: C4ResStrTableKey::IDS_PRC_NONETREPLAY));
751 return false;
752 }
753 }
754 // regular game
755 else
756 {
757 // check player count
758 int32_t iPlrCount = SModuleCount(szList: Config.General.Participants);
759 int32_t iMaxPlrCount = C4S.Head.MaxPlayer;
760 if (C4S.Head.SaveGame)
761 {
762 // Some scenarios have adjusted MaxPlayerCount to 0 after starting to prevent future joins
763 // make sure it's possible to start the savegame anyway
764 iMaxPlrCount = std::max<int32_t>(a: iMinPlrCount, b: iMaxPlrCount);
765 }
766 // normal scenarios: At least one player except in network mode, where it is possible to wait for the additional players
767 // Melees need at least two
768 if ((iPlrCount < iMinPlrCount))
769 {
770 if (pDlg->IsNetworkStart())
771 {
772 // network game: Players may yet join in lobby
773 // only issue a warning for too few players (by setting the error but not returning false here)
774 sErrOut.Copy(pnData: LoadResStr(id: C4ResStrTableKey::IDS_MSG_TOOFEWPLAYERSNET, args: static_cast<int>(iMinPlrCount)).c_str());
775 }
776 else
777 {
778 // for regular games, this is a fatal no-start-cause
779 sErrOut.Copy(pnData: LoadResStr(id: C4ResStrTableKey::IDS_MSG_TOOFEWPLAYERS, args: static_cast<int>(iMinPlrCount)).c_str());
780 return false;
781 }
782 }
783 // scenarios (both normal and savegame) may also impose a maximum player restriction
784 if (iPlrCount > iMaxPlrCount)
785 {
786 sErrOut.Copy(pnData: LoadResStr(id: C4ResStrTableKey::IDS_MSG_TOOMANYPLAYERS, args: static_cast<int>(C4S.Head.MaxPlayer)).c_str());
787 return false;
788 }
789 }
790 // Okay, start!
791 return true;
792}
793
794StdStrBuf C4ScenarioListLoader::Scenario::GetOpenText()
795{
796 return StdStrBuf(LoadResStr(id: C4ResStrTableKey::IDS_BTN_STARTGAME));
797}
798
799StdStrBuf C4ScenarioListLoader::Scenario::GetOpenTooltip()
800{
801 return StdStrBuf(LoadResStr(id: C4ResStrTableKey::IDS_DLGTIP_SCENSELNEXT));
802}
803
804// Folder
805
806C4ScenarioListLoader::Folder::~Folder()
807{
808 delete pMapData;
809 ClearChildren();
810}
811
812bool C4ScenarioListLoader::Folder::Start()
813{
814 // open as subfolder
815 if (!C4StartupScenSelDlg::pInstance) return false;
816 return C4StartupScenSelDlg::pInstance->OpenFolder(pNewFolder: this);
817}
818
819int
820#ifdef _MSC_VER
821__cdecl
822#endif
823EntrySortFunc(const void *pEl1, const void *pEl2)
824{
825 C4ScenarioListLoader::Entry *pEntry1 = *static_cast<C4ScenarioListLoader::Entry * const *>(pEl1), *pEntry2 = *static_cast<C4ScenarioListLoader::Entry * const *>(pEl2);
826 // sort folders before scenarios
827 bool fS1, fS2;
828 if (!(fS1 = !pEntry1->GetIsFolder()) != !true != !(fS2 = !pEntry2->GetIsFolder())) return fS1 - fS2;
829 // sort by folder index (undefined index 0 goes to the end)
830 if (!Config.Startup.AlphabeticalSorting) if (pEntry1->GetFolderIndex() || pEntry2->GetFolderIndex())
831 {
832 if (!pEntry1->GetFolderIndex()) return +1;
833 if (!pEntry2->GetFolderIndex()) return -1;
834 int32_t iDiff = pEntry1->GetFolderIndex() - pEntry2->GetFolderIndex();
835 if (iDiff) return iDiff;
836 }
837 // sort by numbered standard scenario icons
838 if (Inside(ival: pEntry1->GetIconIndex(), lbound: 2, rbound: 11))
839 {
840 int32_t iDiff = pEntry1->GetIconIndex() - pEntry2->GetIconIndex();
841 if (iDiff) return iDiff;
842 }
843 // sort by difficulty (undefined difficulty goes to the end)
844 if (!Config.Startup.AlphabeticalSorting) if (pEntry1->GetDifficulty() || pEntry2->GetDifficulty())
845 {
846 if (!pEntry1->GetDifficulty()) return +1;
847 if (!pEntry2->GetDifficulty()) return -1;
848 int32_t iDiff = pEntry1->GetDifficulty() - pEntry2->GetDifficulty();
849 if (iDiff) return iDiff;
850 }
851 // otherwise, sort by name
852 return stricmp(s1: pEntry1->GetName().getData(), s2: pEntry2->GetName().getData());
853}
854
855uint32_t C4ScenarioListLoader::Folder::GetEntryCount() const
856{
857 uint32_t iCount = 0;
858 for (Entry *i = pFirst; i; i = i->pNext) ++iCount;
859 return iCount;
860}
861
862void C4ScenarioListLoader::Folder::Sort()
863{
864 // use C-Library-QSort on a buffer of entry pointers; then re-link list
865 if (!pFirst) return;
866 uint32_t iCount, i;
867 Entry **ppEntries = new Entry *[i = iCount = GetEntryCount()], **ppI, *pI = pFirst, **ppIThis;
868 for (ppI = ppEntries; i--; pI = pI->pNext) * ppI++ = pI;
869 qsort(base: ppEntries, nmemb: iCount, size: sizeof(Entry *), compar: &EntrySortFunc);
870 ppIThis = &pFirst;
871 for (ppI = ppEntries; iCount--; ppIThis = &((*ppIThis)->pNext)) * ppIThis = *ppI++;
872 *ppIThis = nullptr;
873 delete[] ppEntries;
874}
875
876void C4ScenarioListLoader::Folder::ClearChildren()
877{
878 // folder deletion: del all the tree non-recursively
879 Folder *pDelFolder = this, *pCheckFolder;
880 for (;;)
881 {
882 // delete all children as long as they are not folders
883 Entry *pChild;
884 while (pChild = pDelFolder->pFirst)
885 if (pCheckFolder = pChild->GetIsFolder())
886 // child entry if folder: Continue delete in there
887 pDelFolder = pCheckFolder;
888 else
889 // regular child entry: del it
890 // destructor of child will remove it from list
891 delete pChild;
892 // this emptied: Done!
893 if (pDelFolder == this) break;
894 // deepest child recursion reached: Travel up folders
895 pDelFolder = (pCheckFolder = pDelFolder)->pParent;
896 assert(pDelFolder);
897 delete pCheckFolder;
898 }
899}
900
901bool C4ScenarioListLoader::Folder::LoadContents(C4ScenarioListLoader *pLoader, C4Group *pFromGrp, const StdStrBuf *psFilename, bool fLoadEx, bool fReload)
902{
903 // contents already loaded?
904 if (fContentsLoaded && !fReload) return true;
905 // clear previous
906 delete pMapData; pMapData = nullptr;
907 // if filename is not given, assume it's been loaded in this entry
908 if (!psFilename) psFilename = &this->sFilename; else this->sFilename.Ref(Buf2: *psFilename);
909 // nothing loaded: Load now
910 if (!DoLoadContents(pLoader, pFromGrp, sFilename: *psFilename, fLoadEx)) return false;
911 // sort loaded stuff by name
912 Sort();
913 return true;
914}
915
916C4ScenarioListLoader::Entry *C4ScenarioListLoader::Folder::FindEntryByName(const char *szFilename) const
917{
918 // do a case-insensitive filename comparison
919 for (Entry *pEntry = pFirst; pEntry; pEntry = pEntry->GetNext())
920 if (SEqualNoCase(szStr1: szFilename, szStr2: GetFilename(path: pEntry->GetEntryFilename().getData())))
921 return pEntry;
922 // nothing found
923 return nullptr;
924}
925
926StdStrBuf C4ScenarioListLoader::Folder::GetOpenText()
927{
928 return StdStrBuf(LoadResStr(id: C4ResStrTableKey::IDS_BTN_OPEN));
929}
930
931StdStrBuf C4ScenarioListLoader::Folder::GetOpenTooltip()
932{
933 return StdStrBuf(LoadResStr(id: C4ResStrTableKey::IDS_DLGTIP_SCENSELNEXT));
934}
935
936bool C4ScenarioListLoader::Folder::LoadCustomPre(C4Group &rGrp)
937{
938 // load folder core if available
939 StdStrBuf sFileContents;
940 if (rGrp.LoadEntryString(C4CFN_FolderCore, Buf&: sFileContents))
941 if (!CompileFromBuf_LogWarn<StdCompilerINIRead>(TargetStruct&: C4F, SrcBuf: sFileContents, szName: (rGrp.GetFullName() + DirSep C4CFN_FolderCore).getData()))
942 return false;
943 return true;
944}
945
946// SubFolder
947
948bool C4ScenarioListLoader::SubFolder::LoadCustom(C4Group &rGrp, bool fNameLoaded, bool fIconLoaded)
949{
950 // default icon fallback
951 if (!fIconLoaded)
952 fctIcon.Set(C4Startup::Get()->Graphics.fctScenSelIcons.GetSection(iSection: C4StartupScenSel_DefaultIcon_Folder));
953 // folder index
954 iFolderIndex = C4F.Head.Index;
955 return true;
956}
957
958bool C4ScenarioListLoader::SubFolder::DoLoadContents(C4ScenarioListLoader *pLoader, C4Group *pFromGrp, const StdStrBuf &sFilename, bool fLoadEx)
959{
960 assert(pLoader);
961 // clear any previous
962 ClearChildren();
963 // group specified: Load as child
964 C4Group Group;
965 if (pFromGrp)
966 {
967 if (!Group.OpenAsChild(pMother: pFromGrp, szEntryName: sFilename.getData())) return false;
968 }
969 else
970 // no parent group: Direct load from filename
971 if (!Group.Open(szGroupName: sFilename.getData())) return false;
972 // get number of entries, to estimate progress
973 const char *szC4CFN_ScenarioFiles = C4CFN_ScenarioFiles; // assign values for constant comparison
974 const char *szSearchMask; int32_t iEntryCount = 0;
975 for (szSearchMask = szC4CFN_ScenarioFiles; szSearchMask;)
976 {
977 Group.ResetSearch();
978 while (Group.FindNextEntry(szWildCard: szSearchMask)) ++iEntryCount;
979 // next search mask
980 if (szSearchMask == szC4CFN_ScenarioFiles)
981 szSearchMask = C4CFN_FolderFiles;
982 else
983 szSearchMask = nullptr;
984 }
985 // initial progress estimate
986 if (!pLoader->DoProcessCallback(iProgress: 0, iMaxProgress: iEntryCount)) return false;
987 // iterate through group contents
988 char ChildFilename[_MAX_FNAME + 1]; StdStrBuf sChildFilename; int32_t iLoadCount = 0;
989 for (szSearchMask = szC4CFN_ScenarioFiles; szSearchMask;)
990 {
991 Group.ResetSearch();
992 while (Group.FindNextEntry(szWildCard: szSearchMask, sFileName: ChildFilename))
993 {
994 sChildFilename.Ref(pnData: ChildFilename);
995 // okay; create this item
996 Entry *pNewEntry = Entry::CreateEntryForFile(sFilename: sChildFilename, pParent: this);
997 if (pNewEntry)
998 {
999 // ...and load it
1000 if (!pNewEntry->Load(pFromGrp: &Group, psFilename: &sChildFilename, fLoadEx))
1001 {
1002 DebugLog(level: spdlog::level::err, fmt: "Error loading entry \"{}\" in SubFolder \"{}\"!", args: sChildFilename.getData(), args: Group.GetFullName().getData());
1003 delete pNewEntry;
1004 }
1005 }
1006 // mark progress
1007 if (!pLoader->DoProcessCallback(iProgress: ++iLoadCount, iMaxProgress: iEntryCount)) return false;
1008 }
1009 // next search mask
1010 if (szSearchMask == szC4CFN_ScenarioFiles)
1011 szSearchMask = C4CFN_FolderFiles;
1012 else
1013 szSearchMask = nullptr;
1014 }
1015 // load map folder data
1016 if (Config.Graphics.ShowFolderMaps && Group.FindEntry(C4CFN_MapFolderData))
1017 {
1018 pMapData = new C4MapFolderData();
1019 if (!pMapData->Load(hGroup&: Group, pScenLoaderFolder: this))
1020 {
1021 // load error :(
1022 delete pMapData;
1023 pMapData = nullptr;
1024 }
1025 }
1026 // done, success
1027 fContentsLoaded = true;
1028 return true;
1029}
1030
1031// RegularFolder
1032
1033bool C4ScenarioListLoader::RegularFolder::LoadCustom(C4Group &rGrp, bool fNameLoaded, bool fIconLoaded)
1034{
1035 // default icon fallback
1036 if (!fIconLoaded)
1037 fctIcon.Set(C4Startup::Get()->Graphics.fctScenSelIcons.GetSection(iSection: C4StartupScenSel_DefaultIcon_WinFolder));
1038 // folder index
1039 iFolderIndex = C4F.Head.Index;
1040 return true;
1041}
1042
1043bool C4ScenarioListLoader::RegularFolder::DoLoadContents(C4ScenarioListLoader *pLoader, C4Group *pFromGrp, const StdStrBuf &sFilename, bool fLoadEx)
1044{
1045 // clear any previous
1046 ClearChildren();
1047 // regular folders must exist and not be within group!
1048 assert(!pFromGrp);
1049 if (!DirectoryExists(szFileName: sFilename.getData())) return false;
1050 DirectoryIterator DirIter(sFilename.getData());
1051 const char *szChildFilename; StdStrBuf sChildFilename;
1052 // get number of entries, to estimate progress
1053 int32_t iCountLoaded = 0, iCountTotal = 0;
1054 for (; szChildFilename = *DirIter; ++DirIter)
1055 {
1056 if (!*szChildFilename || *GetFilename(path: szChildFilename) == '.') continue;
1057 ++iCountTotal;
1058 }
1059 // initial progress estimate
1060 if (!pLoader->DoProcessCallback(iProgress: iCountLoaded, iMaxProgress: iCountTotal)) return false;
1061 // do actual loading of files
1062 for (DirIter.Reset(dirname: sFilename.getData()); szChildFilename = *DirIter; ++DirIter)
1063 {
1064 // Ignore directory navigation entries and CVS folders
1065 if (!*szChildFilename || *GetFilename(path: szChildFilename) == '.') continue;
1066 if (SEqualNoCase(szStr1: GetFilename(path: szChildFilename), szStr2: "CVS")) continue;
1067 sChildFilename.Ref(pnData: szChildFilename);
1068 // filename okay; create this item
1069 Entry *pNewEntry = Entry::CreateEntryForFile(sFilename: sChildFilename, pParent: this);
1070 if (pNewEntry)
1071 {
1072 // ...and load it
1073 if (!pNewEntry->Load(pFromGrp: nullptr, psFilename: &sChildFilename, fLoadEx))
1074 {
1075 DebugLog(level: spdlog::level::err, fmt: "Error loading entry \"{}\" in Folder \"{}\"!", args: sChildFilename.getData(), args: sFilename.getData());
1076 delete pNewEntry;
1077 }
1078 }
1079 // progress callback
1080 if (!pLoader->DoProcessCallback(iProgress: ++iCountLoaded, iMaxProgress: iCountTotal)) return false;
1081 }
1082 // done, success
1083 fContentsLoaded = true;
1084 return true;
1085}
1086
1087// C4ScenarioListLoader
1088
1089C4ScenarioListLoader::C4ScenarioListLoader() : pRootFolder(nullptr), pCurrFolder(nullptr),
1090 iLoading(0), iProgress(0), iMaxProgress(0), fAbortThis(false), fAbortPrevious(false) {}
1091
1092C4ScenarioListLoader::~C4ScenarioListLoader()
1093{
1094 delete pRootFolder;
1095}
1096
1097bool C4ScenarioListLoader::BeginActivity(bool fAbortPrevious)
1098{
1099 // if previous activities were running, stop them first if desired
1100 if (iLoading && fAbortPrevious)
1101 this->fAbortPrevious = true;
1102 // mark this activity
1103 ++iLoading;
1104 // progress of activity not yet decided
1105 iProgress = iMaxProgress = 0;
1106 // okay; start activity
1107 return true;
1108}
1109
1110void C4ScenarioListLoader::EndActivity()
1111{
1112 assert(iLoading);
1113 if (!--iLoading)
1114 {
1115 // last activity done: Reset any flags
1116 fAbortThis = false;
1117 fAbortPrevious = false;
1118 iProgress = iMaxProgress = 0;
1119 }
1120 else
1121 {
1122 // child activity done: Transfer abort flag for next activity
1123 fAbortThis = fAbortPrevious;
1124 }
1125}
1126
1127bool C4ScenarioListLoader::DoProcessCallback(int32_t iProgress, int32_t iMaxProgress)
1128{
1129 this->iProgress = iProgress;
1130 this->iMaxProgress = iMaxProgress;
1131 // callback to dialog
1132 if (C4StartupScenSelDlg::pInstance) C4StartupScenSelDlg::pInstance->ProcessCallback();
1133 auto checkTimer = false;
1134 const auto now = timeGetTime();
1135 // limit to real 10 FPS, as it may unnecessarily slow down loading a lot otherwise
1136 if (lastCheckTimer == 0 || now - lastCheckTimer > 100)
1137 {
1138 checkTimer = true;
1139 lastCheckTimer = now;
1140 }
1141 // process callback - abort at a few ugly circumstances...
1142 if (Application.HandleMessage(iTimeout: 0, fCheckTimer: checkTimer) == HR_Failure // WM_QUIT message?
1143 || !C4StartupScenSelDlg::pInstance // host dialog removed?
1144 || !C4StartupScenSelDlg::pInstance->IsShown() // host dialog closed?
1145 ) return false;
1146 // and also abort if flagged
1147 return !fAbortThis;
1148}
1149
1150bool C4ScenarioListLoader::Load(const StdStrBuf &sRootFolder)
1151{
1152 // (unthreaded) loading of all entries in root folder
1153 if (!BeginActivity(fAbortPrevious: true)) return false;
1154 delete pRootFolder; pRootFolder = nullptr;
1155 pCurrFolder = pRootFolder = new RegularFolder(nullptr);
1156 bool fSuccess = pRootFolder->LoadContents(pLoader: this, pFromGrp: nullptr, psFilename: &sRootFolder, fLoadEx: false, fReload: false);
1157 EndActivity();
1158 return fSuccess;
1159}
1160
1161bool C4ScenarioListLoader::Load(Folder *pSpecifiedFolder, bool fReload)
1162{
1163 // call safety
1164 if (!pRootFolder || !pSpecifiedFolder) return false;
1165 // set new current and load it
1166 if (!BeginActivity(fAbortPrevious: true)) return false;
1167 pCurrFolder = pSpecifiedFolder;
1168 bool fSuccess = pCurrFolder->LoadContents(pLoader: this, pFromGrp: nullptr, psFilename: nullptr, fLoadEx: false, fReload);
1169 EndActivity();
1170 return fSuccess;
1171}
1172
1173bool C4ScenarioListLoader::LoadExtended(Entry *pEntry)
1174{
1175 // call safety
1176 if (!pRootFolder || !pEntry) return false;
1177 // load info of selection
1178 if (!BeginActivity(fAbortPrevious: false)) return false;
1179 bool fSuccess = pEntry->Load(pFromGrp: nullptr, psFilename: nullptr, fLoadEx: true);
1180 EndActivity();
1181 return fSuccess;
1182}
1183
1184bool C4ScenarioListLoader::FolderBack()
1185{
1186 // call safety
1187 if (!pRootFolder || !pCurrFolder) return false;
1188 // already in root: Can't go up
1189 if (pCurrFolder == pRootFolder) return false;
1190 // otherwise, up one level
1191 return Load(pSpecifiedFolder: pCurrFolder->GetParent(), fReload: false);
1192}
1193
1194bool C4ScenarioListLoader::ReloadCurrent()
1195{
1196 // call safety
1197 if (!pRootFolder || !pCurrFolder) return false;
1198 // reload current
1199 return Load(pSpecifiedFolder: pCurrFolder, fReload: true);
1200}
1201
1202// Scenario selection GUI
1203
1204// font clrs
1205const uint32_t ClrScenarioItem = 0xff000000,
1206 ClrScenarioItemXtra = 0x7f000000,
1207 ClrScenarioItemDisabled = 0x7f000000;
1208
1209// C4StartupScenSelDlg::ScenListItem
1210C4StartupScenSelDlg::ScenListItem::ScenListItem(C4GUI::ListBox *pForListBox, C4ScenarioListLoader::Entry *pForEntry, C4GUI::Element *pInsertBeforeElement)
1211 : pIcon(nullptr), pNameLabel(nullptr), pScenListEntry(pForEntry)
1212{
1213 assert(pScenListEntry);
1214 CStdFont &rUseFont = C4Startup::Get()->Graphics.BookFont;
1215 StdStrBuf sIgnore;
1216 bool fEnabled = pScenListEntry->CanOpen(sError&: sIgnore);
1217 // calc height
1218 int32_t iHeight = rUseFont.GetLineHeight() + 2 * IconLabelSpacing;
1219 // create subcomponents
1220 pIcon = new C4GUI::Picture(C4Rect(0, 0, iHeight, iHeight), true);
1221 pIcon->SetFacet(pScenListEntry->GetIconFacet());
1222 StdStrBuf name = pScenListEntry->GetName();
1223 CMarkup::StripMarkup(sText: &name);
1224 pNameLabel = new C4GUI::Label(name.getData(), iHeight + IconLabelSpacing, IconLabelSpacing, ALeft, fEnabled ? ClrScenarioItem : ClrScenarioItemDisabled, &rUseFont, false, false);
1225 // calc own bounds - use icon bounds only, because only the height is used when the item is added
1226 SetBounds(pIcon->GetBounds());
1227 // add components
1228 AddElement(pChild: pIcon); AddElement(pChild: pNameLabel);
1229 // tooltip by name, so long names can be read via tooltip
1230 SetToolTip(pScenListEntry->GetName().getData());
1231 // add to listbox (will get resized horizontally and moved) - zero indent; no tree structure in this dialog
1232 pForListBox->InsertElement(pChild: this, pInsertBefore: pInsertBeforeElement, iIndent: 0);
1233 // update name label width to reflect new horizontal size
1234 // name label width must be set so rename edit will take its size
1235 pNameLabel->SetAutosize(false);
1236 C4Rect rcNLB = pNameLabel->GetBounds(); rcNLB.Wdt = GetClientRect().Wdt - rcNLB.x - IconLabelSpacing;
1237 pNameLabel->SetBounds(rcNLB);
1238}
1239
1240void C4StartupScenSelDlg::ScenListItem::UpdateOwnPos()
1241{
1242 // parent for client rect
1243 typedef C4GUI::Window ParentClass;
1244 ParentClass::UpdateOwnPos();
1245 // reposition items
1246 C4GUI::ComponentAligner caBounds(GetContainedClientRect(), IconLabelSpacing, IconLabelSpacing);
1247 // nothing to reposition for now...
1248}
1249
1250void C4StartupScenSelDlg::ScenListItem::MouseInput(C4GUI::CMouse &rMouse, int32_t iButton, int32_t iX, int32_t iY, uint32_t dwKeyParam)
1251{
1252 // inherited processing
1253 typedef C4GUI::Window BaseClass;
1254 BaseClass::MouseInput(rMouse, iButton, iX, iY, dwKeyParam);
1255}
1256
1257bool C4StartupScenSelDlg::ScenListItem::CheckNameHotkey(const char *c)
1258{
1259 // return whether this item can be selected by entering given char:
1260 // first char of name must match
1261 // FIXME: make unicode-ready
1262 if (!pScenListEntry) return false;
1263 const char *szName = pScenListEntry->GetName().getData();
1264 return szName && (toupper(c: *szName) == toupper(c: c[0]));
1265}
1266
1267bool C4StartupScenSelDlg::ScenListItem::KeyRename()
1268{
1269 // rename this entry
1270 C4StartupScenSelDlg::pInstance->StartRenaming(pNewRenameEdit: new C4GUI::CallbackRenameEdit<C4StartupScenSelDlg::ScenListItem, RenameParams>(pNameLabel, this, RenameParams(), &C4StartupScenSelDlg::ScenListItem::DoRenaming, &C4StartupScenSelDlg::ScenListItem::AbortRenaming));
1271 return true;
1272}
1273
1274void C4StartupScenSelDlg::ScenListItem::AbortRenaming(RenameParams par)
1275{
1276 // no renaming
1277 C4StartupScenSelDlg::pInstance->SetRenamingDone();
1278}
1279
1280C4GUI::RenameResult C4StartupScenSelDlg::ScenListItem::DoRenaming(RenameParams par, const char *szNewName)
1281{
1282 // check validity for new name
1283 if (!GetEntry()->RenameTo(szNewName)) return C4GUI::RR_Invalid;
1284 // rename label
1285 pNameLabel->SetText(szText: GetEntry()->GetName().getData());
1286 // main dlg update
1287 C4StartupScenSelDlg::pInstance->SetRenamingDone();
1288 C4StartupScenSelDlg::pInstance->ResortFolder();
1289 C4StartupScenSelDlg::pInstance->UpdateSelection();
1290 C4StartupScenSelDlg::pInstance->FocusScenList();
1291 // done; rename accepted and control deleted by ResortFolder
1292 return C4GUI::RR_Deleted;
1293}
1294
1295// C4StartupScenSelDlg
1296
1297C4StartupScenSelDlg::C4StartupScenSelDlg(bool fNetwork) : C4StartupDlg(LoadResStrNoAmpChoice(condition: fNetwork, ifTrue: C4ResStrTableKey::IDS_DLG_NETSTART, ifFalse: C4ResStrTableKey::IDS_DLG_STARTGAME).c_str()), pScenLoader(nullptr), fIsInitialLoading(false), fStartNetworkGame(fNetwork), pMapData(nullptr), pRenameEdit(nullptr), pfctBackground(nullptr), btnAllowUserChange{nullptr}
1298{
1299 // assign singleton
1300 pInstance = this;
1301
1302 // screen calculations
1303 UpdateSize();
1304 int32_t iButtonWidth, iCaptionFontHgt;
1305 int iButtonHeight = C4GUI_ButtonHgt;
1306 int iBookPageWidth;
1307 int iExtraHPadding = rcBounds.Wdt >= 700 ? rcBounds.Wdt / 50 : 0;
1308 int iExtraVPadding = rcBounds.Hgt >= 540 ? rcBounds.Hgt / 20 : 0;
1309 C4GUI::GetRes()->CaptionFont.GetTextExtent(szText: "<< BACK", rsx&: iButtonWidth, rsy&: iCaptionFontHgt, fCheckMarkup: true);
1310 iButtonWidth *= 3;
1311 C4GUI::ComponentAligner caMain(GetClientRect(), 0, 0, true);
1312 C4GUI::ComponentAligner caButtonArea(caMain.GetFromBottom(iHgt: caMain.GetHeight() / 8), rcBounds.Wdt / (rcBounds.Wdt >= 700 ? 128 : 256), 0);
1313 C4Rect rcMap = caMain.GetCentered(iWdt: caMain.GetWidth(), iHgt: caMain.GetHeight());
1314 int iYOversize = caMain.GetHeight() / 10; // overlap of map to top
1315 rcMap.y -= iYOversize; rcMap.Hgt += iYOversize;
1316 C4GUI::ComponentAligner caMap(rcMap, 0, 0, true);
1317 caMap.ExpandTop(iByHgt: -iYOversize);
1318 C4GUI::ComponentAligner caBook(caMap.GetCentered(iWdt: caMap.GetWidth() * 11 / 12 - 4 * iExtraHPadding, iHgt: caMap.GetHeight()), rcBounds.Wdt / 30, iExtraVPadding, false);
1319 C4GUI::ComponentAligner caBookLeft(caBook.GetFromLeft(iWdt: iBookPageWidth = caBook.GetWidth() * 4 / 9 + 4 - iExtraHPadding * 2), 0, 5);
1320
1321 // tabular for different scenario selection designs
1322 pScenSelStyleTabular = new C4GUI::Tabular(rcMap, C4GUI::Tabular::tbNone);
1323 pScenSelStyleTabular->SetSheetMargin(0);
1324 pScenSelStyleTabular->SetDrawDecoration(false);
1325 AddElement(pChild: pScenSelStyleTabular);
1326 C4GUI::Tabular::Sheet *pSheetBook = pScenSelStyleTabular->AddSheet(szTitle: nullptr);
1327 // map sheet; later queried via GetSheet(ShowStyle_Map)
1328 pScenSelStyleTabular->AddSheet(szTitle: nullptr);
1329
1330 // scenario selection list
1331 CStdFont &rScenSelCaptionFont = C4Startup::Get()->Graphics.BookFontTitle;
1332 pScenSelCaption = new C4GUI::Label("", caBookLeft.GetFromTop(iHgt: rScenSelCaptionFont.GetLineHeight()), ACenter, ClrScenarioItem, &rScenSelCaptionFont, false);
1333 pSheetBook->AddElement(pChild: pScenSelCaption);
1334 pScenSelCaption->SetToolTip(LoadResStr(id: C4ResStrTableKey::IDS_DLGTIP_SELECTSCENARIO));
1335
1336 // search bar
1337 const char *labelText = LoadResStr(id: C4ResStrTableKey::IDS_DLG_SEARCH);
1338 int32_t width = 100, height;
1339 C4GUI::GetRes()->TextFont.GetTextExtent(szText: labelText, rsx&: width, rsy&: height, fCheckMarkup: true);
1340 C4GUI::ComponentAligner caSearchBar(caBookLeft.GetFromBottom(iHgt: height), 0, 0);
1341 auto *searchLabel = new C4GUI::WoodenLabel(labelText, caSearchBar.GetFromLeft(iWdt: width + 10), C4GUI_Caption2FontClr, &C4GUI::GetRes()->TextFont);
1342 searchLabel->SetToolTip(LoadResStr(id: C4ResStrTableKey::IDS_DLGTIP_SEARCHLIST));
1343 pSheetBook->AddElement(pChild: searchLabel);
1344
1345 searchBar = new C4GUI::CallbackEdit<C4StartupScenSelDlg>(caSearchBar.GetAll(), this, &C4StartupScenSelDlg::OnSearchBarEnter);
1346 searchBar->SetToolTip(LoadResStr(id: C4ResStrTableKey::IDS_DLGTIP_SEARCHLIST));
1347 pSheetBook->AddElement(pChild: searchBar);
1348
1349 // scenario selection list box
1350 pScenSelList = new C4GUI::ListBox(caBookLeft.GetAll());
1351 pScenSelList->SetToolTip(LoadResStr(id: C4ResStrTableKey::IDS_DLGTIP_SELECTSCENARIO));
1352 pScenSelList->SetDecoration(fDrawBG: false, pToGfx: &C4Startup::Get()->Graphics.sfctBookScroll, fAutoScroll: true);
1353 pSheetBook->AddElement(pChild: pScenSelList);
1354 pScenSelList->SetSelectionChangeCallbackFn(new C4GUI::CallbackHandler<C4StartupScenSelDlg>(this, &C4StartupScenSelDlg::OnSelChange));
1355 pScenSelList->SetSelectionDblClickFn(new C4GUI::CallbackHandler<C4StartupScenSelDlg>(this, &C4StartupScenSelDlg::OnSelDblClick));
1356 // scenario selection list progress label
1357 pScenSelProgressLabel = new C4GUI::Label("", pScenSelList->GetBounds().GetMiddleX(), pScenSelList->GetBounds().GetMiddleX() - iCaptionFontHgt / 2, ACenter, ClrScenarioItem, &(C4Startup::Get()->Graphics.BookFontCapt), false);
1358 pSheetBook->AddElement(pChild: pScenSelProgressLabel);
1359
1360 // right side of book: Displaying current selection
1361 pSelectionInfo = new C4GUI::TextWindow(caBook.GetFromRight(iWdt: iBookPageWidth), C4StartupScenSel_TitlePictureWdt + 2 * C4StartupScenSel_TitleOverlayMargin, C4StartupScenSel_TitlePictureHgt + 2 * C4StartupScenSel_TitleOverlayMargin,
1362 C4StartupScenSel_TitlePicturePadding, 100, 4096, nullptr, true, &C4Startup::Get()->Graphics.fctScenSelTitleOverlay, C4StartupScenSel_TitleOverlayMargin);
1363 pSelectionInfo->SetDecoration(fDrawBG: false, fDrawFrame: false, pToGfx: &C4Startup::Get()->Graphics.sfctBookScroll, fAutoScroll: true);
1364 pSheetBook->AddElement(pChild: pSelectionInfo);
1365
1366 // back button
1367 C4GUI::CallbackButton<C4StartupScenSelDlg> *btn;
1368 AddElement(pChild: btn = new C4GUI::CallbackButton<C4StartupScenSelDlg>(LoadResStr(id: C4ResStrTableKey::IDS_BTN_BACK), caButtonArea.GetFromLeft(iWdt: iButtonWidth, iHgt: iButtonHeight), &C4StartupScenSelDlg::OnBackBtn));
1369 btn->SetToolTip(LoadResStr(id: C4ResStrTableKey::IDS_DLGTIP_BACKMAIN));
1370 AddElement(pChild: btn);
1371 // next button
1372 pOpenBtn = new C4GUI::CallbackButton<C4StartupScenSelDlg>(LoadResStr(id: C4ResStrTableKey::IDS_BTN_OPEN), caButtonArea.GetFromRight(iWdt: iButtonWidth, iHgt: iButtonHeight), &C4StartupScenSelDlg::OnNextBtn);
1373 pOpenBtn->SetToolTip(LoadResStr(id: C4ResStrTableKey::IDS_DLGTIP_SCENSELNEXT));
1374
1375 // allow user change button
1376 AddElement(pChild: btnAllowUserChange = new C4GUI::CheckBox(caButtonArea.GetFromRight(iWdt: iButtonWidth, iHgt: iButtonHeight), LoadResStr(id: C4ResStrTableKey::IDS_DLG_ALLOWUSERCHANGE), false));
1377
1378 // game options boxes
1379 pGameOptionButtons = new C4GameOptionButtons(caButtonArea.GetAll(), fNetwork, true, false);
1380 AddElement(pChild: pGameOptionButtons);
1381 // next button adding
1382 AddElement(pChild: pOpenBtn);
1383
1384 // dlg starts with focus on listbox
1385 SetFocus(pCtrl: pScenSelList, fByMouse: false);
1386
1387 // key bindings
1388 keyBack.reset(p: new C4KeyBinding(C4KeyCodeEx(K_LEFT), "StartupScenSelFolderUp", KEYSCOPE_Gui,
1389 new C4GUI::DlgKeyCB<C4StartupScenSelDlg>(*this, &C4StartupScenSelDlg::KeyBack), C4CustomKey::PRIO_CtrlOverride));
1390 keyRefresh.reset(p: new C4KeyBinding(C4KeyCodeEx(K_F5), "StartupScenSelReload", KEYSCOPE_Gui,
1391 new C4GUI::DlgKeyCB<C4StartupScenSelDlg>(*this, &C4StartupScenSelDlg::KeyRefresh), C4CustomKey::PRIO_CtrlOverride));
1392 keyForward.reset(p: new C4KeyBinding(C4KeyCodeEx(K_RIGHT), "StartupScenSelNext", KEYSCOPE_Gui,
1393 new C4GUI::DlgKeyCB<C4StartupScenSelDlg>(*this, &C4StartupScenSelDlg::KeyForward), C4CustomKey::PRIO_CtrlOverride));
1394 keyRename.reset(p: new C4KeyBinding(C4KeyCodeEx(K_F2), "StartupScenSelRename", KEYSCOPE_Gui,
1395 new C4GUI::ControlKeyDlgCB<C4StartupScenSelDlg>(pScenSelList, *this, &C4StartupScenSelDlg::KeyRename), C4CustomKey::PRIO_CtrlOverride));
1396 keyDelete.reset(p: new C4KeyBinding(C4KeyCodeEx(K_DELETE), "StartupScenSelDelete", KEYSCOPE_Gui,
1397 new C4GUI::ControlKeyDlgCB<C4StartupScenSelDlg>(pScenSelList, *this, &C4StartupScenSelDlg::KeyDelete), C4CustomKey::PRIO_CtrlOverride));
1398 keyCheat.reset(p: new C4KeyBinding(C4KeyCodeEx(KEY_M, KEYS_Alt), "StartupScenSelCheat", KEYSCOPE_Gui,
1399 new C4GUI::ControlKeyDlgCB<C4StartupScenSelDlg>(pScenSelList, *this, &C4StartupScenSelDlg::KeyCheat), C4CustomKey::PRIO_CtrlOverride));
1400 keySearch.reset(p: new C4KeyBinding(C4KeyCodeEx(KEY_F, KEYS_Control), "StartupScenSelSearch", KEYSCOPE_Gui,
1401 new C4GUI::ControlKeyDlgCB<C4StartupScenSelDlg>(pScenSelList, *this, &C4StartupScenSelDlg::KeySearch), C4CustomKey::PRIO_CtrlOverride));
1402 keyEscape.reset(p: new C4KeyBinding(C4KeyCodeEx(K_ESCAPE), "StartupScenSelEscape", KEYSCOPE_Gui,
1403 new C4GUI::ControlKeyDlgCB<C4StartupScenSelDlg>(pScenSelList, *this, &C4StartupScenSelDlg::KeyEscape), C4CustomKey::PRIO_CtrlOverride));
1404}
1405
1406C4StartupScenSelDlg::~C4StartupScenSelDlg()
1407{
1408 delete pScenLoader;
1409 if (this == pInstance) pInstance = nullptr;
1410}
1411
1412void C4StartupScenSelDlg::DrawElement(C4FacetEx &cgo)
1413{
1414 // draw background
1415 if (pfctBackground)
1416 DrawBackground(cgo, rFromFct&: *pfctBackground);
1417 else
1418 DrawBackground(cgo, rFromFct&: C4Startup::Get()->Graphics.fctScenSelBG);
1419}
1420
1421void C4StartupScenSelDlg::HideTitle(bool hide)
1422{
1423 if (hide == !pFullscreenTitle)
1424 {
1425 return;
1426 }
1427
1428 FullscreenDialog::SetTitle(hide ? "" : LoadResStrNoAmpChoice(condition: fStartNetworkGame, ifTrue: C4ResStrTableKey::IDS_DLG_NETSTART, ifFalse: C4ResStrTableKey::IDS_DLG_STARTGAME).c_str());
1429}
1430
1431void C4StartupScenSelDlg::OnShown()
1432{
1433 C4StartupDlg::OnShown();
1434 // init file list
1435 fIsInitialLoading = true;
1436 if (!pScenLoader) pScenLoader = new C4ScenarioListLoader();
1437 pScenLoader->Load(sRootFolder: StdStrBuf(Config.General.ExePath));
1438 UpdateList();
1439 UpdateSelection();
1440 fIsInitialLoading = false;
1441 // network activation by dialog type
1442 Game.NetworkActive = fStartNetworkGame;
1443}
1444
1445void C4StartupScenSelDlg::OnClosed(bool fOK)
1446{
1447 AbortRenaming();
1448 // clear laoded scenarios
1449 if (pScenLoader)
1450 {
1451 delete pScenLoader;
1452 pScenLoader = nullptr;
1453 UpdateList(); // must clear scenario list, because it points to deleted stuff
1454 UpdateSelection(); // must clear picture facet of selection!
1455 }
1456 // dlg abort: return to main screen
1457 if (!fOK)
1458 {
1459 // clear settings: Password
1460 Game.Network.SetPassword(nullptr);
1461 C4Startup::Get()->SwitchDialog(eToDlg: C4Startup::SDID_Back);
1462 }
1463}
1464
1465void C4StartupScenSelDlg::UpdateUseCrewBtn()
1466{
1467 C4ScenarioListLoader::Entry *pSel = GetSelectedEntry();
1468 C4SForceFairCrew eOpt = pSel ? pSel->GetFairCrewAllowed() : C4SFairCrew_Free;
1469 pGameOptionButtons->SetForceFairCrewState(eOpt);
1470}
1471
1472void C4StartupScenSelDlg::UpdateList()
1473{
1474 AbortRenaming();
1475 // default: Show book (also for loading screen)
1476 pMapData = nullptr;
1477 pScenSelStyleTabular->SelectSheet(iIndex: ShowStyle_Book, fByUser: false);
1478 // and delete any stuff from map selection
1479 C4GUI::Tabular::Sheet *pMapSheet = pScenSelStyleTabular->GetSheet(iIndex: ShowStyle_Map);
1480 while (pMapSheet->GetFirst()) delete pMapSheet->GetFirst();
1481 pfctBackground = nullptr;
1482 // for now, all the list is loaded at once anyway
1483 // so just clear and add all loaded items
1484 // remember old selection
1485 C4ScenarioListLoader::Entry *pOldSelection = GetSelectedEntry();
1486 C4GUI::Element *pEl;
1487 while (pEl = pScenSelList->GetFirst()) delete pEl;
1488 pScenSelCaption->SetText(szText: "");
1489 // scen loader still busy: Nothing to add
1490 if (!pScenLoader) return;
1491 if (pScenLoader->IsLoading())
1492 {
1493 const std::string progressText{LoadResStr(id: C4ResStrTableKey::IDS_MSG_SCENARIODESC_LOADING, args: static_cast<int32_t>(pScenLoader->GetProgressPercent()))};
1494 pScenSelProgressLabel->SetText(szText: progressText.c_str());
1495 pScenSelProgressLabel->SetVisibility(true);
1496 return;
1497 }
1498 pScenSelProgressLabel->SetVisibility(false);
1499 // is this a map folder? Then show the map instead
1500 C4ScenarioListLoader::Folder *pFolder = pScenLoader->GetCurrFolder();
1501 if (pMapData = pFolder->GetMapData())
1502 {
1503 pMapData->ResetSelection();
1504 pMapData->CreateGUIElements(pMainDlg: this, rContainer&: *pScenSelStyleTabular->GetSheet(iIndex: ShowStyle_Map));
1505 pScenSelStyleTabular->SelectSheet(iIndex: ShowStyle_Map, fByUser: false);
1506 }
1507 else
1508 {
1509 // book style selection
1510 HideTitle(hide: false);
1511
1512 // add what has been loaded
1513 for (C4ScenarioListLoader::Entry *pEnt = pScenLoader->GetFirstEntry(); pEnt; pEnt = pEnt->GetNext())
1514 {
1515 StdStrBuf name = pEnt->GetName();
1516 CMarkup::StripMarkup(sText: &name);
1517 if (!SLen(sptr: searchBar->GetText()) || SSearchNoCase(szString: name.getData(), szIndex: searchBar->GetText()))
1518 {
1519 ScenListItem *pEntItem = new ScenListItem(pScenSelList, pEnt);
1520 if (pEnt == pOldSelection) pScenSelList->SelectEntry(pNewSel: pEntItem, fByUser: false);
1521 }
1522 else if (pEnt == pOldSelection)
1523 {
1524 pOldSelection = nullptr;
1525 }
1526 }
1527 // set title of current folder
1528 // but not root
1529 if (pFolder && pFolder != pScenLoader->GetRootFolder())
1530 pScenSelCaption->SetText(szText: pFolder->GetName().getData());
1531 else
1532 {
1533 // special root title
1534 pScenSelCaption->SetText(szText: LoadResStr(id: C4ResStrTableKey::IDS_DLG_SCENARIOS));
1535 }
1536 // new list has been loaded: Select first entry if nothing else had been selected
1537 if (!pOldSelection) pScenSelList->SelectFirstEntry(fByUser: false);
1538 }
1539}
1540
1541void C4StartupScenSelDlg::ResortFolder()
1542{
1543 // if it's still loading, sorting will be done in the end anyway
1544 if (!pScenLoader || pScenLoader->IsLoading()) return;
1545 C4ScenarioListLoader::Folder *pFolder = pScenLoader->GetCurrFolder();
1546 if (!pFolder) return;
1547 pFolder->Resort();
1548 UpdateList();
1549}
1550
1551void C4StartupScenSelDlg::UpdateSelection()
1552{
1553 AbortRenaming();
1554 if (!pScenLoader)
1555 {
1556 C4Facet fctNoPic;
1557 pSelectionInfo->SetPicture(fctNoPic);
1558 pSelectionInfo->ClearText(fDoUpdate: false);
1559 SetOpenButtonDefaultText();
1560 return;
1561 }
1562 // determine target text box
1563 C4GUI::TextWindow *pSelectionInfo = pMapData ? pMapData->GetSelectionInfoBox() : this->pSelectionInfo;
1564 // get selected entry
1565 C4ScenarioListLoader::Entry *pSel = GetSelectedEntry();
1566 if (!pSel)
1567 {
1568 // no selection: Display data of current parent folder
1569 pSel = pScenLoader->GetCurrFolder();
1570 // but not root
1571 if (pSel == pScenLoader->GetRootFolder()) pSel = nullptr;
1572 }
1573 // get title image and desc of selected entry
1574 C4Facet fctTitle; StdStrBuf sTitle, sDesc, sVersion, sAuthor;
1575 if (pSel)
1576 {
1577 pScenLoader->LoadExtended(pEntry: pSel); // 2do: Multithreaded
1578 fctTitle = pSel->GetTitlePicture();
1579 sTitle.Ref(Buf2: pSel->GetName());
1580 sDesc.Ref(Buf2: pSel->GetDesc());
1581 sVersion.Ref(Buf2: pSel->GetVersion());
1582 sAuthor.Ref(Buf2: pSel->GetAuthor());
1583 // never show a pure title string: There must always be some text or an image
1584 if (!fctTitle.Surface && (!sDesc || !*sDesc.getData()))
1585 sTitle.Clear();
1586 // selection specific open/start button
1587 pOpenBtn->SetText(pSel->GetOpenText().getData());
1588 pOpenBtn->SetToolTip(pSel->GetOpenTooltip().getData());
1589
1590 if (auto *scenario = dynamic_cast<C4ScenarioListLoader::Scenario *>(pSel); scenario)
1591 {
1592 btnAllowUserChange->SetEnabled(!scenario->GetC4S().Definitions.LocalOnly);
1593 btnAllowUserChange->SetChecked(scenario->GetC4S().Definitions.AllowUserChange);
1594 }
1595 else
1596 {
1597 btnAllowUserChange->SetChecked(false);
1598 btnAllowUserChange->SetEnabled(false);
1599 }
1600 }
1601 else
1602 {
1603 btnAllowUserChange->SetChecked(false);
1604 btnAllowUserChange->SetEnabled(false);
1605 SetOpenButtonDefaultText();
1606 }
1607 // set data in selection component
1608 pSelectionInfo->ClearText(fDoUpdate: false);
1609 pSelectionInfo->SetPicture(fctTitle);
1610 if (!!sTitle && (!sDesc || !*sDesc.getData())) pSelectionInfo->AddTextLine(szText: sTitle.getData(), pFont: &C4Startup::Get()->Graphics.BookFontCapt, dwClr: ClrScenarioItem, fDoUpdate: false, fMakeReadableOnBlack: false);
1611 if (!!sDesc) pSelectionInfo->AddTextLine(szText: sDesc.getData(), pFont: &C4Startup::Get()->Graphics.BookFont, dwClr: ClrScenarioItem, fDoUpdate: false, fMakeReadableOnBlack: false, pCaptionFont: &C4Startup::Get()->Graphics.BookFontCapt);
1612 if (!!sAuthor) pSelectionInfo->AddTextLine(szText: LoadResStr(id: C4ResStrTableKey::IDS_CTL_AUTHOR, args: sAuthor.getData()).c_str(),
1613 pFont: &C4Startup::Get()->Graphics.BookFont, dwClr: ClrScenarioItemXtra, fDoUpdate: false, fMakeReadableOnBlack: false);
1614 if (!!sVersion) pSelectionInfo->AddTextLine(szText: LoadResStr(id: C4ResStrTableKey::IDS_DLG_VERSION, args: sVersion.getData()).c_str(),
1615 pFont: &C4Startup::Get()->Graphics.BookFont, dwClr: ClrScenarioItemXtra, fDoUpdate: false, fMakeReadableOnBlack: false);
1616 pSelectionInfo->UpdateHeight();
1617 // usecrew-button
1618 UpdateUseCrewBtn();
1619}
1620
1621C4StartupScenSelDlg::ScenListItem *C4StartupScenSelDlg::GetSelectedItem()
1622{
1623 return static_cast<ScenListItem *>(pScenSelList->GetSelectedItem());
1624}
1625
1626C4ScenarioListLoader::Entry *C4StartupScenSelDlg::GetSelectedEntry()
1627{
1628 // map layout: Get selection from map
1629 if (pMapData) return pMapData->GetSelectedEntry();
1630 // get selection in listbox
1631 ScenListItem *pSel = static_cast<ScenListItem *>(pScenSelList->GetSelectedItem());
1632 return pSel ? pSel->GetEntry() : nullptr;
1633}
1634
1635bool C4StartupScenSelDlg::StartScenario(C4ScenarioListLoader::Scenario *pStartScen)
1636{
1637 assert(pStartScen);
1638 if (!pStartScen) return false;
1639 // get required object definitions
1640 if (btnAllowUserChange->GetChecked())
1641 {
1642 // get definitions as user selects them
1643 std::vector<std::string> defs = pStartScen->GetC4S().Definitions.GetModules();
1644 if (defs.empty())
1645 {
1646 defs.push_back(x: "Objects.c4d");
1647 }
1648 if (!C4DefinitionSelDlg::SelectDefinitions(pOnScreen: GetScreen(), selection&: defs))
1649 // user aborted during definition selection
1650 return false;
1651
1652 Game.DefinitionFilenames = defs;
1653 Game.FixedDefinitions = true;
1654 }
1655 else
1656 {
1657 // for no user change, just set default objects. Custom settings will override later anyway
1658 Game.DefinitionFilenames.push_back(x: "Objects.c4d");
1659 }
1660 // set other default startup parameters
1661 SCopy(szSource: pStartScen->GetEntryFilename().getData(), sTarget: Game.ScenarioFilename);
1662 Game.fLobby = !!Game.NetworkActive; // always lobby in network
1663 Game.fObserve = false;
1664 // start with this set!
1665 C4Startup::Get()->Start();
1666 return true;
1667}
1668
1669bool C4StartupScenSelDlg::OpenFolder(C4ScenarioListLoader::Folder *pNewFolder)
1670{
1671 // open it through loader
1672 if (!pScenLoader) return false;
1673 searchBar->ClearText();
1674 bool fSuccess = pScenLoader->Load(pSpecifiedFolder: pNewFolder, fReload: false);
1675 UpdateList();
1676 UpdateSelection();
1677 if (!pMapData) SetFocus(pCtrl: pScenSelList, fByMouse: false);
1678 return fSuccess;
1679}
1680
1681bool C4StartupScenSelDlg::DoOK()
1682{
1683 AbortRenaming();
1684 // get selected entry
1685 C4ScenarioListLoader::Entry *pSel = GetSelectedEntry();
1686 if (!pSel) return false;
1687 // check if open is possible
1688 StdStrBuf sError;
1689 if (!pSel->CanOpen(sError))
1690 {
1691 GetScreen()->ShowMessage(szMessage: sError.getData(), szCaption: LoadResStr(id: C4ResStrTableKey::IDS_MSG_CANNOTSTARTSCENARIO), icoIcon: C4GUI::Ico_Error);
1692 return false;
1693 }
1694 // if CanOpen returned true but set an error message, that means it's a warning. Display it!
1695 if (sError.getLength())
1696 {
1697 if (!GetScreen()->ShowMessageModal(szMessage: sError.getData(), szCaption: LoadResStrNoAmp(id: C4ResStrTableKey::IDS_DLG_STARTGAME).c_str(), dwButtons: C4GUI::MessageDialog::btnOKAbort, icoIcon: C4GUI::Ico_Notify, pbConfigDontShowAgainSetting: &Config.Startup.HideMsgStartDedicated))
1698 // user chose to not start it
1699 return false;
1700 }
1701 // start it!
1702 return pSel->Start();
1703}
1704
1705bool C4StartupScenSelDlg::DoBack(bool fAllowClose)
1706{
1707 AbortRenaming();
1708 // if in a subfolder, try backtrace folders first
1709 if (pScenLoader && pScenLoader->FolderBack())
1710 {
1711 searchBar->ClearText();
1712 UpdateList();
1713 UpdateSelection();
1714 return true;
1715 }
1716 // while this isn't multithreaded, the dialog must not be aborted while initial load...
1717 if (pScenLoader && pScenLoader->IsLoading()) return false;
1718 // return to main screen
1719 if (fAllowClose)
1720 {
1721 Close(fOK: false);
1722 return true;
1723 }
1724 return false;
1725}
1726
1727void C4StartupScenSelDlg::DoRefresh()
1728{
1729 if (pScenLoader && !pScenLoader->IsLoading())
1730 {
1731 pScenSelList->SelectNone(fByUser: false);
1732 pScenLoader->ReloadCurrent();
1733 UpdateList();
1734 UpdateSelection();
1735 }
1736}
1737
1738void C4StartupScenSelDlg::SetOpenButtonDefaultText()
1739{
1740 pOpenBtn->SetText(LoadResStr(id: C4ResStrTableKey::IDS_BTN_OPEN));
1741 pOpenBtn->SetToolTip(LoadResStr(id: C4ResStrTableKey::IDS_DLGTIP_SCENSELNEXT));
1742}
1743
1744bool C4StartupScenSelDlg::KeyRename()
1745{
1746 // no rename in map mode
1747 if (pMapData) return false;
1748 // not if renaming already
1749 if (IsRenaming()) return false;
1750 // forward to selected scenario list item
1751 ScenListItem *pSel = GetSelectedItem();
1752 if (!pSel) return false;
1753 return pSel->KeyRename();
1754}
1755
1756bool C4StartupScenSelDlg::KeyDelete()
1757{
1758 // do not delete from map folder
1759 if (pMapData) return false;
1760 // cancel renaming
1761 AbortRenaming();
1762 // delete selected item: Confirmation first
1763 ScenListItem *pSel = GetSelectedItem();
1764 if (!pSel) return false;
1765 C4ScenarioListLoader::Entry *pEnt = pSel->GetEntry();
1766 bool fOriginal = false;
1767 if (C4Group_IsGroup(szFilename: pEnt->GetEntryFilename().getData()))
1768 {
1769 C4Group Grp;
1770 if (Grp.Open(szGroupName: pEnt->GetEntryFilename().getData()))
1771 {
1772 fOriginal = !!Grp.GetOriginal();
1773 }
1774 Grp.Close();
1775 }
1776 const std::string warning{LoadResStrChoice(condition: fOriginal, ifTrue: C4ResStrTableKey::IDS_MSG_DELETEORIGINAL, ifFalse: C4ResStrTableKey::IDS_MSG_PROMPTDELETE, args: std::format(fmt: "{} {}", args: pEnt->GetTypeName().getData(), args: pEnt->GetName().getData()))};
1777 GetScreen()->ShowRemoveDlg(pDlg: new C4GUI::ConfirmationDialog(warning.c_str(), LoadResStr(id: C4ResStrTableKey::IDS_MNU_DELETE),
1778 new C4GUI::CallbackHandlerExPar<C4StartupScenSelDlg, ScenListItem *>(this, &C4StartupScenSelDlg::DeleteConfirm, pSel), C4GUI::MessageDialog::btnYesNo));
1779 return true;
1780}
1781
1782void C4StartupScenSelDlg::DeleteConfirm(ScenListItem *pSel)
1783{
1784 // deletion confirmed. Do it.
1785 C4ScenarioListLoader::Entry *pEnt = pSel->GetEntry();
1786 if (!C4Group_DeleteItem(szItem: pEnt->GetEntryFilename().getData(), fRecycle: true))
1787 {
1788 Game.pGUI->ShowMessageModal(szMessage: LoadResStr(id: C4ResStrTableKey::IDS_FAIL_DELETE), szCaption: LoadResStr(id: C4ResStrTableKey::IDS_MNU_DELETE), dwButtons: C4GUI::MessageDialog::btnOK, icoIcon: C4GUI::Ico_Error);
1789 return;
1790 }
1791 // remove from scenario list
1792 pScenSelList->SelectEntry(pNewSel: pSel->GetNext(), fByUser: false);
1793 delete pEnt;
1794 delete pSel;
1795}
1796
1797bool C4StartupScenSelDlg::KeyCheat()
1798{
1799 return Game.pGUI->ShowRemoveDlg(pDlg: new C4GUI::InputDialog(LoadResStr(id: C4ResStrTableKey::IDS_TEXT_ENTERMISSIONPASSWORD), LoadResStr(id: C4ResStrTableKey::IDS_DLG_MISSIONACCESS), C4GUI::Ico_Options,
1800 new C4GUI::InputCallback<C4StartupScenSelDlg>(this, &C4StartupScenSelDlg::KeyCheat2),
1801 false));
1802}
1803
1804bool C4StartupScenSelDlg::KeySearch()
1805{
1806 SetFocus(pCtrl: searchBar, fByMouse: false);
1807 return true;
1808}
1809
1810bool C4StartupScenSelDlg::KeyEscape()
1811{
1812 if (GetFocus() == searchBar)
1813 {
1814 SetFocus(pCtrl: pScenSelList, fByMouse: false);
1815 return true;
1816 }
1817 return false;
1818}
1819
1820void C4StartupScenSelDlg::KeyCheat2(const StdStrBuf &rsCheatCode)
1821{
1822 // Special character "-": remove mission password(s)
1823 if (SEqual2(szStr1: rsCheatCode.getData(), szStr2: "-"))
1824 {
1825 const char *szPass = rsCheatCode.getPtr(i: 1);
1826 if (szPass && *szPass)
1827 {
1828 SRemoveModules(szList: Config.General.MissionAccess, szModules: szPass, fCaseSensitive: false);
1829 UpdateList();
1830 UpdateSelection();
1831 return;
1832 }
1833 }
1834
1835 // No special character: add mission password(s)
1836 const char *szPass = rsCheatCode.getPtr(i: 0);
1837 if (szPass && *szPass)
1838 {
1839 SAddModules(szList: Config.General.MissionAccess, szModules: szPass, fCaseSensitive: false);
1840 UpdateList();
1841 UpdateSelection();
1842 return;
1843 }
1844}
1845
1846void C4StartupScenSelDlg::FocusScenList()
1847{
1848 SetFocus(pCtrl: pScenSelList, fByMouse: false);
1849}
1850
1851void C4StartupScenSelDlg::OnButtonScenario(C4GUI::Control *pEl)
1852{
1853 // map button was clicked: Update selected scenario
1854 if (!pMapData || !pEl) return;
1855
1856 // OnButtonScenario may change the current selection
1857 if (C4ScenarioListLoader::Entry *pSel{GetSelectedEntry()}; pMapData->OnButtonScenario(pEl) || (pSel && pSel == GetSelectedEntry()))
1858 {
1859 DoOK();
1860 return;
1861 }
1862
1863 // the first click selects it
1864 SetFocus(pCtrl: pEl, fByMouse: false);
1865 UpdateSelection();
1866}
1867
1868void C4StartupScenSelDlg::DeselectAll()
1869{
1870 // Deselect all so current folder info is displayed
1871 if (GetFocus()) C4GUI::GUISound(szSound: "ArrowHit");
1872 SetFocus(pCtrl: nullptr, fByMouse: true);
1873 if (pMapData) pMapData->ResetSelection();
1874 UpdateSelection();
1875}
1876
1877void C4StartupScenSelDlg::StartRenaming(C4GUI::RenameEdit *pNewRenameEdit)
1878{
1879 pRenameEdit = pNewRenameEdit;
1880}
1881
1882void C4StartupScenSelDlg::AbortRenaming()
1883{
1884 if (pRenameEdit) pRenameEdit->Abort();
1885}
1886
1887// NICHT: 9, 7.2.2, 113-114
1888