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