]> git.sesse.net Git - kdenlive/blob - src/monitor.cpp
Fix freeze when making fast play / pause
[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     disconnect(m_playAction, SIGNAL(triggered()), this, SLOT(slotPlay()));
716     //m_playAction->setChecked(false);
717     connect(m_playAction, SIGNAL(triggered()), this, SLOT(slotPlay()));
718     m_playAction->setIcon(m_playIcon);
719 }
720
721 void Monitor::adjustRulerSize(int length)
722 {
723     if (length > 0) m_length = length;
724     m_ruler->adjustScale(m_length);
725     if (m_currentClip != NULL) {
726         QPoint zone = m_currentClip->zone();
727         m_ruler->setZone(zone.x(), zone.y());
728     }
729 }
730
731 void Monitor::stop()
732 {
733     disconnect(render, SIGNAL(rendererPosition(int)), this, SLOT(seekCursor(int)));
734     if (render) render->stop();
735 }
736
737 void Monitor::start()
738 {
739     if (render) render->start();
740     connect(render, SIGNAL(rendererPosition(int)), this, SLOT(seekCursor(int)));
741 }
742
743 void Monitor::refreshMonitor(bool visible)
744 {
745     if (visible && render) {
746         activateMonitor();
747         render->doRefresh(); //askForRefresh();
748     }
749 }
750
751 void Monitor::refreshMonitor()
752 {
753     if (isActive()) {
754         render->doRefresh();
755     }
756 }
757
758 void Monitor::pause()
759 {
760     if (render == NULL) return;
761     activateMonitor();
762     render->pause();
763     //m_playAction->setChecked(true);
764     m_playAction->setIcon(m_playIcon);
765 }
766
767 void Monitor::slotPlay()
768 {
769     if (render == NULL) return;
770     activateMonitor();
771     if (render->playSpeed() == 0) {
772         //m_playAction->setChecked(true);
773         m_playAction->setIcon(m_pauseIcon);
774         render->switchPlay(true);
775     } else {
776         //m_playAction->setChecked(false);
777         m_playAction->setIcon(m_playIcon);
778         render->switchPlay(false);
779     }
780 }
781
782 void Monitor::slotPlayZone()
783 {
784     if (render == NULL) return;
785     activateMonitor();
786     QPoint p = m_ruler->zone();
787     render->playZone(GenTime(p.x(), m_monitorManager->timecode().fps()), GenTime(p.y(), m_monitorManager->timecode().fps()));
788     //m_playAction->setChecked(true);
789     m_playAction->setIcon(m_pauseIcon);
790 }
791
792 void Monitor::slotLoopZone()
793 {
794     if (render == NULL) return;
795     activateMonitor();
796     QPoint p = m_ruler->zone();
797     render->loopZone(GenTime(p.x(), m_monitorManager->timecode().fps()), GenTime(p.y(), m_monitorManager->timecode().fps()));
798     //m_playAction->setChecked(true);
799     m_playAction->setIcon(m_pauseIcon);
800 }
801
802 void Monitor::slotLoopClip()
803 {
804     if (render == NULL || m_selectedClip == NULL)
805         return;
806     activateMonitor();
807     render->loopZone(m_selectedClip->startPos(), m_selectedClip->endPos());
808     //m_playAction->setChecked(true);
809     m_playAction->setIcon(m_pauseIcon);
810 }
811
812 void Monitor::slotSetXml(DocClipBase *clip, QPoint zone, const int position)
813 {
814     if (render == NULL) return;
815     if (clip == NULL && m_currentClip != NULL) {
816         m_currentClip = NULL;
817         m_length = -1;
818         render->setProducer(NULL, -1);
819         return;
820     }
821     if (m_currentClip != NULL || clip != NULL) activateMonitor();
822     if (clip != m_currentClip) {
823         m_currentClip = clip;
824         updateMarkers(clip);
825         if (render->setProducer(clip->producer(), position) == -1) {
826             // MLT CONSUMER is broken
827             kDebug(QtWarningMsg) << "ERROR, Cannot start monitor";
828         }
829     } else if (position != -1) render->seek(position);
830     if (!zone.isNull()) {
831         m_ruler->setZone(zone.x(), zone.y());
832         render->seek(zone.x());
833     }
834 }
835
836 void Monitor::slotOpenFile(const QString &file)
837 {
838     if (render == NULL) return;
839     activateMonitor();
840     QDomDocument doc;
841     QDomElement mlt = doc.createElement("mlt");
842     doc.appendChild(mlt);
843     QDomElement prod = doc.createElement("producer");
844     mlt.appendChild(prod);
845     prod.setAttribute("mlt_service", "avformat");
846     prod.setAttribute("resource", file);
847     render->setSceneList(doc, 0);
848 }
849
850 void Monitor::slotSaveZone()
851 {
852     if (render == NULL) return;
853     emit saveZone(render, m_ruler->zone());
854
855     //render->setSceneList(doc, 0);
856 }
857
858 void Monitor::resetProfile(const QString profile)
859 {
860     m_timePos->updateTimeCode(m_monitorManager->timecode());
861     if (render == NULL) return;
862     render->resetProfile(profile);
863     if (m_effectWidget)
864         m_effectWidget->resetProfile(render);
865 }
866
867 void Monitor::saveSceneList(QString path, QDomElement info)
868 {
869     if (render == NULL) return;
870     render->saveSceneList(path, info);
871 }
872
873 const QString Monitor::sceneList()
874 {
875     if (render == NULL) return QString();
876     return render->sceneList();
877 }
878
879 void Monitor::setClipZone(QPoint pos)
880 {
881     if (m_currentClip == NULL) return;
882     m_currentClip->setZone(pos);
883 }
884
885 void Monitor::slotSwitchDropFrames(bool show)
886 {
887     render->setDropFrames(show);
888 }
889
890 void Monitor::slotSwitchMonitorInfo(bool show)
891 {
892     KdenliveSettings::setDisplayMonitorInfo(show);
893     if (show) {
894         if (m_overlay) return;
895         if (m_monitorRefresh == NULL) {
896             // Using OpenGL display
897 #if defined(Q_WS_MAC) || defined(USE_OPEN_GL)
898             if (m_glWidget->layout()) delete m_glWidget->layout();
899             m_overlay = new Overlay();
900             connect(m_overlay, SIGNAL(editMarker()), this, SLOT(slotEditMarker()));
901             QVBoxLayout *layout = new QVBoxLayout;
902             layout->addStretch(10);
903             layout->addWidget(m_overlay);
904             m_glWidget->setLayout(layout);
905 #endif
906         } else {
907             if (m_monitorRefresh->layout()) delete m_monitorRefresh->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_monitorRefresh->setLayout(layout);
914             m_overlay->raise();
915             m_overlay->setHidden(true);
916         }
917         checkOverlay();
918     } else {
919         delete m_overlay;
920         m_overlay = NULL;
921     }
922 }
923
924 void Monitor::slotEditMarker()
925 {
926     if (m_editMarker) m_editMarker->trigger();
927 }
928
929 void Monitor::updateTimecodeFormat()
930 {
931     m_timePos->slotUpdateTimeCodeFormat();
932 }
933
934 QStringList Monitor::getZoneInfo() const
935 {
936     QStringList result;
937     if (m_currentClip == NULL) return result;
938     result << m_currentClip->getId();
939     QPoint zone = m_ruler->zone();
940     result << QString::number(zone.x()) << QString::number(zone.y());
941     return result;
942 }
943
944 void Monitor::slotSetSelectedClip(AbstractClipItem* item)
945 {
946     if (item) {
947         m_loopClipAction->setEnabled(true);
948         m_selectedClip = item;
949     } else {
950         m_loopClipAction->setEnabled(false);
951     }
952 }
953
954 void Monitor::slotSetSelectedClip(ClipItem* item)
955 {
956     if (item || (!item && !m_loopClipTransition)) {
957         m_loopClipTransition = false;
958         slotSetSelectedClip((AbstractClipItem*)item);
959     }
960 }
961
962 void Monitor::slotSetSelectedClip(Transition* item)
963 {
964     if (item || (!item && m_loopClipTransition)) {
965         m_loopClipTransition = true;
966         slotSetSelectedClip((AbstractClipItem*)item);
967     }
968 }
969
970
971 void Monitor::slotEffectScene(bool show)
972 {
973     if (m_name == "project") {
974         if (m_monitorRefresh) {
975             m_monitorRefresh->setVisible(!show);
976         } else {
977 #if defined(Q_WS_MAC) || defined(USE_OPEN_GL)
978             m_glWidget->setVisible(!show);
979 #endif
980         }
981         m_effectWidget->setVisible(show);
982         m_effectWidget->getVisibilityAction()->setChecked(show);
983         emit requestFrameForAnalysis(show);
984         if (show) {
985             m_effectWidget->getScene()->slotZoomFit();
986             render->doRefresh();
987         }
988     }
989 }
990
991 MonitorEditWidget* Monitor::getEffectEdit()
992 {
993     return m_effectWidget;
994 }
995
996 bool Monitor::effectSceneDisplayed()
997 {
998     return m_effectWidget->isVisible();
999 }
1000
1001 void Monitor::slotSetVolume(int volume)
1002 {
1003     KdenliveSettings::setVolume(volume);
1004     KIcon icon;
1005     if (volume == 0) icon = KIcon("audio-volume-muted");
1006     else icon = KIcon("audio-volume-medium");
1007     static_cast <QToolButton *>(m_volumeWidget)->setIcon(icon);
1008     render->slotSetVolume(volume);
1009 }
1010
1011 void Monitor::slotShowVolume()
1012 {
1013     m_volumePopup->move(mapToGlobal(m_toolbar->geometry().topLeft()) + QPoint(mapToParent(m_volumeWidget->geometry().bottomLeft()).x(), -m_volumePopup->height()));
1014     int vol = render->volume();
1015     // Disable widget if we cannot get the volume
1016     m_volumePopup->setEnabled(vol != -1);
1017     m_audioSlider->blockSignals(true);
1018     m_audioSlider->setValue(vol);
1019     m_audioSlider->blockSignals(false);
1020     m_volumePopup->show();
1021 }
1022
1023 AbstractRender *Monitor::abstractRender()
1024 {
1025     return render;
1026 }
1027
1028 MonitorRefresh::MonitorRefresh(QWidget* parent) :
1029     QWidget(parent)
1030     , m_renderer(NULL)
1031 {
1032     // MonitorRefresh is used as container for the SDL display (it's window id is passed to SDL)
1033     setAttribute(Qt::WA_PaintOnScreen);
1034     setAttribute(Qt::WA_OpaquePaintEvent);
1035     setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
1036     //setAttribute(Qt::WA_NoSystemBackground);
1037 }
1038
1039 void MonitorRefresh::setRenderer(Render* render)
1040 {
1041     m_renderer = render;
1042 }
1043
1044 void MonitorRefresh::paintEvent(QPaintEvent *event)
1045 {
1046     Q_UNUSED(event)
1047     if (m_renderer) m_renderer->doRefresh();
1048 }
1049
1050 Overlay::Overlay(QWidget* parent) :
1051     QLabel(parent)
1052 {
1053     //setAttribute(Qt::WA_TransparentForMouseEvents);
1054     setAutoFillBackground(true);
1055     setBackgroundRole(QPalette::Base);
1056     setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
1057     setCursor(Qt::PointingHandCursor);
1058 }
1059
1060 // virtual
1061 void Overlay::mouseReleaseEvent ( QMouseEvent * event )
1062 {
1063     event->accept();
1064 }
1065
1066 // virtual
1067 void Overlay::mousePressEvent( QMouseEvent * event )
1068 {
1069     event->accept();
1070 }
1071
1072 // virtual
1073 void Overlay::mouseDoubleClickEvent ( QMouseEvent * event )
1074 {
1075     emit editMarker();
1076     event->accept();
1077 }
1078
1079 void Overlay::setOverlayText(const QString &text, bool isZone)
1080 {
1081     setHidden(true);
1082     m_isZone = isZone;
1083     QPalette p;
1084     p.setColor(QPalette::Text, Qt::white);
1085     if (m_isZone) p.setColor(QPalette::Base, QColor(200, 0, 0));
1086     else p.setColor(QPalette::Base, QColor(0, 0, 200));
1087     setPalette(p);
1088     setText(' ' + text + ' ');
1089     setHidden(false);
1090     update();
1091 }
1092
1093 VideoContainer::VideoContainer(Monitor* parent) :
1094     QFrame()
1095     , m_monitor(parent)
1096 {
1097     setFrameShape(QFrame::NoFrame);
1098     setFocusPolicy(Qt::ClickFocus);
1099     setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
1100 }
1101
1102 // virtual
1103 void VideoContainer::mousePressEvent(QMouseEvent * event)
1104 {
1105     if (m_monitor->underMouse()) event->setAccepted(false);
1106 }
1107
1108 // virtual
1109 void VideoContainer::mouseReleaseEvent(QMouseEvent * event)
1110 {
1111     if (m_monitor->underMouse()) event->setAccepted(false);
1112     else {
1113         if (m_monitor->isActive()) {
1114             m_monitor->slotPlay();
1115             event->accept();
1116         }
1117     }
1118 }
1119
1120 // virtual
1121 void VideoContainer::mouseMoveEvent(QMouseEvent *event)
1122 {
1123     if (m_monitor->underMouse()) event->setAccepted(false);
1124 }
1125
1126 // virtual
1127 void VideoContainer::keyPressEvent(QKeyEvent *event)
1128 {
1129     // Exit fullscreen with Esc key
1130     if (event->key() == Qt::Key_Escape && isFullScreen()) {
1131         switchFullScreen();
1132         event->setAccepted(true);
1133     } else event->setAccepted(false);
1134 }
1135
1136 // virtual
1137 void VideoContainer::wheelEvent(QWheelEvent * event)
1138 {
1139     if (m_monitor->underMouse()) event->setAccepted(false);
1140     else {
1141         m_monitor->slotMouseSeek(event->delta(), event->modifiers() == Qt::ControlModifier);
1142         event->accept();
1143     }
1144 }
1145
1146 void VideoContainer::mouseDoubleClickEvent(QMouseEvent * event)
1147 {
1148     Q_UNUSED(event)
1149
1150     if (!KdenliveSettings::openglmonitors())
1151         switchFullScreen();
1152 }
1153
1154 void VideoContainer::switchFullScreen()
1155 {
1156     // TODO: disable screensaver?
1157     Qt::WindowFlags flags = windowFlags();
1158     if (!isFullScreen()) {
1159         // Check if we ahave a multiple monitor setup
1160         setUpdatesEnabled(false);
1161 #if QT_VERSION >= 0x040600
1162         int monitors = QApplication::desktop()->screenCount();
1163 #else
1164         int monitors = QApplication::desktop()->numScreens();
1165 #endif
1166         if (monitors > 1) {
1167             QRect screenres;
1168             // Move monitor widget to the second screen (one screen for Kdenlive, the other one for the Monitor widget
1169             int currentScreen = QApplication::desktop()->screenNumber(this);
1170             if (currentScreen < monitors - 1)
1171                 screenres = QApplication::desktop()->screenGeometry(currentScreen + 1);
1172             else
1173                 screenres = QApplication::desktop()->screenGeometry(currentScreen - 1);
1174             move(QPoint(screenres.x(), screenres.y()));
1175             resize(screenres.width(), screenres.height());
1176         }
1177
1178         m_baseFlags = flags & (Qt::Window | Qt::SubWindow);
1179         flags |= Qt::Window;
1180         flags ^= Qt::SubWindow;
1181         setWindowFlags(flags);
1182 #ifdef Q_WS_X11
1183         // This works around a bug with Compiz
1184         // as the window must be visible before we can set the state
1185         show();
1186         raise();
1187         setWindowState(windowState() | Qt::WindowFullScreen);   // set
1188 #else
1189         setWindowState(windowState() | Qt::WindowFullScreen);   // set
1190         setUpdatesEnabled(true);
1191         show();
1192 #endif
1193     } else {
1194         setUpdatesEnabled(false);
1195         flags ^= (Qt::Window | Qt::SubWindow); //clear the flags...
1196         flags |= m_baseFlags; //then we reset the flags (window and subwindow)
1197         setWindowFlags(flags);
1198         setWindowState(windowState()  ^ Qt::WindowFullScreen);   // reset
1199         setUpdatesEnabled(true);
1200         show();
1201     }
1202     m_monitor->pause();
1203 }
1204
1205
1206 #include "monitor.moc"