-
Notifications
You must be signed in to change notification settings - Fork 0
/
spiral_scene.cpp
1007 lines (846 loc) · 25.9 KB
/
spiral_scene.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (C) 2023 Michel de Boer
// License: GPLv3
#include "spiral_scene.h"
#include "circle.h"
#include "exception.h"
#include "jni_callback.h"
#include "player.h"
#include "utils.h"
#include <QFile>
#include <QQmlEngine>
#include <QQuickItemGrabResult>
#include <QSGNode>
using namespace std::chrono_literals;
namespace SpiralFun {
int SpiralScene::MAX_DIAMETER = 300;
SpiralScene::SpiralScene(QQuickItem *parent) :
QQuickItem(parent)
{
setFlags(ItemHasContents | ItemIsViewport);
setAntialiasing(true);
setAcceptTouchEvents(true);
// The window size is not yet known at this time. But setting up a scene
// guarantees there are always circles available.
setupCircles();
}
void SpiralScene::init()
{
calcDefaultRadiusSize();
// Now the window size is known, setup with proper position and sizes
setupCircles();
QObject::connect(this, &QQuickItem::widthChanged, this, [this]{ handleWindowSizeChanged(); });
QObject::connect(this, &QQuickItem::heightChanged, this, [this]{ handleWindowSizeChanged(); });
auto& jniCallbackListener = JNICallbackListener::getInstance();
QObject::connect(&jniCallbackListener, &JNICallbackListener::viewUriReceived,
this, [this](const QString& uri){ handleReceivedAndroidIntent(uri); });
QObject::connect(&jniCallbackListener, &JNICallbackListener::mediaScannerFinished,
this, [this](const QString& uri){ handleMediaScannerFinished(uri); });
// Handle possibly pending intent from Android.
Utils::handlePendingIntent();
qInfo() << "Surface format:" << window()->format();
}
void SpiralScene::setMusicGeneration(bool musicGeneration)
{
if (musicGeneration != mMusicGeneration)
{
mMusicGeneration = musicGeneration;
emit musicGenerationChanged();
}
}
void SpiralScene::setPlayingSpeed(int playingSpeed)
{
if (playingSpeed != mPlayingSpeed)
{
mPlayingSpeed = playingSpeed;
emit playingSpeedChanged();
}
}
void SpiralScene::setToneDistance(int toneDistance)
{
if (toneDistance != mToneDistance)
{
mToneDistance = toneDistance;
emit toneDistanceChanged();
}
}
void SpiralScene::calcDefaultRadiusSize()
{
const qreal minDimension = std::min(width(), height());
mDefaultCircleRadius = minDimension / 2.0 / (MAX_CIRCLES * 2 - 1);
const int oldMaxDiameter = MAX_DIAMETER;
MAX_DIAMETER = SpiralConfig::MAX_REL_RADIUS * mDefaultCircleRadius * 2;
if (oldMaxDiameter != MAX_DIAMETER)
emit maxDiameterChanged();
qDebug() << "Scene size:" << size() << "default-radius:" << mDefaultCircleRadius << "max-diameter:" << MAX_DIAMETER;
qDebug() << "Screen:" << window()->screen()->size() << "dpr:" << window()->devicePixelRatio() << window()->screen()->devicePixelRatio();
}
void SpiralScene::handleWindowSizeChanged()
{
calcDefaultRadiusSize();
stop();
}
void SpiralScene::setupCircles(const CircleConfigList& config)
{
mCircles.clear();
for (const auto& c : config)
{
addCircle(mDefaultCircleRadius * c.mRelRadius)->
setSpeed(c.mSpeed)->
setDraw(c.mDraw)->
setColor(c.mColor);
}
setCurrentIndex(0);
setCurrentCircleFocus(true);
emit numCirclesChanged();
}
void SpiralScene::setupExample(const QString& example)
{
const std::unordered_map<QString, std::initializer_list<CircleConfig>> configs = {
{ "/images/example1.png", EXAMPLE1_CONFIG },
{ "/images/example2.png", EXAMPLE2_CONFIG },
{ "/images/example3.png", EXAMPLE3_CONFIG },
{ "/images/example4.png", EXAMPLE4_CONFIG }
};
auto it = configs.find(example);
if (it == configs.end())
{
qWarning() << "Example not found:" << example;
return;
}
setupCircles(it->second);
}
Circle* SpiralScene::getCurrentCircle() const
{
Q_ASSERT(!mCircles.empty());
return mCurrentIndex < mCircles.size() ? mCircles[mCurrentIndex].get() : nullptr;
}
void SpiralScene::setNumCircles(int numCircles)
{
qDebug() << "numCircles:" << numCircles << "current:" << mCircles.size();
const unsigned n = static_cast<unsigned>(numCircles);
if (n == mCircles.size())
return;
if (n < mCircles.size())
{
mCircles.resize(numCircles);
if (mCurrentIndex >= mCircles.size())
{
setCurrentIndex(mCircles.size() - 1);
setCurrentCircleFocus(true);
}
emit numCirclesChanged();
return;
}
Q_ASSERT(n > mCircles.size());
const int delta = n - mCircles.size();
for (int i = 0; i < delta; ++i)
addCircle(mDefaultCircleRadius)->setSpeed(1)->setDraw(true);
setCurrentCircleFocus(false);
setCurrentIndex(mCircles.size() - 1);
setCurrentCircleFocus(true);
emit numCirclesChanged();
}
SpiralFun::Circle* SpiralScene::addCircle(qreal radius)
{
QPointF center = boundingRect().center();
if (!mCircles.empty())
{
const auto& prevCircle = *mCircles.back();
center = prevCircle.getCenter();
center.ry() -= prevCircle.getRadius() + radius;
}
auto circle = std::make_unique<SpiralFun::Circle>(this);
auto* engine = qmlEngine(this);
engine->setContextForObject(circle.get(), qmlContext(this));
circle->setCenter(center);
circle->setRadius(radius);
QObject::connect(circle.get(), &Circle::diameterChanged, this,
[this, c=circle.get()](int oldDiameter){ handleDiameterChange(c, oldDiameter); });
mCircles.push_back(std::move(circle));
return mCircles.back().get();
}
std::optional<unsigned> SpiralScene::findCircle(const Circle* circle)
{
const auto it = std::find_if(mCircles.begin(), mCircles.end(), [circle](const auto& c){
return c.get() == circle;
});
if (it == mCircles.end())
return {};
return it - mCircles.begin();
}
void SpiralScene::handleDiameterChange(Circle* circle, int oldDiameter)
{
std::optional<unsigned> index = findCircle(circle);
if (!index)
{
qWarning() << "Circle not found:" << circle;
return;
}
const int diff = circle->getDiameter() - oldDiameter;
qreal yShift = diff;
if (*index > 0)
{
QPointF center = circle->getCenter();
center.ry() -= diff / 2.0;
circle->setCenter(center);
}
else
{
yShift = diff / 2.0;
}
// Circle changed size, move circles on top of this circle.
moveCircles(*index + 1, yShift);
}
void SpiralScene::moveCircles(unsigned index, qreal yShift)
{
for (unsigned i = index; i < mCircles.size(); ++i)
{
auto& circle = mCircles[i];
QPointF center = circle->getCenter();
center.ry() -= yShift;
circle->setCenter(center);
}
}
void SpiralScene::circleUp()
{
if (mCircles.empty())
return;
if (mCurrentIndex < mCircles.size() - 1)
{
setCurrentCircleFocus(false);
setCurrentIndex(mCurrentIndex + 1);
setCurrentCircleFocus(true);
}
}
void SpiralScene::circleDown()
{
if (mCurrentIndex > 0)
{
setCurrentCircleFocus(false);
setCurrentIndex(mCurrentIndex - 1);
setCurrentCircleFocus(true);
}
}
void SpiralScene::setCurrentCircleFocus(bool focus)
{
if (mCurrentIndex >= mCircles.size())
return;
auto& circle = mCircles[mCurrentIndex];
circle->setFocus(focus);
if (!focus)
return;
emit currentCircleChanged();
}
void SpiralScene::setCurrentIndex(unsigned index)
{
if (mCurrentIndex == index)
return;
mCurrentIndex = index;
emit currentCircleIndexChanged();
}
bool SpiralScene::checkPlayRequirement()
{
const auto it = std::find_if(mCircles.begin(), mCircles.end(), [](const auto& c){
return c->getDraw(); });
if (it == mCircles.end())
{
emit message("Enable line drawing on at least 1 circle");
return false;
}
return true;
}
void SpiralScene::play()
{
if (!checkPlayRequirement())
return;
setPlayState(PLAYING);
setShareMode(SHARE_PIC);
doPlay(nullptr);
}
void SpiralScene::playSequence(const QVariant& mutations, int sequenceLength, bool addReverse,
MutationSequence::SaveAs saveAs, bool createAlbum,
Recorder::FrameRate frameRate)
{
Q_ASSERT(sequenceLength > 0);
if (!checkPlayRequirement())
return;
mMutationSequence = std::make_unique<MutationSequence>(&mCircles, this);
mMutationSequence->setSequenceLength(sequenceLength);
mMutationSequence->setAddReverseSequence(addReverse);
mMutationSequence->setMutations(mutations);
mMutationSequence->setCreateNewPicturesFolder(createAlbum);
mMutationSequence->setFrameRate(frameRate);
emit sequenceLengthChanged();
removeCirclesFromScene();
setPlayState(PLAYING_SEQUENCE);
switch (saveAs)
{
case MutationSequence::SAVE_AS_GIF:
setShareMode(SHARE_GIF);
break;
case MutationSequence::SAVE_AS_VIDEO:
setShareMode(SHARE_VIDEO);
break;
default:
break;
}
connect(mMutationSequence.get(), &MutationSequence::sequenceFramePlaying, this, [this]{ emit sequenceFrameChanged(); });
connect(mMutationSequence.get(), &MutationSequence::sequenceFinished, this, [this](bool success){
setPlayState(DONE_PLAYING);
mMutationSequence = nullptr;
if (!success)
emit message("Failed to play sequence");
});
mMutationSequence->play(saveAs);
}
void SpiralScene::playSequenceFrame()
{
resetCircles();
doPlay(nullptr);
}
void SpiralScene::doPlay(std::unique_ptr<Recorder> recorder)
{
mStats = {};
setCurrentCircleFocus(false);
// Music is only supported in playing state.
std::unique_ptr<MusicGenerator> musicGenerator;
if (mMusicGeneration && mPlayState == PLAYING)
musicGenerator = std::make_unique<MusicGenerator>(mCircles, mToneDistance, MAX_PLAYING_SPEED - mPlayingSpeed + MIN_PLAYING_SPEED, this);
mPlayer = std::make_unique<Player>(mCircles, std::move(musicGenerator));
QObject::connect(mPlayer.get(), &Player::refreshScene, this, [this]{ update(); });
QObject::connect(mPlayer.get(), &Player::angleChanged, this, [this]{ emit playAngleChanged(); });
QObject::connect(mPlayer.get(), &Player::done, this, [this](const Player::Stats& stats){
mStats.mPlayerStats = stats;
removeCirclesFromScene();
if (mPlayState == RECORDING)
{
if (stats.mRecordingFailed)
{
emit message("Recording failed");
}
else
{
const QString fileName = mPlayer->getFileName().split('/').last();
emit statusUpdate(QString("Recording saved: %1").arg(fileName));
}
}
if (mPlayState == PLAYING_SEQUENCE)
{
mDoRender = true;
mClearScene = true;
}
else
{
setPlayState(DONE_PLAYING);
}
update();
});
switch (mPlayState)
{
case PLAYING:
case RECORDING:
mPlayer->play(std::move(recorder));
break;
case PLAYING_SEQUENCE:
mPlayer->playAll();
break;
default:
Q_ASSERT(false);
}
}
void SpiralScene::showSpiralStats()
{
if (mStats.mPlayerStats.mCycles == 0)
{
emit message("No stats available");
return;
}
const QString statMsg = QString(
"| Statistic | Value |\n"
"| :------------- | ----: |\n"
"| Creation steps | %1 |\n"
"| Creation time | %2 s |\n"
"| Step time | %3 ms |\n"
"| Line segments | %4 |")
.arg(mStats.mPlayerStats.mCycles)
.arg(qreal(mStats.mPlayerStats.mPlayTime / 1000.0ms))
.arg(qreal(mStats.mPlayerStats.mPlayTime / (qreal)mStats.mPlayerStats.mCycles / 1000.0us))
.arg(mStats.mLineSegmentCount);
emit message(statMsg);
}
void SpiralScene::record(Recorder::Format format)
{
const qreal r = mCircles.back()->getRadius();
QRectF recordRect = mSceneRect.adjusted(-r, -r, r, r);
auto sceneGrabber = createSceneGrabber(recordRect);
auto recorder = Recorder::createRecorder(format, std::move(sceneGrabber));
// Seems to give a reasonable tradeoff between quality and file size
const int bitsPerFrame = std::max(int(mStats.mLineSegmentCount * 0.8), 6000);
recorder->setBitsPerFrame(bitsPerFrame);
resetScene();
setPlayState(RECORDING);
switch (format)
{
case Recorder::FMT_GIF:
setShareMode(SHARE_GIF);
break;
case Recorder::FMT_VIDEO:
setShareMode(SHARE_VIDEO);
break;
}
mShareMediaUri.clear();
doPlay(std::move(recorder));
}
void SpiralScene::stop()
{
mPlayer = nullptr;
mMutationSequence = nullptr;
resetScene();
setPlayState(NOT_PLAYING);
setCurrentCircleFocus(true);
setShareMode(SHARE_NONE);
}
void SpiralScene::setPlayState(PlayState state)
{
switch (state)
{
case NOT_PLAYING:
mDoRender = true;
Utils::setKeepScreenOn(false);
break;
case PLAYING:
mDoRender = true;
Utils::setKeepScreenOn(true);
break;
case RECORDING:
mDoRender = true;
Utils::setKeepScreenOn(true);
break;
case DONE_PLAYING:
mDoRender = true;
Utils::setKeepScreenOn(false);
break;
case PLAYING_SEQUENCE:
mDoRender = false;
Utils::setKeepScreenOn(true);
break;
}
mPlayState = state;
emit playStateChanged();
}
void SpiralScene::setShareMode(ShareMode shareMode)
{
mShareMode = shareMode;
emit shareModeChanged();
}
void SpiralScene::addCirclesToScene()
{
for (auto& circle : mCircles)
circle->addToScene();
}
void SpiralScene::removeCirclesFromScene()
{
for (auto& circle : mCircles)
circle->removeFromScene();
}
void SpiralScene::resetCircles()
{
if (mCircles.empty())
return;
QPointF center = boundingRect().center();
mCircles[0]->setCenter(center);
for (unsigned i = 1; i < mCircles.size(); ++i)
{
auto& circle = mCircles[i];
auto& prev = mCircles[i - 1];
center.ry() -= prev->getRadius() + circle->getRadius();
circle->setCenter(center);
}
}
void SpiralScene::resetScene()
{
for (auto& [_, line] : mLines)
line.mLinePoints.clear();
removeCirclesFromScene();
mClearScene = true;
resetCircles();
addCirclesToScene();
mScaleFactor = 1.0;
setScale(mScaleFactor);
update();
setSharingInProgress(false);
mShareMediaUri.clear();
}
void SpiralScene::selectCircle(Circle* circle)
{
const auto it = std::find_if(mCircles.begin(), mCircles.end(), [circle](const auto& c){
return c.get() == circle;
});
if (it == mCircles.end())
return;
const unsigned index = it - mCircles.begin();
if (index != mCurrentIndex)
{
setCurrentCircleFocus(false);
setCurrentIndex(index);
setCurrentCircleFocus(true);
}
}
ScopedLine SpiralScene::addLine(QObject* object, const QColor& color, int lineWidth, const QPointF& startPoint)
{
Q_ASSERT(!mLines.count(object));
Line& line = mLines[object];
line.mColor = color;
line.mLineWidth = lineWidth;
line.mLinePoints.reserve(256);
line.mLinePoints.push_back(startPoint);
return std::forward<ScopedLine>(ScopedLine(&line, [this, object]{ mLines.erase(object); }));
}
QSGNode* SpiralScene::updatePaintNode(QSGNode* oldNode, UpdatePaintNodeData*)
{
if (!mDoRender)
return oldNode;
QSGNode* sceneRoot = (oldNode ? oldNode : new QSGNode);
if (mClearScene)
{
for (auto& [_, line] : mLines)
line.mRoot = nullptr;
delete sceneRoot;
sceneRoot = new QSGNode;
mSceneRect = {};
mClearScene = false;
}
for (auto& [_, line] : mLines)
{
if (line.mLinePoints.size() < 2)
continue;
if (!line.mRoot)
{
line.mRoot = new QSGNode;
line.mRoot->setFlag(QSGNode::OwnedByParent);
sceneRoot->appendChildNode(line.mRoot);
}
auto* node = createLineNode(line);
node->setFlag(QSGNode::OwnedByParent);
line.mRoot->appendChildNode(node);
QPointF p = line.mLinePoints.back();
line.mLinePoints.clear();
line.mLinePoints.push_back(p);
}
if (mPlayState == PLAYING_SEQUENCE)
{
mDoRender = false;
emit sequenceFramePlayed();
}
return sceneRoot;
}
QSGNode* SpiralScene::createLineNode(Line& line)
{
auto* node = new QSGGeometryNode;
auto* geometry = new QSGGeometry(QSGGeometry::defaultAttributes_Point2D(), line.mLinePoints.size());
geometry->setLineWidth(line.mLineWidth);
geometry->setDrawingMode(QSGGeometry::DrawLineStrip);
node->setGeometry(geometry);
node->setFlag(QSGNode::OwnsGeometry);
line.setNodeMaterial(node);
auto* vertices = geometry->vertexDataAsPoint2D();
for (int unsigned i = 0; i < line.mLinePoints.size(); ++i)
{
const QPointF& p = line.mLinePoints[i];
vertices[i].set(p.x(), p.y());
updateSceneRect(p);
}
node->markDirty(QSGNode::DirtyGeometry);
mStats.mLineSegmentCount += line.mLinePoints.size() - 1;
mStats.mLinePointsSum += line.mLinePoints.size();
++mStats.mLineCount;
return node;
}
void SpiralScene::updateSceneRect(const QPointF& p)
{
const qreal x = std::clamp(p.x(), 0.0, size().width());
const qreal y = std::clamp(p.y(), 0.0, size().height());
if (mSceneRect.isNull())
{
mSceneRect = QRectF(QPointF(x, y), QSizeF(1, 1));
return;
}
if (x < mSceneRect.left())
mSceneRect.setLeft(x);
else if (x > mSceneRect.right())
mSceneRect.setRight(x);
if (y < mSceneRect.top())
mSceneRect.setTop(y);
else if (y > mSceneRect.bottom())
mSceneRect.setBottom(y);
}
void SpiralScene::touchEvent(QTouchEvent* event)
{
switch (event->type())
{
case QEvent::TouchCancel:
event->accept();
return;
case QEvent::TouchBegin:
case QEvent::TouchEnd:
case QEvent::TouchUpdate:
break;
default:
qWarning() << "Unknown touch event:" << event->type();
return;
}
QTouchEvent* touch = static_cast<QTouchEvent*>(event);
if (touch->points().size() == 2)
{
const QEventPoint& p1 = touch->points()[0];
const QEventPoint& p2 = touch->points()[1];
const qreal currentDist = QLineF(p1.position(), p2.position()).length();
const qreal startDist = QLineF(p1.pressPosition(), p2.pressPosition()).length();
qreal currentScaleFactor = currentDist / startDist;
if (touch->touchPointStates() & QEventPoint::Released)
{
// If one finger is temporarily released, remember the current scale factor.
mScaleFactor *= currentScaleFactor;
currentScaleFactor = 1.0;
}
setScale(mScaleFactor * currentScaleFactor);
}
event->accept();
}
bool SpiralScene::saveImage(const QRectF cutRect, const QString subDir, const QString& baseNameSuffix,
const SavedCallback& savedCallback)
{
QString picPath;
try {
picPath = Utils::getPicturesPath(subDir);
} catch (RuntimeException& e) {
emit message(e.msg());
return false;
}
if (picPath.isEmpty())
{
emit message("Cannot save file.");
return false;
}
const QString baseFileName = Utils::createPictureFileName(baseNameSuffix);
const QString fileName = picPath + "/" + baseFileName;
if (QFile::exists(fileName))
{
emit message(QString("Failed to create: %1").arg(fileName));
return false;
}
const QRectF grabRect = cutRect.isNull() ? mSceneRect : cutRect;
mSceneGrabber = createSceneGrabber(grabRect);
const bool grabbed = mSceneGrabber->grabScene(
[this, fileName, baseFileName, savedCallback](const QImage& img){
if (img.save(fileName))
{
qDebug() << "Saved file:" << fileName;
emit statusUpdate(QString("Image saved: %1").arg(baseFileName));
Utils::scanMediaFile(fileName);
if (savedCallback)
savedCallback(true);
}
else
{
emit message(QString("Failed to save: %1").arg(fileName));
setSharingInProgress(false);
if (savedCallback)
savedCallback(false);
}
});
if (!grabbed)
emit message("Failed to grab image.");
return grabbed;
}
void SpiralScene::share()
{
switch (mShareMode)
{
case SHARE_PIC:
shareImage();
break;
case SHARE_GIF:
case SHARE_VIDEO:
shareVideo();
break;
case SHARE_NONE:
qDebug() << "Nothing to share";
break;
}
}
void SpiralScene::shareImage()
{
setSharingInProgress(true);
if (!mShareMediaUri.isEmpty())
{
qDebug() << "Share content uri available:" << mShareMediaUri;
shareMedia();
}
else
{
if (!saveImage())
setSharingInProgress(false);
}
}
void SpiralScene::shareMedia()
{
Q_ASSERT(!mShareMediaUri.isEmpty());
SpiralConfig cfg(mCircles, mDefaultCircleRadius);
const QString configAppUri = cfg.getConfigAppUri();
QString mimeType;
switch (mShareMode)
{
case SHARE_PIC:
mimeType = "image/jpg";
break;
case SHARE_GIF:
mimeType = "image/gif";
break;
case SHARE_VIDEO:
mimeType = "video/mp4";
break;
case SHARE_NONE:
qWarning() << "Nothing to share";
return;
}
Utils::shareMedia(mShareMediaUri, configAppUri, mimeType);
}
bool SpiralScene::hasVideoTypeShareMode() const
{
return mShareMode == SHARE_GIF || mShareMode == SHARE_VIDEO;
}
void SpiralScene::shareVideo()
{
if (!hasVideoTypeShareMode() || mShareMediaUri.isEmpty())
{
qDebug() << "No video to share";
return;
}
setSharingInProgress(true);
shareMedia();
setSharingInProgress(false);
}
void SpiralScene::handleMediaScannerFinished(const QString& contentUri)
{
if (mShareMediaUri.isEmpty() && (hasVideoTypeShareMode() || mSharingInProgress))
{
mShareMediaUri = contentUri;
qDebug() << "Content sharing URI:" << contentUri << "share mode:" << mShareMode;
}
if (!mSharingInProgress)
return;
if (!contentUri.isEmpty())
shareMedia();
else
qDebug() << "No content URI for sharing";
setSharingInProgress(false);
}
void SpiralScene::setSharingInProgress(bool inProgress)
{
if (inProgress != mSharingInProgress)
{
qDebug() << "Sharing in progress:" << inProgress;
mSharingInProgress = inProgress;
emit sharingInProgressChanged();
}
}
void SpiralScene::handleReceivedAndroidIntent(const QString& uri)
{
stop();
SpiralConfig cfg(mCircles, mDefaultCircleRadius);
try {
CircleConfigList circleCfg = cfg.decodeConfigAppUri(uri);
if (!circleCfg.empty())
{
setupCircles(circleCfg);
}
} catch (RuntimeException& e) {
emit message(QString("Broken link: %1").arg(e.msg()));
}
}
void SpiralScene::saveConfig()
{
const QSize imageSize = size().scaled(CFG_IMAGE_SIZE, CFG_IMAGE_SIZE, Qt::KeepAspectRatioByExpanding).toSize();
auto grabResult = grabToImage(imageSize);
if (!grabResult)
{
emit message("Failed to grab image.");
return;
}
QObject::connect(grabResult.get(), &QQuickItemGrabResult::ready, this,
[this, grabResult]{
const QImage img = grabResult->image();
const QImage thumbnail = Utils::createThumbnail(img, size(), mSceneRect, CFG_IMAGE_SIZE);
SpiralConfig cfg(mCircles, mDefaultCircleRadius);
try {
cfg.save(thumbnail);
emit statusUpdate("Config saved");
} catch (RuntimeException& e) {
emit message(e.msg());
}
});
}
QObjectList SpiralScene::getConfigFileList()
{
mConfigFileList.clear();
SpiralConfig cfg(mCircles, mDefaultCircleRadius);
QObjectList l;
try {
l = cfg.getConfigFiles();
} catch (RuntimeException& e) {
emit message(e.msg());
return {};
}
// The listview in QML needs raw pointers.
// Wrap them in unique pointers so we can cleanup next time.
for (auto obj : l)
mConfigFileList.emplace_back(obj);
return l;
}
void SpiralScene::loadConfig(const QString& fileName)
{
SpiralConfig cfg(mCircles, mDefaultCircleRadius);
try {
const CircleConfigList circleCfgList = cfg.load(fileName);
if (!circleCfgList.empty())
setupCircles(circleCfgList);
} catch (RuntimeException& e) {
emit message(e.msg());
}
}
void SpiralScene::deleteConfig(const QStringList& fileNameList)
{
SpiralConfig cfg(mCircles, mDefaultCircleRadius);
cfg.remove(fileNameList);
}
QStringList SpiralScene::getCircleColorList() const
{
QStringList colorList;
for (const auto& c : mCircles)
{
const QString colorName = c->getColor().name();
colorList.push_back(colorName);
}
return colorList;
}
QRectF SpiralScene::getMaxSceneRect() const
{
Q_ASSERT(!mCircles.empty());
qreal halfSize = mCircles[0]->getRadius();
for (unsigned i = 1; i < mCircles.size(); ++i)
halfSize += mCircles[i]->getDiameter();
const QPointF& center = mCircles[0]->getCenter();
const qreal x = center.x() - halfSize;
const qreal y = center.y() - halfSize;
return QRectF(x, y, halfSize * 2, halfSize * 2) & boundingRect();
}
std::unique_ptr<SceneGrabber> SpiralScene::createSceneGrabber(const QRectF& rect)
{
return std::make_unique<SceneGrabber>(this, rect);
}