]> git.sesse.net Git - kdenlive/blob - src/monitor.cpp
Fix some avformat producer concurrency crashes
[kdenlive] / src / monitor.cpp
1 /***************************************************************************
2  *   Copyright (C) 2007 by Jean-Baptiste Mardelle (jb@kdenlive.org)        *
3  *                                                                         *
4  *   This program is free software; you can redistribute it and/or modify  *
5  *   it under the terms of the GNU General Public License as published by  *
6  *   the Free Software Foundation; either version 2 of the License, or     *
7  *   (at your option) any later version.                                   *
8  *                                                                         *
9  *   This program is distributed in the hope that it will be useful,       *
10  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
11  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
12  *   GNU General Public License for more details.                          *
13  *                                                                         *
14  *   You should have received a copy of the GNU General Public License     *
15  *   along with this program; if not, write to the                         *
16  *   Free Software Foundation, Inc.,                                       *
17  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA          *
18  ***************************************************************************/
19
20
21 #include "monitor.h"
22 #include "smallruler.h"
23 #include "docclipbase.h"
24 #include "abstractclipitem.h"
25 #include "monitorscene.h"
26 #include "monitoreditwidget.h"
27 #include "kdenlivesettings.h"
28
29 #include <KDebug>
30 #include <KLocale>
31 #include <KFileDialog>
32 #include <KApplication>
33 #include <KMessageBox>
34
35 #include <QMouseEvent>
36 #include <QStylePainter>
37 #include <QMenu>
38 #include <QToolButton>
39 #include <QToolBar>
40 #include <QDesktopWidget>
41 #include <QLabel>
42 #include <QIntValidator>
43 #include <QVBoxLayout>
44
45
46 Monitor::Monitor(QString name, MonitorManager *manager, QString profile, QWidget *parent) :
47     AbstractMonitor(parent),
48     render(NULL),
49     m_name(name),
50     m_monitorManager(manager),
51     m_currentClip(NULL),
52     m_ruler(new SmallRuler(m_monitorManager)),
53     m_overlay(NULL),
54     m_scale(1),
55     m_length(0),
56     m_dragStarted(false),
57     m_monitorRefresh(NULL),
58     m_effectWidget(NULL),
59     m_selectedClip(NULL),
60     m_loopClipTransition(true),
61     m_editMarker(NULL)
62
63 {
64     QVBoxLayout *layout = new QVBoxLayout;
65     layout->setContentsMargins(0, 0, 0, 0);
66     layout->setSpacing(0);
67
68     // Video widget holder
69     m_videoBox = new VideoContainer(this);
70     m_videoBox->setContentsMargins(0, 0, 0, 0);
71     m_videoBox->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
72     layout->addWidget(m_videoBox, 10);
73     layout->addStretch();
74
75     // Get base size for icons
76     int s = style()->pixelMetric(QStyle::PM_SmallIconSize);
77
78     // Monitor ruler
79     layout->addWidget(m_ruler);
80     // Tool bar buttons
81     m_toolbar = new QToolBar(name, this);
82     m_toolbar->setIconSize(QSize(s, s));
83
84     m_playIcon = KIcon("media-playback-start");
85     m_pauseIcon = KIcon("media-playback-pause");
86
87     if (name != "chapter") {
88         m_toolbar->addAction(KIcon("kdenlive-zone-start"), i18n("Set zone start"), this, SLOT(slotSetZoneStart()));
89         m_toolbar->addAction(KIcon("kdenlive-zone-end"), i18n("Set zone end"), this, SLOT(slotSetZoneEnd()));
90     } else {
91         m_ruler->setZone(-3, -2);
92     }
93
94     m_toolbar->addAction(KIcon("media-seek-backward"), i18n("Rewind"), this, SLOT(slotRewind()));
95     //m_toolbar->addAction(KIcon("media-skip-backward"), i18n("Rewind 1 frame"), this, SLOT(slotRewindOneFrame()));
96
97     QToolButton *playButton = new QToolButton(m_toolbar);
98     m_playMenu = new QMenu(i18n("Play..."), this);
99     m_playAction = m_playMenu->addAction(m_playIcon, i18n("Play"));
100     //m_playAction->setCheckable(true);
101     connect(m_playAction, SIGNAL(triggered()), this, SLOT(slotPlay()));
102
103     playButton->setMenu(m_playMenu);
104     playButton->setPopupMode(QToolButton::MenuButtonPopup);
105     m_toolbar->addWidget(playButton);
106
107     //m_toolbar->addAction(KIcon("media-skip-forward"), i18n("Forward 1 frame"), this, SLOT(slotForwardOneFrame()));
108     m_toolbar->addAction(KIcon("media-seek-forward"), i18n("Forward"), this, SLOT(slotForward()));
109
110     playButton->setDefaultAction(m_playAction);
111
112     if (name != "chapter") {
113         QToolButton *configButton = new QToolButton(m_toolbar);
114         m_configMenu = new QMenu(i18n("Misc..."), this);
115         configButton->setIcon(KIcon("system-run"));
116         configButton->setMenu(m_configMenu);
117         configButton->setPopupMode(QToolButton::QToolButton::InstantPopup);
118         m_toolbar->addWidget(configButton);
119
120         if (name == "clip") {
121             m_markerMenu = new QMenu(i18n("Go to marker..."), this);
122             m_markerMenu->setEnabled(false);
123             m_configMenu->addMenu(m_markerMenu);
124             connect(m_markerMenu, SIGNAL(triggered(QAction *)), this, SLOT(slotGoToMarker(QAction *)));
125         }
126         m_configMenu->addAction(KIcon("transform-scale"), i18n("Resize (100%)"), this, SLOT(slotSetSizeOneToOne()));
127         m_configMenu->addAction(KIcon("transform-scale"), i18n("Resize (50%)"), this, SLOT(slotSetSizeOneToTwo()));
128     }
129
130     // Create Volume slider popup
131     m_volumePopup = new QFrame(this, Qt::Popup);
132     QVBoxLayout *poplayout = new QVBoxLayout;
133     poplayout->setContentsMargins(0, 0, 0, 0);
134     m_audioSlider = new QSlider(Qt::Vertical);
135     m_audioSlider->setRange(0, 100);
136     poplayout->addWidget(m_audioSlider);
137     m_volumePopup->setLayout(poplayout);
138     KIcon icon;
139     if (KdenliveSettings::volume() == 0) icon = KIcon("audio-volume-muted");
140     else icon = KIcon("audio-volume-medium");
141
142     m_volumeWidget = m_toolbar->widgetForAction(m_toolbar->addAction(icon, i18n("Audio volume"), this, SLOT(slotShowVolume())));
143
144     // we need to show / hide the popup once so that it's geometry can be calculated in slotShowVolume
145     m_volumePopup->show();
146     m_volumePopup->hide();
147
148     setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
149     setLayout(layout);
150     setMinimumHeight(200);
151
152     if (profile.isEmpty()) profile = KdenliveSettings::current_profile();
153
154     bool monitorCreated = false;
155 #ifdef Q_WS_MAC
156     createOpenGlWidget(m_videoBox, profile);
157     monitorCreated = true;
158     //m_glWidget->setFixedSize(width, height);
159 #elif defined (USE_OPEN_GL)
160     if (KdenliveSettings::openglmonitors()) {
161         monitorCreated = createOpenGlWidget(m_videoBox, profile);
162     }
163 #endif
164     QVBoxLayout *lay = new QVBoxLayout;
165     lay->setContentsMargins(0, 0, 0, 0);
166     if (!monitorCreated) {
167         m_monitorRefresh = new MonitorRefresh;
168         lay->addWidget(m_monitorRefresh);
169         m_videoBox->setLayout(lay);
170         render = new Render(m_name, (int) m_monitorRefresh->winId(), profile, this);
171         m_monitorRefresh->setRenderer(render);
172     }
173 #if defined (USE_OPEN_GL)
174     else if (m_glWidget) {
175         lay->addWidget(m_glWidget);
176         m_videoBox->setLayout(lay);
177     }
178 #endif
179
180     connect(m_audioSlider, SIGNAL(valueChanged(int)), this, SLOT(slotSetVolume(int)));
181     connect(m_ruler, SIGNAL(seekRenderer(int)), this, SLOT(slotSeek(int)));
182     connect(render, SIGNAL(durationChanged(int)), this, SLOT(adjustRulerSize(int)));
183     connect(render, SIGNAL(rendererStopped(int)), this, SLOT(rendererStopped(int)));
184
185     if (name != "clip") {
186         connect(render, SIGNAL(rendererPosition(int)), this, SIGNAL(renderPosition(int)));
187         connect(render, SIGNAL(durationChanged(int)), this, SIGNAL(durationChanged(int)));
188         connect(m_ruler, SIGNAL(zoneChanged(QPoint)), this, SIGNAL(zoneUpdated(QPoint)));
189     } else {
190         connect(m_ruler, SIGNAL(zoneChanged(QPoint)), this, SLOT(setClipZone(QPoint)));
191     }
192
193     if (m_monitorRefresh) m_monitorRefresh->show();
194
195     if (name == "project") {
196         m_effectWidget = new MonitorEditWidget(render, m_videoBox);
197         m_toolbar->addAction(m_effectWidget->getVisibilityAction());
198         lay->addWidget(m_effectWidget);
199         m_effectWidget->hide();
200     }
201
202     QWidget *spacer = new QWidget(this);
203     spacer->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred);
204     m_toolbar->addWidget(spacer);
205     m_timePos = new TimecodeDisplay(m_monitorManager->timecode(), this);
206     m_toolbar->addWidget(m_timePos);
207     connect(m_timePos, SIGNAL(editingFinished()), this, SLOT(slotSeek()));
208     m_toolbar->setMaximumHeight(s * 1.5);
209     layout->addWidget(m_toolbar);
210 }
211
212 Monitor::~Monitor()
213 {
214     delete m_ruler;
215     delete m_timePos;
216     delete m_overlay;
217     if (m_effectWidget)
218         delete m_effectWidget;
219     delete m_monitorRefresh;
220     delete render;
221 }
222
223 QWidget *Monitor::container()
224 {
225     return m_videoBox;
226 }
227
228 const QString Monitor::name() const
229 {
230     return m_name;
231 }
232
233 #if defined(Q_WS_MAC) || defined(USE_OPEN_GL)
234 bool Monitor::createOpenGlWidget(QWidget *parent, const QString profile)
235 {
236     render = new Render(m_name, 0, profile, this);
237     m_glWidget = new VideoGLWidget(parent);
238     if (m_glWidget == NULL) {
239         // Creation failed, we are in trouble...
240         return false;
241     }
242     m_glWidget->setImageAspectRatio(render->dar());
243     m_glWidget->setBackgroundColor(KdenliveSettings::window_background());
244     connect(render, SIGNAL(showImageSignal(QImage)), m_glWidget, SLOT(showImage(QImage)));
245     return true;
246 }
247 #endif
248
249 void Monitor::setupMenu(QMenu *goMenu, QAction *playZone, QAction *loopZone, QMenu *markerMenu, QAction *loopClip)
250 {
251     m_contextMenu = new QMenu(this);
252     m_contextMenu->addMenu(m_playMenu);
253     if (goMenu)
254         m_contextMenu->addMenu(goMenu);
255     if (markerMenu) {
256         m_contextMenu->addMenu(markerMenu);
257         QList <QAction *>list = markerMenu->actions();
258         for (int i = 0; i < list.count(); i++) {
259             if (list.at(i)->data().toString() == "edit_marker") {
260                 m_editMarker = list.at(i);
261                 break;
262             }
263         }
264     }
265
266     m_playMenu->addAction(playZone);
267     m_playMenu->addAction(loopZone);
268     if (loopClip) {
269         m_loopClipAction = loopClip;
270         m_playMenu->addAction(loopClip);
271     }
272
273     //TODO: add save zone to timeline monitor when fixed
274     if (m_name == "clip") {
275         m_contextMenu->addMenu(m_markerMenu);
276         m_contextMenu->addAction(KIcon("document-save"), i18n("Save zone"), this, SLOT(slotSaveZone()));
277     }
278     QAction *extractFrame = m_configMenu->addAction(KIcon("document-new"), i18n("Extract frame"), this, SLOT(slotExtractCurrentFrame()));
279     m_contextMenu->addAction(extractFrame);
280
281     if (m_name != "clip") {
282         QAction *splitView = m_contextMenu->addAction(KIcon("view-split-left-right"), i18n("Split view"), render, SLOT(slotSplitView(bool)));
283         splitView->setCheckable(true);
284         m_configMenu->addAction(splitView);
285     } else {
286         QAction *setThumbFrame = m_contextMenu->addAction(KIcon("document-new"), i18n("Set current image as thumbnail"), this, SLOT(slotSetThumbFrame()));
287         m_configMenu->addAction(setThumbFrame);
288     }
289
290     QAction *showTips = m_contextMenu->addAction(KIcon("help-hint"), i18n("Monitor overlay infos"));
291     showTips->setCheckable(true);
292     connect(showTips, SIGNAL(toggled(bool)), this, SLOT(slotSwitchMonitorInfo(bool)));
293     showTips->setChecked(KdenliveSettings::displayMonitorInfo());
294
295     QAction *dropFrames = m_contextMenu->addAction(KIcon(), i18n("Real time (drop frames)"));
296     dropFrames->setCheckable(true);
297     dropFrames->setChecked(true);
298     connect(dropFrames, SIGNAL(toggled(bool)), this, SLOT(slotSwitchDropFrames(bool)));
299
300     m_configMenu->addAction(showTips);
301     m_configMenu->addAction(dropFrames);
302
303 }
304
305 void Monitor::slotGoToMarker(QAction *action)
306 {
307     int pos = action->data().toInt();
308     slotSeek(pos);
309 }
310
311 void Monitor::slotSetSizeOneToOne()
312 {
313     QRect r = QApplication::desktop()->screenGeometry();
314     const int maxWidth = r.width() - 20;
315     const int maxHeight = r.height() - 20;
316     int width = render->renderWidth();
317     int height = render->renderHeight();
318     kDebug() << "// render info: " << width << "x" << height;
319     while (width >= maxWidth || height >= maxHeight) {
320         width = width * 0.8;
321         height = height * 0.8;
322     }
323     kDebug() << "// MONITOR; set SIZE: " << width << ", " << height;
324     m_videoBox->setFixedSize(width, height);
325     updateGeometry();
326     adjustSize();
327     //m_ui.video_frame->setMinimumSize(0, 0);
328     emit adjustMonitorSize();
329 }
330
331 void Monitor::slotSetSizeOneToTwo()
332 {
333     QRect r = QApplication::desktop()->screenGeometry();
334     const int maxWidth = r.width() - 20;
335     const int maxHeight = r.height() - 20;
336     int width = render->renderWidth() / 2;
337     int height = render->renderHeight() / 2;
338     kDebug() << "// render info: " << width << "x" << height;
339     while (width >= maxWidth || height >= maxHeight) {
340         width = width * 0.8;
341         height = height * 0.8;
342     }
343     kDebug() << "// MONITOR; set SIZE: " << width << ", " << height;
344     m_videoBox->setFixedSize(width, height);
345     updateGeometry();
346     adjustSize();
347     //m_ui.video_frame->setMinimumSize(0, 0);
348     emit adjustMonitorSize();
349 }
350
351 void Monitor::resetSize()
352 {
353     m_videoBox->setMinimumSize(0, 0);
354 }
355
356 DocClipBase *Monitor::activeClip()
357 {
358     return m_currentClip;
359 }
360
361 void Monitor::updateMarkers(DocClipBase *source)
362 {
363     if (source == m_currentClip && source != NULL) {
364         m_markerMenu->clear();
365         QList <CommentedTime> markers = m_currentClip->commentedSnapMarkers();
366         if (!markers.isEmpty()) {
367             QList <int> marks;
368             for (int i = 0; i < markers.count(); i++) {
369                 int pos = (int) markers.at(i).time().frames(m_monitorManager->timecode().fps());
370                 marks.append(pos);
371                 QString position = m_monitorManager->timecode().getTimecode(markers.at(i).time()) + ' ' + markers.at(i).comment();
372                 QAction *go = m_markerMenu->addAction(position);
373                 go->setData(pos);
374             }
375             m_ruler->setMarkers(marks);
376         } else m_ruler->setMarkers(QList <int>());
377         m_markerMenu->setEnabled(!m_markerMenu->isEmpty());
378     }
379 }
380
381 void Monitor::slotSeekToPreviousSnap()
382 {
383     if (m_currentClip) slotSeek(getSnapForPos(true).frames(m_monitorManager->timecode().fps()));
384 }
385
386 void Monitor::slotSeekToNextSnap()
387 {
388     if (m_currentClip) slotSeek(getSnapForPos(false).frames(m_monitorManager->timecode().fps()));
389 }
390
391 GenTime Monitor::position()
392 {
393     return render->seekPosition();
394 }
395
396 GenTime Monitor::getSnapForPos(bool previous)
397 {
398     QList <GenTime> snaps;
399     QList < GenTime > markers = m_currentClip->snapMarkers();
400     for (int i = 0; i < markers.size(); ++i) {
401         GenTime t = markers.at(i);
402         snaps.append(t);
403     }
404     QPoint zone = m_ruler->zone();
405     snaps.append(GenTime(zone.x(), m_monitorManager->timecode().fps()));
406     snaps.append(GenTime(zone.y(), m_monitorManager->timecode().fps()));
407     snaps.append(GenTime());
408     snaps.append(m_currentClip->duration());
409     qSort(snaps);
410
411     const GenTime pos = render->seekPosition();
412     for (int i = 0; i < snaps.size(); ++i) {
413         if (previous && snaps.at(i) >= pos) {
414             if (i == 0) i = 1;
415             return snaps.at(i - 1);
416         } else if (!previous && snaps.at(i) > pos) {
417             return snaps.at(i);
418         }
419     }
420     return GenTime();
421 }
422
423 void Monitor::slotZoneMoved(int start, int end)
424 {
425     m_ruler->setZone(start, end);
426     checkOverlay();
427     setClipZone(m_ruler->zone());
428 }
429
430 void Monitor::slotSetZoneStart()
431 {
432     m_ruler->setZone(render->seekFramePosition(), -1);
433     emit zoneUpdated(m_ruler->zone());
434     checkOverlay();
435     setClipZone(m_ruler->zone());
436 }
437
438 void Monitor::slotSetZoneEnd()
439 {
440     m_ruler->setZone(-1, render->seekFramePosition());
441     emit zoneUpdated(m_ruler->zone());
442     checkOverlay();
443     setClipZone(m_ruler->zone());
444 }
445
446 // virtual
447 void Monitor::mousePressEvent(QMouseEvent * event)
448 {
449     if (event->button() != Qt::RightButton) {
450         if (m_videoBox->underMouse() && (!m_overlay || !m_overlay->underMouse())) {
451             m_dragStarted = true;
452             m_DragStartPosition = event->pos();
453         }
454     } else if (!m_effectWidget || !m_effectWidget->isVisible()) {
455         m_contextMenu->popup(event->globalPos());
456     }
457 }
458
459 void Monitor::slotSwitchFullScreen()
460 {
461     m_videoBox->switchFullScreen();
462 }
463
464 // virtual
465 void Monitor::mouseReleaseEvent(QMouseEvent * event)
466 {
467     if (m_dragStarted) {
468         if (m_videoBox->underMouse() && (!m_effectWidget || !m_effectWidget->isVisible())) {
469             if (isActive()) slotPlay();
470             else activateMonitor();
471         } else QWidget::mouseReleaseEvent(event);
472         m_dragStarted = false;
473     }
474 }
475
476 // virtual
477 void Monitor::mouseMoveEvent(QMouseEvent *event)
478 {
479     // kDebug() << "// DRAG STARTED, MOUSE MOVED: ";
480     if (!m_dragStarted || m_currentClip == NULL) return;
481
482     if ((event->pos() - m_DragStartPosition).manhattanLength()
483             < QApplication::startDragDistance())
484         return;
485
486     {
487         QDrag *drag = new QDrag(this);
488         QMimeData *mimeData = new QMimeData;
489
490         QStringList list;
491         list.append(m_currentClip->getId());
492         QPoint p = m_ruler->zone();
493         list.append(QString::number(p.x()));
494         list.append(QString::number(p.y()));
495         QByteArray data;
496         data.append(list.join(";").toUtf8());
497         mimeData->setData("kdenlive/clip", data);
498         drag->setMimeData(mimeData);
499         QPixmap pix = m_currentClip->thumbnail();
500         drag->setPixmap(pix);
501         drag->setHotSpot(QPoint(0, 50));
502         drag->start(Qt::MoveAction);
503
504         //Qt::DropAction dropAction;
505         //dropAction = drag->start(Qt::CopyAction | Qt::MoveAction);
506
507         //Qt::DropAction dropAction = drag->exec();
508
509     }
510     //event->accept();
511 }
512
513 /*void Monitor::dragMoveEvent(QDragMoveEvent * event) {
514     event->setDropAction(Qt::IgnoreAction);
515     event->setDropAction(Qt::MoveAction);
516     if (event->mimeData()->hasText()) {
517         event->acceptProposedAction();
518     }
519 }
520
521 Qt::DropActions Monitor::supportedDropActions() const {
522     // returns what actions are supported when dropping
523     return Qt::MoveAction;
524 }*/
525
526 QStringList Monitor::mimeTypes() const
527 {
528     QStringList qstrList;
529     // list of accepted mime types for drop
530     qstrList.append("kdenlive/clip");
531     return qstrList;
532 }
533
534 // virtual
535 void Monitor::wheelEvent(QWheelEvent * event)
536 {
537     slotMouseSeek(event->delta(), event->modifiers() == Qt::ControlModifier);
538     event->accept();
539 }
540
541 void Monitor::slotMouseSeek(int eventDelta, bool fast)
542 {
543     if (fast) {
544         int delta = m_monitorManager->timecode().fps();
545         if (eventDelta > 0) delta = 0 - delta;
546         slotSeek(render->seekFramePosition() - delta);
547     } else {
548         if (eventDelta >= 0) slotForwardOneFrame();
549         else slotRewindOneFrame();
550     }
551 }
552
553 void Monitor::slotSetThumbFrame()
554 {
555     if (m_currentClip == NULL) {
556         return;
557     }
558     m_currentClip->setClipThumbFrame((uint) render->seekFramePosition());
559     emit refreshClipThumbnail(m_currentClip->getId(), true);
560 }
561
562 void Monitor::slotExtractCurrentFrame()
563 {
564     QImage frame;
565     // check if we are using a proxy
566     if (m_currentClip && !m_currentClip->getProperty("proxy").isEmpty() && m_currentClip->getProperty("proxy") != "-") {
567         // using proxy, use original clip url to get frame
568         frame = render->extractFrame(render->seekFramePosition(), m_currentClip->fileURL().path());
569     }
570     else frame = render->extractFrame(render->seekFramePosition());
571     KFileDialog *fs = new KFileDialog(KUrl(), "image/png", this);
572     fs->setOperationMode(KFileDialog::Saving);
573     fs->setMode(KFile::File);
574 #if KDE_IS_VERSION(4,2,0)
575     fs->setConfirmOverwrite(true);
576 #endif
577     fs->setKeepLocation(true);
578     fs->exec();
579     QString path = fs->selectedFile();
580     delete fs;
581     if (!path.isEmpty()) {
582         frame.save(path);
583     }
584 }
585
586 bool Monitor::isActive() const
587 {
588     return m_monitorManager->isActive(m_name);
589 }
590
591 void Monitor::activateMonitor()
592 {
593     m_monitorManager->activateMonitor(m_name);
594 }
595
596 void Monitor::setTimePos(const QString &pos)
597 {
598     m_timePos->setValue(pos);
599     slotSeek();
600 }
601
602 void Monitor::slotSeek()
603 {
604     slotSeek(m_timePos->getValue());
605 }
606
607 void Monitor::slotSeek(int pos)
608 {
609     //activateMonitor();
610     if (render == NULL) return;
611     render->seekToFrame(pos);
612 }
613
614 void Monitor::checkOverlay()
615 {
616     if (m_overlay == NULL) return;
617     int pos = render->seekFramePosition();
618     QPoint zone = m_ruler->zone();
619     if (pos == zone.x())
620         m_overlay->setOverlayText(i18n("In Point"));
621     else if (pos == zone.y())
622         m_overlay->setOverlayText(i18n("Out Point"));
623     else {
624         if (m_currentClip) {
625             QString markerComment = m_currentClip->markerComment(GenTime(pos, m_monitorManager->timecode().fps()));
626             if (markerComment.isEmpty())
627                 m_overlay->setHidden(true);
628             else
629                 m_overlay->setOverlayText(markerComment, false);
630         } else m_overlay->setHidden(true);
631     }
632 }
633
634 void Monitor::slotStart()
635 {
636     activateMonitor();
637     render->play(0);
638     render->seekToFrame(0);
639 }
640
641 void Monitor::slotEnd()
642 {
643     activateMonitor();
644     render->play(0);
645     render->seekToFrame(render->getLength());
646 }
647
648 void Monitor::slotZoneStart()
649 {
650     activateMonitor();
651     render->play(0);
652     render->seekToFrame(m_ruler->zone().x());
653 }
654
655 void Monitor::slotZoneEnd()
656 {
657     activateMonitor();
658     render->play(0);
659     render->seekToFrame(m_ruler->zone().y());
660 }
661
662 void Monitor::slotRewind(double speed)
663 {
664     activateMonitor();
665     if (speed == 0) {
666         double currentspeed = render->playSpeed();
667         if (currentspeed >= 0) render->play(-2);
668         else render->play(currentspeed * 2);
669     } else render->play(speed);
670     //m_playAction->setChecked(true);
671     m_playAction->setIcon(m_pauseIcon);
672 }
673
674 void Monitor::slotForward(double speed)
675 {
676     activateMonitor();
677     if (speed == 0) {
678         double currentspeed = render->playSpeed();
679         if (currentspeed <= 1) render->play(2);
680         else render->play(currentspeed * 2);
681     } else render->play(speed);
682     //m_playAction->setChecked(true);
683     m_playAction->setIcon(m_pauseIcon);
684 }
685
686 void Monitor::slotRewindOneFrame(int diff)
687 {
688     activateMonitor();
689     render->play(0);
690     render->seekToFrameDiff(-diff);
691 }
692
693 void Monitor::slotForwardOneFrame(int diff)
694 {
695     activateMonitor();
696     render->play(0);
697     render->seekToFrameDiff(diff);
698 }
699
700 void Monitor::seekCursor(int pos)
701 {
702     //activateMonitor();
703     if (m_ruler->slotNewValue(pos)) {
704         checkOverlay();
705         m_timePos->setValue(pos);
706     }
707 }
708
709 void Monitor::rendererStopped(int pos)
710 {
711     if (m_ruler->slotNewValue(pos)) {
712         checkOverlay();
713         m_timePos->setValue(pos);
714     }
715     m_playAction->setIcon(m_playIcon);
716 }
717
718 void Monitor::adjustRulerSize(int length)
719 {
720     if (length > 0) m_length = length;
721     m_ruler->adjustScale(m_length);
722     if (m_currentClip != NULL) {
723         QPoint zone = m_currentClip->zone();
724         m_ruler->setZone(zone.x(), zone.y());
725     }
726 }
727
728 void Monitor::stop()
729 {
730     disconnect(render, SIGNAL(rendererPosition(int)), this, SLOT(seekCursor(int)));
731     if (render) render->stop();
732 }
733
734 void Monitor::start()
735 {
736     if (render && (m_name != "clip" || m_currentClip != NULL)) render->start();
737     connect(render, SIGNAL(rendererPosition(int)), this, SLOT(seekCursor(int)));
738 }
739
740 void Monitor::refreshMonitor(bool visible)
741 {
742     if (visible && render) {
743         activateMonitor();
744         render->doRefresh(); //askForRefresh();
745     }
746 }
747
748 void Monitor::refreshMonitor()
749 {
750     if (isActive()) {
751         render->doRefresh();
752     }
753 }
754
755 void Monitor::pause()
756 {
757     if (render == NULL) return;
758     activateMonitor();
759     render->pause();
760     //m_playAction->setChecked(true);
761     m_playAction->setIcon(m_playIcon);
762 }
763
764 void Monitor::slotPlay()
765 {
766     if (render == NULL) return;
767     activateMonitor();
768     if (render->playSpeed() == 0) {
769         m_playAction->setIcon(m_pauseIcon);
770         render->switchPlay(true);
771     } else {
772         m_playAction->setIcon(m_playIcon);
773         render->switchPlay(false);
774     }
775 }
776
777 void Monitor::slotPlayZone()
778 {
779     if (render == NULL) return;
780     activateMonitor();
781     QPoint p = m_ruler->zone();
782     render->playZone(GenTime(p.x(), m_monitorManager->timecode().fps()), GenTime(p.y(), m_monitorManager->timecode().fps()));
783     //m_playAction->setChecked(true);
784     m_playAction->setIcon(m_pauseIcon);
785 }
786
787 void Monitor::slotLoopZone()
788 {
789     if (render == NULL) return;
790     activateMonitor();
791     QPoint p = m_ruler->zone();
792     render->loopZone(GenTime(p.x(), m_monitorManager->timecode().fps()), GenTime(p.y(), m_monitorManager->timecode().fps()));
793     //m_playAction->setChecked(true);
794     m_playAction->setIcon(m_pauseIcon);
795 }
796
797 void Monitor::slotLoopClip()
798 {
799     if (render == NULL || m_selectedClip == NULL)
800         return;
801     activateMonitor();
802     render->loopZone(m_selectedClip->startPos(), m_selectedClip->endPos());
803     //m_playAction->setChecked(true);
804     m_playAction->setIcon(m_pauseIcon);
805 }
806
807 void Monitor::slotSetXml(DocClipBase *clip, QPoint zone, const int position)
808 {
809     if (render == NULL) return;
810     if (clip == NULL && m_currentClip != NULL) {
811         m_currentClip = NULL;
812         m_length = -1;
813         render->setProducer(NULL, -1);
814         return;
815     }
816     if (clip != m_currentClip) {
817         m_currentClip = clip;
818         if (m_currentClip) activateMonitor();
819         updateMarkers(clip);
820         if (render->setProducer(clip->getProducer(), position) == -1) {
821             // MLT CONSUMER is broken
822             kDebug(QtWarningMsg) << "ERROR, Cannot start monitor";
823         }
824     } else {
825         if (m_currentClip) activateMonitor();
826         if (position != -1) render->seek(position);
827     }
828     if (!zone.isNull()) {
829         m_ruler->setZone(zone.x(), zone.y());
830         render->seek(zone.x());
831     }
832 }
833
834 void Monitor::slotOpenFile(const QString &file)
835 {
836     if (render == NULL) return;
837     activateMonitor();
838     QDomDocument doc;
839     QDomElement mlt = doc.createElement("mlt");
840     doc.appendChild(mlt);
841     QDomElement prod = doc.createElement("producer");
842     mlt.appendChild(prod);
843     prod.setAttribute("mlt_service", "avformat");
844     prod.setAttribute("resource", file);
845     render->setSceneList(doc, 0);
846 }
847
848 void Monitor::slotSaveZone()
849 {
850     if (render == NULL) return;
851     emit saveZone(render, m_ruler->zone(), m_currentClip);
852
853     //render->setSceneList(doc, 0);
854 }
855
856 void Monitor::resetProfile(const QString &profile)
857 {
858     m_timePos->updateTimeCode(m_monitorManager->timecode());
859     if (render == NULL) return;
860     render->resetProfile(profile);
861     if (m_effectWidget)
862         m_effectWidget->resetProfile(render);
863 }
864
865 void Monitor::saveSceneList(QString path, QDomElement info)
866 {
867     if (render == NULL) return;
868     render->saveSceneList(path, info);
869 }
870
871 const QString Monitor::sceneList()
872 {
873     if (render == NULL) return QString();
874     return render->sceneList();
875 }
876
877 void Monitor::setClipZone(QPoint pos)
878 {
879     if (m_currentClip == NULL) return;
880     m_currentClip->setZone(pos);
881 }
882
883 void Monitor::slotSwitchDropFrames(bool show)
884 {
885     render->setDropFrames(show);
886 }
887
888 void Monitor::slotSwitchMonitorInfo(bool show)
889 {
890     KdenliveSettings::setDisplayMonitorInfo(show);
891     if (show) {
892         if (m_overlay) return;
893         if (m_monitorRefresh == NULL) {
894             // Using OpenGL display
895 #if defined(Q_WS_MAC) || defined(USE_OPEN_GL)
896             if (m_glWidget->layout()) delete m_glWidget->layout();
897             m_overlay = new Overlay();
898             connect(m_overlay, SIGNAL(editMarker()), this, SLOT(slotEditMarker()));
899             QVBoxLayout *layout = new QVBoxLayout;
900             layout->addStretch(10);
901             layout->addWidget(m_overlay);
902             m_glWidget->setLayout(layout);
903 #endif
904         } else {
905             if (m_monitorRefresh->layout()) delete m_monitorRefresh->layout();
906             m_overlay = new Overlay();
907             connect(m_overlay, SIGNAL(editMarker()), this, SLOT(slotEditMarker()));
908             QVBoxLayout *layout = new QVBoxLayout;
909             layout->addStretch(10);
910             layout->addWidget(m_overlay);
911             m_monitorRefresh->setLayout(layout);
912             m_overlay->raise();
913             m_overlay->setHidden(true);
914         }
915         checkOverlay();
916     } else {
917         delete m_overlay;
918         m_overlay = NULL;
919     }
920 }
921
922 void Monitor::slotEditMarker()
923 {
924     if (m_editMarker) m_editMarker->trigger();
925 }
926
927 void Monitor::updateTimecodeFormat()
928 {
929     m_timePos->slotUpdateTimeCodeFormat();
930 }
931
932 QStringList Monitor::getZoneInfo() const
933 {
934     QStringList result;
935     if (m_currentClip == NULL) return result;
936     result << m_currentClip->getId();
937     QPoint zone = m_ruler->zone();
938     result << QString::number(zone.x()) << QString::number(zone.y());
939     return result;
940 }
941
942 void Monitor::slotSetSelectedClip(AbstractClipItem* item)
943 {
944     if (item) {
945         m_loopClipAction->setEnabled(true);
946         m_selectedClip = item;
947     } else {
948         m_loopClipAction->setEnabled(false);
949     }
950 }
951
952 void Monitor::slotSetSelectedClip(ClipItem* item)
953 {
954     if (item || (!item && !m_loopClipTransition)) {
955         m_loopClipTransition = false;
956         slotSetSelectedClip((AbstractClipItem*)item);
957     }
958 }
959
960 void Monitor::slotSetSelectedClip(Transition* item)
961 {
962     if (item || (!item && m_loopClipTransition)) {
963         m_loopClipTransition = true;
964         slotSetSelectedClip((AbstractClipItem*)item);
965     }
966 }
967
968
969 void Monitor::slotEffectScene(bool show)
970 {
971     if (m_name == "project") {
972         if (m_monitorRefresh) {
973             m_monitorRefresh->setVisible(!show);
974         } else {
975 #if defined(Q_WS_MAC) || defined(USE_OPEN_GL)
976             m_glWidget->setVisible(!show);
977 #endif
978         }
979         m_effectWidget->setVisible(show);
980         m_effectWidget->getVisibilityAction()->setChecked(show);
981         emit requestFrameForAnalysis(show);
982         if (show) {
983             m_effectWidget->getScene()->slotZoomFit();
984             render->doRefresh();
985         }
986     }
987 }
988
989 MonitorEditWidget* Monitor::getEffectEdit()
990 {
991     return m_effectWidget;
992 }
993
994 bool Monitor::effectSceneDisplayed()
995 {
996     return m_effectWidget->isVisible();
997 }
998
999 void Monitor::slotSetVolume(int volume)
1000 {
1001     KdenliveSettings::setVolume(volume);
1002     KIcon icon;
1003     if (volume == 0) icon = KIcon("audio-volume-muted");
1004     else icon = KIcon("audio-volume-medium");
1005     static_cast <QToolButton *>(m_volumeWidget)->setIcon(icon);
1006     render->slotSetVolume(volume);
1007 }
1008
1009 void Monitor::slotShowVolume()
1010 {
1011     m_volumePopup->move(mapToGlobal(m_toolbar->geometry().topLeft()) + QPoint(mapToParent(m_volumeWidget->geometry().bottomLeft()).x(), -m_volumePopup->height()));
1012     int vol = render->volume();
1013     // Disable widget if we cannot get the volume
1014     m_volumePopup->setEnabled(vol != -1);
1015     m_audioSlider->blockSignals(true);
1016     m_audioSlider->setValue(vol);
1017     m_audioSlider->blockSignals(false);
1018     m_volumePopup->show();
1019 }
1020
1021 AbstractRender *Monitor::abstractRender()
1022 {
1023     return render;
1024 }
1025
1026 MonitorRefresh::MonitorRefresh(QWidget* parent) :
1027     QWidget(parent)
1028     , m_renderer(NULL)
1029 {
1030     // MonitorRefresh is used as container for the SDL display (it's window id is passed to SDL)
1031     setAttribute(Qt::WA_PaintOnScreen);
1032     setAttribute(Qt::WA_OpaquePaintEvent);
1033     setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
1034     //setAttribute(Qt::WA_NoSystemBackground);
1035 }
1036
1037 void MonitorRefresh::setRenderer(Render* render)
1038 {
1039     m_renderer = render;
1040 }
1041
1042
1043 void MonitorRefresh::resizeEvent(QResizeEvent *event)
1044 {
1045     if (m_renderer) m_renderer->doRefresh();
1046 }
1047
1048 Overlay::Overlay(QWidget* parent) :
1049     QLabel(parent)
1050 {
1051     //setAttribute(Qt::WA_TransparentForMouseEvents);
1052     setAutoFillBackground(true);
1053     setBackgroundRole(QPalette::Base);
1054     setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
1055     setCursor(Qt::PointingHandCursor);
1056 }
1057
1058 // virtual
1059 void Overlay::mouseReleaseEvent ( QMouseEvent * event )
1060 {
1061     event->accept();
1062 }
1063
1064 // virtual
1065 void Overlay::mousePressEvent( QMouseEvent * event )
1066 {
1067     event->accept();
1068 }
1069
1070 // virtual
1071 void Overlay::mouseDoubleClickEvent ( QMouseEvent * event )
1072 {
1073     emit editMarker();
1074     event->accept();
1075 }
1076
1077 void Overlay::setOverlayText(const QString &text, bool isZone)
1078 {
1079     setHidden(true);
1080     m_isZone = isZone;
1081     QPalette p;
1082     p.setColor(QPalette::Text, Qt::white);
1083     if (m_isZone) p.setColor(QPalette::Base, QColor(200, 0, 0));
1084     else p.setColor(QPalette::Base, QColor(0, 0, 200));
1085     setPalette(p);
1086     setText(' ' + text + ' ');
1087     setHidden(false);
1088     update();
1089 }
1090
1091 VideoContainer::VideoContainer(Monitor* parent) :
1092     QFrame()
1093     , m_monitor(parent)
1094 {
1095     setFrameShape(QFrame::NoFrame);
1096     setFocusPolicy(Qt::ClickFocus);
1097     setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
1098 }
1099
1100 // virtual
1101 void VideoContainer::mousePressEvent(QMouseEvent * event)
1102 {
1103     if (m_monitor->underMouse()) event->setAccepted(false);
1104 }
1105
1106 // virtual
1107 void VideoContainer::mouseReleaseEvent(QMouseEvent * event)
1108 {
1109     if (m_monitor->underMouse()) event->setAccepted(false);
1110     else {
1111         if (m_monitor->isActive()) {
1112             m_monitor->slotPlay();
1113             event->accept();
1114         }
1115     }
1116 }
1117
1118 // virtual
1119 void VideoContainer::mouseMoveEvent(QMouseEvent *event)
1120 {
1121     if (m_monitor->underMouse()) event->setAccepted(false);
1122 }
1123
1124 // virtual
1125 void VideoContainer::keyPressEvent(QKeyEvent *event)
1126 {
1127     // Exit fullscreen with Esc key
1128     if (event->key() == Qt::Key_Escape && isFullScreen()) {
1129         switchFullScreen();
1130         event->setAccepted(true);
1131     } else event->setAccepted(false);
1132 }
1133
1134 // virtual
1135 void VideoContainer::wheelEvent(QWheelEvent * event)
1136 {
1137     if (m_monitor->underMouse()) event->setAccepted(false);
1138     else {
1139         m_monitor->slotMouseSeek(event->delta(), event->modifiers() == Qt::ControlModifier);
1140         event->accept();
1141     }
1142 }
1143
1144 void VideoContainer::mouseDoubleClickEvent(QMouseEvent * event)
1145 {
1146     Q_UNUSED(event)
1147
1148     if (!KdenliveSettings::openglmonitors())
1149         switchFullScreen();
1150 }
1151
1152 void VideoContainer::switchFullScreen()
1153 {
1154     // TODO: disable screensaver?
1155     Qt::WindowFlags flags = windowFlags();
1156     if (!isFullScreen()) {
1157         // Check if we ahave a multiple monitor setup
1158         setUpdatesEnabled(false);
1159 #if QT_VERSION >= 0x040600
1160         int monitors = QApplication::desktop()->screenCount();
1161 #else
1162         int monitors = QApplication::desktop()->numScreens();
1163 #endif
1164         if (monitors > 1) {
1165             QRect screenres;
1166             // Move monitor widget to the second screen (one screen for Kdenlive, the other one for the Monitor widget
1167             int currentScreen = QApplication::desktop()->screenNumber(this);
1168             if (currentScreen < monitors - 1)
1169                 screenres = QApplication::desktop()->screenGeometry(currentScreen + 1);
1170             else
1171                 screenres = QApplication::desktop()->screenGeometry(currentScreen - 1);
1172             move(QPoint(screenres.x(), screenres.y()));
1173             resize(screenres.width(), screenres.height());
1174         }
1175
1176         m_baseFlags = flags & (Qt::Window | Qt::SubWindow);
1177         flags |= Qt::Window;
1178         flags ^= Qt::SubWindow;
1179         setWindowFlags(flags);
1180 #ifdef Q_WS_X11
1181         // This works around a bug with Compiz
1182         // as the window must be visible before we can set the state
1183         show();
1184         raise();
1185         setWindowState(windowState() | Qt::WindowFullScreen);   // set
1186 #else
1187         setWindowState(windowState() | Qt::WindowFullScreen);   // set
1188         setUpdatesEnabled(true);
1189         show();
1190 #endif
1191     } else {
1192         setUpdatesEnabled(false);
1193         flags ^= (Qt::Window | Qt::SubWindow); //clear the flags...
1194         flags |= m_baseFlags; //then we reset the flags (window and subwindow)
1195         setWindowFlags(flags);
1196         setWindowState(windowState()  ^ Qt::WindowFullScreen);   // reset
1197         setUpdatesEnabled(true);
1198         show();
1199     }
1200     m_monitor->pause();
1201 }
1202
1203
1204 #include "monitor.moc"