Krita Source Code Documentation
Loading...
Searching...
No Matches
recorderdocker_dock.cpp
Go to the documentation of this file.
1/*
2 * SPDX-FileCopyrightText: 2019 Shi Yan <billconan@gmail.net>
3 * SPDX-FileCopyrightText: 2020 Dmitrii Utkin <loentar@gmail.com>
4 *
5 * SPDX-License-Identifier: LGPL-2.1-only
6 */
7
9#include "recorder_config.h"
10#include "recorder_writer.h"
11#include "recorder_const.h"
12#include "ui_recorderdocker.h"
14#include "recorder_export.h"
17
18#include <klocalizedstring.h>
19#include <kactioncollection.h>
20#include "kcolorscheme.h"
21
22#include <kis_action_registry.h>
23#include <kis_canvas2.h>
24#include <kis_icon_utils.h>
25#include <kis_statusbar.h>
26#include <KisDocument.h>
27#include <KisViewManager.h>
28#include <KoDocumentInfo.h>
29#include <KisPart.h>
30#include <KisKineticScroller.h>
31#include "KisMainWindow.h"
32#include "KoFileDialog.h"
33
34#include <QFileInfo>
35#include <QPointer>
36#include <QMessageBox>
37#include <QTimer>
38#include <QRegularExpression>
39
40#ifdef Q_OS_ANDROID
41#include <QDir>
42#include <QFile>
43#include <QThreadPool>
44#endif
45
46namespace
47{
48const QString keyActionRecordToggle = "recorder_record_toggle";
49const QString keyActionExport = "recorder_export";
50
51#if QT_VERSION > QT_VERSION_CHECK(6, 0, 0)
52QString activeColorPositive;
53QString activeColorNeutral;
54QString activeColorNegative;
55QString colorNormal;
56QString inactiveColorPositive;
57QString inactiveColorNeutral;
58QString inactiveColorNegative;
59
60QColor textColorNeutral;
61QColor buttonColorNeutral;
62QColor textColorNegative;
63QColor buttonColorNegative;
64#else
65const QString activeColorPositive("#5cab25");
66const QString activeColorNeutral("#ca8f14");
67const QString activeColorNegative("#da4453");
68const QString colorNormal("#3e3e3e");
69const QString inactiveColorPositive("#b4e196");
70const QString inactiveColorNeutral("#ffe5af");
71const QString inactiveColorNegative("#f2c4c9");
72
73const QColor textColorNeutral(0xff, 0xe5, 0xaf);
74const QColor buttonColorNeutral(0xca, 0x8f, 0x14);
75const QColor textColorNegative(0xf2, 0xc4, 0xc9);
76const QColor buttonColorNegative(0xda, 0x44, 0x53);
77#endif
78
79}
80
81
83{
84public:
86 QScopedPointer<Ui::RecorderDocker> ui;
91
92 QAction *recordToggleAction = nullptr;
93 QAction *exportAction = nullptr;
94
96 QString prefix;
98 double captureInterval = 0.;
100 int quality = 0;
101 int compression = 0;
102 int resolution = 0;
106 bool focusedRecord = false;
107
108 bool paused = true;
109#ifdef Q_OS_ANDROID
110 bool internalMoveInProgress{false};
111#endif
114
117
118 QMap<QString, bool> enabledIds;
119
121 : q(q_ptr)
122 , ui(new Ui::RecorderDocker())
123 , writer(es)
124 , statusBarLabel(new QLabel())
125 , statusBarWarningLabel(new QLabel())
126 {
128 statusBarWarningLabel->setPixmap(KisIconUtils::loadIcon("warning").pixmap(16, 16));
129 statusBarWarningLabel->hide();
130 warningTimer.setInterval(10000);
131 warningTimer.setSingleShot(true);
132 pausedTimer.setSingleShot(true);
133 connect(&warningTimer, SIGNAL(timeout()), q, SLOT(onWarningTimeout()));
134 connect(&pausedTimer, SIGNAL(timeout()), q, SLOT(onPausedTimeout()));
135 }
136
137 // For technical reasons recorder can not capture an image that is larger than 2^31 - 1 bytes in size, It is also
138 // kinda absurd that you'd even want to do it, so we just shouldn't support it
140 {
141 QSize imageSize = canvas->image()->size();
142
143 // We always convert to RGBA8, so can assume 4 bytes/pixel
144 quint64 totalSize = (quint64)imageSize.width() * (quint64)imageSize.height() * 4;
145
146 return totalSize <= 2147483647;
147 }
148
150 {
151 RecorderConfig config(true);
153#ifdef Q_OS_ANDROID
154 fixInternalSnapshotDirectory();
155#endif
157 format = config.format();
158 quality = config.quality();
159 compression = config.compression();
160 resolution = config.resolution();
164 q->exportSettings->lockFps = true;
166 }
169 focusedRecord = config.focusedRecord();
170
172 }
173
175 {
176 RecorderExportConfig config(true);
177 q->exportSettings->fps = config.fps();
178 }
179
181 int index = 0;
182 QString title;
183 QString hint;
184 int minValue = 0;
185 int maxValue = 0;
186 QString suffix;
187 int factor = 0;
188 switch (format) {
190 index = 0;
191 title = i18nc("Title for label. JPEG Quality level", "Quality:");
192 hint = i18nc("@tooltip", "Greater value will produce a larger file and a better quality. Doesn't affect CPU consumption.\nValues lower than 50 are not recommended due to high artifacts.");
193 minValue = 1;
194 maxValue = 100;
195 suffix = "%";
196 factor = quality;
197 break;
199 index = 1;
200 title = i18nc("Title for label. PNG Compression level", "Compression:");
201 hint = i18nc("@tooltip", "Greater value will produce a smaller file but will require more from your CPU. Doesn't affect quality.\nCompression set to 0 is not recommended due to high disk space consumption.\nValues above 3 are not recommended due to high performance impact.");
202 minValue = 0;
203 maxValue = 5;
204 suffix = "";
205 factor = compression;
206 break;
207 }
208
209 ui->comboFormat->setCurrentIndex(index);
210 ui->labelQuality->setText(title);
211 ui->spinQuality->setToolTip(hint);
212 QSignalBlocker blocker(ui->spinQuality);
213 ui->spinQuality->setMinimum(minValue);
214 ui->spinQuality->setMaximum(maxValue);
215 ui->spinQuality->setValue(factor);
216 ui->spinQuality->setSuffix(suffix);
217 }
218
220 QString title;
221 double minValue = 0;
222 double maxValue = 0;
223 double value = 0;
224 int decimals = 0;
225 QString suffix;
226 QSignalBlocker blocker(ui->spinRate);
227
229 title = i18nc("Title for label. Video frames per second", "Video FPS:");
230 minValue = 1;
231 maxValue = 60;
232 decimals = 0;
234 suffix = "";
235 disconnect(ui->spinRate, SIGNAL(valueChanged(double)), q, SLOT(onCaptureIntervalChanged(double)));
236 connect(ui->spinRate, SIGNAL(valueChanged(double)), q, SLOT(onVideoFPSChanged(double)));
237 } else {
238 title = i18nc("Title for label. Capture rate", "Capture interval:");
239 minValue = 0.10;
240 maxValue = 100.0;
241 decimals = 1;
243 suffix = " sec.";
244 disconnect(ui->spinRate, SIGNAL(valueChanged(double)), q, SLOT(onVideoFPSChanged(double)));
245 connect(ui->spinRate, SIGNAL(valueChanged(double)), q, SLOT(onCaptureIntervalChanged(double)));
246 }
247
248 ui->labelRate->setText(title);
249 ui->spinRate->setDecimals(decimals);
250 ui->spinRate->setMinimum(minValue);
251 ui->spinRate->setMaximum(maxValue);
252 ui->spinRate->setSuffix(suffix);
253 ui->spinRate->setValue(value);
254 }
255
257 {
258 outputDirectory = snapshotDirectory % QDir::separator() % prefix % QDir::separator();
259 writer.setup({
261 format,
262 quality,
269 }
270
271 QString getPrefix()
272 {
273 return !canvas ? ""
274 : canvas->imageView()->document()->documentInfo()->aboutInfo("creation-date").remove(QRegularExpression("[^0-9]"));
275 }
276
277 void updateComboResolution(quint32 width, quint32 height)
278 {
279 const QStringList titles = {
280 i18nc("Use original resolution for the frames when recording the canvas", "Original"),
281 i18nc("Use the resolution two times smaller than the original resolution for the frames when recording the canvas", "Half"),
282 i18nc("Use the resolution four times smaller than the original resolution for the frames when recording the canvas", "Quarter")
283 };
284
285 QStringList items;
286 for (int index = 0, len = titles.length(); index < len; ++index) {
287 int divider = 1 << index;
288 items += QString("%1 (%2x%3)").arg(titles[index])
289 .arg((width / divider) & ~1)
290 .arg((height / divider) & ~1);
291 }
292 QSignalBlocker blocker(ui->comboResolution);
293 const int currentIndex = ui->comboResolution->currentIndex();
294 ui->comboResolution->clear();
295 ui->comboResolution->addItems(items);
296 ui->comboResolution->setCurrentIndex(currentIndex);
297 }
298
299 void updateRecordStatus(bool isRecording)
300 {
301 QSignalBlocker blocker(ui->buttonRecordToggle);
302 recordToggleAction->setChecked(isRecording);
303 recordToggleAction->setEnabled(true);
304
305 ui->buttonRecordToggle->setChecked(isRecording);
306 ui->buttonRecordToggle->setIcon(KisIconUtils::loadIcon(isRecording ? "media-playback-stop" : "media-record"));
307 ui->buttonRecordToggle->setText(isRecording ? i18nc("Stop recording the canvas", "Stop")
308 : i18nc("Start recording the canvas", "Record"));
309
310 if (canRecord()) {
311 ui->buttonRecordToggle->setEnabled(true);
312 ui->buttonRecordToggle->setToolTip("");
313 } else {
314 ui->buttonRecordToggle->setEnabled(false);
315 ui->buttonRecordToggle->setToolTip(i18n("Image too large to be recorded"));
316 }
317 ui->widgetSettings->setEnabled(!isRecording);
318
319 statusBarLabel->setVisible(isRecording);
320
321 if (!canvas)
322 return;
323
324 KisStatusBar *statusBar = canvas->viewManager()->statusBar();
325 if (isRecording) {
327 statusBar->addExtraWidget(statusBarLabel);
329 } else {
332 }
333 }
334
336 {
337 uint threads = writer.recorderThreads.get();
338 uint threadsInUse = writer.recorderThreads.getUsed();
339 QString label("<font style='letter-spacing:-4px'>");
340 QString threadColor;
341 for (unsigned int threadNr = 1; threadNr <= ThreadSystemValue::MaxThreadCount ; threadNr++)
342 {
343 if (threadNr > threads) {
344 threadColor = colorNormal;
345 } else if (threadNr > ThreadSystemValue::MaxRecordThreadCount) {
346 threadColor = threadNr <= threadsInUse ? activeColorNegative : inactiveColorNegative;
347 } else if (threadNr > ThreadSystemValue::IdealRecordThreadCount) {
348 threadColor = threadNr <= threadsInUse ? activeColorNeutral : inactiveColorNeutral;
349 } else {
350 threadColor = threadNr <= threadsInUse ? activeColorPositive : inactiveColorPositive;
351 }
352 label.append(QString("<font color='%1'>▍</font>").arg(threadColor));
353 }
354 // don't remove empty <font></font> tag else label will jump a few pixels around
355 label.append(QString("</font><font> %1 </font><font color='%2'>●</font>")
356 .arg(i18nc("Recording symbol", "REC"))
357 .arg(paused ? "" : activeColorNegative));
358 statusBarLabel->setText(label);
359 statusBarLabel->setToolTip(paused ? i18n("Recorder is paused") : QString(i18n("Active recording with %1 of %2 available threads")).arg(threadsInUse).arg(threads));
360 }
361
362 void showWarning(const QString &hint) {
363 if (statusBarWarningLabel->isHidden()) {
364 statusBarWarningLabel->setToolTip(hint);
365 statusBarWarningLabel->show();
366 warningTimer.start();
367 }
368 }
369
371 {
372 QString toolTipText;
373 auto threads = writer.recorderThreads.get();
375 // Number of threads exceeds ideal thread count
376 // -> switch color of threads slider and spin wheel to red
377 QPalette pal;
378 pal.setColor(QPalette::Text, textColorNegative);
379 pal.setColor(QPalette::Button, buttonColorNegative);
380 ui->spinThreads->setPalette(pal);
381 ui->sliderThreads->setPalette(pal);
382 toolTipText = QString(
383 i18n("Set the number of recording threads.\nThe number of threads exceeds the ideal max number of your hardware setup.\nPlease be aware, that a number greater than %1 probably won't give you any performance boost.")
385 } else if (threads > ThreadSystemValue::IdealRecordThreadCount) {
386 // Number of threads exceeds ideal recorder thread count
387 // -> switch color of threads slider and spin wheel to orange
388 QPalette pal;
389 pal.setColor(QPalette::Text, textColorNeutral);
390 pal.setColor(QPalette::Button, buttonColorNeutral);
391 ui->spinThreads->setPalette(pal);
392 ui->sliderThreads->setPalette(pal);
393 toolTipText = QString(
394 i18n("Set the number of recording threads.\nAccording to your hardware setup you should record with no more than %1 threads.\nYou can play around with one or two more threads, but keep an eye on your overall system performance.")
396 } else {
397 ui->spinThreads->setPalette(threadsSpinPalette);
398 ui->sliderThreads->setPalette(threadsSliderPalette);
399 toolTipText = i18n("Set the number of threads to be used for recording.");
400 }
401 ui->spinThreads->setToolTip(toolTipText);
402 ui->sliderThreads->setToolTip(toolTipText);
403 }
404
405#ifdef Q_OS_ANDROID
406 void fixInternalSnapshotDirectory()
407 {
408 // Older versions of Krita used an internal directory as the snapshots
409 // directory by default, which is a bogus place to save stuff to because
410 // the user can't access it. That means the files stored there are stuck
411 // inaccessible and once the user picks a "real" directory, they can no
412 // longer even delete the files. So here we're rectifying the situation.
413 if (snapshotDirectory == RecorderConfig::defaultInternalSnapshotDirectory()) {
414 // Internal path got persisted to settings. Clear that out, replace
415 // it with the default of nothing.
416 snapshotDirectory = QString();
417 } else {
418 q->moveFilesFromInternalSnapshotDirectory();
419 }
420 }
421#endif
422};
423
425 : QDockWidget(i18nc("Title of the docker", "Recorder"))
426 , exportSettings(new RecorderExportSettings())
427 , d(new Private(*exportSettings, this))
428{
429 QWidget* page = new QWidget(this);
430 d->ui->setupUi(page);
431
432 d->ui->buttonManageRecordings->setIcon(KisIconUtils::loadIcon("configure-thicker"));
433 d->ui->buttonBrowse->setIcon(KisIconUtils::loadIcon("folder"));
434 d->ui->buttonRecordToggle->setIcon(KisIconUtils::loadIcon("media-record"));
435 d->ui->buttonExport->setIcon(KisIconUtils::loadIcon("export-timelapse"));
436 d->ui->sliderThreads->setTickPosition(QSlider::TickPosition::TicksBelow);
437 d->ui->sliderThreads->setMinimum(1);
438 d->ui->sliderThreads->setMaximum(ThreadSystemValue::MaxThreadCount);
439 d->ui->spinThreads->setMinimum(1);
440 d->ui->spinThreads->setMaximum(ThreadSystemValue::MaxThreadCount);
441 d->threadsSpinPalette = d->ui->spinThreads->palette();
442 d->threadsSliderPalette = d->ui->sliderThreads->palette();
443
444 d->loadSettings();
446 d->updateThreadUi();
447
448 d->ui->editDirectory->setText(d->snapshotDirectory);
449 d->ui->spinQuality->setValue(d->quality);
450 d->ui->spinThreads->setValue(d->writer.recorderThreads.get());
451 d->ui->comboResolution->setCurrentIndex(d->resolution);
452 d->ui->checkBoxRealTimeCaptureMode->setChecked(d->realTimeCaptureMode);
453 d->ui->checkBoxRecordIsolateMode->setChecked(d->recordIsolateLayerMode);
454 d->ui->checkBoxAutoRecord->setChecked(d->recordAutomatically);
455 d->ui->checkBoxFocusedRecord->setChecked(d->focusedRecord);
456
458 d->recordToggleAction = actionRegistry->makeQAction(keyActionRecordToggle, this);
459 d->exportAction = actionRegistry->makeQAction(keyActionExport, this);
460
461 connect(d->recordToggleAction, SIGNAL(toggled(bool)), d->ui->buttonRecordToggle, SLOT(setChecked(bool)));
462 connect(d->exportAction, SIGNAL(triggered()), d->ui->buttonExport, SIGNAL(clicked()));
463 connect(d->ui->buttonRecordToggle, SIGNAL(toggled(bool)), d->ui->buttonExport, SLOT(setDisabled(bool)));
465 d->ui->buttonExport->setDisabled(true);
466
467 // Need to register toolbar actions before attaching canvas else it wont appear after restart.
468 // Is there any better way to do this?
469 connect(KisPart::instance(), SIGNAL(sigMainWindowIsBeingCreated(KisMainWindow *)),
471
472 connect(d->ui->buttonManageRecordings, SIGNAL(clicked()), this, SLOT(onManageRecordingsButtonClicked()));
473 connect(d->ui->buttonBrowse, SIGNAL(clicked()), this, SLOT(slotSelectSnapshotDirectory()));
474 connect(d->ui->comboFormat, SIGNAL(currentIndexChanged(int)), this, SLOT(onFormatChanged(int)));
475 connect(d->ui->spinQuality, SIGNAL(valueChanged(int)), this, SLOT(onQualityChanged(int)));
476 connect(d->ui->spinThreads, SIGNAL(valueChanged(int)), this, SLOT(onThreadsChanged(int)));
477 connect(d->ui->comboResolution, SIGNAL(currentIndexChanged(int)), this, SLOT(onResolutionChanged(int)));
478 connect(d->ui->checkBoxRealTimeCaptureMode, SIGNAL(toggled(bool)), this, SLOT(onRealTimeCaptureModeToggled(bool)));
479 connect(d->ui->checkBoxRecordIsolateMode, SIGNAL(toggled(bool)), this, SLOT(onRecordIsolateLayerModeToggled(bool)));
480 connect(d->ui->checkBoxAutoRecord, SIGNAL(toggled(bool)), this, SLOT(onAutoRecordToggled(bool)));
481 connect(d->ui->buttonRecordToggle, SIGNAL(toggled(bool)), this, SLOT(onRecordButtonToggled(bool)));
482 connect(d->ui->buttonExport, SIGNAL(clicked()), this, SLOT(onExportButtonClicked()));
483
484 connect(d->ui->checkBoxFocusedRecord, SIGNAL(toggled(bool)), this, SLOT(onFocusedCaptureToggled(bool)));
485
486 connect(&d->writer.recorderThreads, SIGNAL(notifyInUseChange(bool)), this, SLOT(onActiveRecording(bool)));
487 connect(&d->writer.recorderThreads, SIGNAL(notifyInUseChange(bool)), this, SLOT(onUpdateRecIndicator()));
488 connect(&d->writer, SIGNAL(started()), this, SLOT(onWriterStarted()));
489 connect(&d->writer, SIGNAL(stopped()), this, SLOT(onWriterStopped()));
490 connect(&d->writer, SIGNAL(frameWriteFailed()), this, SLOT(onWriterFrameWriteFailed()));
491 connect(&d->writer, SIGNAL(recorderStopWarning()), this, SLOT(onRecorderStopWarning()));
492 connect(&d->writer, SIGNAL(lowPerformanceWarning()), this, SLOT(onLowPerformanceWarning()));
493
494
495 QScroller *scroller = KisKineticScroller::createPreconfiguredScroller(d->ui->scrollArea);
496 if (scroller) {
497 connect(scroller, SIGNAL(stateChanged(QScroller::State)),
498 this, SLOT(slotScrollerStateChanged(QScroller::State)));
499 }
500
501 // The system is not efficient enough for the RealTime Recording Feature
503 {
504 d->ui->checkBoxRealTimeCaptureMode->setCheckState(Qt::Unchecked);
505 d->ui->checkBoxRealTimeCaptureMode->setDisabled(true);
506 d->ui->checkBoxRealTimeCaptureMode->setToolTip(
507 i18n("Your system is not efficient enough for this feature"));
508 }
509
510 setWidget(page);
511}
512
514{
515 delete d;
516 delete exportSettings;
517}
518
519// This signal is called when the last view of a document is closed. We can use it to properly stop recording for that
520// document and create tail frame(s), knowing that it won't be called too often. Creating tail frames can be very
521// expensive, depending on how zoomed in the user is, so doing that overzealously is unviable.
523{
524 KisCanvas2 *cptr = dynamic_cast<KisCanvas2 *>(canvas);
525
526 KisCanvas2 *oldCanvas = nullptr;
527 if (d->canvas != cptr) {
528 oldCanvas = d->canvas;
529 setCanvas(canvas);
530 }
531
532 d->writer.stop(false, true);
533
534 if (oldCanvas) {
535 setCanvas((KoCanvasBase *)oldCanvas);
536 d->writer.start(false, false);
537 }
538}
539
540// This is called whenever a tab is switched, be that when a user clicks on a tab, or another tab closing, so we only do
541// basic recorder state save. We can not rely on this function to create tail frames, as it's called too often
543{
544 setEnabled(canvas != nullptr);
545
546 if (d->canvas == canvas)
547 return;
548
549 d->canvas = dynamic_cast<KisCanvas2*>(canvas);
551
552 if (!d->canvas)
553 return;
554
555 connect(d->canvas->imageView(),
556 SIGNAL(sigDocumentAboutToClose(KoCanvasBase *)),
557 this,
559 Qt::UniqueConnection);
560
561 KisDocument *document = d->canvas->imageView()->document();
562 d->updateComboResolution(document->image()->width(), document->image()->height());
563
564 d->prefix = d->getPrefix();
565 bool wasToggled = false;
566 if (d->recordAutomatically && !d->snapshotDirectory.isEmpty()
567 && !d->enabledIds.contains(document->linkedResourcesStorageId()) && d->canRecord()) {
568 wasToggled = onRecordButtonToggled(true);
569 }
570 if (!wasToggled) { // onRecordButtonToggled(true) may call these, don't call them twice.
572 d->updateUiFormat();
573 }
575
576 bool enabled = d->enabledIds.value(document->linkedResourcesStorageId(), false);
577 d->writer.setEnabled(enabled);
578 d->updateRecordStatus(enabled);
579}
580
581// This function is only called when the last document/canvas is closed, in all other cases setCanvas is called instead.
583{
584 d->updateRecordStatus(false);
585 d->recordToggleAction->setChecked(false);
586 setEnabled(false);
587 d->writer.stop(true, false);
588 d->writer.setCanvas(nullptr);
589 d->canvas = nullptr;
590 d->enabledIds.clear();
591}
592
594{
595 KisKActionCollection *actionCollection = window->viewManager()->actionCollection();
596 actionCollection->addAction(keyActionRecordToggle, d->recordToggleAction);
597 actionCollection->addAction(keyActionExport, d->exportAction);
598
599#if QT_VERSION > QT_VERSION_CHECK(6, 0, 0)
600 connect(window, SIGNAL(themeChanged()), this, SLOT(onThemeChanged()));
602#endif
603}
604
606{
607#if QT_VERSION > QT_VERSION_CHECK(6, 0, 0)
608 KColorScheme activeScheme(QPalette::Active, KColorScheme::Window);
609 activeColorPositive = activeScheme.foreground(KColorScheme::PositiveText).color().name();
610 activeColorNeutral = activeScheme.foreground(KColorScheme::NeutralText).color().name();
611 activeColorNegative = activeScheme.foreground(KColorScheme::NegativeText).color().name();
612
613 KColorScheme disabledScheme(QPalette::Disabled, KColorScheme::Window);
614 inactiveColorPositive = disabledScheme.foreground(KColorScheme::PositiveText).color().name();
615 inactiveColorNeutral = disabledScheme.foreground(KColorScheme::NeutralText).color().name();
616 inactiveColorNegative = disabledScheme.foreground(KColorScheme::NegativeText).color().name();
617 colorNormal = disabledScheme.foreground(KColorScheme::NormalText).color().name();
618
619 textColorNeutral = activeScheme.foreground(KColorScheme::NeutralText).color();
620 buttonColorNeutral = activeScheme.background(KColorScheme::NeutralBackground).color();
621 textColorNegative = activeScheme.foreground(KColorScheme::NegativeText).color();
622 buttonColorNegative = activeScheme.background(KColorScheme::NegativeBackground).color();
623
624 d->updateThreadUi();
626#endif
627}
628
630{
631 QSignalBlocker blocker(d->ui->buttonRecordToggle);
632
633 // Ask the user to pick a directory if we don't have one. This should only
634 // happen on Android, other operating systems have a non-empty default that
635 // the user is not able to clear out via the user interface.
636 if (checked && d->snapshotDirectory.isEmpty()) {
638 if (d->snapshotDirectory.isEmpty()) {
639 d->ui->buttonRecordToggle->setChecked(false);
640 d->recordToggleAction->setChecked(false);
641 return false;
642 }
643 }
644
645 d->recordToggleAction->setChecked(checked);
646
647 if (!d->canvas) {
648 return false;
649 }
650
651 const QString &id = d->canvas->imageView()->document()->linkedResourcesStorageId();
652
653 bool wasEmpty = !d->enabledIds.values().contains(true);
654
655 d->enabledIds[id] = checked;
656
657 bool isEmpty = !d->enabledIds.values().contains(true);
658
659 d->writer.setEnabled(checked);
660
661 if (isEmpty == wasEmpty) {
662 d->updateRecordStatus(checked);
663 if (checked) {
666 } else {
667 d->writer.saveState();
668 }
669 return false;
670 }
671
672 d->ui->buttonRecordToggle->setEnabled(false);
673
674 if (checked) {
676 d->updateUiFormat();
677 d->writer.start(true, true);
678
679 // Calculate Rec symbol activity timeout depending on the capture interval
680 // The pausedTimer interval is set to a slightly greater value than the capture interval
681 // to avoid flickering for ongoing painting. This is also the reason for the min and max
682 // values 305 and 2005 (instead of 300 and 2000, respectively).
683 if (d->realTimeCaptureMode) {
684 d->pausedTimer.setInterval(qBound(305, static_cast<int>(1000.0/static_cast<double>(exportSettings->fps)) + 5,2005));
685 } else {
686 d->pausedTimer.setInterval(qBound(305, static_cast<int>(qMax(d->captureInterval, .1) * 1000.0) + 5, 2005));
687 }
688 } else {
689 d->writer.stop(true, true);
690 d->warningTimer.stop();
691 d->pausedTimer.stop();
692 d->statusBarWarningLabel->hide();
693 d->paused = true;
694 }
695
696 return true;
697}
698
700{
701 if (!d->canvas)
702 return;
703
704 KisDocument *document = d->canvas->imageView()->document();
705
706#ifndef Q_OS_ANDROID
707 exportSettings->videoFileName = QFileInfo(document->caption().trimmed()).completeBaseName();
708#endif
712
713 RecorderExport exportDialog(exportSettings, this);
714 exportDialog.setup();
715 exportDialog.exec();
716
718 d->ui->spinRate->setValue(exportSettings->fps);
719}
720
722{
723 RecorderSnapshotsManager snapshotsManager(this);
724 snapshotsManager.execFor(d->snapshotDirectory);
725}
726
728{
729 KoFileDialog dialog(this, KoFileDialog::OpenDirectory, "SelectRecordingsDirectory");
730 dialog.setCaption(i18n("Select a Directory for Recordings"));
731 dialog.setDefaultDir(d->ui->editDirectory->text());
732 QString directory = dialog.filename();
733 if (!directory.isEmpty()) {
734 d->ui->editDirectory->setText(directory);
735 RecorderConfig(false).setSnapshotDirectory(directory);
736 d->loadSettings();
737 }
738}
739
741{
742 d->focusedRecord = checked;
743 RecorderConfig(false).setFocusedRecord(checked);
744 d->loadSettings();
745}
746
753
755{
756 d->recordAutomatically = checked;
758 d->loadSettings();
759}
760
772
774{
775 d->captureInterval = interval;
776 RecorderConfig(false).setCaptureInterval(interval);
777 d->loadSettings();
778}
785
787{
788 switch (d->format) {
790 d->quality = value;
792 d->loadSettings();
793 break;
797 d->loadSettings();
798 break;
799 }
800}
801
803{
804 d->format = static_cast<RecorderFormat>(format);
805 d->updateUiFormat();
806
808 d->loadSettings();
809}
810
812{
813 d->resolution = resolution;
814 RecorderConfig(false).setResolution(resolution);
815 d->loadSettings();
816}
817
819{
820 d->writer.recorderThreads.set(threads);
821 RecorderConfig(false).setThreads(threads);
822 d->loadSettings();
823 d->updateThreadUi();
824}
825
830
835
840
841void RecorderDockerDock::onActiveRecording(bool valueWasIncreased)
842{
843 if (!valueWasIncreased)
844 return;
845
846 d->paused = false;
847 d->pausedTimer.start();
848}
849
855
857{
858 QMessageBox::warning(this, i18nc("@title:window", "Recorder"),
859 i18n("The recorder has been stopped due to failure while writing a frame. Please check free disk space and start the recorder again."));
860}
861
863{
864 QMessageBox::warning(this, i18nc("@title:window", "Recorder"),
865 i18n("Krita was unable to stop the recorder probably. Please try to restart Krita."));
866}
868{
869 if (d->realTimeCaptureMode) {
870 d->showWarning(i18n("Low performance warning. The recorder is not able to write all the frames in time during Real Time Capture mode.\nTry to reduce the frame rate for the ffmpeg export or reduce the scaling filtering in the canvas acceleration settings."));
871 } else {
872 d->showWarning(i18n("Low performance warning. The recorder is not able to write all the frames in time.\nTry to increase the capture interval or reduce the scaling filtering in the canvas acceleration settings."));
873 }
874}
875
880
882{
884}
885
886#ifdef Q_OS_ANDROID
887void RecorderDockerDock::moveFilesFromInternalSnapshotDirectory()
888{
889 if (!d->internalMoveInProgress) {
890 const QString &internalPath = RecorderConfig::defaultInternalSnapshotDirectory();
891 if (!d->snapshotDirectory.isEmpty() && QFileInfo::exists(internalPath)) {
892 // The user has picked a directory to record to, but the nonsense
893 // internal directory is present and may have stuff inside that
894 // would become effectively inaccessible. To fix that, we move the
895 // files over to the selected directory. Of course moving files on
896 // Android is gobsmackingly slow, so we'll have to do it in the
897 // background to not lock the UI for ages. The moving should be
898 // re-entrant, so getting interrupted and continuing later is fine.
899 qWarning().nospace() << "Moving recordings stuck in internal directory '" << internalPath
900 << "' to selected directory '" << d->snapshotDirectory << "'";
901 RecorderDockerInternalSnapshotsMover *mover =
902 new RecorderDockerInternalSnapshotsMover(internalPath, d->snapshotDirectory);
903 connect(mover,
904 &RecorderDockerInternalSnapshotsMover::sigMoveFinished,
905 this,
906 &RecorderDockerDock::slotInternalSnapshotMoveFinished,
907 Qt::QueuedConnection);
908 d->internalMoveInProgress = true;
909 QThreadPool::globalInstance()->start(mover);
910 }
911 }
912}
913
914void RecorderDockerDock::slotInternalSnapshotMoveFinished(const QString &srcRoot)
915{
916 d->internalMoveInProgress = false;
917 if (srcRoot != d->snapshotDirectory) {
918 // Directory changed meanwhile, trigger another move.
919 moveFilesFromInternalSnapshotDirectory();
920 }
921}
922
923RecorderDockerInternalSnapshotsMover::RecorderDockerInternalSnapshotsMover(const QString &srcRoot,
924 const QString &dstRoot)
925 : m_srcRoot(srcRoot)
926 , m_dstRoot(dstRoot)
927{
928}
929
930void RecorderDockerInternalSnapshotsMover::run()
931{
932 moveFromInternalSnapshotDirectory(QDir(m_srcRoot), QDir(m_dstRoot));
933 if (!QDir().rmdir(m_srcRoot)) {
934 qWarning().nospace() << "Failed to remove root directory '" << m_srcRoot << "'";
935 }
936 Q_EMIT sigMoveFinished(m_srcRoot);
937}
938
939void RecorderDockerInternalSnapshotsMover::moveFromInternalSnapshotDirectory(const QDir &src, const QDir &dst)
940{
941 for (const QFileInfo &srcInfo : src.entryInfoList(FILTERS)) {
942 QString srcName = srcInfo.fileName();
943 QString dstPath = dst.filePath(srcName);
944
945 if (srcInfo.isDir()) {
946 // Move the directory over recursively.
947 if (dst.mkpath(dstPath)) {
948 moveFromInternalSnapshotDirectory(QDir(srcInfo.filePath()), QDir(dstPath));
949 } else {
950 qWarning().nospace() << "Failed to create directory '" << dstPath << "' in '" << dst.path() << "'";
951 }
952
953 // Removal will fail if the directory is non-empty, so we
954 // can just attempt it unconditionally.
955 if (!src.rmdir(srcName)) {
956 qWarning().nospace() << "Failed to remove directory '" << srcName << "' in '" << src.path() << "'";
957 }
958
959 } else {
960 QFile srcFile(srcInfo.filePath());
961 // Rename refuses to replace files in the destination, so
962 // try to remove that first. The only reason it should
963 // already exist is if a previous attempt to move the file
964 // partially copied it and then got interrupted.
965 QFile::remove(dstPath);
966 if (!srcFile.rename(dstPath)) {
967 qWarning().nospace() << "Error " << srcFile.error() << " moving '" << srcFile.fileName() << "' to '"
968 << dstPath << "': " << srcFile.errorString();
969 }
970 }
971 }
972}
973#endif
float value(const T *src, size_t ch)
unsigned int uint
QBrush background(BackgroundRole=NormalBackground) const
QBrush foreground(ForegroundRole=NormalText) const
QAction * makeQAction(const QString &name, QObject *parent=0)
static KisActionRegistry * instance()
A container for a set of QAction objects.
Q_INVOKABLE QAction * addAction(const QString &name, QAction *action)
Main window for Krita.
KisViewManager * viewManager
static KisPart * instance()
Definition KisPart.cpp:131
void removeExtraWidget(QWidget *widget)
void addExtraWidget(QWidget *widget)
virtual KisKActionCollection * actionCollection() const
double captureInterval() const
QString snapshotDirectory() const
void setFormat(RecorderFormat value)
void setRealTimeCaptureMode(bool value)
bool recordIsolateLayerMode() const
RecorderFormat format() const
int resolution() const
void setRecordAutomatically(bool value)
void setResolution(int value)
void setCaptureInterval(double value)
void setSnapshotDirectory(const QString &value)
void setRecordIsolateLayerMode(bool value)
void setFocusedRecord(bool value)
void setCompression(int value)
bool recordAutomatically() const
void setQuality(int value)
bool realTimeCaptureMode() const
int compression() const
bool focusedRecord() const
void setThreads(int value)
int quality() const
void showWarning(const QString &hint)
Private(const RecorderExportSettings &es, RecorderDockerDock *q_ptr)
QScopedPointer< Ui::RecorderDocker > ui
void updateRecordStatus(bool isRecording)
RecorderDockerDock *const q
void updateComboResolution(quint32 width, quint32 height)
void onDocumentAboutToClose(KoCanvasBase *canvas)
void slotScrollerStateChanged(QScroller::State state)
RecorderExportSettings *const exportSettings
void onCaptureIntervalChanged(double interval)
void setCanvas(KoCanvasBase *canvas) override
void onThreadsChanged(int threads)
void onVideoFPSChanged(double interval)
void onFocusedCaptureToggled(bool checked)
void onQualityChanged(int value)
void onRecordIsolateLayerModeToggled(bool checked)
void onRealTimeCaptureModeToggled(bool checked)
void onResolutionChanged(int resolution)
bool onRecordButtonToggled(bool checked)
void onAutoRecordToggled(bool checked)
void onActiveRecording(bool valueWasIncreased)
void onMainWindowIsBeingCreated(KisMainWindow *window)
void onFormatChanged(int format)
void execFor(const QString &snapshotsDirectory)
void saveState()
Generate a tail and save the recording region.
void start(bool toggleEnabled, bool restoreState)
bool stop(bool toggleEnabled, bool saveState)
void restoreState()
Remove the tail and restore region from a file.
void setCanvas(QPointer< KisCanvas2 > canvas)
void setEnabled(bool enabled)
void setup(const RecorderWriterSettings &settings)
ThreadCounter recorderThreads
unsigned int getUsed() const
unsigned int get() const
bool set(int value)
QIcon loadIcon(const QString &name)
KRITAWIDGETUTILS_EXPORT void updateCursor(QWidget *source, QScroller::State state)
KRITAWIDGETUTILS_EXPORT QScroller * createPreconfiguredScroller(QAbstractScrollArea *target)
const unsigned int IdealRecordThreadCount
const unsigned int MaxThreadCount
const unsigned int MaxRecordThreadCount
RecorderFormat