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 | #include "gfCShareManager.h"
#if defined fsShare
#include <algorithm>
#include <chrono>
#include <cmath>
#include <vector>
#include <fsCore/fsIFile.h>
#include <fsCore/src/fsCAppSettings.h>
#include <fsCore/src/fsCGlobalSavedData.h>
#include <fsCore/src/debug/fsLog.h>
#include <fsAppCore/src/components/gui/elements/fsCButtonComponent.h>
#include <fsAppCore/src/components/gui/elements/fsCModalGuiComponent.h>
#include <fsAppCore/src/components/gui/fsCConfirmBoxGui.h>
#include <fsAppCore/src/components/gui/fsIGuiComponent.h>
#include <fsAppCore/src/fsCAppCoreMain.h>
#include <fsAppCore/src/fsCGuiMessageDispatcher.h>
#include <fsAppCore/src/fsCLocalisedStrings.h>
#include <fsAppCore/src/fsCProfileManager.h>
#include <fsAppCore/src/fsCShareCard.h>
#include <fsAppCore/src/fsNGuiLayout.h>
#include <fsAppCore/src/fsCEntity.h>
#include <fsRenderer/src/components/fsISpriteComponent.h>
#include <fsAppCore/fsIScene.h>
#include <fsPlatform/social/fsCShareText.h>
#include <fsPlatform/social/fsShareSheetFactory.h>
const fsCUniqueId gfCShareManager::mShareActionMsg("share");
const fsCUniqueId gfCShareManager::mShareTargetActionMsg("shareTarget");
namespace
{
const char* const kTargetsLayout = "gui/share/targets.txt";
fsCAppSettings* settingsGet()
{
return fsCAppCoreMain::instanceGet()->settingsGet();
}
std::string localisedGet(const fsStr& pKey, const std::string& pDefault)
{
fsStr value;
return fsCLocalisedStrings::localisedStringGetIfExists(pKey, value) ? std::string(value.utf8Get()) : pDefault;
}
// The shared file's name, as share sheets and recipients see it: share_<moment>_fileName
// (e.g. "Canvas Trails - {stateName}"), else the game's name, else the moment id.
std::string fileNameGet(const gfSShareMoment& pMoment)
{
const std::string gameName = settingsGet()->strGetWithDefault("installedName", "").utf8Get();
const std::string name = fsCShareText::substitute(
localisedGet("share_" + pMoment.mId + "_fileName", gameName), pMoment.mFields);
return name.empty() ? std::string(pMoment.mId.utf8Get()) : name;
}
std::int64_t utcMsGet()
{
return std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()).count();
}
std::string mimeTypeGet(const std::string& pExtension)
{
return pExtension == ".jpg" || pExtension == ".jpeg" ? "image/jpeg" : "image/png";
}
fsBool assetExistsGet(const fsStr& pPath)
{
return fsIFile::fileExistsGet(fsCResourceName(pPath, fsCResourceName::eRES_LOCATION_ASSETS));
}
std::filesystem::path cacheRootGet()
{
const fsCResourceName folder("share", fsCResourceName::eRES_LOCATION_USER_SETTINGS);
return std::filesystem::u8path(folder.nameGet().utf8Get());
}
}
gfCShareManager* gfCShareManager::instanceGet()
{
// Lives as long as the app: the GUI dispatcher it listens to is torn down at exit anyway.
static gfCShareManager* const instance = new gfCShareManager();
return instance;
}
gfCShareManager::gfCShareManager() :
fsIMessageListener(ePRIORITY_NORMAL),
mService(fsShareSheetServiceCreate(settingsGet()->strGetWithDefault("installedName", "Game").utf8Get(),
settingsGet()->boolGetWithDefault("shareSaveReveal", true))),
mCache(cacheRootGet())
{
listenersRegister();
#if !defined fsRELEASE
if (!settingsGet()->debugSettingsGet()->strGetWithDefault("shareTestMoment", "").emptyGet())
{
testCardSchedule(180);
}
#endif
}
gfCShareManager::~gfCShareManager()
{
if (fsCGuiMessageDispatcher::existsGet())
{
listenersDeregister();
}
}
fsBool gfCShareManager::availableGet() const
{
// Autotest must never open share sheets on a test machine.
const fsStr autoTest = settingsGet()->strGetWithDefault("autoTest", "");
if (!autoTest.emptyGet() && autoTest.find("none") == fsStr::npos)
{
return false;
}
return mService && !mService->targetsGet().empty();
}
void gfCShareManager::providerRegister(const fsStr& pMomentId, Provider pProvider)
{
mProviders[pMomentId] = std::move(pProvider);
}
void gfCShareManager::momentShare(const fsStr& pMomentId, fsCButtonComponent* const pSource)
{
if (!availableGet())
{
return;
}
const auto provider = mProviders.find(pMomentId);
gfSShareMoment moment;
moment.mId = pMomentId;
if (provider == mProviders.end() || !provider->second(pMomentId, pSource, moment))
{
fsLogMsg("Share moment %s has no provider or was declined.", pMomentId.utf8Get());
return;
}
const auto targets = mService->targetsGet();
if (targets.size() > 1 && assetExistsGet(kTargetsLayout))
{
mChooserMoment = moment;
fsCEntity* const chooser = fsIGuiComponent::guiCreateFromFile(
fsCResourceName(kTargetsLayout, fsCResourceName::eRES_LOCATION_ASSETS),
fsCAppCoreMain::instanceGet()->sceneGet(), true);
if (chooser)
{
targetChooserPrepare(chooser);
}
return;
}
share(moment);
}
void gfCShareManager::targetChooserPrepare(fsCEntity* const pChooser) const
{
// The layout can offer every target; this build may have fewer.
const auto targets = mService->targetsGet();
const std::string prefix = "ShareTarget_";
std::vector<fsINode*> buttons;
std::function<void(fsINode*)> collect = [&](fsINode* pNode)
{
if (pNode->nameGet().find(prefix.c_str()) == 0)
{
buttons.push_back(pNode);
}
for (fsINode* const child : pNode->childrenGet())
{
collect(child);
}
};
collect(pChooser);
for (fsINode* const button : buttons)
{
const std::string id = std::string(button->nameGet().utf8Get()).substr(prefix.size());
button->visibleSet(std::any_of(targets.begin(), targets.end(),
[&](const fsShareTarget& pTarget) { return pTarget.id == id; }));
}
// Hidden rows give their height back, so a Mac without Steam has no hole in the chooser.
if (!buttons.empty())
{
fsNGuiLayout::hiddenRowsCollapse(dynamic_cast<fsCEntity*>(buttons.front()->parentGet()));
}
}
void gfCShareManager::share(const gfSShareMoment& pMoment, const fsStr& pTargetId, DoneCallback pDone)
{
if (!availableGet())
{
if (pDone)
{
pDone(fsShareResult::eUNAVAILABLE);
}
return;
}
const fsShareTarget target = targetGet(pTargetId);
fsShareRequest request = requestBuild(pMoment);
const std::string path = fsSharePathUtf8(mCache.pathMake(fileNameGet(pMoment), target.fileExtension, utcMsGet()));
++mPending;
if (!fsCShareCard::supportedGet())
{
deliver(std::move(request), pMoment, target, path, false, fsPoint(), std::move(pDone));
return;
}
fsCShareCard::sSpec spec;
spec.mLayout = layoutGet(pMoment, target);
spec.mFields = pMoment.mFields;
spec.mImages = pMoment.mImages;
spec.mPath = fsStr(path.c_str());
fsCShareCard::render(spec, [this, request, pMoment, target, path, pDone](fsBool pSaved, const fsPoint& pSize)
{
deliver(request, pMoment, target, path, pSaved, pSize, pDone);
});
}
void gfCShareManager::deliver(fsShareRequest pRequest, const gfSShareMoment& pMoment, const fsShareTarget& pTarget,
const std::string& pCardPath, fsBool pCardSaved, const fsPoint& pCardSize,
DoneCallback pDone)
{
if (pCardSaved)
{
pRequest.files.push_back({pCardPath, mimeTypeGet(pTarget.fileExtension), pCardSize.x, pCardSize.y});
}
else if (!pMoment.mFallbackImage.nameGet().emptyGet() && fsIFile::fileExistsGet(pMoment.mFallbackImage))
{
// Packed assets have no real path, so the picture is written out to the cache first.
// Binary-safe: strGetFromFile() stops at the first 0x00 byte.
const fsStr bytes = fsIFile::bytesGetFromCompressedFileBinary(pMoment.mFallbackImage);
const std::string name = pMoment.mFallbackImage.nameGet().utf8Get();
const std::string extension = name.substr(std::min(name.size(), name.rfind('.')));
const auto written = mCache.write(fileNameGet(pMoment), extension, utcMsGet(),
std::string(bytes.utf8Get(), bytes.dataSizeGet()));
if (!written.empty())
{
pRequest.files.push_back({fsSharePathUtf8(written), mimeTypeGet(extension), 0, 0});
}
}
else
{
fsLogMsg("Share card for %s could not be drawn; sharing text only.", pMoment.mId.utf8Get());
}
mService->share(pRequest, pTarget.id, [this, pDone, id = pMoment.mId, targetId = pTarget.id](fsShareResult pResult, const std::string& pDetail)
{
--mPending;
fsLogMsg("Share %s finished: result %d %s", id.utf8Get(), static_cast<int>(pResult), pDetail.c_str());
resultShow(targetId, pResult, pDetail);
if (pDone)
{
pDone(pResult);
}
});
mCache.prune();
pumpSchedule();
}
void gfCShareManager::resultShow(const std::string& pTargetId, const fsShareResult pResult, const std::string& pDetail) const
{
// Share sheets give their own feedback; targets that save quietly (the Pictures folder, Steam's
// library) say so here. Only games with the strings get a box: shareResult_<targetId> on success,
// shareResult_failed on an error.
fsStr key;
if (pResult == fsShareResult::eSAVED)
{
key = fsStr(("shareResult_" + pTargetId).c_str());
}
else if (pResult == fsShareResult::eERROR && pTargetId != "system")
{
key = "shareResult_failed";
}
fsStr text;
if (key.emptyGet() || !fsCLocalisedStrings::localisedStringGetIfExists(key, text))
{
return;
}
// {file} and {folder} are the saved picture's name and the folder it went into.
std::map<std::string, std::string> fields;
if (pResult == fsShareResult::eSAVED)
{
const std::filesystem::path saved = std::filesystem::u8path(pDetail);
fields["file"] = fsSharePathUtf8(saved.filename());
fields["folder"] = fsSharePathUtf8(saved.parent_path().filename());
}
fsIScene* const scene = fsCAppCoreMain::instanceGet()->sceneGet();
if (scene)
{
fsCConfirmBoxGui::okBoxCreate(scene, fsStr(fsCShareText::substitute(text.utf8Get(), fields).c_str()));
}
}
fsShareTarget gfCShareManager::targetGet(const fsStr& pTargetId) const
{
const auto targets = mService->targetsGet();
for (const auto& target : targets)
{
if (target.id == pTargetId.utf8Get())
{<--- Consider using std::find_if algorithm instead of a raw loop.
return target;
}
}
return targets.empty() ? fsShareTarget{"system", "shareTarget_system", ".png"} : targets.front();
}
fsCResourceName gfCShareManager::layoutGet(const gfSShareMoment& pMoment, const fsShareTarget& pTarget) const
{
const fsStr base = settingsGet()->strGetWithDefault("shareLayout_" + pMoment.mId, "gui/share/" + pMoment.mId);
fsStr stem = base;
stem.replaceFirst(".txt", "");
// Steam's library and desktop share sheets suit wide cards; phones suit square.
#if defined fsDesktop
const fsStr preferred = "wide";
#else
const fsStr preferred = pTarget.id == "steamScreenshots" ? fsStr("wide") : fsStr("square");
#endif
for (const fsStr& variant : {pMoment.mVariant, preferred, fsStr("square"), fsStr("wide")})
{
if (!variant.emptyGet() && assetExistsGet(stem + "_" + variant + ".txt"))
{
return fsCResourceName(stem + "_" + variant + ".txt", fsCResourceName::eRES_LOCATION_ASSETS);
}
}
return fsCResourceName(stem + ".txt", fsCResourceName::eRES_LOCATION_ASSETS);
}
fsShareRequest gfCShareManager::requestBuild(const gfSShareMoment& pMoment) const
{
const std::string gameName = settingsGet()->strGetWithDefault("installedName", "").utf8Get();
const fsStr prefix = "share_" + pMoment.mId;
fsShareRequest request;
request.subject = fsCShareText::substitute(localisedGet(prefix + "_subject", gameName), pMoment.mFields);
const std::string message = fsCShareText::substitute(localisedGet(prefix + "_text", gameName), pMoment.mFields);
// The moment is the share; the store link is an opt-in extra line.
const fsBool link = settingsGet()->boolGetWithDefault("shareStoreLink_" + pMoment.mId,
settingsGet()->boolGetWithDefault("shareStoreLink", false));
const std::string url = link ? std::string(settingsGet()->strGetWithDefault("shareMeUrl", "").utf8Get()) : std::string();
request.text = fsCShareText::compose(message, localisedGet("share_getTheGame", ""), url);
request.url = url;
return request;
}
void gfCShareManager::pumpSchedule()
{
// Results arrive asynchronously, so poll the service each frame only while shares are open.
if (mPumping || mPending <= 0)
{
return;
}
mPumping = true;
fsCAppCoreMain::instanceGet()->preRenderJobAdd([this]()
{
mPumping = false;
mService->update();
pumpSchedule();
});
}
#if !defined fsRELEASE
void gfCShareManager::testCardSchedule(fsS32 pFramesLeft)
{
// Waits a few seconds of frames, then for a loaded profile: moments read the player's progress.
fsCAppCoreMain::instanceGet()->preRenderJobAdd([this, pFramesLeft]()
{
const fsCGlobalSavedData* const saved = fsCProfileManager::instanceGet()->savedDataGet();
const fsBool profileLoaded = fsCGlobalSavedData::mNoProfileLoaded != saved->currentProfileIndexGet();
if (pFramesLeft > 0 || !profileLoaded)
{
testCardSchedule(pFramesLeft - 1);
return;
}
testCardRender(settingsGet()->debugSettingsGet()->strGetWithDefault("shareTestMoment", ""));
});
}
void gfCShareManager::testCardRender(const fsStr& pMomentId)
{
const auto provider = mProviders.find(pMomentId);
gfSShareMoment moment;
moment.mId = pMomentId;
if (provider == mProviders.end() || !provider->second(pMomentId, nullptr, moment))
{
fsLogError("Share test: moment %s has no provider or was declined.", pMomentId.utf8Get());
return;
}
const fsShareTarget target = targetGet(fsStr());
fsCShareCard::sSpec spec;
spec.mLayout = layoutGet(moment, target);
spec.mFields = moment.mFields;
spec.mImages = moment.mImages;
const std::string path = fsSharePathUtf8(mCache.pathMake("test-" + std::string(pMomentId.utf8Get()),
target.fileExtension, utcMsGet()));
spec.mPath = fsStr(path.c_str());
fsCShareCard::render(spec, [path](fsBool pSaved, const fsPoint& pSize)
{
fsLogError("Share test card %s: saved %d, %d x %d", path.c_str(), pSaved ? 1 : 0, pSize.x, pSize.y);
});
}
#endif
void gfCShareManager::listenersRegisterDo()
{
fsCGuiMessageDispatcher::instanceGet()->listenerRegister(mShareActionMsg, this);
fsCGuiMessageDispatcher::instanceGet()->listenerRegister(mShareTargetActionMsg, this);
}
void gfCShareManager::listenersDeregisterDo()
{
fsCGuiMessageDispatcher::instanceGet()->listenerDeregister(mShareActionMsg, this);
fsCGuiMessageDispatcher::instanceGet()->listenerDeregister(mShareTargetActionMsg, this);
}
fsBool gfCShareManager::messageProcessDo(const fsCUniqueId& pMessageType,
const fsIMessageDispatcher::sMessageParameters& pParam)
{
if (mShareActionMsg != pMessageType && mShareTargetActionMsg != pMessageType)
{
return false;
}
const auto& button = static_cast<const fsCButtonComponent::sButtonEventMsgParam&>(pParam);
if (mShareActionMsg == pMessageType)
{
momentShare(button.mStr, button.mParent);
return true;
}
// A target picked in the chooser: close it, then share what was waiting. The chooser's root is a
// modal (gui/share/targets.txt), not a gui component, so it is found by that: looking for the
// button's gui parent went past it, left the chooser open and its next pick had nothing to share.
for (fsINode* node = button.mParent->parentGet(); node; node = node->parentGet())
{
fsCEntity* const entity = dynamic_cast<fsCEntity*>(node);
if (entity && entity->componentGet<fsCModalGuiComponent>())
{
entity->destroy();
break;
}
}
if (!mChooserMoment.mId.emptyGet())
{
const gfSShareMoment moment = mChooserMoment;
mChooserMoment = gfSShareMoment();
share(moment, button.mStr);
}
return true;
}
#endif
|