]> git.sesse.net Git - kdenlive/blob - src/monitor.cpp
Merge branch 'buildsystem' into next
[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_OPENGL)
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 #ifdef USE_OPENGL
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 #ifdef USE_OPENGL
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(m_ruler->position(), -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, m_ruler->position());
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::resizeEvent(QResizeEvent *event)
459 {
460     Q_UNUSED(event);
461     if (render && isVisible() && isActive()) render->doRefresh();
462 }
463
464
465 void Monitor::slotSwitchFullScreen()
466 {
467     m_videoBox->switchFullScreen();
468 }
469
470 // virtual
471 void Monitor::mouseReleaseEvent(QMouseEvent * event)
472 {
473     if (m_dragStarted) {
474         if (m_videoBox->underMouse() && (!m_effectWidget || !m_effectWidget->isVisible())) {
475             if (isActive()) slotPlay();
476             else activateMonitor();
477         } else QWidget::mouseReleaseEvent(event);
478         m_dragStarted = false;
479     }
480 }
481
482 // virtual
483 void Monitor::mouseMoveEvent(QMouseEvent *event)
484 {
485     // kDebug() << "// DRAG STARTED, MOUSE MOVED: ";
486     if (!m_dragStarted || m_currentClip == NULL) return;
487
488     if ((event->pos() - m_DragStartPosition).manhattanLength()
489             < QApplication::startDragDistance())
490         return;
491
492     {
493         QDrag *drag = new QDrag(this);
494         QMimeData *mimeData = new QMimeData;
495
496         QStringList list;
497         list.append(m_currentClip->getId());
498         QPoint p = m_ruler->zone();
499         list.append(QString::number(p.x()));
500         list.append(QString::number(p.y()));
501         QByteArray data;
502         data.append(list.join(";").toUtf8());
503         mimeData->setData("kdenlive/clip", data);
504         drag->setMimeData(mimeData);
505         QPixmap pix = m_currentClip->thumbnail();
506         drag->setPixmap(pix);
507         drag->setHotSpot(QPoint(0, 50));
508         drag->start(Qt::MoveAction);
509
510         //Qt::DropAction dropAction;
511         //dropAction = drag->start(Qt::CopyAction | Qt::MoveAction);
512
513         //Qt::DropAction dropAction = drag->exec();
514
515     }
516     //event->accept();
517 }
518
519 /*void Monitor::dragMoveEvent(QDragMoveEvent * event) {
520     event->setDropAction(Qt::IgnoreAction);
521     event->setDropAction(Qt::MoveAction);
522     if (event->mimeData()->hasText()) {
523         event->acceptProposedAction();
524     }
525 }
526
527 Qt::DropActions Monitor::supportedDropActions() const {
528     // returns what actions are supported when dropping
529     return Qt::MoveAction;
530 }*/
531
532 QStringList Monitor::mimeTypes() const
533 {
534     QStringList qstrList;
535     // list of accepted mime types for drop
536     qstrList.append("kdenlive/clip");
537     return qstrList;
538 }
539
540 // virtual
541 void Monitor::wheelEvent(QWheelEvent * event)
542 {
543     slotMouseSeek(event->delta(), event->modifiers() == Qt::ControlModifier);
544     event->accept();
545 }
546
547 void Monitor::slotMouseSeek(int eventDelta, bool fast)
548 {
549     if (fast) {
550         int delta = m_monitorManager->timecode().fps();
551         if (eventDelta > 0) delta = 0 - delta;
552         slotSeek(m_ruler->position() - delta);
553     } else {
554         if (eventDelta >= 0) slotForwardOneFrame();
555         else slotRewindOneFrame();
556     }
557 }
558
559 void Monitor::slotSetThumbFrame()
560 {
561     if (m_currentClip == NULL) {
562         return;
563     }
564     m_currentClip->setClipThumbFrame((uint) render->seekFramePosition());
565     emit refreshClipThumbnail(m_currentClip->getId(), true);
566 }
567
568 void Monitor::slotExtractCurrentFrame()
569 {
570     QImage frame;
571     // check if we are using a proxy
572     if (m_currentClip && !m_currentClip->getProperty("proxy").isEmpty() && m_currentClip->getProperty("proxy") != "-") {
573         // using proxy, use original clip url to get frame
574         frame = render->extractFrame(render->seekFramePosition(), m_currentClip->fileURL().path());
575     }
576     else frame = render->extractFrame(render->seekFramePosition());
577     KFileDialog *fs = new KFileDialog(KUrl(), "image/png", this);
578     fs->setOperationMode(KFileDialog::Saving);
579     fs->setMode(KFile::File);
580     fs->setConfirmOverwrite(true);
581     fs->setKeepLocation(true);
582     fs->exec();
583     QString path = fs->selectedFile();
584     delete fs;
585     if (!path.isEmpty()) {
586         frame.save(path);
587     }
588 }
589
590 bool Monitor::isActive() const
591 {
592     return m_monitorManager->isActive(m_name);
593 }
594
595 bool Monitor::activateMonitor()
596 {
597     return m_monitorManager->activateMonitor(m_name);
598 }
599
600 void Monitor::setTimePos(const QString &pos)
601 {
602     m_timePos->setValue(pos);
603     slotSeek();
604 }
605
606 void Monitor::slotSeek()
607 {
608     slotSeek(m_timePos->getValue());
609 }
610
611 void Monitor::slotSeek(int pos)
612 {
613     if (render == NULL) return;
614     activateMonitor();
615     render->seekToFrame(pos);
616 }
617
618 void Monitor::checkOverlay()
619 {
620     if (m_overlay == NULL) return;
621     int pos = m_ruler->position();
622     QPoint zone = m_ruler->zone();
623     if (pos == zone.x())
624         m_overlay->setOverlayText(i18n("In Point"));
625     else if (pos == zone.y())
626         m_overlay->setOverlayText(i18n("Out Point"));
627     else {
628         if (m_currentClip) {
629             QString markerComment = m_currentClip->markerComment(GenTime(pos, m_monitorManager->timecode().fps()));
630             if (markerComment.isEmpty())
631                 m_overlay->setHidden(true);
632             else
633                 m_overlay->setOverlayText(markerComment, false);
634         } else m_overlay->setHidden(true);
635     }
636 }
637
638 void Monitor::slotStart()
639 {
640     activateMonitor();
641     render->play(0);
642     render->seekToFrame(0);
643 }
644
645 void Monitor::slotEnd()
646 {
647     activateMonitor();
648     render->play(0);
649     render->seekToFrame(render->getLength());
650 }
651
652 void Monitor::slotZoneStart()
653 {
654     activateMonitor();
655     render->play(0);
656     render->seekToFrame(m_ruler->zone().x());
657 }
658
659 void Monitor::slotZoneEnd()
660 {
661     activateMonitor();
662     render->play(0);
663     render->seekToFrame(m_ruler->zone().y());
664 }
665
666 void Monitor::slotRewind(double speed)
667 {
668     activateMonitor();
669     if (speed == 0) {
670         double currentspeed = render->playSpeed();
671         if (currentspeed >= 0) render->play(-2);
672         else render->play(currentspeed * 2);
673     } else render->play(speed);
674     //m_playAction->setChecked(true);
675     m_playAction->setIcon(m_pauseIcon);
676 }
677
678 void Monitor::slotForward(double speed)
679 {
680     activateMonitor();
681     if (speed == 0) {
682         double currentspeed = render->playSpeed();
683         if (currentspeed <= 1) render->play(2);
684         else render->play(currentspeed * 2);
685     } else render->play(speed);
686     //m_playAction->setChecked(true);
687     m_playAction->setIcon(m_pauseIcon);
688 }
689
690 void Monitor::slotRewindOneFrame(int diff)
691 {
692     activateMonitor();
693     render->play(0);
694     render->seekToFrameDiff(-diff);
695 }
696
697 void Monitor::slotForwardOneFrame(int diff)
698 {
699     activateMonitor();
700     render->play(0);
701     render->seekToFrameDiff(diff);
702 }
703
704 void Monitor::seekCursor(int pos)
705 {
706     //activateMonitor();
707     if (m_ruler->slotNewValue(pos)) {
708         checkOverlay();
709         m_timePos->setValue(pos);
710     }
711 }
712
713 void Monitor::rendererStopped(int pos)
714 {
715     if (m_ruler->slotNewValue(pos)) {
716         checkOverlay();
717         m_timePos->setValue(pos);
718     }
719     m_playAction->setIcon(m_playIcon);
720 }
721
722 void Monitor::adjustRulerSize(int length)
723 {
724     if (length > 0) m_length = length;
725     m_ruler->adjustScale(m_length);
726     if (m_currentClip != NULL) {
727         QPoint zone = m_currentClip->zone();
728         m_ruler->setZone(zone.x(), zone.y());
729     }
730 }
731
732 void Monitor::stop()
733 {
734     disconnect(render, SIGNAL(rendererPosition(int)), this, SLOT(seekCursor(int)));
735     if (render) render->stop();
736 }
737
738 void Monitor::start()
739 {
740     if (!isVisible()) return;
741     if (render) render->start();
742     connect(render, SIGNAL(rendererPosition(int)), this, SLOT(seekCursor(int)));
743 }
744
745 void Monitor::refreshMonitor(bool visible)
746 {
747     if (visible && render) {
748         if (!activateMonitor()) {
749             // the monitor was already active, simply refreshClipThumbnail
750             render->doRefresh();
751         }
752     }
753 }
754
755 void Monitor::refreshMonitor()
756 {
757     if (isActive()) {
758         render->doRefresh();
759     }
760 }
761
762 void Monitor::pause()
763 {
764     if (render == NULL) return;
765     activateMonitor();
766     render->pause();
767     //m_playAction->setChecked(true);
768     m_playAction->setIcon(m_playIcon);
769 }
770
771 void Monitor::slotPlay()
772 {
773     if (render == NULL) return;
774     activateMonitor();
775     if (render->playSpeed() == 0.0) {
776         m_playAction->setIcon(m_pauseIcon);
777         render->switchPlay(true);
778     } else {
779         m_playAction->setIcon(m_playIcon);
780         render->switchPlay(false);
781     }
782 }
783
784 void Monitor::slotPlayZone()
785 {
786     if (render == NULL) return;
787     activateMonitor();
788     QPoint p = m_ruler->zone();
789     render->playZone(GenTime(p.x(), m_monitorManager->timecode().fps()), GenTime(p.y(), m_monitorManager->timecode().fps()));
790     //m_playAction->setChecked(true);
791     m_playAction->setIcon(m_pauseIcon);
792 }
793
794 void Monitor::slotLoopZone()
795 {
796     if (render == NULL) return;
797     activateMonitor();
798     QPoint p = m_ruler->zone();
799     render->loopZone(GenTime(p.x(), m_monitorManager->timecode().fps()), GenTime(p.y(), m_monitorManager->timecode().fps()));
800     //m_playAction->setChecked(true);
801     m_playAction->setIcon(m_pauseIcon);
802 }
803
804 void Monitor::slotLoopClip()
805 {
806     if (render == NULL || m_selectedClip == NULL)
807         return;
808     activateMonitor();
809     render->loopZone(m_selectedClip->startPos(), m_selectedClip->endPos());
810     //m_playAction->setChecked(true);
811     m_playAction->setIcon(m_pauseIcon);
812 }
813
814 void Monitor::updateClipProducer(Mlt::Producer *prod)
815 {
816     if (render == NULL) return;
817    render->setProducer(prod, render->seekFramePosition());
818 }
819
820 void Monitor::slotSetClipProducer(DocClipBase *clip, QPoint zone, int position)
821 {
822     if (render == NULL) return;
823     if (clip == NULL && m_currentClip != NULL) {
824         kDebug()<<"// SETTING NULL CLIP MONITOR";
825         m_currentClip = NULL;
826         m_length = -1;
827         render->setProducer(NULL, -1);
828         return;
829     }
830     
831     if (clip != m_currentClip) {
832         m_currentClip = clip;
833         if (m_currentClip) activateMonitor();
834         updateMarkers(clip);
835         Mlt::Producer *prod = NULL;
836         if (clip) prod = clip->getCloneProducer();
837         if (render->setProducer(prod, position) == -1) {
838             // MLT CONSUMER is broken
839             kDebug(QtWarningMsg) << "ERROR, Cannot start monitor";
840         }
841     } else {
842         if (m_currentClip) {
843             activateMonitor();
844             if (position == -1) position = render->seekFramePosition();
845             render->seek(position);
846         }
847     }
848     if (!zone.isNull()) {
849         m_ruler->setZone(zone.x(), zone.y());
850         render->seek(zone.x());
851     }
852 }
853
854 void Monitor::slotOpenFile(const QString &file)
855 {
856     if (render == NULL) return;
857     activateMonitor();
858     QDomDocument doc;
859     QDomElement mlt = doc.createElement("mlt");
860     doc.appendChild(mlt);
861     QDomElement prod = doc.createElement("producer");
862     mlt.appendChild(prod);
863     prod.setAttribute("mlt_service", "avformat");
864     prod.setAttribute("resource", file);
865     render->setSceneList(doc, 0);
866 }
867
868 void Monitor::slotSaveZone()
869 {
870     if (render == NULL) return;
871     emit saveZone(render, m_ruler->zone(), m_currentClip);
872
873     //render->setSceneList(doc, 0);
874 }
875
876 void Monitor::resetProfile(const QString &profile)
877 {
878     m_timePos->updateTimeCode(m_monitorManager->timecode());
879     if (render == NULL) return;
880     if (!render->hasProfile(profile)) {
881         activateMonitor();
882         render->resetProfile(profile);
883     }
884     if (m_effectWidget)
885         m_effectWidget->resetProfile(render);
886 }
887
888 void Monitor::saveSceneList(QString path, QDomElement info)
889 {
890     if (render == NULL) return;
891     render->saveSceneList(path, info);
892 }
893
894 const QString Monitor::sceneList()
895 {
896     if (render == NULL) return QString();
897     return render->sceneList();
898 }
899
900 void Monitor::setClipZone(QPoint pos)
901 {
902     if (m_currentClip == NULL) return;
903     m_currentClip->setZone(pos);
904 }
905
906 void Monitor::slotSwitchDropFrames(bool show)
907 {
908     render->setDropFrames(show);
909 }
910
911 void Monitor::slotSwitchMonitorInfo(bool show)
912 {
913     KdenliveSettings::setDisplayMonitorInfo(show);
914     if (show) {
915         if (m_overlay) return;
916         if (m_monitorRefresh == NULL) {
917             // Using OpenGL display
918 #ifdef USE_OPENGL
919             if (m_glWidget->layout()) delete m_glWidget->layout();
920             m_overlay = new Overlay();
921             connect(m_overlay, SIGNAL(editMarker()), this, SLOT(slotEditMarker()));
922             QVBoxLayout *layout = new QVBoxLayout;
923             layout->addStretch(10);
924             layout->addWidget(m_overlay);
925             m_glWidget->setLayout(layout);
926 #endif
927         } else {
928             if (m_monitorRefresh->layout()) delete m_monitorRefresh->layout();
929             m_overlay = new Overlay();
930             connect(m_overlay, SIGNAL(editMarker()), this, SLOT(slotEditMarker()));
931             QVBoxLayout *layout = new QVBoxLayout;
932             layout->addStretch(10);
933             layout->addWidget(m_overlay);
934             m_monitorRefresh->setLayout(layout);
935             m_overlay->raise();
936             m_overlay->setHidden(true);
937         }
938         checkOverlay();
939     } else {
940         delete m_overlay;
941         m_overlay = NULL;
942     }
943 }
944
945 void Monitor::slotEditMarker()
946 {
947     if (m_editMarker) m_editMarker->trigger();
948 }
949
950 void Monitor::updateTimecodeFormat()
951 {
952     m_timePos->slotUpdateTimeCodeFormat();
953 }
954
955 QStringList Monitor::getZoneInfo() const
956 {
957     QStringList result;
958     if (m_currentClip == NULL) return result;
959     result << m_currentClip->getId();
960     QPoint zone = m_ruler->zone();
961     result << QString::number(zone.x()) << QString::number(zone.y());
962     return result;
963 }
964
965 void Monitor::slotSetSelectedClip(AbstractClipItem* item)
966 {
967     if (item) {
968         m_loopClipAction->setEnabled(true);
969         m_selectedClip = item;
970     } else {
971         m_loopClipAction->setEnabled(false);
972     }
973 }
974
975 void Monitor::slotSetSelectedClip(ClipItem* item)
976 {
977     if (item || (!item && !m_loopClipTransition)) {
978         m_loopClipTransition = false;
979         slotSetSelectedClip((AbstractClipItem*)item);
980     }
981 }
982
983 void Monitor::slotSetSelectedClip(Transition* item)
984 {
985     if (item || (!item && m_loopClipTransition)) {
986         m_loopClipTransition = true;
987         slotSetSelectedClip((AbstractClipItem*)item);
988     }
989 }
990
991
992 void Monitor::slotEffectScene(bool show)
993 {
994     if (m_name == "project") {
995         if (m_monitorRefresh) {
996             m_monitorRefresh->setVisible(!show);
997         } else {
998 #ifdef USE_OPENGL
999             m_glWidget->setVisible(!show);
1000 #endif
1001         }
1002         m_effectWidget->setVisible(show);
1003         m_effectWidget->getVisibilityAction()->setChecked(show);
1004         emit requestFrameForAnalysis(show);
1005         if (show) {
1006             m_effectWidget->getScene()->slotZoomFit();
1007         }
1008         render->doRefresh();
1009     }
1010 }
1011
1012 MonitorEditWidget* Monitor::getEffectEdit()
1013 {
1014     return m_effectWidget;
1015 }
1016
1017 bool Monitor::effectSceneDisplayed()
1018 {
1019     return m_effectWidget->isVisible();
1020 }
1021
1022 void Monitor::slotSetVolume(int volume)
1023 {
1024     KdenliveSettings::setVolume(volume);
1025     KIcon icon;
1026     if (volume == 0) icon = KIcon("audio-volume-muted");
1027     else icon = KIcon("audio-volume-medium");
1028     static_cast <QToolButton *>(m_volumeWidget)->setIcon(icon);
1029     render->slotSetVolume(volume);
1030 }
1031
1032 void Monitor::slotShowVolume()
1033 {
1034     m_volumePopup->move(mapToGlobal(m_toolbar->geometry().topLeft()) + QPoint(mapToParent(m_volumeWidget->geometry().bottomLeft()).x(), -m_volumePopup->height()));
1035     int vol = render->volume();
1036     // Disable widget if we cannot get the volume
1037     m_volumePopup->setEnabled(vol != -1);
1038     m_audioSlider->blockSignals(true);
1039     m_audioSlider->setValue(vol);
1040     m_audioSlider->blockSignals(false);
1041     m_volumePopup->show();
1042 }
1043
1044 AbstractRender *Monitor::abstractRender()
1045 {
1046     return render;
1047 }
1048
1049 MonitorRefresh::MonitorRefresh(QWidget* parent) :
1050     QWidget(parent)
1051     , m_renderer(NULL)
1052 {
1053     // MonitorRefresh is used as container for the SDL display (it's window id is passed to SDL)
1054     setAttribute(Qt::WA_PaintOnScreen);
1055     setAttribute(Qt::WA_OpaquePaintEvent);
1056     setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
1057     //setAttribute(Qt::WA_NoSystemBackground);
1058 }
1059
1060 void MonitorRefresh::setRenderer(Render* render)
1061 {
1062     m_renderer = render;
1063 }
1064
1065
1066 Overlay::Overlay(QWidget* parent) :
1067     QLabel(parent)
1068 {
1069     //setAttribute(Qt::WA_TransparentForMouseEvents);
1070     setAutoFillBackground(true);
1071     setBackgroundRole(QPalette::Base);
1072     setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
1073     setCursor(Qt::PointingHandCursor);
1074 }
1075
1076 // virtual
1077 void Overlay::mouseReleaseEvent ( QMouseEvent * event )
1078 {
1079     event->accept();
1080 }
1081
1082 // virtual
1083 void Overlay::mousePressEvent( QMouseEvent * event )
1084 {
1085     event->accept();
1086 }
1087
1088 // virtual
1089 void Overlay::mouseDoubleClickEvent ( QMouseEvent * event )
1090 {
1091     emit editMarker();
1092     event->accept();
1093 }
1094
1095 void Overlay::setOverlayText(const QString &text, bool isZone)
1096 {
1097     setHidden(true);
1098     m_isZone = isZone;
1099     QPalette p;
1100     p.setColor(QPalette::Text, Qt::white);
1101     if (m_isZone) p.setColor(QPalette::Base, QColor(200, 0, 0));
1102     else p.setColor(QPalette::Base, QColor(0, 0, 200));
1103     setPalette(p);
1104     setText(' ' + text + ' ');
1105     setHidden(false);
1106     update();
1107 }
1108
1109 VideoContainer::VideoContainer(Monitor* parent) :
1110     QFrame()
1111     , m_monitor(parent)
1112 {
1113     setFrameShape(QFrame::NoFrame);
1114     setFocusPolicy(Qt::ClickFocus);
1115     setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
1116 }
1117
1118 // virtual
1119 void VideoContainer::mousePressEvent(QMouseEvent * event)
1120 {
1121     if (m_monitor->underMouse()) event->setAccepted(false);
1122 }
1123
1124 // virtual
1125 void VideoContainer::mouseReleaseEvent(QMouseEvent * event)
1126 {
1127     if (m_monitor->underMouse()) event->setAccepted(false);
1128     else {
1129         if (m_monitor->isActive()) {
1130             m_monitor->slotPlay();
1131             event->accept();
1132         }
1133     }
1134 }
1135
1136 // virtual
1137 void VideoContainer::mouseMoveEvent(QMouseEvent *event)
1138 {
1139     if (m_monitor->underMouse()) event->setAccepted(false);
1140 }
1141
1142 // virtual
1143 void VideoContainer::keyPressEvent(QKeyEvent *event)
1144 {
1145     // Exit fullscreen with Esc key
1146     if (event->key() == Qt::Key_Escape && isFullScreen()) {
1147         switchFullScreen();
1148         event->setAccepted(true);
1149     } else event->setAccepted(false);
1150 }
1151
1152 // virtual
1153 void VideoContainer::wheelEvent(QWheelEvent * event)
1154 {
1155     if (m_monitor->underMouse()) event->setAccepted(false);
1156     else {
1157         m_monitor->slotMouseSeek(event->delta(), event->modifiers() == Qt::ControlModifier);
1158         event->accept();
1159     }
1160 }
1161
1162 void VideoContainer::mouseDoubleClickEvent(QMouseEvent * event)
1163 {
1164     Q_UNUSED(event)
1165
1166     if (!KdenliveSettings::openglmonitors())
1167         switchFullScreen();
1168 }
1169
1170 void VideoContainer::switchFullScreen()
1171 {
1172     // TODO: disable screensaver?
1173     Qt::WindowFlags flags = windowFlags();
1174     if (!isFullScreen()) {
1175         // Check if we ahave a multiple monitor setup
1176         setUpdatesEnabled(false);
1177 #if QT_VERSION >= 0x040600
1178         int monitors = QApplication::desktop()->screenCount();
1179 #else
1180         int monitors = QApplication::desktop()->numScreens();
1181 #endif
1182         if (monitors > 1) {
1183             QRect screenres;
1184             // Move monitor widget to the second screen (one screen for Kdenlive, the other one for the Monitor widget
1185             int currentScreen = QApplication::desktop()->screenNumber(this);
1186             if (currentScreen < monitors - 1)
1187                 screenres = QApplication::desktop()->screenGeometry(currentScreen + 1);
1188             else
1189                 screenres = QApplication::desktop()->screenGeometry(currentScreen - 1);
1190             move(QPoint(screenres.x(), screenres.y()));
1191             resize(screenres.width(), screenres.height());
1192         }
1193
1194         m_baseFlags = flags & (Qt::Window | Qt::SubWindow);
1195         flags |= Qt::Window;
1196         flags ^= Qt::SubWindow;
1197         setWindowFlags(flags);
1198 #ifdef Q_WS_X11
1199         // This works around a bug with Compiz
1200         // as the window must be visible before we can set the state
1201         show();
1202         raise();
1203         setWindowState(windowState() | Qt::WindowFullScreen);   // set
1204 #else
1205         setWindowState(windowState() | Qt::WindowFullScreen);   // set
1206         setUpdatesEnabled(true);
1207         show();
1208 #endif
1209     } else {
1210         setUpdatesEnabled(false);
1211         flags ^= (Qt::Window | Qt::SubWindow); //clear the flags...
1212         flags |= m_baseFlags; //then we reset the flags (window and subwindow)
1213         setWindowFlags(flags);
1214         setWindowState(windowState()  ^ Qt::WindowFullScreen);   // reset
1215         setUpdatesEnabled(true);
1216         show();
1217     }
1218     m_monitor->pause();
1219 }
1220
1221
1222 #include "monitor.moc"