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