Debian Codegraph @

avogadro/qtplugins/playertool/playertool.cpp

raw
1 /******************************************************************************
2 This source file is part of the Avogadro project.
3 This source code is released under the 3-Clause BSD License, (see "LICENSE").
4 ******************************************************************************/
5
6 #include "playertool.h"
7
8 #include <gif.h>
9 #include <gwavi.h>
10
11 #include <avogadro/core/vector.h>
12 #include <avogadro/qtgui/molecule.h>
13
14 #include <QAction>
15 #include <QOpenGLFramebufferObject>
16 #include <QOpenGLWidget>
17 #include <QtCore/QBuffer>
18 #include <QtCore/QProcess>
19 #include <QtGui/QIcon>
20 #include <QtGui/QKeyEvent>
21 #include <QtGui/QScreen>
22 #include <QtGui/QWindow>
23 #include <QtWidgets/QApplication>
24 #include <QtWidgets/QCheckBox>
25 #include <QtWidgets/QFileDialog>
26 #include <QtWidgets/QHBoxLayout>
27 #include <QtWidgets/QLabel>
28 #include <QtWidgets/QLineEdit>
29 #include <QtWidgets/QMessageBox>
30 #include <QtWidgets/QPushButton>
31 #include <QtWidgets/QSlider>
32 #include <QtWidgets/QSpinBox>
33 #include <QtWidgets/QVBoxLayout>
34
35 #include <QScreen>
36
37 #include <algorithm>
38 #include <cmath>
39
40 namespace Avogadro::QtPlugins {
41
42 using QtGui::Molecule;
43
44 PlayerTool::PlayerTool(QObject* parent_)
45 : QtGui::ToolPlugin(parent_), m_activateAction(new QAction(this)),
46 m_molecule(nullptr), m_renderer(nullptr), m_currentFrame(0),
47 m_toolWidget(nullptr), m_frameIdx(nullptr), m_firstFrameIdx(nullptr),
48 m_lastFrameIdx(nullptr), m_slider(nullptr), m_dynamicBonding(nullptr),
49 m_glWidget(nullptr), m_timer(this), m_animationFPS(nullptr),
50 playButton(nullptr)
51 {
52 QString shortcut = tr("Ctrl+9", "control-key 9");
53 m_activateAction->setText(tr("Player"));
54 m_activateAction->setToolTip(tr("Animation Tool\t(%1)").arg(shortcut));
55 setIcon();
56 }
57
58 PlayerTool::~PlayerTool() {}
59
60 void PlayerTool::setIcon(bool darkTheme)
61 {
62 if (darkTheme) {
63 m_activateAction->setIcon(QIcon(":/icons/player_dark.svg"));
64 } else {
65 m_activateAction->setIcon(QIcon(":/icons/player_light.svg"));
66 }
67 }
68
69 QWidget* PlayerTool::toolWidget() const
70 {
71 if (!m_toolWidget) {
72 m_toolWidget = new QWidget(qobject_cast<QWidget*>(parent()));
73 auto* layout = new QVBoxLayout;
74 auto* controls = new QHBoxLayout;
75 controls->addStretch(1);
76 auto* leftButton = new QPushButton("<");
77 connect(leftButton, SIGNAL(clicked()), SLOT(back()));
78 controls->addWidget(leftButton);
79
80 int maxFrame = m_molecule->coordinate3dCount();
81 if (maxFrame < 1)
82 maxFrame = 1;
83
84 auto* frameLabel = new QLabel(tr("Frame:"));
85 controls->addWidget(frameLabel);
86 m_frameIdx = new QSpinBox;
87 m_frameIdx->setMinimum(1);
88 m_frameIdx->setMaximum(maxFrame);
89 m_frameIdx->setValue(1);
90 m_frameIdx->setSuffix("/" + QString::number(maxFrame));
91 connect(m_frameIdx, SIGNAL(valueChanged(int)),
92 SLOT(spinnerPositionChanged(int)));
93 controls->addWidget(m_frameIdx);
94
95 auto* rightButton = new QPushButton(">");
96 connect(rightButton, SIGNAL(clicked()), SLOT(forward()));
97 controls->addWidget(rightButton);
98 controls->addStretch(1);
99 layout->addLayout(controls);
100
101 auto* sliderLayout = new QHBoxLayout;
102 m_slider = new QSlider(Qt::Horizontal);
103 m_slider->setMinimum(0);
104 m_slider->setTickInterval(1);
105 connect(m_slider, SIGNAL(valueChanged(int)),
106 SLOT(sliderPositionChanged(int)));
107 sliderLayout->addWidget(m_slider);
108 layout->addLayout(sliderLayout);
109 if (maxFrame > 1)
110 m_slider->setMaximum(maxFrame - 1);
111
112 // start / end frame limits
113 auto* frameLayout = new QHBoxLayout;
114 auto* label3 = new QLabel(tr("Start:", "start or first frame index"));
115 m_firstFrameIdx = new QSpinBox;
116 m_firstFrameIdx->setMinimum(1);
117 m_firstFrameIdx->setMaximum(maxFrame);
118 m_firstFrameIdx->setValue(1);
119 connect(m_firstFrameIdx, SIGNAL(valueChanged(int)),
120 SLOT(firstFramePositionChanged(int)));
121 frameLayout->addWidget(label3);
122 frameLayout->addWidget(m_firstFrameIdx);
123
124 // last frame index
125 auto* label5 = new QLabel(tr("End:", "end or last frame index"));
126 m_lastFrameIdx = new QSpinBox;
127 m_lastFrameIdx->setMinimum(1);
128 m_lastFrameIdx->setMaximum(maxFrame);
129 m_lastFrameIdx->setValue(maxFrame);
130 connect(m_lastFrameIdx, SIGNAL(valueChanged(int)),
131 SLOT(lastFramePositionChanged(int)));
132 frameLayout->addWidget(label5);
133 frameLayout->addWidget(m_lastFrameIdx);
134
135 layout->addLayout(frameLayout);
136
137 auto* bonding = new QHBoxLayout;
138 bonding->addStretch(1);
139 m_dynamicBonding = new QCheckBox(tr("Dynamic bonding?"));
140 m_dynamicBonding->setChecked(false);
141 bonding->addWidget(m_dynamicBonding);
142 bonding->addStretch(1);
143 layout->addLayout(bonding);
144
145 auto* frames = new QHBoxLayout;
146 frames->addStretch(1);
147 auto* label = new QLabel(tr("Frame rate:"));
148 frames->addWidget(label);
149 m_animationFPS = new QSpinBox;
150 m_animationFPS->setValue(5);
151 m_animationFPS->setMinimum(0);
152 m_animationFPS->setMaximum(1000);
153 m_animationFPS->setSuffix(tr(" FPS", "frames per second"));
154 frames->addWidget(m_animationFPS);
155 frames->addStretch(1);
156 layout->addLayout(frames);
157
158 auto* recordLayout = new QHBoxLayout;
159 recordLayout->addStretch(1);
160
161 playButton = new QPushButton(tr("Play"));
162 playButton->setIcon(QIcon::fromTheme("media-playback-start"));
163 connect(playButton, SIGNAL(clicked()), SLOT(play()));
164 recordLayout->addWidget(playButton);
165
166 auto* recordButton = new QPushButton(tr("Record…"));
167 recordButton->setIcon(QIcon::fromTheme("media-record"));
168 connect(recordButton, SIGNAL(clicked()), SLOT(recordMovie()));
169 recordLayout->addWidget(recordButton);
170 recordLayout->addStretch(1);
171 layout->addLayout(recordLayout);
172
173 m_toolWidget->setLayout(layout);
174 }
175 connect(&m_timer, SIGNAL(timeout()), SLOT(animate()));
176
177 return m_toolWidget;
178 }
179
180 QUndoCommand* PlayerTool::mousePressEvent(QMouseEvent*)
181 {
182 return nullptr;
183 }
184
185 QUndoCommand* PlayerTool::mouseReleaseEvent(QMouseEvent*)
186 {
187 return nullptr;
188 }
189
190 QUndoCommand* PlayerTool::mouseDoubleClickEvent(QMouseEvent*)
191 {
192 return nullptr;
193 }
194
195 QUndoCommand* PlayerTool::keyPressEvent(QKeyEvent* e)
196 {
197 switch (e->key()) {
198 case Qt::Key_Space:
199 // start or stop
200 play();
201 e->accept();
202 break;
203 case Qt::Key_Right:
204 // go forward
205 if (e->modifiers() & Qt::ShiftModifier)
206 animate(10);
207 else
208 animate(1);
209 e->accept();
210 break;
211 case Qt::Key_Left:
212 // go back
213 if (e->modifiers() & Qt::ShiftModifier)
214 animate(-10);
215 else
216 animate(-1);
217 e->accept();
218 break;
219 case Qt::Key_Up:
220 // go to first frame
221 if (m_firstFrameIdx)
222 animate(m_firstFrameIdx->value() - 1 - m_currentFrame);
223 e->accept();
224 break;
225 case Qt::Key_Down:
226 // go to last frame
227 if (m_lastFrameIdx)
228 animate(m_lastFrameIdx->value() - 1 - m_currentFrame);
229 e->accept();
230 break;
231 default:
232 e->ignore();
233 break;
234 }
235 return nullptr;
236 }
237
238 void PlayerTool::setActiveWidget(QWidget* widget)
239 {
240 m_glWidget = qobject_cast<QOpenGLWidget*>(widget);
241 }
242
243 void PlayerTool::back()
244 {
245 animate(-1);
246 }
247
248 void PlayerTool::forward()
249 {
250 animate(1);
251 }
252
253 void PlayerTool::play()
254 {
255 if (m_timer.isActive()) {
256 stop();
257 return;
258 } else {
259 // change the button to stop / pause
260 playButton->setText(tr("Pause"));
261 playButton->setIcon(QIcon::fromTheme("media-playback-pause"));
262 }
263
264 auto fps = static_cast<double>(m_animationFPS->value());
265 if (fps < 0.00001)
266 fps = 5;
267 int timeOut = static_cast<int>(1000 / fps);
268 if (m_timer.isActive())
269 m_timer.stop();
270 m_timer.start(timeOut);
271 }
272
273 void PlayerTool::stop()
274 {
275 m_timer.stop();
276
277 // set the button for play
278 playButton->setText(tr("Play"));
279 playButton->setIcon(QIcon::fromTheme("media-playback-start"));
280 }
281
282 void PlayerTool::animate(int advance)
283 {
284 // check the start and end boxes
285 int firstFrame = m_firstFrameIdx->value() - 1;
286 int lastFrame = m_lastFrameIdx->value() - 1;
287
288 if (m_molecule) {
289 if (m_currentFrame < m_molecule->coordinate3dCount() - advance &&
290 m_currentFrame + advance >= firstFrame &&
291 m_currentFrame + advance <= lastFrame) {
292 m_currentFrame += advance;
293 m_molecule->setCoordinate3d(m_currentFrame);
294 } else {
295 int end = std::min(static_cast<int>(m_molecule->coordinate3dCount() - 1),
296 lastFrame);
297 m_currentFrame = advance > 0 ? firstFrame : end;
298 m_molecule->setCoordinate3d(m_currentFrame);
299 }
300 if (m_dynamicBonding->isChecked()) {
301 m_molecule->clearBonds();
302 m_molecule->perceiveBondsSimple();
303 // Bonds were modified, so use Added flag
304 m_molecule->emitChanged(Molecule::Atoms | Molecule::Bonds |
305 Molecule::Removed | Molecule::Added);
306 } else {
307 // Coordinate-only change, use Moved flag
308 m_molecule->emitChanged(Molecule::Atoms | Molecule::Moved);
309 }
310 m_slider->setValue(m_currentFrame);
311 m_frameIdx->setValue(m_currentFrame + 1);
312 }
313 }
314
315 void PlayerTool::recordMovie()
316 {
317 // Qt 5.14 or later gives the more reliable way for multi-screen
318 #if QT_VERSION >= 0x050E00
319 qreal scaling = m_glWidget->screen()->devicePixelRatio();
320 #else
321 qreal scaling = qApp->devicePixelRatio();
322 #endif
323 int EXPORT_WIDTH = m_glWidget->width() * scaling;
324 int EXPORT_HEIGHT = m_glWidget->height() * scaling;
325
326 if (m_timer.isActive())
327 m_timer.stop();
328
329 QString baseFileName;
330 if (m_molecule)
331 baseFileName = m_molecule->data("fileName").toString().c_str();
332
333 // TODO: check path for avconv and disable MP4 if not found
334 // TODO: add PNG as an export (i.e., pile of PNG for later use)
335 QString selfFilter = tr("Movie (*.mp4)");
336 QString baseName = QFileDialog::getSaveFileName(
337 qobject_cast<QWidget*>(parent()), tr("Export Bitmap Graphics"), "",
338 tr("Movie (*.mp4);;Movie (*.avi);;GIF (*.gif)"), &selfFilter);
339
340 if (baseName.isEmpty())
341 return;
342
343 QFileInfo fileInfo(baseName);
344 if (!fileInfo.suffix().isEmpty())
345 baseName = fileInfo.absolutePath() + "/" + fileInfo.baseName();
346
347 bool bonding = m_dynamicBonding->isChecked();
348 int numberLength = static_cast<int>(
349 ceil(log10(static_cast<float>(m_molecule->coordinate3dCount()) + 1)));
350 // m_glWidget->resize(EXPORT_WIDTH, EXPORT_HEIGHT);
351
352 if (selfFilter == tr("GIF (*.gif)")) {
353 GifWriter writer;
354 // GIF only supports up to 100 FPS, this minimizes breakage when FPS>100
355
356 if (m_animationFPS->value() > 100) {
357 QMessageBox::warning(
358 qobject_cast<QWidget*>(parent()), tr("GIF FPS support warning"),
359 tr("The GIF file format does not support frame rates over 100 FPS."));
360 }
361 GifBegin(&writer, (baseName + ".gif").toLatin1().data(), EXPORT_WIDTH,
362 EXPORT_HEIGHT, 100 / std::min(m_animationFPS->value(), 100));
363 for (int i = 0; i < m_molecule->coordinate3dCount(); ++i) {
364 qApp->processEvents();
365 m_molecule->setCoordinate3d(i);
366 if (bonding) {
367 m_molecule->clearBonds();
368 m_molecule->perceiveBondsSimple();
369 }
370 m_molecule->emitChanged(Molecule::Atoms | Molecule::Modified);
371
372 QImage exportImage;
373 m_glWidget->raise();
374 m_glWidget->repaint();
375 if (QOpenGLFramebufferObject::hasOpenGLFramebufferObjects()) {
376 exportImage = m_glWidget->grabFramebuffer();
377 } else {
378 auto* screen = QGuiApplication::primaryScreen();
379 auto pixmap = screen->grabWindow(m_glWidget->winId());
380 exportImage = pixmap.toImage();
381 }
382
383 int frameWidth = exportImage.width();
384 int frameHeight = exportImage.height();
385 int numbPixels = frameWidth * frameHeight;
386
387 auto* imageData = new uint8_t[numbPixels * 4];
388 int imageIndex = 0;
389 for (int j = 0; j < frameHeight; ++j) {
390 for (int k = 0; k < frameWidth; ++k) {
391 QColor color = exportImage.pixel(k, j);
392 imageData[imageIndex] = (uint8_t)color.red();
393 imageData[imageIndex + 1] = (uint8_t)color.green();
394 imageData[imageIndex + 2] = (uint8_t)color.blue();
395 imageData[imageIndex + 3] = (uint8_t)color.alpha();
396 imageIndex += 4;
397 }
398 }
399 GifWriteFrame(&writer, imageData, EXPORT_WIDTH, EXPORT_HEIGHT,
400 100 / std::min(m_animationFPS->value(), 100));
401 delete[] imageData;
402 }
403 GifEnd(&writer);
404 } else if (selfFilter == tr("Movie (*.avi)")) {
405 gwavi_t* gwavi;
406 gwavi = gwavi_open((baseName + ".avi").toLatin1().data(), EXPORT_WIDTH,
407 EXPORT_HEIGHT, "MJPG", m_animationFPS->value(), nullptr);
408 for (int i = 0; i < m_molecule->coordinate3dCount(); ++i) {
409 qApp->processEvents();
410 m_molecule->setCoordinate3d(i);
411 if (bonding) {
412 m_molecule->clearBonds();
413 m_molecule->perceiveBondsSimple();
414 }
415 m_molecule->emitChanged(Molecule::Atoms | Molecule::Modified);
416
417 QImage exportImage;
418 m_glWidget->raise();
419 m_glWidget->repaint();
420 if (QOpenGLFramebufferObject::hasOpenGLFramebufferObjects()) {
421 exportImage = m_glWidget->grabFramebuffer();
422 } else {
423 auto* screen = QGuiApplication::primaryScreen();
424 auto pixmap = screen->grabWindow(m_glWidget->winId());
425 exportImage = pixmap.toImage();
426 }
427 QByteArray ba;
428 QBuffer buffer(&ba);
429 buffer.open(QIODevice::WriteOnly);
430 exportImage.save(&buffer, "JPG");
431
432 if (gwavi_add_frame(
433 gwavi, reinterpret_cast<const unsigned char*>(buffer.data().data()),
434 buffer.size()) == -1) {
435 QMessageBox::warning(qobject_cast<QWidget*>(parent()), tr("Avogadro"),
436 tr("Error: cannot add frame to video."));
437 }
438 }
439 gwavi_close(gwavi);
440 } else if (selfFilter == tr("Movie (*.mp4)")) {
441 for (int i = 0; i < m_molecule->coordinate3dCount(); ++i) {
442 qApp->processEvents();
443 m_molecule->setCoordinate3d(i);
444 if (bonding) {
445 m_molecule->clearBonds();
446 m_molecule->perceiveBondsSimple();
447 }
448 m_molecule->emitChanged(Molecule::Atoms | Molecule::Modified);
449 QString fileName = QString::number(i);
450 while (fileName.length() < numberLength)
451 fileName.prepend('0');
452 fileName.prepend(baseName);
453 fileName.append(".png");
454
455 QImage exportImage;
456 m_glWidget->raise();
457 m_glWidget->repaint();
458 if (QOpenGLFramebufferObject::hasOpenGLFramebufferObjects()) {
459 exportImage = m_glWidget->grabFramebuffer();
460 } else {
461 auto* screen = QGuiApplication::primaryScreen();
462 auto pixmap = screen->grabWindow(m_glWidget->winId());
463 exportImage = pixmap.toImage();
464 }
465
466 if (!exportImage.save(fileName)) {
467 QMessageBox::warning(qobject_cast<QWidget*>(parent()), tr("Avogadro"),
468 tr("Cannot save file %1.").arg(fileName));
469 return;
470 }
471 QProcess proc;
472 QStringList args;
473 args << "-y"
474 << "-r" << QString::number(m_animationFPS->value()) << "-i"
475 << baseName + "%0" + QString::number(numberLength) + "d.png"
476 << "-c:v"
477 << "libx264"
478 << "-r"
479 << "30"
480 << "-pix_fmt"
481 << "yuv420p" << baseName + ".mp4";
482 proc.execute("avconv", args);
483 }
484 }
485 }
486
487 void PlayerTool::sliderPositionChanged(int k)
488 {
489 animate(k - m_currentFrame);
490 }
491
492 void PlayerTool::spinnerPositionChanged(int k)
493 {
494 animate(k - m_currentFrame - 1);
495 }
496
497 void PlayerTool::firstFramePositionChanged(int k)
498 {
499 if (k < 1 || k > m_molecule->coordinate3dCount()) {
500 m_firstFrameIdx->setValue(1);
501 return;
502 }
503 m_frameIdx->setMinimum(k);
504 if (m_frameIdx->value() < k)
505 m_frameIdx->setValue(k);
506
507 m_lastFrameIdx->setMinimum(k);
508 if (m_lastFrameIdx->value() < k)
509 m_lastFrameIdx->setValue(k);
510 }
511
512 void PlayerTool::lastFramePositionChanged(int k)
513 {
514 if (k < 1 || k > m_molecule->coordinate3dCount()) {
515 m_lastFrameIdx->setValue(m_molecule->coordinate3dCount());
516 return;
517 }
518 m_frameIdx->setMaximum(k);
519 if (m_frameIdx->value() > k)
520 m_frameIdx->setValue(k);
521 }
522
523 void PlayerTool::updateLimits()
524 {
525 int coordCount = m_molecule->coordinate3dCount();
526
527 if (coordCount > 1 && m_slider)
528 m_slider->setMaximum(coordCount - 1);
529 if (coordCount > 1 && m_frameIdx) {
530 m_frameIdx->setMaximum(coordCount);
531 m_frameIdx->setSuffix("/" + QString::number(coordCount));
532 }
533 if (coordCount > 1 && m_firstFrameIdx)
534 m_firstFrameIdx->setMaximum(coordCount);
535 if (coordCount > 1 && m_lastFrameIdx)
536 m_lastFrameIdx->setMaximum(coordCount);
537
538 if (m_firstFrameIdx)
539 m_firstFrameIdx->setValue(1);
540 if (m_lastFrameIdx)
541 m_lastFrameIdx->setValue(coordCount);
542 }
543
544 } // namespace Avogadro::QtPlugins