]> git.sesse.net Git - kdenlive/blob - src/monitor.cpp
Merge branch 'master' of git://anongit.kde.org/kdenlive
[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     connect(render, SIGNAL(rendererPosition(int)), this, SLOT(seekCursor(int)));
184
185     if (name != "clip") {
186         connect(render, SIGNAL(rendererPosition(int)), this, SIGNAL(renderPosition(int)));
187         connect(render, SIGNAL(durationChanged(int)), this, SIGNAL(durationChanged(int)));
188         connect(m_ruler, SIGNAL(zoneChanged(QPoint)), this, SIGNAL(zoneUpdated(QPoint)));
189     } else {
190         connect(m_ruler, SIGNAL(zoneChanged(QPoint)), this, SLOT(setClipZone(QPoint)));
191     }
192
193     if (m_monitorRefresh) m_monitorRefresh->show();
194
195     if (name == "project") {
196         m_effectWidget = new MonitorEditWidget(render, m_videoBox);
197         m_toolbar->addAction(m_effectWidget->getVisibilityAction());
198         lay->addWidget(m_effectWidget);
199         m_effectWidget->hide();
200     }
201
202     QWidget *spacer = new QWidget(this);
203     spacer->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred);
204     m_toolbar->addWidget(spacer);
205     m_timePos = new TimecodeDisplay(m_monitorManager->timecode(), this);
206     m_toolbar->addWidget(m_timePos);
207     connect(m_timePos, SIGNAL(editingFinished()), this, SLOT(slotSeek()));
208     m_toolbar->setMaximumHeight(s * 1.5);
209     layout->addWidget(m_toolbar);
210 }
211
212 Monitor::~Monitor()
213 {
214     delete m_ruler;
215     delete m_timePos;
216     delete m_overlay;
217     if (m_effectWidget)
218         delete m_effectWidget;
219     delete m_monitorRefresh;
220     delete render;
221 }
222
223 QWidget *Monitor::container()
224 {
225     return m_videoBox;
226 }
227
228 const QString Monitor::name() const
229 {
230     return m_name;
231 }
232
233 #ifdef USE_OPENGL
234 bool Monitor::createOpenGlWidget(QWidget *parent, const QString profile)
235 {
236     render = new Render(m_name, 0, profile, this);
237     m_glWidget = new VideoGLWidget(parent);
238     if (m_glWidget == NULL) {
239         // Creation failed, we are in trouble...
240         return false;
241     }
242     m_glWidget->setImageAspectRatio(render->dar());
243     m_glWidget->setBackgroundColor(KdenliveSettings::window_background());
244     connect(render, SIGNAL(showImageSignal(QImage)), m_glWidget, SLOT(showImage(QImage)));
245     return true;
246 }
247 #endif
248
249 void Monitor::setupMenu(QMenu *goMenu, QAction *playZone, QAction *loopZone, QMenu *markerMenu, QAction *loopClip)
250 {
251     m_contextMenu = new QMenu(this);
252     m_contextMenu->addMenu(m_playMenu);
253     if (goMenu)
254         m_contextMenu->addMenu(goMenu);
255     if (markerMenu) {
256         m_contextMenu->addMenu(markerMenu);
257         QList <QAction *>list = markerMenu->actions();
258         for (int i = 0; i < list.count(); i++) {
259             if (list.at(i)->data().toString() == "edit_marker") {
260                 m_editMarker = list.at(i);
261                 break;
262             }
263         }
264     }
265
266     m_playMenu->addAction(playZone);
267     m_playMenu->addAction(loopZone);
268     if (loopClip) {
269         m_loopClipAction = loopClip;
270         m_playMenu->addAction(loopClip);
271     }
272
273     //TODO: add save zone to timeline monitor when fixed
274     if (m_name == "clip") {
275         m_contextMenu->addMenu(m_markerMenu);
276         m_contextMenu->addAction(KIcon("document-save"), i18n("Save zone"), this, SLOT(slotSaveZone()));
277         QAction *extractZone = m_configMenu->addAction(KIcon("document-new"), i18n("Extract Zone"), this, SLOT(slotExtractCurrentZone()));
278         m_contextMenu->addAction(extractZone);
279     }
280     QAction *extractFrame = m_configMenu->addAction(KIcon("document-new"), i18n("Extract frame"), this, SLOT(slotExtractCurrentFrame()));
281     m_contextMenu->addAction(extractFrame);
282
283     if (m_name != "clip") {
284         QAction *splitView = m_contextMenu->addAction(KIcon("view-split-left-right"), i18n("Split view"), render, SLOT(slotSplitView(bool)));
285         splitView->setCheckable(true);
286         m_configMenu->addAction(splitView);
287     } else {
288         QAction *setThumbFrame = m_contextMenu->addAction(KIcon("document-new"), i18n("Set current image as thumbnail"), this, SLOT(slotSetThumbFrame()));
289         m_configMenu->addAction(setThumbFrame);
290     }
291
292     QAction *showTips = m_contextMenu->addAction(KIcon("help-hint"), i18n("Monitor overlay infos"));
293     showTips->setCheckable(true);
294     connect(showTips, SIGNAL(toggled(bool)), this, SLOT(slotSwitchMonitorInfo(bool)));
295     showTips->setChecked(KdenliveSettings::displayMonitorInfo());
296
297     QAction *dropFrames = m_contextMenu->addAction(KIcon(), i18n("Real time (drop frames)"));
298     dropFrames->setCheckable(true);
299     dropFrames->setChecked(true);
300     connect(dropFrames, SIGNAL(toggled(bool)), this, SLOT(slotSwitchDropFrames(bool)));
301
302     m_configMenu->addAction(showTips);
303     m_configMenu->addAction(dropFrames);
304
305 }
306
307 void Monitor::slotGoToMarker(QAction *action)
308 {
309     int pos = action->data().toInt();
310     slotSeek(pos);
311 }
312
313 void Monitor::slotSetSizeOneToOne()
314 {
315     QRect r = QApplication::desktop()->screenGeometry();
316     const int maxWidth = r.width() - 20;
317     const int maxHeight = r.height() - 20;
318     int width = render->renderWidth();
319     int height = render->renderHeight();
320     kDebug() << "// render info: " << width << "x" << height;
321     while (width >= maxWidth || height >= maxHeight) {
322         width = width * 0.8;
323         height = height * 0.8;
324     }
325     kDebug() << "// MONITOR; set SIZE: " << width << ", " << height;
326     m_videoBox->setFixedSize(width, height);
327     updateGeometry();
328     adjustSize();
329     //m_ui.video_frame->setMinimumSize(0, 0);
330     emit adjustMonitorSize();
331 }
332
333 void Monitor::slotSetSizeOneToTwo()
334 {
335     QRect r = QApplication::desktop()->screenGeometry();
336     const int maxWidth = r.width() - 20;
337     const int maxHeight = r.height() - 20;
338     int width = render->renderWidth() / 2;
339     int height = render->renderHeight() / 2;
340     kDebug() << "// render info: " << width << "x" << height;
341     while (width >= maxWidth || height >= maxHeight) {
342         width = width * 0.8;
343         height = height * 0.8;
344     }
345     kDebug() << "// MONITOR; set SIZE: " << width << ", " << height;
346     m_videoBox->setFixedSize(width, height);
347     updateGeometry();
348     adjustSize();
349     //m_ui.video_frame->setMinimumSize(0, 0);
350     emit adjustMonitorSize();
351 }
352
353 void Monitor::resetSize()
354 {
355     m_videoBox->setMinimumSize(0, 0);
356 }
357
358 DocClipBase *Monitor::activeClip()
359 {
360     return m_currentClip;
361 }
362
363 void Monitor::updateMarkers(DocClipBase *source)
364 {
365     if (source == m_currentClip && source != NULL) {
366         m_markerMenu->clear();
367         QList <CommentedTime> markers = m_currentClip->commentedSnapMarkers();
368         if (!markers.isEmpty()) {
369             QList <int> marks;
370             for (int i = 0; i < markers.count(); i++) {
371                 int pos = (int) markers.at(i).time().frames(m_monitorManager->timecode().fps());
372                 marks.append(pos);
373                 QString position = m_monitorManager->timecode().getTimecode(markers.at(i).time()) + ' ' + markers.at(i).comment();
374                 QAction *go = m_markerMenu->addAction(position);
375                 go->setData(pos);
376             }
377             m_ruler->setMarkers(marks);
378         } else m_ruler->setMarkers(QList <int>());
379         m_markerMenu->setEnabled(!m_markerMenu->isEmpty());
380     }
381 }
382
383 void Monitor::slotSeekToPreviousSnap()
384 {
385     if (m_currentClip) slotSeek(getSnapForPos(true).frames(m_monitorManager->timecode().fps()));
386 }
387
388 void Monitor::slotSeekToNextSnap()
389 {
390     if (m_currentClip) slotSeek(getSnapForPos(false).frames(m_monitorManager->timecode().fps()));
391 }
392
393 GenTime Monitor::position()
394 {
395     return render->seekPosition();
396 }
397
398 GenTime Monitor::getSnapForPos(bool previous)
399 {
400     QList <GenTime> snaps;
401     QList < GenTime > markers = m_currentClip->snapMarkers();
402     for (int i = 0; i < markers.size(); ++i) {
403         GenTime t = markers.at(i);
404         snaps.append(t);
405     }
406     QPoint zone = m_ruler->zone();
407     snaps.append(GenTime(zone.x(), m_monitorManager->timecode().fps()));
408     snaps.append(GenTime(zone.y(), m_monitorManager->timecode().fps()));
409     snaps.append(GenTime());
410     snaps.append(m_currentClip->duration());
411     qSort(snaps);
412
413     const GenTime pos = render->seekPosition();
414     for (int i = 0; i < snaps.size(); ++i) {
415         if (previous && snaps.at(i) >= pos) {
416             if (i == 0) i = 1;
417             return snaps.at(i - 1);
418         } else if (!previous && snaps.at(i) > pos) {
419             return snaps.at(i);
420         }
421     }
422     return GenTime();
423 }
424
425 void Monitor::slotZoneMoved(int start, int end)
426 {
427     m_ruler->setZone(start, end);
428     checkOverlay();
429     setClipZone(m_ruler->zone());
430 }
431
432 void Monitor::slotSetZoneStart()
433 {
434     m_ruler->setZone(m_ruler->position(), -1);
435     emit zoneUpdated(m_ruler->zone());
436     checkOverlay();
437     setClipZone(m_ruler->zone());
438 }
439
440 void Monitor::slotSetZoneEnd()
441 {
442     m_ruler->setZone(-1, m_ruler->position());
443     emit zoneUpdated(m_ruler->zone());
444     checkOverlay();
445     setClipZone(m_ruler->zone());
446 }
447
448 // virtual
449 void Monitor::mousePressEvent(QMouseEvent * event)
450 {
451     if (event->button() != Qt::RightButton) {
452         if (m_videoBox->geometry().contains(event->pos()) && (!m_overlay || !m_overlay->underMouse())) {
453             m_dragStarted = true;
454             m_DragStartPosition = event->pos();
455         }
456     } else if (!m_effectWidget || !m_effectWidget->isVisible()) {
457         m_contextMenu->popup(event->globalPos());
458     }
459 }
460
461 void Monitor::resizeEvent(QResizeEvent *event)
462 {
463     Q_UNUSED(event);
464     if (render && isVisible() && isActive()) render->doRefresh();
465 }
466
467
468 void Monitor::slotSwitchFullScreen()
469 {
470     m_videoBox->switchFullScreen();
471 }
472
473 // virtual
474 void Monitor::mouseReleaseEvent(QMouseEvent * event)
475 {
476     if (m_dragStarted && event->button() != Qt::RightButton) {
477         if (m_videoBox->geometry().contains(event->pos()) && (!m_effectWidget || !m_effectWidget->isVisible())) {
478             if (isActive()) slotPlay();
479             else activateMonitor();
480         } //else event->ignore(); //QWidget::mouseReleaseEvent(event);
481         m_dragStarted = false;
482     }
483 }
484
485 // virtual
486 void Monitor::mouseMoveEvent(QMouseEvent *event)
487 {
488     if (!m_dragStarted || m_currentClip == NULL) return;
489
490     if ((event->pos() - m_DragStartPosition).manhattanLength()
491             < QApplication::startDragDistance())
492         return;
493
494     {
495         QDrag *drag = new QDrag(this);
496         QMimeData *mimeData = new QMimeData;
497
498         QStringList list;
499         list.append(m_currentClip->getId());
500         QPoint p = m_ruler->zone();
501         list.append(QString::number(p.x()));
502         list.append(QString::number(p.y()));
503         QByteArray data;
504         data.append(list.join(";").toUtf8());
505         mimeData->setData("kdenlive/clip", data);
506         drag->setMimeData(mimeData);
507         /*QPixmap pix = m_currentClip->thumbnail();
508         drag->setPixmap(pix);
509         drag->setHotSpot(QPoint(0, 50));*/
510         drag->start(Qt::MoveAction);
511
512         //Qt::DropAction dropAction;
513         //dropAction = drag->start(Qt::CopyAction | Qt::MoveAction);
514
515         //Qt::DropAction dropAction = drag->exec();
516
517     }
518     //event->accept();
519 }
520
521 /*void Monitor::dragMoveEvent(QDragMoveEvent * event) {
522     event->setDropAction(Qt::IgnoreAction);
523     event->setDropAction(Qt::MoveAction);
524     if (event->mimeData()->hasText()) {
525         event->acceptProposedAction();
526     }
527 }
528
529 Qt::DropActions Monitor::supportedDropActions() const {
530     // returns what actions are supported when dropping
531     return Qt::MoveAction;
532 }*/
533
534 QStringList Monitor::mimeTypes() const
535 {
536     QStringList qstrList;
537     // list of accepted mime types for drop
538     qstrList.append("kdenlive/clip");
539     return qstrList;
540 }
541
542 // virtual
543 void Monitor::wheelEvent(QWheelEvent * event)
544 {
545     slotMouseSeek(event->delta(), event->modifiers() == Qt::ControlModifier);
546     event->accept();
547 }
548
549 void Monitor::mouseDoubleClickEvent(QMouseEvent * event)
550 {
551     if (!KdenliveSettings::openglmonitors()) {
552         m_videoBox->switchFullScreen();
553         event->accept();
554     }
555 }
556
557 void Monitor::slotMouseSeek(int eventDelta, bool fast)
558 {
559     if (fast) {
560         int delta = m_monitorManager->timecode().fps();
561         if (eventDelta > 0) delta = 0 - delta;
562         slotSeek(m_ruler->position() - delta);
563     } else {
564         if (eventDelta >= 0) slotForwardOneFrame();
565         else slotRewindOneFrame();
566     }
567 }
568
569 void Monitor::slotSetThumbFrame()
570 {
571     if (m_currentClip == NULL) {
572         return;
573     }
574     m_currentClip->setClipThumbFrame((uint) render->seekFramePosition());
575     emit refreshClipThumbnail(m_currentClip->getId(), true);
576 }
577
578 void Monitor::slotExtractCurrentZone()
579 {
580     if (m_currentClip == NULL) return;
581     emit extractZone(m_currentClip->getId(), m_ruler->zone());
582 }
583
584 void Monitor::slotExtractCurrentFrame()
585 {
586     QImage frame;
587     // check if we are using a proxy
588     if (m_currentClip && !m_currentClip->getProperty("proxy").isEmpty() && m_currentClip->getProperty("proxy") != "-") {
589         // using proxy, use original clip url to get frame
590         frame = render->extractFrame(render->seekFramePosition(), m_currentClip->fileURL().path());
591     }
592     else frame = render->extractFrame(render->seekFramePosition());
593     KFileDialog *fs = new KFileDialog(KUrl(), "image/png", this);
594     fs->setOperationMode(KFileDialog::Saving);
595     fs->setMode(KFile::File);
596     fs->setConfirmOverwrite(true);
597     fs->setKeepLocation(true);
598     fs->exec();
599     QString path = fs->selectedFile();
600     delete fs;
601     if (!path.isEmpty()) {
602         frame.save(path);
603     }
604 }
605
606 bool Monitor::isActive() const
607 {
608     return m_monitorManager->isActive(m_name);
609 }
610
611 bool Monitor::activateMonitor()
612 {
613     return m_monitorManager->activateMonitor(m_name);
614 }
615
616 void Monitor::setTimePos(const QString &pos)
617 {
618     m_timePos->setValue(pos);
619     slotSeek();
620 }
621
622 void Monitor::slotSeek()
623 {
624     slotSeek(m_timePos->getValue());
625 }
626
627 void Monitor::slotSeek(int pos)
628 {
629     if (render == NULL) return;
630     activateMonitor();
631     render->seekToFrame(pos);
632 }
633
634 void Monitor::checkOverlay()
635 {
636     if (m_overlay == NULL) return;
637     int pos = m_ruler->position();
638     QPoint zone = m_ruler->zone();
639     if (pos == zone.x())
640         m_overlay->setOverlayText(i18n("In Point"));
641     else if (pos == zone.y())
642         m_overlay->setOverlayText(i18n("Out Point"));
643     else {
644         if (m_currentClip) {
645             QString markerComment = m_currentClip->markerComment(GenTime(pos, m_monitorManager->timecode().fps()));
646             if (markerComment.isEmpty())
647                 m_overlay->setHidden(true);
648             else
649                 m_overlay->setOverlayText(markerComment, false);
650         } else m_overlay->setHidden(true);
651     }
652 }
653
654 void Monitor::slotStart()
655 {
656     activateMonitor();
657     render->play(0);
658     render->seekToFrame(0);
659 }
660
661 void Monitor::slotEnd()
662 {
663     activateMonitor();
664     render->play(0);
665     render->seekToFrame(render->getLength());
666 }
667
668 void Monitor::slotZoneStart()
669 {
670     activateMonitor();
671     render->play(0);
672     render->seekToFrame(m_ruler->zone().x());
673 }
674
675 void Monitor::slotZoneEnd()
676 {
677     activateMonitor();
678     render->play(0);
679     render->seekToFrame(m_ruler->zone().y());
680 }
681
682 void Monitor::slotRewind(double speed)
683 {
684     activateMonitor();
685     if (speed == 0) {
686         double currentspeed = render->playSpeed();
687         if (currentspeed >= 0) render->play(-2);
688         else render->play(currentspeed * 2);
689     } else render->play(speed);
690     //m_playAction->setChecked(true);
691     m_playAction->setIcon(m_pauseIcon);
692 }
693
694 void Monitor::slotForward(double speed)
695 {
696     activateMonitor();
697     if (speed == 0) {
698         double currentspeed = render->playSpeed();
699         if (currentspeed <= 1) render->play(2);
700         else render->play(currentspeed * 2);
701     } else render->play(speed);
702     //m_playAction->setChecked(true);
703     m_playAction->setIcon(m_pauseIcon);
704 }
705
706 void Monitor::slotRewindOneFrame(int diff)
707 {
708     activateMonitor();
709     render->play(0);
710     render->seekToFrameDiff(-diff);
711 }
712
713 void Monitor::slotForwardOneFrame(int diff)
714 {
715     activateMonitor();
716     render->play(0);
717     render->seekToFrameDiff(diff);
718 }
719
720 void Monitor::seekCursor(int pos)
721 {
722     //activateMonitor();
723     if (m_ruler->slotNewValue(pos)) {
724         checkOverlay();
725         m_timePos->setValue(pos);
726     }
727 }
728
729 void Monitor::rendererStopped(int pos)
730 {
731     if (m_ruler->slotNewValue(pos)) {
732         checkOverlay();
733         m_timePos->setValue(pos);
734     }
735     m_playAction->setIcon(m_playIcon);
736 }
737
738 void Monitor::adjustRulerSize(int length)
739 {
740     if (length > 0) m_length = length;
741     m_ruler->adjustScale(m_length);
742     if (m_currentClip != NULL) {
743         QPoint zone = m_currentClip->zone();
744         m_ruler->setZone(zone.x(), zone.y());
745     }
746 }
747
748 void Monitor::stop()
749 {
750     if (render) render->stop();
751 }
752
753 void Monitor::start()
754 {
755     if (!isVisible()) return;
756     if (render) render->start();
757 }
758
759 void Monitor::refreshMonitor(bool visible)
760 {
761     if (visible && render) {
762         if (!activateMonitor()) {
763             // the monitor was already active, simply refreshClipThumbnail
764             render->doRefresh();
765         }
766     }
767 }
768
769 void Monitor::refreshMonitor()
770 {
771     if (isActive()) {
772         render->doRefresh();
773     }
774 }
775
776 void Monitor::pause()
777 {
778     if (render == NULL) return;
779     activateMonitor();
780     render->pause();
781     //m_playAction->setChecked(true);
782     m_playAction->setIcon(m_playIcon);
783 }
784
785 void Monitor::slotPlay()
786 {
787     if (render == NULL) return;
788     activateMonitor();
789     if (render->playSpeed() == 0.0) {
790         m_playAction->setIcon(m_pauseIcon);
791         render->switchPlay(true);
792     } else {
793         m_playAction->setIcon(m_playIcon);
794         render->switchPlay(false);
795     }
796 }
797
798 void Monitor::slotPlayZone()
799 {
800     if (render == NULL) return;
801     activateMonitor();
802     QPoint p = m_ruler->zone();
803     render->playZone(GenTime(p.x(), m_monitorManager->timecode().fps()), GenTime(p.y(), m_monitorManager->timecode().fps()));
804     //m_playAction->setChecked(true);
805     m_playAction->setIcon(m_pauseIcon);
806 }
807
808 void Monitor::slotLoopZone()
809 {
810     if (render == NULL) return;
811     activateMonitor();
812     QPoint p = m_ruler->zone();
813     render->loopZone(GenTime(p.x(), m_monitorManager->timecode().fps()), GenTime(p.y(), m_monitorManager->timecode().fps()));
814     //m_playAction->setChecked(true);
815     m_playAction->setIcon(m_pauseIcon);
816 }
817
818 void Monitor::slotLoopClip()
819 {
820     if (render == NULL || m_selectedClip == NULL)
821         return;
822     activateMonitor();
823     render->loopZone(m_selectedClip->startPos(), m_selectedClip->endPos());
824     //m_playAction->setChecked(true);
825     m_playAction->setIcon(m_pauseIcon);
826 }
827
828 void Monitor::updateClipProducer(Mlt::Producer *prod)
829 {
830     if (render == NULL) return;
831    render->setProducer(prod, render->seekFramePosition());
832 }
833
834 void Monitor::slotSetClipProducer(DocClipBase *clip, QPoint zone, bool forceUpdate, int position)
835 {
836     if (render == NULL) return;
837     if (clip == NULL && m_currentClip != NULL) {
838         kDebug()<<"// SETTING NULL CLIP MONITOR";
839         m_currentClip = NULL;
840         m_length = -1;
841         render->setProducer(NULL, -1);
842         return;
843     }
844     
845     if (clip != m_currentClip || forceUpdate) {
846         m_currentClip = clip;
847         if (m_currentClip) activateMonitor();
848         updateMarkers(clip);
849         Mlt::Producer *prod = NULL;
850         if (clip) prod = clip->getCloneProducer();
851         if (render->setProducer(prod, position) == -1) {
852             // MLT CONSUMER is broken
853             kDebug(QtWarningMsg) << "ERROR, Cannot start monitor";
854         }
855     } else {
856         if (m_currentClip) {
857             activateMonitor();
858             if (position == -1) position = render->seekFramePosition();
859             render->seek(position);
860         }
861     }
862     if (!zone.isNull()) {
863         m_ruler->setZone(zone.x(), zone.y());
864         render->seek(zone.x());
865     }
866 }
867
868 void Monitor::slotOpenFile(const QString &file)
869 {
870     if (render == NULL) return;
871     activateMonitor();
872     QDomDocument doc;
873     QDomElement mlt = doc.createElement("mlt");
874     doc.appendChild(mlt);
875     QDomElement prod = doc.createElement("producer");
876     mlt.appendChild(prod);
877     prod.setAttribute("mlt_service", "avformat");
878     prod.setAttribute("resource", file);
879     render->setSceneList(doc, 0);
880 }
881
882 void Monitor::slotSaveZone()
883 {
884     if (render == NULL) return;
885     emit saveZone(render, m_ruler->zone(), m_currentClip);
886
887     //render->setSceneList(doc, 0);
888 }
889
890 void Monitor::resetProfile(const QString &profile)
891 {
892     m_timePos->updateTimeCode(m_monitorManager->timecode());
893     if (render == NULL) return;
894     if (!render->hasProfile(profile)) {
895         activateMonitor();
896         render->resetProfile(profile);
897     }
898     if (m_effectWidget)
899         m_effectWidget->resetProfile(render);
900 }
901
902 void Monitor::saveSceneList(QString path, QDomElement info)
903 {
904     if (render == NULL) return;
905     render->saveSceneList(path, info);
906 }
907
908 const QString Monitor::sceneList()
909 {
910     if (render == NULL) return QString();
911     return render->sceneList();
912 }
913
914 void Monitor::setClipZone(QPoint pos)
915 {
916     if (m_currentClip == NULL) return;
917     m_currentClip->setZone(pos);
918 }
919
920 void Monitor::slotSwitchDropFrames(bool show)
921 {
922     render->setDropFrames(show);
923 }
924
925 void Monitor::slotSwitchMonitorInfo(bool show)
926 {
927     KdenliveSettings::setDisplayMonitorInfo(show);
928     if (show) {
929         if (m_overlay) return;
930         if (m_monitorRefresh == NULL) {
931             // Using OpenGL display
932 #ifdef USE_OPENGL
933             if (m_glWidget->layout()) delete m_glWidget->layout();
934             m_overlay = new Overlay();
935             connect(m_overlay, SIGNAL(editMarker()), this, SLOT(slotEditMarker()));
936             QVBoxLayout *layout = new QVBoxLayout;
937             layout->addStretch(10);
938             layout->addWidget(m_overlay);
939             m_glWidget->setLayout(layout);
940 #endif
941         } else {
942             if (m_monitorRefresh->layout()) delete m_monitorRefresh->layout();
943             m_overlay = new Overlay();
944             connect(m_overlay, SIGNAL(editMarker()), this, SLOT(slotEditMarker()));
945             QVBoxLayout *layout = new QVBoxLayout;
946             layout->addStretch(10);
947             layout->addWidget(m_overlay);
948             m_monitorRefresh->setLayout(layout);
949             m_overlay->raise();
950             m_overlay->setHidden(true);
951         }
952         checkOverlay();
953     } else {
954         delete m_overlay;
955         m_overlay = NULL;
956     }
957 }
958
959 void Monitor::slotEditMarker()
960 {
961     if (m_editMarker) m_editMarker->trigger();
962 }
963
964 void Monitor::updateTimecodeFormat()
965 {
966     m_timePos->slotUpdateTimeCodeFormat();
967 }
968
969 QStringList Monitor::getZoneInfo() const
970 {
971     QStringList result;
972     if (m_currentClip == NULL) return result;
973     result << m_currentClip->getId();
974     QPoint zone = m_ruler->zone();
975     result << QString::number(zone.x()) << QString::number(zone.y());
976     return result;
977 }
978
979 void Monitor::slotSetSelectedClip(AbstractClipItem* item)
980 {
981     if (item) {
982         m_loopClipAction->setEnabled(true);
983         m_selectedClip = item;
984     } else {
985         m_loopClipAction->setEnabled(false);
986     }
987 }
988
989 void Monitor::slotSetSelectedClip(ClipItem* item)
990 {
991     if (item || (!item && !m_loopClipTransition)) {
992         m_loopClipTransition = false;
993         slotSetSelectedClip((AbstractClipItem*)item);
994     }
995 }
996
997 void Monitor::slotSetSelectedClip(Transition* item)
998 {
999     if (item || (!item && m_loopClipTransition)) {
1000         m_loopClipTransition = true;
1001         slotSetSelectedClip((AbstractClipItem*)item);
1002     }
1003 }
1004
1005
1006 void Monitor::slotEffectScene(bool show)
1007 {
1008     if (m_name == "project") {
1009         if (m_monitorRefresh) {
1010             m_monitorRefresh->setVisible(!show);
1011         } else {
1012 #ifdef USE_OPENGL
1013             m_glWidget->setVisible(!show);
1014 #endif
1015         }
1016         m_effectWidget->setVisible(show);
1017         m_effectWidget->getVisibilityAction()->setChecked(show);
1018         emit requestFrameForAnalysis(show);
1019         if (show) {
1020             m_effectWidget->getScene()->slotZoomFit();
1021         }
1022         m_videoBox->setEnabled(show);
1023         render->doRefresh();
1024     }
1025 }
1026
1027 MonitorEditWidget* Monitor::getEffectEdit()
1028 {
1029     return m_effectWidget;
1030 }
1031
1032 bool Monitor::effectSceneDisplayed()
1033 {
1034     return m_effectWidget->isVisible();
1035 }
1036
1037 void Monitor::slotSetVolume(int volume)
1038 {
1039     KdenliveSettings::setVolume(volume);
1040     KIcon icon;
1041     if (volume == 0) icon = KIcon("audio-volume-muted");
1042     else icon = KIcon("audio-volume-medium");
1043     static_cast <QToolButton *>(m_volumeWidget)->setIcon(icon);
1044     render->slotSetVolume(volume);
1045 }
1046
1047 void Monitor::slotShowVolume()
1048 {
1049     m_volumePopup->move(mapToGlobal(m_toolbar->geometry().topLeft()) + QPoint(mapToParent(m_volumeWidget->geometry().bottomLeft()).x(), -m_volumePopup->height()));
1050     int vol = render->volume();
1051     // Disable widget if we cannot get the volume
1052     m_volumePopup->setEnabled(vol != -1);
1053     m_audioSlider->blockSignals(true);
1054     m_audioSlider->setValue(vol);
1055     m_audioSlider->blockSignals(false);
1056     m_volumePopup->show();
1057 }
1058
1059 AbstractRender *Monitor::abstractRender()
1060 {
1061     return render;
1062 }
1063
1064 void Monitor::reloadProducer(const QString &id)
1065 {
1066     if (!m_currentClip) return;
1067     if (m_currentClip->getId() == id)
1068         slotSetClipProducer(m_currentClip, m_currentClip->zone(), true);
1069 }
1070
1071 MonitorRefresh::MonitorRefresh(QWidget* parent) :
1072     QWidget(parent)
1073     , m_renderer(NULL)
1074 {
1075     // MonitorRefresh is used as container for the SDL display (it's window id is passed to SDL)
1076     setAttribute(Qt::WA_PaintOnScreen);
1077     setAttribute(Qt::WA_OpaquePaintEvent);
1078     setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
1079     //setAttribute(Qt::WA_NoSystemBackground);
1080 }
1081
1082 void MonitorRefresh::setRenderer(Render* render)
1083 {
1084     m_renderer = render;
1085 }
1086
1087
1088 Overlay::Overlay(QWidget* parent) :
1089     QLabel(parent)
1090 {
1091     //setAttribute(Qt::WA_TransparentForMouseEvents);
1092     setAutoFillBackground(true);
1093     setBackgroundRole(QPalette::Base);
1094     setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
1095     setCursor(Qt::PointingHandCursor);
1096 }
1097
1098 // virtual
1099 void Overlay::mouseReleaseEvent ( QMouseEvent * event )
1100 {
1101     event->ignore();
1102 }
1103
1104 // virtual
1105 void Overlay::mousePressEvent( QMouseEvent * event )
1106 {
1107     event->ignore();
1108 }
1109
1110 // virtual
1111 void Overlay::mouseDoubleClickEvent ( QMouseEvent * event )
1112 {
1113     emit editMarker();
1114     event->ignore();
1115 }
1116
1117 void Overlay::setOverlayText(const QString &text, bool isZone)
1118 {
1119     setHidden(true);
1120     m_isZone = isZone;
1121     QPalette p;
1122     p.setColor(QPalette::Text, Qt::white);
1123     if (m_isZone) p.setColor(QPalette::Base, QColor(200, 0, 0));
1124     else p.setColor(QPalette::Base, QColor(0, 0, 200));
1125     setPalette(p);
1126     setText(' ' + text + ' ');
1127     setHidden(false);
1128     update();
1129 }
1130
1131 VideoContainer::VideoContainer(Monitor* parent) :
1132     QFrame()
1133     , m_monitor(parent)
1134 {
1135     setFrameShape(QFrame::NoFrame);
1136     setFocusPolicy(Qt::ClickFocus);
1137     setEnabled(false);
1138     setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
1139 }
1140
1141 // virtual
1142 void VideoContainer::mouseReleaseEvent(QMouseEvent * event)
1143 {
1144     if (event->button() != Qt::RightButton) {
1145         if (m_monitor->isActive()) {
1146             m_monitor->slotPlay();
1147         }
1148     }
1149 }
1150
1151
1152 // virtual
1153 void VideoContainer::keyPressEvent(QKeyEvent *event)
1154 {
1155     // Exit fullscreen with Esc key
1156     if (event->key() == Qt::Key_Escape && isFullScreen()) {
1157         switchFullScreen();
1158         event->setAccepted(true);
1159     } else event->setAccepted(false);
1160 }
1161
1162 // virtual
1163 void VideoContainer::wheelEvent(QWheelEvent * event)
1164 {
1165     m_monitor->slotMouseSeek(event->delta(), event->modifiers() == Qt::ControlModifier);
1166     event->accept();
1167 }
1168
1169 void VideoContainer::mouseDoubleClickEvent(QMouseEvent * event)
1170 {
1171     if (!KdenliveSettings::openglmonitors())
1172         switchFullScreen();
1173     event->accept();
1174 }
1175
1176 void VideoContainer::switchFullScreen()
1177 {
1178     // TODO: disable screensaver?
1179     Qt::WindowFlags flags = windowFlags();
1180     if (!isFullScreen()) {
1181         // Check if we ahave a multiple monitor setup
1182         setUpdatesEnabled(false);
1183 #if QT_VERSION >= 0x040600
1184         int monitors = QApplication::desktop()->screenCount();
1185 #else
1186         int monitors = QApplication::desktop()->numScreens();
1187 #endif
1188         if (monitors > 1) {
1189             QRect screenres;
1190             // Move monitor widget to the second screen (one screen for Kdenlive, the other one for the Monitor widget
1191             int currentScreen = QApplication::desktop()->screenNumber(this);
1192             if (currentScreen < monitors - 1)
1193                 screenres = QApplication::desktop()->screenGeometry(currentScreen + 1);
1194             else
1195                 screenres = QApplication::desktop()->screenGeometry(currentScreen - 1);
1196             move(QPoint(screenres.x(), screenres.y()));
1197             resize(screenres.width(), screenres.height());
1198         }
1199
1200         m_baseFlags = flags & (Qt::Window | Qt::SubWindow);
1201         flags |= Qt::Window;
1202         flags ^= Qt::SubWindow;
1203         setWindowFlags(flags);
1204 #ifdef Q_WS_X11
1205         // This works around a bug with Compiz
1206         // as the window must be visible before we can set the state
1207         show();
1208         raise();
1209         setWindowState(windowState() | Qt::WindowFullScreen);   // set
1210 #else
1211         setWindowState(windowState() | Qt::WindowFullScreen);   // set
1212         setUpdatesEnabled(true);
1213         show();
1214 #endif
1215         setEnabled(true);
1216     } else {
1217         setUpdatesEnabled(false);
1218         flags ^= (Qt::Window | Qt::SubWindow); //clear the flags...
1219         flags |= m_baseFlags; //then we reset the flags (window and subwindow)
1220         setWindowFlags(flags);
1221         setWindowState(windowState()  ^ Qt::WindowFullScreen);   // reset
1222         setUpdatesEnabled(true);
1223         setEnabled(false);
1224         show();
1225     }
1226     m_monitor->pause();
1227 }
1228
1229
1230 #include "monitor.moc"