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