]> git.sesse.net Git - kdenlive/blob - src/monitor.cpp
720d667487406e8fd6f1e9e78ba311c22e46f7d8
[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 "renderer.h"
23 #include "monitormanager.h"
24 #include "smallruler.h"
25 #include "docclipbase.h"
26 #include "abstractclipitem.h"
27 #include "monitorscene.h"
28 #include "monitoreditwidget.h"
29 #include "kdenlivesettings.h"
30
31 #include <KDebug>
32 #include <KLocale>
33 #include <KFileDialog>
34 #include <KApplication>
35 #include <KMessageBox>
36
37 #include <QMouseEvent>
38 #include <QStylePainter>
39 #include <QMenu>
40 #include <QToolButton>
41 #include <QToolBar>
42 #include <QDesktopWidget>
43 #include <QLabel>
44 #include <QIntValidator>
45 #include <QVBoxLayout>
46
47
48 Monitor::Monitor(QString name, MonitorManager *manager, QString profile, QWidget *parent) :
49     QWidget(parent),
50     render(NULL),
51     m_name(name),
52     m_monitorManager(manager),
53     m_currentClip(NULL),
54     m_ruler(new SmallRuler(m_monitorManager)),
55     m_overlay(NULL),
56     m_isActive(false),
57     m_scale(1),
58     m_length(0),
59     m_dragStarted(false),
60     m_monitorRefresh(NULL),
61     m_effectWidget(NULL),
62     m_selectedClip(NULL),
63     m_loopClipTransition(true),
64     m_editMarker(NULL)
65
66 {
67     QVBoxLayout *layout = new QVBoxLayout;
68     layout->setContentsMargins(0, 0, 0, 0);
69     layout->setSpacing(0);
70
71     // Video widget holder
72     m_videoBox = new VideoContainer(this);
73     m_videoBox->setContentsMargins(0, 0, 0, 0);
74     m_videoBox->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
75     layout->addWidget(m_videoBox, 10);
76     layout->addStretch();
77
78     // Get base size for icons
79     int s = style()->pixelMetric(QStyle::PM_SmallIconSize);
80
81     // Monitor ruler
82     layout->addWidget(m_ruler);
83     // Tool bar buttons
84     m_toolbar = new QToolBar(name, this);
85     m_toolbar->setIconSize(QSize(s, s));
86
87     m_playIcon = KIcon("media-playback-start");
88     m_pauseIcon = KIcon("media-playback-pause");
89
90     if (name != "chapter") {
91         m_toolbar->addAction(KIcon("kdenlive-zone-start"), i18n("Set zone start"), this, SLOT(slotSetZoneStart()));
92         m_toolbar->addAction(KIcon("kdenlive-zone-end"), i18n("Set zone end"), this, SLOT(slotSetZoneEnd()));
93     } else {
94         m_ruler->setZone(-3, -2);
95     }
96
97     m_toolbar->addAction(KIcon("media-seek-backward"), i18n("Rewind"), this, SLOT(slotRewind()));
98     //m_toolbar->addAction(KIcon("media-skip-backward"), i18n("Rewind 1 frame"), this, SLOT(slotRewindOneFrame()));
99
100     QToolButton *playButton = new QToolButton(m_toolbar);
101     m_playMenu = new QMenu(i18n("Play..."), this);
102     m_playAction = m_playMenu->addAction(m_playIcon, i18n("Play"));
103     //m_playAction->setCheckable(true);
104     connect(m_playAction, SIGNAL(triggered()), this, SLOT(slotPlay()));
105
106     playButton->setMenu(m_playMenu);
107     playButton->setPopupMode(QToolButton::MenuButtonPopup);
108     m_toolbar->addWidget(playButton);
109
110     //m_toolbar->addAction(KIcon("media-skip-forward"), i18n("Forward 1 frame"), this, SLOT(slotForwardOneFrame()));
111     m_toolbar->addAction(KIcon("media-seek-forward"), i18n("Forward"), this, SLOT(slotForward()));
112
113     playButton->setDefaultAction(m_playAction);
114
115     if (name != "chapter") {
116         QToolButton *configButton = new QToolButton(m_toolbar);
117         m_configMenu = new QMenu(i18n("Misc..."), this);
118         configButton->setIcon(KIcon("system-run"));
119         configButton->setMenu(m_configMenu);
120         configButton->setPopupMode(QToolButton::QToolButton::InstantPopup);
121         m_toolbar->addWidget(configButton);
122
123         if (name == "clip") {
124             m_markerMenu = new QMenu(i18n("Go to marker..."), this);
125             m_markerMenu->setEnabled(false);
126             m_configMenu->addMenu(m_markerMenu);
127             connect(m_markerMenu, SIGNAL(triggered(QAction *)), this, SLOT(slotGoToMarker(QAction *)));
128         }
129         m_configMenu->addAction(KIcon("transform-scale"), i18n("Resize (100%)"), this, SLOT(slotSetSizeOneToOne()));
130         m_configMenu->addAction(KIcon("transform-scale"), i18n("Resize (50%)"), this, SLOT(slotSetSizeOneToTwo()));
131     }
132
133     // Create Volume slider popup
134     m_volumePopup = new QFrame(this, Qt::Popup);
135     QVBoxLayout *poplayout = new QVBoxLayout;
136     poplayout->setContentsMargins(0, 0, 0, 0);
137     m_audioSlider = new QSlider(Qt::Vertical);
138     m_audioSlider->setRange(0, 100);
139     poplayout->addWidget(m_audioSlider);
140     m_volumePopup->setLayout(poplayout);
141     KIcon icon;
142     if (KdenliveSettings::volume() == 0) icon = KIcon("audio-volume-muted");
143     else icon = KIcon("audio-volume-medium");
144
145     m_volumeWidget = m_toolbar->widgetForAction(m_toolbar->addAction(icon, i18n("Audio volume"), this, SLOT(slotShowVolume())));
146
147     // we need to show / hide the popup once so that it's geometry can be calculated in slotShowVolume
148     m_volumePopup->show();
149     m_volumePopup->hide();
150
151     setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
152     setLayout(layout);
153     setMinimumHeight(200);
154
155     if (profile.isEmpty()) profile = KdenliveSettings::current_profile();
156
157     bool monitorCreated = false;
158 #ifdef Q_WS_MAC
159     createOpenGlWidget(m_videoBox, profile);
160     monitorCreated = true;
161     //m_glWidget->setFixedSize(width, height);
162 #elif defined (USE_OPEN_GL)
163     if (KdenliveSettings::openglmonitors()) {
164         monitorCreated = createOpenGlWidget(m_videoBox, profile);
165     }
166 #endif
167     QVBoxLayout *lay = new QVBoxLayout;
168     lay->setContentsMargins(0, 0, 0, 0);
169     if (!monitorCreated) {
170         m_monitorRefresh = new MonitorRefresh;
171         lay->addWidget(m_monitorRefresh);
172         m_videoBox->setLayout(lay);
173         render = new Render(m_name, (int) m_monitorRefresh->winId(), profile, this);
174         m_monitorRefresh->setRenderer(render);
175     }
176 #if defined (USE_OPEN_GL)
177     else if (m_glWidget) {
178         lay->addWidget(m_glWidget);
179         m_videoBox->setLayout(lay);
180     }
181 #endif
182
183     connect(m_audioSlider, SIGNAL(valueChanged(int)), this, SLOT(slotSetVolume(int)));
184     connect(m_ruler, SIGNAL(seekRenderer(int)), this, SLOT(slotSeek(int)));
185     connect(render, SIGNAL(durationChanged(int)), this, SLOT(adjustRulerSize(int)));
186     connect(render, SIGNAL(rendererStopped(int)), this, SLOT(rendererStopped(int)));
187
188     //render->createVideoXWindow(m_ui.video_frame->winId(), -1);
189
190     if (name != "clip") {
191         connect(render, SIGNAL(rendererPosition(int)), this, SIGNAL(renderPosition(int)));
192         connect(render, SIGNAL(durationChanged(int)), this, SIGNAL(durationChanged(int)));
193         connect(m_ruler, SIGNAL(zoneChanged(QPoint)), this, SIGNAL(zoneUpdated(QPoint)));
194     } else {
195         connect(m_ruler, SIGNAL(zoneChanged(QPoint)), this, SLOT(setClipZone(QPoint)));
196     }
197
198     if (m_monitorRefresh) m_monitorRefresh->show();
199
200     if (name == "project") {
201         m_effectWidget = new MonitorEditWidget(render, m_videoBox);
202         m_toolbar->addAction(m_effectWidget->getVisibilityAction());
203         lay->addWidget(m_effectWidget);
204         m_effectWidget->hide();
205     }
206
207     QWidget *spacer = new QWidget(this);
208     spacer->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred);
209     m_toolbar->addWidget(spacer);
210     m_timePos = new TimecodeDisplay(m_monitorManager->timecode(), this);
211     m_toolbar->addWidget(m_timePos);
212     connect(m_timePos, SIGNAL(editingFinished()), this, SLOT(slotSeek()));
213     m_toolbar->setMaximumHeight(s * 1.5);
214     layout->addWidget(m_toolbar);
215 }
216
217 Monitor::~Monitor()
218 {
219     delete m_ruler;
220     delete m_timePos;
221     delete m_overlay;
222     if (m_effectWidget)
223         delete m_effectWidget;
224     delete m_monitorRefresh;
225     delete render;
226 }
227
228 QWidget *Monitor::container()
229 {
230     return m_videoBox;
231 }
232
233 QString Monitor::name() const
234 {
235     return m_name;
236 }
237
238 #if defined(Q_WS_MAC) || defined(USE_OPEN_GL)
239 bool Monitor::createOpenGlWidget(QWidget *parent, const QString profile)
240 {
241     render = new Render(m_name, 0, profile, this);
242     m_glWidget = new VideoGLWidget(parent);
243     if (m_glWidget == NULL) {
244         // Creation failed, we are in trouble...
245         return false;
246     }
247     m_glWidget->setImageAspectRatio(render->dar());
248     m_glWidget->setBackgroundColor(KdenliveSettings::window_background());
249     connect(render, SIGNAL(showImageSignal(QImage)), m_glWidget, SLOT(showImage(QImage)));
250     return true;
251 }
252 #endif
253
254 void Monitor::setupMenu(QMenu *goMenu, QAction *playZone, QAction *loopZone, QMenu *markerMenu, QAction *loopClip)
255 {
256     m_contextMenu = new QMenu(this);
257     m_contextMenu->addMenu(m_playMenu);
258     if (goMenu)
259         m_contextMenu->addMenu(goMenu);
260     if (markerMenu) {
261         m_contextMenu->addMenu(markerMenu);
262         QList <QAction *>list = markerMenu->actions();
263         for (int i = 0; i < list.count(); i++) {
264             if (list.at(i)->data().toString() == "edit_marker") {
265                 m_editMarker = list.at(i);
266                 break;
267             }
268         }
269     }
270
271     m_playMenu->addAction(playZone);
272     m_playMenu->addAction(loopZone);
273     if (loopClip) {
274         m_loopClipAction = loopClip;
275         m_playMenu->addAction(loopClip);
276     }
277
278     //TODO: add save zone to timeline monitor when fixed
279     if (m_name == "clip") {
280         m_contextMenu->addMenu(m_markerMenu);
281         m_contextMenu->addAction(KIcon("document-save"), i18n("Save zone"), this, SLOT(slotSaveZone()));
282     }
283     QAction *extractFrame = m_configMenu->addAction(KIcon("document-new"), i18n("Extract frame"), this, SLOT(slotExtractCurrentFrame()));
284     m_contextMenu->addAction(extractFrame);
285
286     if (m_name != "clip") {
287         QAction *splitView = m_contextMenu->addAction(KIcon("view-split-left-right"), i18n("Split view"), render, SLOT(slotSplitView(bool)));
288         splitView->setCheckable(true);
289         m_configMenu->addAction(splitView);
290     } else {
291         QAction *setThumbFrame = m_contextMenu->addAction(KIcon("document-new"), i18n("Set current image as thumbnail"), this, SLOT(slotSetThumbFrame()));
292         m_configMenu->addAction(setThumbFrame);
293     }
294
295     QAction *showTips = m_contextMenu->addAction(KIcon("help-hint"), i18n("Monitor overlay infos"));
296     showTips->setCheckable(true);
297     connect(showTips, SIGNAL(toggled(bool)), this, SLOT(slotSwitchMonitorInfo(bool)));
298     showTips->setChecked(KdenliveSettings::displayMonitorInfo());
299
300     QAction *dropFrames = m_contextMenu->addAction(KIcon(), i18n("Real time (drop frames)"));
301     dropFrames->setCheckable(true);
302     dropFrames->setChecked(true);
303     connect(dropFrames, SIGNAL(toggled(bool)), this, SLOT(slotSwitchDropFrames(bool)));
304
305     m_configMenu->addAction(showTips);
306     m_configMenu->addAction(dropFrames);
307
308 }
309
310 void Monitor::slotGoToMarker(QAction *action)
311 {
312     int pos = action->data().toInt();
313     slotSeek(pos);
314 }
315
316 void Monitor::slotSetSizeOneToOne()
317 {
318     QRect r = QApplication::desktop()->screenGeometry();
319     const int maxWidth = r.width() - 20;
320     const int maxHeight = r.height() - 20;
321     int width = render->renderWidth();
322     int height = render->renderHeight();
323     kDebug() << "// render info: " << width << "x" << height;
324     while (width >= maxWidth || height >= maxHeight) {
325         width = width * 0.8;
326         height = height * 0.8;
327     }
328     kDebug() << "// MONITOR; set SIZE: " << width << ", " << height;
329     m_videoBox->setFixedSize(width, height);
330     updateGeometry();
331     adjustSize();
332     //m_ui.video_frame->setMinimumSize(0, 0);
333     emit adjustMonitorSize();
334 }
335
336 void Monitor::slotSetSizeOneToTwo()
337 {
338     QRect r = QApplication::desktop()->screenGeometry();
339     const int maxWidth = r.width() - 20;
340     const int maxHeight = r.height() - 20;
341     int width = render->renderWidth() / 2;
342     int height = render->renderHeight() / 2;
343     kDebug() << "// render info: " << width << "x" << height;
344     while (width >= maxWidth || height >= maxHeight) {
345         width = width * 0.8;
346         height = height * 0.8;
347     }
348     kDebug() << "// MONITOR; set SIZE: " << width << ", " << height;
349     m_videoBox->setFixedSize(width, height);
350     updateGeometry();
351     adjustSize();
352     //m_ui.video_frame->setMinimumSize(0, 0);
353     emit adjustMonitorSize();
354 }
355
356 void Monitor::resetSize()
357 {
358     m_videoBox->setMinimumSize(0, 0);
359 }
360
361 DocClipBase *Monitor::activeClip()
362 {
363     return m_currentClip;
364 }
365
366 void Monitor::updateMarkers(DocClipBase *source)
367 {
368     if (source == m_currentClip && source != NULL) {
369         m_markerMenu->clear();
370         QList <CommentedTime> markers = m_currentClip->commentedSnapMarkers();
371         if (!markers.isEmpty()) {
372             QList <int> marks;
373             for (int i = 0; i < markers.count(); i++) {
374                 int pos = (int) markers.at(i).time().frames(m_monitorManager->timecode().fps());
375                 marks.append(pos);
376                 QString position = m_monitorManager->timecode().getTimecode(markers.at(i).time()) + ' ' + markers.at(i).comment();
377                 QAction *go = m_markerMenu->addAction(position);
378                 go->setData(pos);
379             }
380             m_ruler->setMarkers(marks);
381         } else m_ruler->setMarkers(QList <int>());
382         m_markerMenu->setEnabled(!m_markerMenu->isEmpty());
383     }
384 }
385
386 void Monitor::slotSeekToPreviousSnap()
387 {
388     if (m_currentClip) slotSeek(getSnapForPos(true).frames(m_monitorManager->timecode().fps()));
389 }
390
391 void Monitor::slotSeekToNextSnap()
392 {
393     if (m_currentClip) slotSeek(getSnapForPos(false).frames(m_monitorManager->timecode().fps()));
394 }
395
396 GenTime Monitor::position()
397 {
398     return render->seekPosition();
399 }
400
401 GenTime Monitor::getSnapForPos(bool previous)
402 {
403     QList <GenTime> snaps;
404     QList < GenTime > markers = m_currentClip->snapMarkers();
405     for (int i = 0; i < markers.size(); ++i) {
406         GenTime t = markers.at(i);
407         snaps.append(t);
408     }
409     QPoint zone = m_ruler->zone();
410     snaps.append(GenTime(zone.x(), m_monitorManager->timecode().fps()));
411     snaps.append(GenTime(zone.y(), m_monitorManager->timecode().fps()));
412     snaps.append(GenTime());
413     snaps.append(m_currentClip->duration());
414     qSort(snaps);
415
416     const GenTime pos = render->seekPosition();
417     for (int i = 0; i < snaps.size(); ++i) {
418         if (previous && snaps.at(i) >= pos) {
419             if (i == 0) i = 1;
420             return snaps.at(i - 1);
421         } else if (!previous && snaps.at(i) > pos) {
422             return snaps.at(i);
423         }
424     }
425     return GenTime();
426 }
427
428 void Monitor::slotZoneMoved(int start, int end)
429 {
430     m_ruler->setZone(start, end);
431     checkOverlay();
432     setClipZone(m_ruler->zone());
433 }
434
435 void Monitor::slotSetZoneStart()
436 {
437     m_ruler->setZone(render->seekFramePosition(), -1);
438     emit zoneUpdated(m_ruler->zone());
439     checkOverlay();
440     setClipZone(m_ruler->zone());
441 }
442
443 void Monitor::slotSetZoneEnd()
444 {
445     m_ruler->setZone(-1, render->seekFramePosition());
446     emit zoneUpdated(m_ruler->zone());
447     checkOverlay();
448     setClipZone(m_ruler->zone());
449 }
450
451 // virtual
452 void Monitor::mousePressEvent(QMouseEvent * event)
453 {
454     if (event->button() != Qt::RightButton) {
455         if (m_videoBox->underMouse() && (!m_overlay || !m_overlay->underMouse())) {
456             m_dragStarted = true;
457             m_DragStartPosition = event->pos();
458         }
459     } else if (!m_effectWidget || !m_effectWidget->isVisible()) {
460         m_contextMenu->popup(event->globalPos());
461     }
462 }
463
464 void Monitor::slotSwitchFullScreen()
465 {
466     m_videoBox->switchFullScreen();
467 }
468
469 // virtual
470 void Monitor::mouseReleaseEvent(QMouseEvent * event)
471 {
472     if (m_dragStarted) {
473         if (m_videoBox->underMouse() && (!m_effectWidget || !m_effectWidget->isVisible())) {
474             if (isActive()) slotPlay();
475             else activateMonitor();
476         } else QWidget::mouseReleaseEvent(event);
477         m_dragStarted = false;
478     }
479 }
480
481 // virtual
482 void Monitor::mouseMoveEvent(QMouseEvent *event)
483 {
484     // kDebug() << "// DRAG STARTED, MOUSE MOVED: ";
485     if (!m_dragStarted || m_currentClip == NULL) return;
486
487     if ((event->pos() - m_DragStartPosition).manhattanLength()
488             < QApplication::startDragDistance())
489         return;
490
491     {
492         QDrag *drag = new QDrag(this);
493         QMimeData *mimeData = new QMimeData;
494
495         QStringList list;
496         list.append(m_currentClip->getId());
497         QPoint p = m_ruler->zone();
498         list.append(QString::number(p.x()));
499         list.append(QString::number(p.y()));
500         QByteArray data;
501         data.append(list.join(";").toUtf8());
502         mimeData->setData("kdenlive/clip", data);
503         drag->setMimeData(mimeData);
504         QPixmap pix = m_currentClip->thumbnail();
505         drag->setPixmap(pix);
506         drag->setHotSpot(QPoint(0, 50));
507         drag->start(Qt::MoveAction);
508
509         //Qt::DropAction dropAction;
510         //dropAction = drag->start(Qt::CopyAction | Qt::MoveAction);
511
512         //Qt::DropAction dropAction = drag->exec();
513
514     }
515     //event->accept();
516 }
517
518 /*void Monitor::dragMoveEvent(QDragMoveEvent * event) {
519     event->setDropAction(Qt::IgnoreAction);
520     event->setDropAction(Qt::MoveAction);
521     if (event->mimeData()->hasText()) {
522         event->acceptProposedAction();
523     }
524 }
525
526 Qt::DropActions Monitor::supportedDropActions() const {
527     // returns what actions are supported when dropping
528     return Qt::MoveAction;
529 }*/
530
531 QStringList Monitor::mimeTypes() const
532 {
533     QStringList qstrList;
534     // list of accepted mime types for drop
535     qstrList.append("kdenlive/clip");
536     return qstrList;
537 }
538
539 // virtual
540 void Monitor::wheelEvent(QWheelEvent * event)
541 {
542     slotMouseSeek(event->delta(), event->modifiers() == Qt::ControlModifier);
543     event->accept();
544 }
545
546 void Monitor::slotMouseSeek(int eventDelta, bool fast)
547 {
548     if (fast) {
549         int delta = m_monitorManager->timecode().fps();
550         if (eventDelta > 0) delta = 0 - delta;
551         slotSeek(render->seekFramePosition() - delta);
552     } else {
553         if (eventDelta >= 0) slotForwardOneFrame();
554         else slotRewindOneFrame();
555     }
556 }
557
558 void Monitor::slotSetThumbFrame()
559 {
560     if (m_currentClip == NULL) {
561         return;
562     }
563     m_currentClip->setClipThumbFrame((uint) render->seekFramePosition());
564     emit refreshClipThumbnail(m_currentClip->getId());
565 }
566
567 void Monitor::slotExtractCurrentFrame()
568 {
569     QImage frame = render->extractFrame(render->seekFramePosition());
570     KFileDialog *fs = new KFileDialog(KUrl(), "image/png", this);
571     fs->setOperationMode(KFileDialog::Saving);
572     fs->setMode(KFile::File);
573 #if KDE_IS_VERSION(4,2,0)
574     fs->setConfirmOverwrite(true);
575 #endif
576     fs->setKeepLocation(true);
577     fs->exec();
578     QString path = fs->selectedFile();
579     delete fs;
580     if (!path.isEmpty()) {
581         frame.save(path);
582     }
583 }
584
585 bool Monitor::isActive() const
586 {
587     return m_isActive;
588 }
589
590 void Monitor::activateMonitor()
591 {
592     if (!m_isActive) {
593         m_monitorManager->slotSwitchMonitors(m_name == "clip");
594     }
595 }
596
597 void Monitor::setTimePos(const QString &pos)
598 {
599     m_timePos->setValue(pos);
600     slotSeek();
601 }
602
603 void Monitor::slotSeek()
604 {
605     slotSeek(m_timePos->getValue());
606 }
607
608 void Monitor::slotSeek(int pos)
609 {
610     activateMonitor();
611     if (render == NULL) return;
612     render->seekToFrame(pos);
613 }
614
615 void Monitor::checkOverlay()
616 {
617     if (m_overlay == NULL) return;
618     int pos = render->seekFramePosition();
619     QPoint zone = m_ruler->zone();
620     if (pos == zone.x())
621         m_overlay->setOverlayText(i18n("In Point"));
622     else if (pos == zone.y())
623         m_overlay->setOverlayText(i18n("Out Point"));
624     else {
625         if (m_currentClip) {
626             QString markerComment = m_currentClip->markerComment(GenTime(pos, m_monitorManager->timecode().fps()));
627             if (markerComment.isEmpty())
628                 m_overlay->setHidden(true);
629             else
630                 m_overlay->setOverlayText(markerComment, false);
631         } else m_overlay->setHidden(true);
632     }
633 }
634
635 void Monitor::slotStart()
636 {
637     activateMonitor();
638     render->play(0);
639     render->seekToFrame(0);
640 }
641
642 void Monitor::slotEnd()
643 {
644     activateMonitor();
645     render->play(0);
646     render->seekToFrame(render->getLength());
647 }
648
649 void Monitor::slotZoneStart()
650 {
651     activateMonitor();
652     render->play(0);
653     render->seekToFrame(m_ruler->zone().x());
654 }
655
656 void Monitor::slotZoneEnd()
657 {
658     activateMonitor();
659     render->play(0);
660     render->seekToFrame(m_ruler->zone().y());
661 }
662
663 void Monitor::slotRewind(double speed)
664 {
665     activateMonitor();
666     if (speed == 0) {
667         double currentspeed = render->playSpeed();
668         if (currentspeed >= 0) render->play(-2);
669         else render->play(currentspeed * 2);
670     } else render->play(speed);
671     //m_playAction->setChecked(true);
672     m_playAction->setIcon(m_pauseIcon);
673 }
674
675 void Monitor::slotForward(double speed)
676 {
677     activateMonitor();
678     if (speed == 0) {
679         double currentspeed = render->playSpeed();
680         if (currentspeed <= 1) render->play(2);
681         else render->play(currentspeed * 2);
682     } else render->play(speed);
683     //m_playAction->setChecked(true);
684     m_playAction->setIcon(m_pauseIcon);
685 }
686
687 void Monitor::slotRewindOneFrame(int diff)
688 {
689     activateMonitor();
690     render->play(0);
691     render->seekToFrameDiff(-diff);
692 }
693
694 void Monitor::slotForwardOneFrame(int diff)
695 {
696     activateMonitor();
697     render->play(0);
698     render->seekToFrameDiff(diff);
699 }
700
701 void Monitor::seekCursor(int pos)
702 {
703     activateMonitor();
704     if (m_ruler->slotNewValue(pos)) {
705         checkOverlay();
706         m_timePos->setValue(pos);
707     }
708 }
709
710 void Monitor::rendererStopped(int pos)
711 {
712     if (m_ruler->slotNewValue(pos)) {
713         checkOverlay();
714         m_timePos->setValue(pos);
715     }
716     disconnect(m_playAction, SIGNAL(triggered()), this, SLOT(slotPlay()));
717     //m_playAction->setChecked(false);
718     connect(m_playAction, SIGNAL(triggered()), this, SLOT(slotPlay()));
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     m_isActive = false;
735     disconnect(render, SIGNAL(rendererPosition(int)), this, SLOT(seekCursor(int)));
736     if (render) render->stop();
737 }
738
739 void Monitor::start()
740 {
741     m_isActive = true;
742     if (render) render->start();
743     connect(render, SIGNAL(rendererPosition(int)), this, SLOT(seekCursor(int)));
744 }
745
746 void Monitor::refreshMonitor(bool visible)
747 {
748     if (visible && render && !m_isActive) {
749         activateMonitor();
750         render->doRefresh(); //askForRefresh();
751     }
752 }
753
754 void Monitor::refreshMonitor()
755 {
756     if (m_isActive) {
757         render->doRefresh();
758     }
759 }
760
761 void Monitor::pause()
762 {
763     if (render == NULL) return;
764     activateMonitor();
765     render->pause();
766     //m_playAction->setChecked(true);
767     m_playAction->setIcon(m_playIcon);
768 }
769
770 void Monitor::slotPlay()
771 {
772     if (render == NULL) return;
773     activateMonitor();
774     if (render->playSpeed() == 0) {
775         //m_playAction->setChecked(true);
776         m_playAction->setIcon(m_pauseIcon);
777     } else {
778         //m_playAction->setChecked(false);
779         m_playAction->setIcon(m_playIcon);
780     }
781     render->switchPlay();
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::slotSetXml(DocClipBase *clip, QPoint zone, const int position)
815 {
816     if (render == NULL) return;
817     if (clip == NULL && m_currentClip != NULL) {
818         m_currentClip = NULL;
819         m_length = -1;
820         render->setProducer(NULL, -1);
821         return;
822     }
823     if (m_currentClip != NULL || clip != NULL) activateMonitor();
824     if (clip != m_currentClip) {
825         m_currentClip = clip;
826         updateMarkers(clip);
827         if (render->setProducer(clip->producer(), position) == -1) {
828             // MLT CONSUMER is broken
829             kDebug(QtWarningMsg) << "ERROR, Cannot start monitor";
830         }
831     } else if (position != -1) render->seek(position);
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());
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 MonitorRefresh::MonitorRefresh(QWidget* parent) :
1026     QWidget(parent)
1027     , m_renderer(NULL)
1028 {
1029     // MonitorRefresh is used as container for the SDL display (it's window id is passed to SDL)
1030     setAttribute(Qt::WA_PaintOnScreen);
1031     setAttribute(Qt::WA_OpaquePaintEvent);
1032     setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
1033     //setAttribute(Qt::WA_NoSystemBackground);
1034 }
1035
1036 void MonitorRefresh::setRenderer(Render* render)
1037 {
1038     m_renderer = render;
1039 }
1040
1041 void MonitorRefresh::paintEvent(QPaintEvent *event)
1042 {
1043     Q_UNUSED(event);
1044     if (m_renderer) m_renderer->doRefresh();
1045 }
1046
1047 Overlay::Overlay(QWidget* parent) :
1048     QLabel(parent)
1049 {
1050     //setAttribute(Qt::WA_TransparentForMouseEvents);
1051     setAutoFillBackground(true);
1052     setBackgroundRole(QPalette::Base);
1053     setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
1054     setCursor(Qt::PointingHandCursor);
1055 }
1056
1057 // virtual
1058 void Overlay::mouseReleaseEvent ( QMouseEvent * event )
1059 {
1060     event->accept();
1061 }
1062
1063 // virtual
1064 void Overlay::mousePressEvent( QMouseEvent * event )
1065 {
1066     event->accept();
1067 }
1068
1069 // virtual
1070 void Overlay::mouseDoubleClickEvent ( QMouseEvent * event )
1071 {
1072     emit editMarker();
1073     event->accept();
1074 }
1075
1076 void Overlay::setOverlayText(const QString &text, bool isZone)
1077 {
1078     setHidden(true);
1079     m_isZone = isZone;
1080     QPalette p;
1081     p.setColor(QPalette::Text, Qt::white);
1082     if (m_isZone) p.setColor(QPalette::Base, QColor(200, 0, 0));
1083     else p.setColor(QPalette::Base, QColor(0, 0, 200));
1084     setPalette(p);
1085     setText(' ' + text + ' ');
1086     setHidden(false);
1087     update();
1088 }
1089
1090 VideoContainer::VideoContainer(Monitor* parent) :
1091     QFrame()
1092     , m_monitor(parent)
1093 {
1094     setFrameShape(QFrame::NoFrame);
1095     setFocusPolicy(Qt::ClickFocus);
1096     setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
1097 }
1098
1099 // virtual
1100 void VideoContainer::mousePressEvent(QMouseEvent * event)
1101 {
1102     if (m_monitor->underMouse()) event->setAccepted(false);
1103 }
1104
1105 // virtual
1106 void VideoContainer::mouseReleaseEvent(QMouseEvent * event)
1107 {
1108     if (m_monitor->underMouse()) event->setAccepted(false);
1109     else {
1110         if (m_monitor->isActive()) {
1111             m_monitor->slotPlay();
1112             event->accept();
1113         }
1114     }
1115 }
1116
1117 // virtual
1118 void VideoContainer::mouseMoveEvent(QMouseEvent *event)
1119 {
1120     if (m_monitor->underMouse()) event->setAccepted(false);
1121 }
1122
1123 // virtual
1124 void VideoContainer::keyPressEvent(QKeyEvent *event)
1125 {
1126     // Exit fullscreen with Esc key
1127     if (event->key() == Qt::Key_Escape && isFullScreen()) {
1128         switchFullScreen();
1129         event->setAccepted(true);
1130     } else event->setAccepted(false);
1131 }
1132
1133 // virtual
1134 void VideoContainer::wheelEvent(QWheelEvent * event)
1135 {
1136     if (m_monitor->underMouse()) event->setAccepted(false);
1137     else {
1138         m_monitor->slotMouseSeek(event->delta(), event->modifiers() == Qt::ControlModifier);
1139         event->accept();
1140     }
1141 }
1142
1143 void VideoContainer::mouseDoubleClickEvent(QMouseEvent * event)
1144 {
1145     Q_UNUSED(event);
1146
1147     if (!KdenliveSettings::openglmonitors())
1148         switchFullScreen();
1149 }
1150
1151 void VideoContainer::switchFullScreen()
1152 {
1153     // TODO: disable screensaver?
1154     Qt::WindowFlags flags = windowFlags();
1155     if (!isFullScreen()) {
1156         // Check if we ahave a multiple monitor setup
1157         setUpdatesEnabled(false);
1158 #if QT_VERSION >= 0x040600
1159         int monitors = QApplication::desktop()->screenCount();
1160 #else
1161         int monitors = QApplication::desktop()->numScreens();
1162 #endif
1163         if (monitors > 1) {
1164             QRect screenres;
1165             // Move monitor widget to the second screen (one screen for Kdenlive, the other one for the Monitor widget
1166             int currentScreen = QApplication::desktop()->screenNumber(this);
1167             if (currentScreen < monitors - 1)
1168                 screenres = QApplication::desktop()->screenGeometry(currentScreen + 1);
1169             else
1170                 screenres = QApplication::desktop()->screenGeometry(currentScreen - 1);
1171             move(QPoint(screenres.x(), screenres.y()));
1172             resize(screenres.width(), screenres.height());
1173         }
1174
1175         m_baseFlags = flags & (Qt::Window | Qt::SubWindow);
1176         flags |= Qt::Window;
1177         flags ^= Qt::SubWindow;
1178         setWindowFlags(flags);
1179 #ifdef Q_WS_X11
1180         // This works around a bug with Compiz
1181         // as the window must be visible before we can set the state
1182         show();
1183         raise();
1184         setWindowState(windowState() | Qt::WindowFullScreen);   // set
1185 #else
1186         setWindowState(windowState() | Qt::WindowFullScreen);   // set
1187         setUpdatesEnabled(true);
1188         show();
1189 #endif
1190     } else {
1191         setUpdatesEnabled(false);
1192         flags ^= (Qt::Window | Qt::SubWindow); //clear the flags...
1193         flags |= m_baseFlags; //then we reset the flags (window and subwindow)
1194         setWindowFlags(flags);
1195         setWindowState(windowState()  ^ Qt::WindowFullScreen);   // reset
1196         setUpdatesEnabled(true);
1197         show();
1198     }
1199     m_monitor->pause();
1200 }
1201
1202
1203 #include "monitor.moc"