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