]> git.sesse.net Git - kdenlive/blob - src/customtrackview.cpp
Fix timeline handling of objects (move them instead of changing their bounding rect
[kdenlive] / src / customtrackview.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 #include <QMouseEvent>
21 #include <QStylePainter>
22 #include <QGraphicsItem>
23 #include <QDomDocument>
24 #include <QScrollBar>
25 #include <QApplication>
26 #include <QInputDialog>
27
28 #include <KDebug>
29 #include <KLocale>
30 #include <KUrl>
31 #include <KIcon>
32 #include <KCursor>
33
34 #include "customtrackview.h"
35 #include "docclipbase.h"
36 #include "clipitem.h"
37 #include "definitions.h"
38 #include "moveclipcommand.h"
39 #include "movetransitioncommand.h"
40 #include "resizeclipcommand.h"
41 #include "editguidecommand.h"
42 #include "addtimelineclipcommand.h"
43 #include "addeffectcommand.h"
44 #include "editeffectcommand.h"
45 #include "moveeffectcommand.h"
46 #include "addtransitioncommand.h"
47 #include "edittransitioncommand.h"
48 #include "editkeyframecommand.h"
49 #include "changespeedcommand.h"
50 #include "addmarkercommand.h"
51 #include "razorclipcommand.h"
52 #include "kdenlivesettings.h"
53 #include "transition.h"
54 #include "clipitem.h"
55 #include "customtrackview.h"
56 #include "clipmanager.h"
57 #include "renderer.h"
58 #include "markerdialog.h"
59 #include "mainwindow.h"
60 #include "ui_keyframedialog_ui.h"
61 #include "clipdurationdialog.h"
62
63
64 //TODO:
65 // disable animation if user asked it in KDE's global settings
66 // http://lists.kde.org/?l=kde-commits&m=120398724717624&w=2
67 // needs something like below (taken from dolphin)
68 // #include <kglobalsettings.h>
69 // const bool animate = KGlobalSettings::graphicEffectsLevel() & KGlobalSettings::SimpleAnimationEffects;
70 // const int duration = animate ? 1500 : 1;
71
72 CustomTrackView::CustomTrackView(KdenliveDoc *doc, QGraphicsScene * projectscene, QWidget *parent)
73         : QGraphicsView(projectscene, parent), m_cursorPos(0), m_dropItem(NULL), m_cursorLine(NULL), m_operationMode(NONE), m_dragItem(NULL), m_visualTip(NULL), m_moveOpMode(NONE), m_animation(NULL), m_projectDuration(0), m_scale(1.0), m_clickPoint(QPoint()), m_document(doc), m_autoScroll(KdenliveSettings::autoscroll()), m_tracksHeight(KdenliveSettings::trackheight()), m_tool(SELECTTOOL), m_dragGuide(NULL), m_findIndex(0), m_menuPosition(QPoint()), m_blockRefresh(false) {
74     if (doc) m_commandStack = doc->commandStack();
75     else m_commandStack == NULL;
76     setMouseTracking(true);
77     setAcceptDrops(true);
78     m_animationTimer = new QTimeLine(800);
79     m_animationTimer->setFrameRange(0, 5);
80     m_animationTimer->setUpdateInterval(100);
81     m_animationTimer->setLoopCount(0);
82     m_tipColor = QColor(0, 192, 0, 200);
83     QColor border = QColor(255, 255, 255, 100);
84     m_tipPen.setColor(border);
85     m_tipPen.setWidth(3);
86     setContentsMargins(0, 0, 0, 0);
87     if (projectscene) {
88         m_cursorLine = projectscene->addLine(0, 0, 0, m_tracksHeight);
89         m_cursorLine->setFlags(QGraphicsItem::ItemIsMovable);
90         m_cursorLine->setZValue(1000);
91     }
92
93     KIcon razorIcon("edit-cut");
94     m_razorCursor = QCursor(razorIcon.pixmap(22, 22));
95     verticalScrollBar()->setTracking(true);
96     connect(verticalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(slotRefreshGuides()));
97 }
98
99 CustomTrackView::~CustomTrackView() {
100     qDeleteAll(m_guides);
101 }
102
103
104 void CustomTrackView::setContextMenu(QMenu *timeline, QMenu *clip, QMenu *transition) {
105     m_timelineContextMenu = timeline;
106     m_timelineContextClipMenu = clip;
107     m_timelineContextTransitionMenu = transition;
108 }
109
110 void CustomTrackView::checkAutoScroll() {
111     m_autoScroll = KdenliveSettings::autoscroll();
112 }
113
114 QList <TrackInfo> CustomTrackView::tracksList() const {
115     return m_tracksList;
116 }
117
118 void CustomTrackView::checkTrackHeight() {
119     if (m_tracksHeight == KdenliveSettings::trackheight()) return;
120     m_tracksHeight = KdenliveSettings::trackheight();
121     emit trackHeightChanged();
122     QList<QGraphicsItem *> itemList = items();
123     ClipItem *item;
124     Transition *transitionitem;
125     for (int i = 0; i < itemList.count(); i++) {
126         if (itemList.at(i)->type() == AVWIDGET) {
127             item = (ClipItem*) itemList.at(i);
128             item->setRect(0, 0, item->rect().width(), m_tracksHeight - 1);
129             item->setPos((qreal) item->startPos().frames(m_document->fps()) * m_scale, (qreal) item->track() * m_tracksHeight);
130             item->resetThumbs();
131         } else if (itemList.at(i)->type() == TRANSITIONWIDGET) {
132             transitionitem = (Transition*) itemList.at(i);
133             transitionitem->setRect(0, 0, transitionitem->rect().width(), m_tracksHeight / 3 * 2 - 1);
134             transitionitem->setPos((qreal) transitionitem->startPos().frames(m_document->fps()) * m_scale, (qreal) transitionitem->track() * m_tracksHeight + m_tracksHeight / 3 * 2);
135         }
136     }
137     m_cursorLine->setLine(m_cursorLine->line().x1(), 0, m_cursorLine->line().x1(), m_tracksHeight * m_tracksList.count());
138
139     for (int i = 0; i < m_guides.count(); i++) {
140         QLineF l = m_guides.at(i)->line();
141         l.setP2(QPointF(l.x2(), m_tracksHeight * m_tracksList.count()));
142         m_guides.at(i)->setLine(l);
143     }
144
145     setSceneRect(0, 0, sceneRect().width(), m_tracksHeight * m_tracksList.count());
146     verticalScrollBar()->setMaximum(m_tracksHeight * m_tracksList.count());
147     update();
148 }
149
150 // virtual
151 void CustomTrackView::resizeEvent(QResizeEvent * event) {
152     QGraphicsView::resizeEvent(event);
153 }
154
155 // virtual
156 void CustomTrackView::wheelEvent(QWheelEvent * e) {
157     if (e->modifiers() == Qt::ControlModifier) {
158         if (e->delta() > 0) emit zoomIn();
159         else emit zoomOut();
160     } else {
161         if (e->delta() > 0) horizontalScrollBar()->setValue(horizontalScrollBar()->value() + horizontalScrollBar()->singleStep());
162         else  horizontalScrollBar()->setValue(horizontalScrollBar()->value() - horizontalScrollBar()->singleStep());
163     }
164 }
165
166 int CustomTrackView::getPreviousVideoTrack(int track) {
167     track = m_tracksList.count() - track - 1;
168     track --;
169     for (int i = track; i > -1; i--) {
170         if (m_tracksList.at(i).type == VIDEOTRACK) return i + 1;
171     }
172     return 0;
173 }
174
175 // virtual
176
177 void CustomTrackView::mouseMoveEvent(QMouseEvent * event) {
178     int pos = event->x();
179     emit mousePosition((int)(mapToScene(event->pos()).x() / m_scale));
180     if (event->buttons() & Qt::MidButton) return;
181     if (event->buttons() != Qt::NoButton) {
182         if (m_dragItem && m_tool == SELECTTOOL) { //event->button() == Qt::LeftButton) {
183             // a button was pressed, delete visual tips
184             if (m_operationMode == MOVE && (event->pos() - m_clickEvent).manhattanLength() >= QApplication::startDragDistance()) {
185                 double snappedPos = getSnapPointForPos(mapToScene(event->pos()).x() - m_clickPoint.x());
186                 //kDebug() << "///////  MOVE CLIP, EVENT Y: "<<m_clickPoint.y();//<<event->scenePos().y()<<", SCENE HEIGHT: "<<scene()->sceneRect().height();
187                 int moveTrack = (int)  mapToScene(event->pos() - QPoint(0, (m_dragItem->type() == TRANSITIONWIDGET ? m_dragItem->boundingRect().height() / 2 : 0))).y() / m_tracksHeight;
188                 int currentTrack = m_dragItem->track();
189
190                 if (moveTrack > 1000) moveTrack = 0;
191                 else if (moveTrack > m_tracksList.count() - 1) moveTrack = m_tracksList.count() - 1;
192                 else if (moveTrack < 0) moveTrack = 0;
193
194                 int offset = moveTrack - currentTrack;
195                 if (m_selectedClipList.count() == 1) m_dragItem->moveTo((int)(snappedPos / m_scale), m_scale, offset * m_tracksHeight, moveTrack);
196                 else {
197                     int moveOffset = (int)(snappedPos / m_scale) - m_dragItem->startPos().frames(m_document->fps());
198                     if (canBeMoved(m_selectedClipList, GenTime(moveOffset, m_document->fps()), offset)) {
199                         for (int i = 0; i < m_selectedClipList.count(); i++) {
200                             AbstractClipItem *item = m_selectedClipList.at(i);
201                             item->moveTo(item->startPos().frames(m_document->fps()) + moveOffset, m_scale, offset * m_tracksHeight, item->track() + offset, false);
202                         }
203                     }
204                 }
205
206             } else if (m_operationMode == RESIZESTART) {
207                 double snappedPos = getSnapPointForPos(mapToScene(event->pos()).x());
208                 m_dragItem->resizeStart((int)(snappedPos / m_scale), m_scale);
209             } else if (m_operationMode == RESIZEEND) {
210                 double snappedPos = getSnapPointForPos(mapToScene(event->pos()).x());
211                 m_dragItem->resizeEnd((int)(snappedPos / m_scale), m_scale);
212             } else if (m_operationMode == FADEIN) {
213                 int pos = (int)(mapToScene(event->pos()).x() / m_scale);
214                 ((ClipItem*) m_dragItem)->setFadeIn((int)(pos - m_dragItem->startPos().frames(m_document->fps())), m_scale);
215             } else if (m_operationMode == FADEOUT) {
216                 int pos = (int)(mapToScene(event->pos()).x() / m_scale);
217                 ((ClipItem*) m_dragItem)->setFadeOut((int)(m_dragItem->endPos().frames(m_document->fps()) - pos), m_scale);
218             } else if (m_operationMode == KEYFRAME) {
219                 GenTime keyFramePos = GenTime((int)(mapToScene(event->pos()).x() / m_scale), m_document->fps()) - m_dragItem->startPos() + m_dragItem->cropStart();
220                 double pos = mapToScene(event->pos()).toPoint().y();
221                 QRectF br = m_dragItem->sceneBoundingRect();
222                 double maxh = 100.0 / br.height();
223                 pos = (br.bottom() - pos) * maxh;
224                 m_dragItem->updateKeyFramePos(keyFramePos, pos);
225             }
226
227             if (m_animation) delete m_animation;
228             m_animation = NULL;
229             if (m_visualTip) delete m_visualTip;
230             m_visualTip = NULL;
231             QGraphicsView::mouseMoveEvent(event);
232             return;
233         } else if (m_operationMode == MOVEGUIDE) {
234             if (m_animation) delete m_animation;
235             m_animation = NULL;
236             if (m_visualTip) delete m_visualTip;
237             m_visualTip = NULL;
238             QGraphicsView::mouseMoveEvent(event);
239             return;
240         }
241     }
242
243     if (m_tool == RAZORTOOL) {
244         setCursor(m_razorCursor);
245         //QGraphicsView::mouseMoveEvent(event);
246         //return;
247     }
248
249     QList<QGraphicsItem *> itemList = items(event->pos());
250     QGraphicsRectItem *item = NULL;
251     OPERATIONTYPE opMode = NONE;
252
253     if (itemList.count() == 1 && itemList.at(0)->type() == GUIDEITEM) {
254         opMode = MOVEGUIDE;
255     } else for (int i = 0; i < itemList.count(); i++) {
256             if (itemList.at(i)->type() == AVWIDGET || itemList.at(i)->type() == TRANSITIONWIDGET) {
257                 item = (QGraphicsRectItem*) itemList.at(i);
258                 break;
259             }
260         }
261
262     if (item && event->buttons() == Qt::NoButton) {
263         AbstractClipItem *clip = static_cast <AbstractClipItem*>(item);
264         if (m_tool == RAZORTOOL) {
265             // razor tool over a clip, display current frame in monitor
266             if (!m_blockRefresh && item->type() == AVWIDGET) {
267                 emit showClipFrame(((ClipItem *) item)->baseClip(), mapToScene(event->pos()).x() / m_scale - (clip->startPos() - clip->cropStart()).frames(m_document->fps()));
268             }
269             event->accept();
270             return;
271         }
272         opMode = clip->operationMode(mapToScene(event->pos()), m_scale);
273         double size = 8;
274         if (opMode == m_moveOpMode) {
275             QGraphicsView::mouseMoveEvent(event);
276             return;
277         } else {
278             if (m_visualTip) {
279                 if (m_animation) delete m_animation;
280                 m_animation = NULL;
281                 m_animationTimer->stop();
282                 delete m_visualTip;
283                 m_visualTip = NULL;
284             }
285         }
286         m_moveOpMode = opMode;
287         if (opMode == MOVE) {
288             setCursor(Qt::OpenHandCursor);
289         } else if (opMode == RESIZESTART) {
290             setCursor(KCursor("left_side", Qt::SizeHorCursor));
291             if (m_visualTip == NULL) {
292                 QRectF rect = clip->sceneBoundingRect();
293                 QPolygon polygon;
294                 polygon << QPoint((int)rect.x(), (int)(rect.y() + rect.height() / 2 - size * 2));
295                 polygon << QPoint((int)(rect.x() + size * 2), (int)(rect.y() + rect.height() / 2));
296                 polygon << QPoint((int)rect.x(), (int)(rect.y() + rect.height() / 2 + size * 2));
297                 polygon << QPoint((int)rect.x(), (int)(rect.y() + rect.height() / 2 - size * 2));
298
299                 m_visualTip = new QGraphicsPolygonItem(polygon);
300                 ((QGraphicsPolygonItem*) m_visualTip)->setBrush(m_tipColor);
301                 ((QGraphicsPolygonItem*) m_visualTip)->setPen(m_tipPen);
302                 m_visualTip->setZValue(100);
303                 m_animation = new QGraphicsItemAnimation;
304                 m_animation->setItem(m_visualTip);
305                 m_animation->setTimeLine(m_animationTimer);
306                 m_visualTip->setPos(0, 0);
307                 double scale = 2.0;
308                 m_animation->setScaleAt(.5, scale, 1);
309                 m_animation->setPosAt(.5, QPointF(rect.x() - rect.x() * scale, 0));
310                 scale = 1.0;
311                 m_animation->setScaleAt(1, scale, 1);
312                 m_animation->setPosAt(1, QPointF(rect.x() - rect.x() * scale, 0));
313                 scene()->addItem(m_visualTip);
314                 m_animationTimer->start();
315             }
316         } else if (opMode == RESIZEEND) {
317             setCursor(KCursor("right_side", Qt::SizeHorCursor));
318             if (m_visualTip == NULL) {
319                 QRectF rect = clip->sceneBoundingRect();
320                 QPolygon polygon;
321                 polygon << QPoint((int)(rect.x() + rect.width()), (int)(rect.y() + rect.height() / 2 - size * 2));
322                 polygon << QPoint((int)(rect.x() + rect.width() - size * 2), (int)(rect.y() + rect.height() / 2));
323                 polygon << QPoint((int)(rect.x() + rect.width()), (int)(rect.y() + rect.height() / 2 + size * 2));
324                 polygon << QPoint((int)(rect.x() + rect.width()), (int)(rect.y() + rect.height() / 2 - size * 2));
325
326                 m_visualTip = new QGraphicsPolygonItem(polygon);
327                 ((QGraphicsPolygonItem*) m_visualTip)->setBrush(m_tipColor);
328                 ((QGraphicsPolygonItem*) m_visualTip)->setPen(m_tipPen);
329
330                 m_visualTip->setZValue(100);
331                 m_animation = new QGraphicsItemAnimation;
332                 m_animation->setItem(m_visualTip);
333                 m_animation->setTimeLine(m_animationTimer);
334                 m_visualTip->setPos(0, 0);
335                 double scale = 2.0;
336                 m_animation->setScaleAt(.5, scale, 1);
337                 m_animation->setPosAt(.5, QPointF(rect.x() - rect.x() * scale - rect.width(), 0));
338                 scale = 1.0;
339                 m_animation->setScaleAt(1, scale, 1);
340                 m_animation->setPosAt(1, QPointF(rect.x() - rect.x() * scale, 0));
341                 scene()->addItem(m_visualTip);
342                 m_animationTimer->start();
343             }
344         } else if (opMode == FADEIN) {
345             if (m_visualTip == NULL) {
346                 ClipItem *item = (ClipItem *) clip;
347                 m_visualTip = new QGraphicsEllipseItem(item->pos().x() + item->fadeIn() * m_scale - size, item->pos().y() - 8, size * 2, 16);
348                 ((QGraphicsEllipseItem*) m_visualTip)->setBrush(m_tipColor);
349                 ((QGraphicsEllipseItem*) m_visualTip)->setPen(m_tipPen);
350                 m_visualTip->setZValue(100);
351                 m_animation = new QGraphicsItemAnimation;
352                 m_animation->setItem(m_visualTip);
353                 m_animation->setTimeLine(m_animationTimer);
354                 m_visualTip->setPos(0, 0);
355                 double scale = 2.0;
356                 m_animation->setScaleAt(.5, scale, scale);
357                 m_animation->setPosAt(.5, QPointF(item->pos().x() - item->pos().x() * scale -  item->fadeIn() * m_scale, item->pos().y() - item->pos().y() * scale));
358                 scale = 1.0;
359                 m_animation->setScaleAt(1, scale, scale);
360                 m_animation->setPosAt(1, QPointF(item->pos().x() - item->pos().x() * scale, item->pos().y() - item->pos().y() * scale));
361                 scene()->addItem(m_visualTip);
362                 m_animationTimer->start();
363             }
364             setCursor(Qt::PointingHandCursor);
365         } else if (opMode == FADEOUT) {
366             if (m_visualTip == NULL) {
367                 ClipItem *item = (ClipItem *) clip;
368                 m_visualTip = new QGraphicsEllipseItem(item->pos().x() + item->rect().width() - item->fadeOut() * m_scale - size, item->pos().y() - 8, size*2, 16);
369                 ((QGraphicsEllipseItem*) m_visualTip)->setBrush(m_tipColor);
370                 ((QGraphicsEllipseItem*) m_visualTip)->setPen(m_tipPen);
371                 m_visualTip->setZValue(100);
372                 m_animation = new QGraphicsItemAnimation;
373                 m_animation->setItem(m_visualTip);
374                 m_animation->setTimeLine(m_animationTimer);
375                 m_visualTip->setPos(0, 0);
376                 double scale = 2.0;
377                 m_animation->setScaleAt(.5, scale, scale);
378                 m_animation->setPosAt(.5, QPointF(item->pos().x() - item->pos().x() * scale - item->rect().width() + item->fadeOut() * m_scale, item->pos().y() - item->pos().y() * scale));
379                 scale = 1.0;
380                 m_animation->setScaleAt(1, scale, scale);
381                 m_animation->setPosAt(1, QPointF(item->pos().x() - item->pos().x() * scale, item->pos().y() - item->pos().y() * scale));
382                 scene()->addItem(m_visualTip);
383                 m_animationTimer->start();
384             }
385             setCursor(Qt::PointingHandCursor);
386         } else if (opMode == TRANSITIONSTART) {
387             if (m_visualTip == NULL) {
388                 QRectF rect = clip->sceneBoundingRect();
389                 m_visualTip = new QGraphicsEllipseItem(-5, -5 , 10, 10);
390                 ((QGraphicsEllipseItem*) m_visualTip)->setBrush(m_tipColor);
391                 ((QGraphicsEllipseItem*) m_visualTip)->setPen(m_tipPen);
392                 m_visualTip->setZValue(100);
393                 m_animation = new QGraphicsItemAnimation;
394                 m_animation->setItem(m_visualTip);
395                 m_animation->setTimeLine(m_animationTimer);
396                 m_visualTip->setPos(rect.x() + 10, rect.y() + rect.height() / 2 + 12);
397                 double scale = 2.0;
398                 m_animation->setScaleAt(.5, scale, scale);
399                 scale = 1.0;
400                 m_animation->setScaleAt(1, scale, scale);
401                 scene()->addItem(m_visualTip);
402                 m_animationTimer->start();
403             }
404             setCursor(Qt::PointingHandCursor);
405         } else if (opMode == TRANSITIONEND) {
406             if (m_visualTip == NULL) {
407                 QRectF rect = clip->sceneBoundingRect();
408                 m_visualTip = new QGraphicsEllipseItem(-5, -5 , 10, 10);
409                 ((QGraphicsEllipseItem*) m_visualTip)->setBrush(m_tipColor);
410                 ((QGraphicsEllipseItem*) m_visualTip)->setPen(m_tipPen);
411                 m_visualTip->setZValue(100);
412                 m_animation = new QGraphicsItemAnimation;
413                 m_animation->setItem(m_visualTip);
414                 m_animation->setTimeLine(m_animationTimer);
415                 m_visualTip->setPos(rect.x() + rect.width() - 10 , rect.y() + rect.height() / 2 + 12);
416                 double scale = 2.0;
417                 m_animation->setScaleAt(.5, scale, scale);
418                 scale = 1.0;
419                 m_animation->setScaleAt(1, scale, scale);
420                 scene()->addItem(m_visualTip);
421                 m_animationTimer->start();
422             }
423             setCursor(Qt::PointingHandCursor);
424         } else if (opMode == KEYFRAME) {
425             setCursor(Qt::PointingHandCursor);
426         }
427     } // no clip under mouse
428     else if (m_tool == RAZORTOOL) {
429         event->accept();
430         return;
431     } else if (opMode == MOVEGUIDE) {
432         m_moveOpMode = opMode;
433         setCursor(Qt::SplitHCursor);
434     } else {
435         m_moveOpMode = NONE;
436         if (event->buttons() != Qt::NoButton && event->modifiers() == Qt::NoModifier) {
437             setCursorPos((int)(mapToScene(event->pos().x(), 0).x() / m_scale));
438         }
439         if (m_visualTip) {
440             if (m_animation) delete m_animation;
441             m_animationTimer->stop();
442             m_animation = NULL;
443             delete m_visualTip;
444             m_visualTip = NULL;
445
446         }
447         setCursor(Qt::ArrowCursor);
448     }
449     QGraphicsView::mouseMoveEvent(event);
450 }
451
452 // virtual
453 void CustomTrackView::mousePressEvent(QMouseEvent * event) {
454     m_menuPosition = QPoint();
455     m_blockRefresh = true;
456     if (m_tool != RAZORTOOL) activateMonitor();
457     m_clickEvent = event->pos();
458     QList<QGraphicsItem *> collisionList = items(event->pos());
459     if (event->button() == Qt::MidButton) {
460         m_document->renderer()->switchPlay();
461         m_blockRefresh = false;
462         return;
463     }
464     if (event->modifiers() == Qt::ControlModifier && collisionList.count() == 0) {
465         setDragMode(QGraphicsView::ScrollHandDrag);
466         QGraphicsView::mousePressEvent(event);
467         m_blockRefresh = false;
468         return;
469     } else if (event->modifiers() == Qt::ShiftModifier && collisionList.count() == 0) {
470         setDragMode(QGraphicsView::RubberBandDrag);
471         QGraphicsView::mousePressEvent(event);
472         m_blockRefresh = false;
473         return;
474     } else {
475         bool collision = false;
476         if (collisionList.count() == 1 && collisionList.at(0)->type() == GUIDEITEM) {
477             // a guide item was pressed
478             collisionList.at(0)->setFlag(QGraphicsItem::ItemIsMovable, true);
479             m_dragItem = NULL;
480             m_dragGuide = (Guide *) collisionList.at(0);
481             collision = true;
482             m_operationMode = MOVEGUIDE;
483             // deselect all clips so that only the guide will move
484             QList<QGraphicsItem *> clips = scene()->selectedItems();
485             for (int i = 0; i < clips.count(); ++i)
486                 clips.at(i)->setSelected(false);
487             updateSnapPoints(NULL);
488             QGraphicsView::mousePressEvent(event);
489         } else for (int i = 0; i < collisionList.count(); ++i) {
490                 QGraphicsItem *item = collisionList.at(i);
491                 if (item->type() == AVWIDGET || item->type() == TRANSITIONWIDGET) {
492                     if (m_tool == RAZORTOOL) {
493                         m_dragItem = NULL;
494                         if (item->type() == TRANSITIONWIDGET) {
495                             emit displayMessage(i18n("Cannot cut a transition"), ErrorMessage);
496                             event->accept();
497                             return;
498                         }
499                         AbstractClipItem *clip = static_cast <AbstractClipItem *>(item);
500                         RazorClipCommand* command = new RazorClipCommand(this, clip->info(), GenTime((int)(mapToScene(event->pos()).x() / m_scale), m_document->fps()), true);
501                         m_commandStack->push(command);
502                         m_document->setModified(true);
503                         event->accept(); //QGraphicsView::mousePressEvent(event);
504                         return;
505                     }
506                     // select item
507                     if (!item->isSelected()) {
508
509                         if (event->modifiers() != Qt::ControlModifier) {
510                             QList<QGraphicsItem *> itemList = items();
511                             for (int i = 0; i < itemList.count(); i++) {
512                                 itemList.at(i)->setSelected(false);
513                                 itemList.at(i)->update();
514                             }
515                         }
516                         item->setSelected(true);
517                         item->update();
518                     }
519
520                     m_dragItem = (AbstractClipItem *) item;
521
522                     m_clickPoint = QPoint((int)(mapToScene(event->pos()).x() - m_dragItem->startPos().frames(m_document->fps()) * m_scale), (int)(event->pos().y() - m_dragItem->pos().y()));
523                     m_dragItemInfo.startPos = m_dragItem->startPos();
524                     m_dragItemInfo.endPos = m_dragItem->endPos();
525                     m_dragItemInfo.track = m_dragItem->track();
526
527                     m_selectedClipList.clear();
528                     QList<QGraphicsItem *> selected = scene()->selectedItems();
529                     for (int i = 0; i < selected.count(); i++) {
530                         if (selected.at(i)->type() == AVWIDGET || selected.at(i)->type() == TRANSITIONWIDGET)
531                             m_selectedClipList.append(static_cast <AbstractClipItem *>(selected.at(i)));
532                     }
533
534                     m_operationMode = m_dragItem->operationMode(mapToScene(event->pos()), m_scale);
535                     if (m_operationMode == KEYFRAME) {
536                         m_dragItem->updateSelectedKeyFrame();
537                         m_blockRefresh = false;
538                         return;
539                     } else if (m_operationMode == MOVE) setCursor(Qt::ClosedHandCursor);
540                     else if (m_operationMode == TRANSITIONSTART) {
541                         ItemInfo info;
542                         info.startPos = m_dragItem->startPos();
543                         info.track = m_dragItem->track();
544                         int transitiontrack = getPreviousVideoTrack(info.track);
545                         ClipItem *transitionClip = NULL;
546                         if (transitiontrack != 0) transitionClip = getClipItemAt((int) info.startPos.frames(m_document->fps()), m_tracksList.count() - transitiontrack);
547                         if (transitionClip && transitionClip->endPos() < m_dragItem->endPos()) {
548                             info.endPos = transitionClip->endPos();
549                         } else info.endPos = info.startPos + GenTime(2.5);
550
551                         slotAddTransition((ClipItem *) m_dragItem, info, transitiontrack);
552                     } else if (m_operationMode == TRANSITIONEND) {
553                         ItemInfo info;
554                         info.endPos = m_dragItem->endPos();
555                         info.track = m_dragItem->track();
556                         int transitiontrack = getPreviousVideoTrack(info.track);
557                         ClipItem *transitionClip = NULL;
558                         if (transitiontrack != 0) transitionClip = getClipItemAt((int) info.endPos.frames(m_document->fps()), m_tracksList.count() - transitiontrack);
559                         if (transitionClip && transitionClip->startPos() > m_dragItem->startPos()) {
560                             info.startPos = transitionClip->startPos();
561                         } else info.startPos = info.endPos - GenTime(2.5);
562                         slotAddTransition((ClipItem *) m_dragItem, info, transitiontrack);
563                     }
564                     updateSnapPoints(m_dragItem);
565                     collision = true;
566                     break;
567                 }
568             }
569         if (!collision) {
570             kDebug() << "//////// NO ITEM FOUND ON CLICK";
571             m_dragItem = NULL;
572             setCursor(Qt::ArrowCursor);
573             QList<QGraphicsItem *> itemList = items();
574             for (int i = 0; i < itemList.count(); i++)
575                 itemList.at(i)->setSelected(false);
576             //emit clipItemSelected(NULL);
577             if (event->button() == Qt::RightButton) {
578                 displayContextMenu(event->globalPos());
579                 m_menuPosition = event->pos();
580             } else setCursorPos((int)(mapToScene(event->x(), 0).x() / m_scale));
581         } else if (event->button() == Qt::RightButton) {
582             m_operationMode = NONE;
583             displayContextMenu(event->globalPos(), m_dragItem);
584             m_dragItem = NULL;
585         }
586         if (m_dragItem && m_dragItem->type() == AVWIDGET) emit clipItemSelected((ClipItem*) m_dragItem);
587         else emit clipItemSelected(NULL);
588     }
589     m_blockRefresh = false;
590     //kDebug()<<pos;
591     //QGraphicsView::mousePressEvent(event);
592 }
593
594 void CustomTrackView::mouseDoubleClickEvent(QMouseEvent *event) {
595     if (m_dragItem && m_dragItem->hasKeyFrames()) {
596         if (m_moveOpMode == KEYFRAME) {
597             // user double clicked on a keyframe, open edit dialog
598             QDialog d(parentWidget());
599             Ui::KeyFrameDialog_UI view;
600             view.setupUi(&d);
601             view.kfr_position->setText(m_document->timecode().getTimecode(GenTime(m_dragItem->selectedKeyFramePos(), m_document->fps()) - m_dragItem->cropStart(), m_document->fps()));
602             view.kfr_value->setValue(m_dragItem->selectedKeyFrameValue());
603             view.kfr_value->setFocus();
604             if (d.exec() == QDialog::Accepted) {
605                 int pos = m_document->timecode().getFrameCount(view.kfr_position->text(), m_document->fps());
606                 m_dragItem->updateKeyFramePos(GenTime(pos, m_document->fps()) + m_dragItem->cropStart(), (double) view.kfr_value->value() * m_dragItem->keyFrameFactor());
607                 ClipItem *item = (ClipItem *)m_dragItem;
608                 QString previous = item->keyframes(item->selectedEffectIndex());
609                 item->updateKeyframeEffect();
610                 QString next = item->keyframes(item->selectedEffectIndex());
611                 EditKeyFrameCommand *command = new EditKeyFrameCommand(this, item->track(), item->startPos(), item->selectedEffectIndex(), previous, next, false);
612                 m_commandStack->push(command);
613                 updateEffect(m_tracksList.count() - item->track(), item->startPos(), item->selectedEffect(), item->selectedEffectIndex());
614             }
615
616         } else  {
617             // add keyframe
618             GenTime keyFramePos = GenTime((int)(mapToScene(event->pos()).x() / m_scale), m_document->fps()) - m_dragItem->startPos() + m_dragItem->cropStart();
619             m_dragItem->addKeyFrame(keyFramePos, mapToScene(event->pos()).toPoint().y());
620             ClipItem * item = (ClipItem *) m_dragItem;
621             QString previous = item->keyframes(item->selectedEffectIndex());
622             item->updateKeyframeEffect();
623             QString next = item->keyframes(item->selectedEffectIndex());
624             EditKeyFrameCommand *command = new EditKeyFrameCommand(this, m_dragItem->track(), m_dragItem->startPos(), item->selectedEffectIndex(), previous, next, false);
625             m_commandStack->push(command);
626             updateEffect(m_tracksList.count() - item->track(), item->startPos(), item->selectedEffect(), item->selectedEffectIndex());
627         }
628     } else if (m_dragItem) {
629         ClipDurationDialog d(m_dragItem, m_document->timecode(), this);
630         if (d.exec() == QDialog::Accepted) {
631             if (d.startPos() != m_dragItem->startPos()) {
632                 if (m_dragItem->type() == AVWIDGET) {
633                     ItemInfo startInfo;
634                     startInfo.startPos = m_dragItem->startPos();
635                     startInfo.endPos = m_dragItem->endPos();
636                     startInfo.track = m_dragItem->track();
637                     ItemInfo endInfo;
638                     endInfo.startPos = d.startPos();
639                     endInfo.endPos = m_dragItem->endPos() + (endInfo.startPos - startInfo.startPos);
640                     endInfo.track = m_dragItem->track();
641                     MoveClipCommand *command = new MoveClipCommand(this, startInfo, endInfo, true);
642                     m_commandStack->push(command);
643                 } else {
644                     //TODO: move transition
645                 }
646             }
647             if (d.duration() != m_dragItem->duration()) {
648                 if (m_dragItem->type() == AVWIDGET) {
649                     ItemInfo startInfo;
650                     startInfo.startPos = m_dragItem->startPos();
651                     startInfo.endPos = m_dragItem->endPos();
652                     startInfo.track = m_dragItem->track();
653                     ItemInfo endInfo;
654                     endInfo.startPos = startInfo.startPos;
655                     endInfo.endPos = endInfo.startPos + d.duration();
656                     endInfo.track = m_dragItem->track();
657                     ResizeClipCommand *command = new ResizeClipCommand(this, startInfo, endInfo, true);
658                     m_commandStack->push(command);
659                 } else {
660                     //TODO: resize transition
661                 }
662             }
663         }
664     } else {
665         QList<QGraphicsItem *> collisionList = items(event->pos());
666         if (collisionList.count() == 1 && collisionList.at(0)->type() == GUIDEITEM) {
667             Guide *editGuide = (Guide *) collisionList.at(0);
668             if (editGuide) slotEditGuide(editGuide->info());
669         }
670     }
671 }
672
673
674 void CustomTrackView::editKeyFrame(const GenTime pos, const int track, const int index, const QString keyframes) {
675     ClipItem *clip = getClipItemAt((int)pos.frames(m_document->fps()), track);
676     if (clip) {
677         clip->setKeyframes(index, keyframes);
678         updateEffect(m_tracksList.count() - clip->track(), clip->startPos(), clip->effectAt(index), index);
679     } else emit displayMessage(i18n("Cannot find clip with keyframe"), ErrorMessage);
680 }
681
682
683 void CustomTrackView::displayContextMenu(QPoint pos, AbstractClipItem *clip) {
684     if (clip == NULL) m_timelineContextMenu->popup(pos);
685     else if (clip->type() == AVWIDGET) m_timelineContextClipMenu->popup(pos);
686     else if (clip->type() == TRANSITIONWIDGET) m_timelineContextTransitionMenu->popup(pos);
687 }
688
689 void CustomTrackView::activateMonitor() {
690     emit activateDocumentMonitor();
691 }
692
693 void CustomTrackView::dragEnterEvent(QDragEnterEvent * event) {
694     if (event->mimeData()->hasFormat("kdenlive/producerslist")) {
695         kDebug() << "///////////////  DRAG ENTERED, TEXT: " << event->mimeData()->data("kdenlive/producerslist");
696         QStringList ids = QString(event->mimeData()->data("kdenlive/producerslist")).split(";");
697         //TODO: drop of several clips
698         for (int i = 0; i < ids.size(); ++i) {
699         }
700         DocClipBase *clip = m_document->getBaseClip(ids.at(0).toInt());
701         if (clip == NULL) kDebug() << " WARNING))))))))) CLIP NOT FOUND : " << ids.at(0).toInt();
702         addItem(clip, event->pos());
703         event->acceptProposedAction();
704     } else QGraphicsView::dragEnterEvent(event);
705 }
706
707 void CustomTrackView::slotRefreshEffects(ClipItem *clip) {
708     int track = m_tracksList.count() - clip->track();
709     GenTime pos = clip->startPos();
710     if (!m_document->renderer()->mltRemoveEffect(track, pos, "-1", false)) {
711         emit displayMessage(i18n("Problem deleting effect"), ErrorMessage);
712         return;
713     }
714     bool success = true;
715     for (int i = 0; i < clip->effectsCount(); i++) {
716         if (!m_document->renderer()->mltAddEffect(track, pos, clip->getEffectArgs(clip->effectAt(i)), false)) success = false;
717     }
718     if (!success) emit displayMessage(i18n("Problem adding effect to clip"), ErrorMessage);
719     m_document->renderer()->doRefresh();
720 }
721
722 void CustomTrackView::addEffect(int track, GenTime pos, QDomElement effect) {
723     ClipItem *clip = getClipItemAt((int)pos.frames(m_document->fps()) + 1, m_tracksList.count() - track);
724     if (clip) {
725         QMap <QString, QString> effectParams = clip->addEffect(effect);
726         if (!m_document->renderer()->mltAddEffect(track, pos, effectParams))
727             emit displayMessage(i18n("Problem adding effect to clip"), ErrorMessage);
728         emit clipItemSelected(clip);
729     } else emit displayMessage(i18n("Cannot find clip to add effect"), ErrorMessage);
730 }
731
732 void CustomTrackView::deleteEffect(int track, GenTime pos, QDomElement effect) {
733     QString index = effect.attribute("kdenlive_ix");
734     if (effect.attribute("disabled") != "1" && !m_document->renderer()->mltRemoveEffect(track, pos, index)) {
735         emit displayMessage(i18n("Problem deleting effect"), ErrorMessage);
736         return;
737     }
738     ClipItem *clip = getClipItemAt((int)pos.frames(m_document->fps()) + 1, m_tracksList.count() - track);
739     if (clip) {
740         clip->deleteEffect(index);
741         emit clipItemSelected(clip);
742     }
743 }
744
745 void CustomTrackView::slotAddEffect(QDomElement effect, GenTime pos, int track) {
746     QList<QGraphicsItem *> itemList;
747     if (track == -1) itemList = scene()->selectedItems();
748     if (itemList.isEmpty()) {
749         ClipItem *clip = getClipItemAt((int)pos.frames(m_document->fps()) + 1, track);
750         if (clip) itemList.append(clip);
751         else emit displayMessage(i18n("Select a clip if you want to apply an effect"), ErrorMessage);
752     }
753     kDebug() << "// REQUESTING EFFECT ON CLIP: " << pos.frames(25) << ", TRK: " << track << "SELECTED ITEMS: " << itemList.count();
754     for (int i = 0; i < itemList.count(); i++) {
755         if (itemList.at(i)->type() == AVWIDGET) {
756             ClipItem *item = (ClipItem *)itemList.at(i);
757             item->initEffect(effect);
758             AddEffectCommand *command = new AddEffectCommand(this, m_tracksList.count() - item->track(), item->startPos(), effect, true);
759             m_commandStack->push(command);
760         }
761     }
762     m_document->setModified(true);
763 }
764
765 void CustomTrackView::slotDeleteEffect(ClipItem *clip, QDomElement effect) {
766     AddEffectCommand *command = new AddEffectCommand(this, m_tracksList.count() - clip->track(), clip->startPos(), effect, false);
767     m_commandStack->push(command);
768     m_document->setModified(true);
769 }
770
771 void CustomTrackView::updateEffect(int track, GenTime pos, QDomElement effect, int ix) {
772     ClipItem *clip = getClipItemAt((int)pos.frames(m_document->fps()) + 1, m_tracksList.count() - track);
773     if (clip) {
774         QMap <QString, QString> effectParams = clip->getEffectArgs(effect);
775         if (effectParams.value("disabled") == "1") {
776             if (m_document->renderer()->mltRemoveEffect(track, pos, effectParams.value("kdenlive_ix"))) {
777                 kDebug() << "//////  DISABLING EFFECT: " << index << ", CURRENTLA: " << clip->selectedEffectIndex();
778             } else emit displayMessage(i18n("Problem deleting effect"), ErrorMessage);
779         } else if (!m_document->renderer()->mltEditEffect(m_tracksList.count() - clip->track(), clip->startPos(), effectParams))
780             emit displayMessage(i18n("Problem editing effect"), ErrorMessage);
781         if (ix == clip->selectedEffectIndex()) {
782             clip->setSelectedEffect(clip->selectedEffectIndex());
783         }
784     }
785     m_document->setModified(true);
786 }
787
788 void CustomTrackView::moveEffect(int track, GenTime pos, int oldPos, int newPos) {
789     ClipItem *clip = getClipItemAt((int)pos.frames(m_document->fps()) + 1, m_tracksList.count() - track);
790     if (clip) {
791         m_document->renderer()->mltMoveEffect(track, pos, oldPos, newPos);
792     }
793     m_document->setModified(true);
794 }
795
796 void CustomTrackView::slotChangeEffectState(ClipItem *clip, int effectPos, bool disable) {
797     QDomElement effect = clip->effectAt(effectPos);
798     QDomElement oldEffect = effect.cloneNode().toElement();
799     effect.setAttribute("disabled", disable);
800     EditEffectCommand *command = new EditEffectCommand(this, m_tracksList.count() - clip->track(), clip->startPos(), oldEffect, effect, effectPos, true);
801     m_commandStack->push(command);
802     m_document->setModified(true);
803 }
804
805 void CustomTrackView::slotChangeEffectPosition(ClipItem *clip, int currentPos, int newPos) {
806     MoveEffectCommand *command = new MoveEffectCommand(this, m_tracksList.count() - clip->track(), clip->startPos(), currentPos, newPos, true);
807     m_commandStack->push(command);
808     m_document->setModified(true);
809 }
810
811 void CustomTrackView::slotUpdateClipEffect(ClipItem *clip, QDomElement oldeffect, QDomElement effect, int ix) {
812     EditEffectCommand *command = new EditEffectCommand(this, m_tracksList.count() - clip->track(), clip->startPos(), oldeffect, effect, ix, true);
813     m_commandStack->push(command);
814 }
815
816 void CustomTrackView::cutClip(ItemInfo info, GenTime cutTime, bool cut) {
817     if (cut) {
818         // cut clip
819         ClipItem *item = getClipItemAt((int) info.startPos.frames(m_document->fps()) + 1, info.track);
820         if (!item || cutTime >= item->endPos() || cutTime <= item->startPos()) {
821             emit displayMessage(i18n("Cannot find clip to cut"), ErrorMessage);
822             kDebug() << "/////////  ERROR CUTTING CLIP : (" << item->startPos().frames(25) << "-" << item->endPos().frames(25) << "), INFO: (" << info.startPos.frames(25) << "-" << info.endPos.frames(25) << ")" << ", CUT: " << cutTime.frames(25);
823             m_blockRefresh = false;
824             return;
825         }
826         kDebug() << "/////////  CUTTING CLIP : (" << item->startPos().frames(25) << "-" << item->endPos().frames(25) << "), INFO: (" << info.startPos.frames(25) << "-" << info.endPos.frames(25) << ")" << ", CUT: " << cutTime.frames(25);
827
828         m_document->renderer()->mltCutClip(m_tracksList.count() - info.track, cutTime);
829         int cutPos = (int) cutTime.frames(m_document->fps());
830         ItemInfo newPos;
831         newPos.startPos = cutTime;
832         newPos.endPos = info.endPos;
833         newPos.cropStart = item->cropStart() + (cutTime - info.startPos);
834         newPos.track = info.track;
835         ClipItem *dup = item->clone(m_scale, newPos);
836         kDebug() << "// REsizing item to: " << cutPos;
837         item->resizeEnd(cutPos, m_scale);
838         scene()->addItem(dup);
839         item->baseClip()->addReference();
840         m_document->updateClip(item->baseClip()->getId());
841         kDebug() << "/////////  CUTTING CLIP RESULT: (" << item->startPos().frames(25) << "-" << item->endPos().frames(25) << "), DUP: (" << dup->startPos().frames(25) << "-" << dup->endPos().frames(25) << ")" << ", CUT: " << cutTime.frames(25);
842         kDebug() << "//  CUTTING CLIP dONE";
843     } else {
844         // uncut clip
845
846         ClipItem *item = getClipItemAt((int) info.startPos.frames(m_document->fps()), info.track);
847         ClipItem *dup = getClipItemAt((int) cutTime.frames(m_document->fps()) + 1, info.track);
848         if (!item || !dup || item == dup) {
849             emit displayMessage(i18n("Cannot find clip to uncut"), ErrorMessage);
850             m_blockRefresh = false;
851             return;
852         }
853
854         kDebug() << "// UNCUTTING CLIPS: ITEM 1 (" << item->startPos().frames(25) << "x" << item->endPos().frames(25) << ")";
855         kDebug() << "// UNCUTTING CLIPS: ITEM 2 (" << dup->startPos().frames(25) << "x" << dup->endPos().frames(25) << ")";
856         kDebug() << "// UNCUTTING CLIPS, INFO (" << info.startPos.frames(25) << "x" << info.endPos.frames(25) << ") , CUT: " << cutTime.frames(25);;
857         //deleteClip(dup->info());
858
859
860         if (dup->isSelected()) emit clipItemSelected(NULL);
861         dup->baseClip()->removeReference();
862         m_document->updateClip(dup->baseClip()->getId());
863         scene()->removeItem(dup);
864         delete dup;
865         m_document->renderer()->mltRemoveClip(m_tracksList.count() - info.track, cutTime);
866
867         ItemInfo clipinfo = item->info();
868         clipinfo.track = m_tracksList.count() - clipinfo.track;
869         bool success = m_document->renderer()->mltResizeClipEnd(clipinfo, info.endPos - info.startPos);
870         if (success) {
871             item->resizeEnd((int) info.endPos.frames(m_document->fps()), m_scale);
872         } else
873             emit displayMessage(i18n("Error when resizing clip"), ErrorMessage);
874
875     }
876     QTimer::singleShot(3000, this, SLOT(slotEnableRefresh()));
877 }
878
879 void CustomTrackView::slotEnableRefresh() {
880     m_blockRefresh = false;
881 }
882
883 void CustomTrackView::slotAddTransitionToSelectedClips(QDomElement transition) {
884     QList<QGraphicsItem *> itemList = scene()->selectedItems();
885     for (int i = 0; i < itemList.count(); i++) {
886         if (itemList.at(i)->type() == AVWIDGET) {
887             ClipItem *item = (ClipItem *) itemList.at(i);
888             ItemInfo info;
889             info.startPos = item->startPos();
890             info.endPos = info.startPos + GenTime(2.5);
891             info.track = item->track();
892             int transitiontrack = getPreviousVideoTrack(info.track);
893             slotAddTransition(item, info, transitiontrack, transition);
894         }
895     }
896 }
897
898 void CustomTrackView::slotAddTransition(ClipItem* clip, ItemInfo transitionInfo, int endTrack, QDomElement transition) {
899     AddTransitionCommand* command = new AddTransitionCommand(this, transitionInfo, endTrack, transition, false, true);
900     m_commandStack->push(command);
901     m_document->setModified(true);
902 }
903
904 void CustomTrackView::addTransition(ItemInfo transitionInfo, int endTrack, QDomElement params) {
905     Transition *tr = new Transition(transitionInfo, endTrack, m_scale, m_document->fps(), params);
906     scene()->addItem(tr);
907
908     //kDebug() << "---- ADDING transition " << e.attribute("tag") << ", on tracks " << m_tracksList.count() - e.attribute("transition_track").toInt() << " / " << getPreviousVideoTrack(e.attribute("transition_track").toInt());
909     m_document->renderer()->mltAddTransition(tr->transitionTag(), endTrack, m_tracksList.count() - transitionInfo.track, transitionInfo.startPos, transitionInfo.endPos, tr->toXML());
910     m_document->setModified(true);
911 }
912
913 void CustomTrackView::deleteTransition(ItemInfo transitionInfo, int endTrack, QDomElement params) {
914     Transition *item = getTransitionItemAt((int)transitionInfo.startPos.frames(m_document->fps()) + 1, transitionInfo.track);
915     m_document->renderer()->mltDeleteTransition(item->transitionTag(), endTrack, m_tracksList.count() - transitionInfo.track, transitionInfo.startPos, transitionInfo.endPos, item->toXML());
916     delete item;
917     emit transitionItemSelected(NULL);
918     m_document->setModified(true);
919 }
920
921 void CustomTrackView::slotTransitionUpdated(Transition *tr, QDomElement old) {
922     EditTransitionCommand *command = new EditTransitionCommand(this, tr->track(), tr->startPos(), old, tr->toXML() , true);
923     m_commandStack->push(command);
924     m_document->setModified(true);
925 }
926
927 void CustomTrackView::updateTransition(int track, GenTime pos, QDomElement oldTransition, QDomElement transition) {
928     Transition *item = getTransitionItemAt((int)pos.frames(m_document->fps()) + 1, track);
929     if (!item) {
930         kWarning() << "Unable to find transition at pos :" << pos.frames(m_document->fps()) << ", ON track: " << track;
931         return;
932     }
933     m_document->renderer()->mltUpdateTransition(oldTransition.attribute("tag"), transition.attribute("tag"), transition.attribute("transition_btrack").toInt(), m_tracksList.count() - transition.attribute("transition_atrack").toInt(), item->startPos(), item->endPos(), transition);
934     item->setTransitionParameters(transition);
935     m_document->setModified(true);
936 }
937
938 void CustomTrackView::addItem(DocClipBase *clip, QPoint pos) {
939     ItemInfo info;
940     info.startPos = GenTime((int)(mapToScene(pos).x() / m_scale), m_document->fps());
941     info.endPos = info.startPos + clip->duration();
942     info.track = (int)(pos.y() / m_tracksHeight);
943     kDebug() << "------------  ADDING CLIP ITEM----: " << info.startPos.frames(25) << ", " << info.endPos.frames(25) << ", " << info.track;
944     m_dropItem = new ClipItem(clip, info, m_scale, m_document->fps());
945     scene()->addItem(m_dropItem);
946 }
947
948
949 void CustomTrackView::dragMoveEvent(QDragMoveEvent * event) {
950     event->setDropAction(Qt::IgnoreAction);
951     if (m_dropItem) {
952         int track = (int)(mapToScene(event->pos()).y() / m_tracksHeight);  //) * (m_scale * 50) + m_scale;
953         m_dropItem->moveTo((int)(mapToScene(event->pos()).x() / m_scale), m_scale, (int)((track - m_dropItem->track()) * m_tracksHeight), track);
954         event->setDropAction(Qt::MoveAction);
955         if (event->mimeData()->hasFormat("kdenlive/producerslist")) {
956             event->acceptProposedAction();
957         }
958     } else {
959         QGraphicsView::dragMoveEvent(event);
960     }
961 }
962
963 void CustomTrackView::dragLeaveEvent(QDragLeaveEvent * event) {
964     if (m_dropItem) {
965         delete m_dropItem;
966         m_dropItem = NULL;
967     } else QGraphicsView::dragLeaveEvent(event);
968 }
969
970 void CustomTrackView::dropEvent(QDropEvent * event) {
971     if (m_dropItem) {
972         AddTimelineClipCommand *command = new AddTimelineClipCommand(this, m_dropItem->xml(), m_dropItem->clipProducer(), m_dropItem->info(), m_dropItem->effectList(), false, false);
973         m_commandStack->push(command);
974         m_dropItem->baseClip()->addReference();
975         m_document->updateClip(m_dropItem->baseClip()->getId());
976         ItemInfo info;
977         info = m_dropItem->info();
978         info.track = m_tracksList.count() - m_dropItem->track();
979         //kDebug()<<"IIIIIIIIIIIIIIIIIIIIIIII TRAX CNT: "<<m_tracksList.count()<<", DROP: "<<m_dropItem->track();
980         m_document->renderer()->mltInsertClip(info, m_dropItem->xml(), m_dropItem->baseClip()->producer());
981         //if (m_dropItem->baseClip()->isTransparent()) m_document->renderer()->mltAddClipTransparency(info, getPreviousVideoTrack(m_dropItem->track()), m_dropItem->baseClip()->getId());
982         m_dropItem = NULL;
983         m_document->setModified(true);
984     } else QGraphicsView::dropEvent(event);
985     m_dropItem = NULL;
986 }
987
988
989 QStringList CustomTrackView::mimeTypes() const {
990     QStringList qstrList;
991     // list of accepted mime types for drop
992     qstrList.append("text/plain");
993     qstrList.append("kdenlive/producerslist");
994     return qstrList;
995 }
996
997 Qt::DropActions CustomTrackView::supportedDropActions() const {
998     // returns what actions are supported when dropping
999     return Qt::MoveAction;
1000 }
1001
1002 void CustomTrackView::setDuration(int duration) {
1003     kDebug() << "/////////////  PRO DUR: " << duration << ", SCALE. " << (m_projectDuration + 500) * m_scale << ", height: " << 50 * m_tracksList.count();
1004     m_projectDuration = duration;
1005     setSceneRect(0, 0, (m_projectDuration + 100) * m_scale, sceneRect().height());
1006 }
1007
1008 int CustomTrackView::duration() const {
1009     return m_projectDuration;
1010 }
1011
1012 void CustomTrackView::addTrack(TrackInfo type) {
1013     m_tracksList << type;
1014     m_cursorLine->setLine(m_cursorLine->line().x1(), 0, m_cursorLine->line().x1(), m_tracksHeight * m_tracksList.count());
1015     setSceneRect(0, 0, sceneRect().width(), m_tracksHeight * m_tracksList.count());
1016     verticalScrollBar()->setMaximum(m_tracksHeight * m_tracksList.count());
1017     //setFixedHeight(50 * m_tracksCount);
1018 }
1019
1020 void CustomTrackView::removeTrack() {
1021     // TODO: implement track deletion
1022     //m_tracksCount--;
1023     m_cursorLine->setLine(m_cursorLine->line().x1(), 0, m_cursorLine->line().x1(), m_tracksHeight * m_tracksList.count());
1024 }
1025
1026
1027 void CustomTrackView::slotSwitchTrackAudio(int ix) {
1028     int tracknumber = m_tracksList.count() - ix;
1029     kDebug() << "/////  MUTING TRK: " << ix << "; PL NUM: " << tracknumber;
1030     m_tracksList[tracknumber - 1].isMute = !m_tracksList.at(tracknumber - 1).isMute;
1031     m_document->renderer()->mltChangeTrackState(tracknumber, m_tracksList.at(tracknumber - 1).isMute, m_tracksList.at(tracknumber - 1).isBlind);
1032 }
1033
1034 void CustomTrackView::slotSwitchTrackVideo(int ix) {
1035     int tracknumber = m_tracksList.count() - ix;
1036     m_tracksList[tracknumber - 1].isBlind = !m_tracksList.at(tracknumber - 1).isBlind;
1037     m_document->renderer()->mltChangeTrackState(tracknumber, m_tracksList.at(tracknumber - 1).isMute, m_tracksList.at(tracknumber - 1).isBlind);
1038 }
1039
1040 void CustomTrackView::deleteClip(int clipId) {
1041     QList<QGraphicsItem *> itemList = items();
1042     for (int i = 0; i < itemList.count(); i++) {
1043         if (itemList.at(i)->type() == AVWIDGET) {
1044             ClipItem *item = (ClipItem *)itemList.at(i);
1045             if (item->clipProducer() == clipId) {
1046                 AddTimelineClipCommand *command = new AddTimelineClipCommand(this, item->xml(), item->clipProducer(), item->info(), item->effectList(), true, true);
1047                 m_commandStack->push(command);
1048                 //delete item;
1049             }
1050         }
1051     }
1052 }
1053
1054 void CustomTrackView::setCursorPos(int pos, bool seek) {
1055     emit cursorMoved((int)(m_cursorPos * m_scale), (int)(pos * m_scale));
1056     m_cursorPos = pos;
1057     m_cursorLine->setPos(pos * m_scale, 0);
1058     if (seek) m_document->renderer()->seek(GenTime(pos, m_document->fps()));
1059     else if (m_autoScroll && m_scale < 50) checkScrolling();
1060 }
1061
1062 void CustomTrackView::updateCursorPos() {
1063     m_cursorLine->setPos(m_cursorPos * m_scale, 0);
1064 }
1065
1066 int CustomTrackView::cursorPos() {
1067     return (int)(m_cursorPos * m_scale);
1068 }
1069
1070 void CustomTrackView::moveCursorPos(int delta) {
1071     if (m_cursorPos + delta < 0) delta = 0 - m_cursorPos;
1072     emit cursorMoved((int)(m_cursorPos * m_scale), (int)((m_cursorPos + delta) * m_scale));
1073     m_cursorPos += delta;
1074     m_cursorLine->setPos(m_cursorPos * m_scale, 0);
1075     m_document->renderer()->seek(GenTime(m_cursorPos, m_document->fps()));
1076     //if (m_autoScroll && m_scale < 50) checkScrolling();
1077 }
1078
1079 void CustomTrackView::checkScrolling() {
1080     int vert = verticalScrollBar()->value();
1081     int hor = cursorPos();
1082     ensureVisible(hor, vert + 10, 2, 2, 50, 0);
1083     //centerOn(QPointF(cursorPos(), m_tracksHeight));
1084     /*QRect rectInView = viewport()->rect();
1085     int delta = rectInView.width() / 3;
1086     int max = rectInView.right() + horizontalScrollBar()->value() - delta;
1087     //kDebug() << "CURSOR POS: "<<m_cursorPos<< "Scale: "<<m_scale;
1088     if (m_cursorPos * m_scale >= max) horizontalScrollBar()->setValue((int)(horizontalScrollBar()->value() + 1 + m_scale));*/
1089 }
1090
1091 void CustomTrackView::mouseReleaseEvent(QMouseEvent * event) {
1092     QGraphicsView::mouseReleaseEvent(event);
1093     if (event->button() == Qt::MidButton) {
1094         return;
1095     }
1096     setDragMode(QGraphicsView::NoDrag);
1097     if (m_operationMode == MOVEGUIDE) {
1098         setCursor(Qt::ArrowCursor);
1099         m_operationMode = NONE;
1100         m_dragGuide->setFlag(QGraphicsItem::ItemIsMovable, false);
1101         EditGuideCommand *command = new EditGuideCommand(this, m_dragGuide->position(), m_dragGuide->label(), GenTime(m_dragGuide->pos().x() / m_scale, m_document->fps()), m_dragGuide->label(), false);
1102         m_commandStack->push(command);
1103         m_dragGuide->updateGuide(GenTime(m_dragGuide->pos().x() / m_scale, m_document->fps()));
1104         m_dragGuide = NULL;
1105         m_dragItem = NULL;
1106         return;
1107     }
1108     if (m_dragItem == NULL) {
1109         emit transitionItemSelected(NULL);
1110         return;
1111     }
1112     ItemInfo info = m_dragItem->info();
1113
1114     if (m_operationMode == MOVE) {
1115         setCursor(Qt::OpenHandCursor);
1116
1117         if (m_selectedClipList.count() == 1) {
1118             // we are moving one clip, easy
1119             if (m_dragItem->type() == AVWIDGET && (m_dragItemInfo.startPos != info.startPos || m_dragItemInfo.track != info.track)) {
1120                 bool success = m_document->renderer()->mltMoveClip((int)(m_tracksList.count() - m_dragItemInfo.track), (int)(m_tracksList.count() - m_dragItem->track()), (int) m_dragItemInfo.startPos.frames(m_document->fps()), (int)(m_dragItem->startPos().frames(m_document->fps())));
1121                 if (success) {
1122                     MoveClipCommand *command = new MoveClipCommand(this, m_dragItemInfo, info, false);
1123                     m_commandStack->push(command);
1124                 } else {
1125                     // undo last move and emit error message
1126                     MoveClipCommand *command = new MoveClipCommand(this, info, m_dragItemInfo, true);
1127                     m_commandStack->push(command);
1128                     emit displayMessage(i18n("Cannot move clip to position %1seconds", QString::number(m_dragItemInfo.startPos.seconds(), 'g', 2)), ErrorMessage);
1129                 }
1130             }
1131             if (m_dragItem->type() == TRANSITIONWIDGET && (m_dragItemInfo.startPos != info.startPos || m_dragItemInfo.track != info.track)) {
1132                 MoveTransitionCommand *command = new MoveTransitionCommand(this, m_dragItemInfo, info, false);
1133                 m_commandStack->push(command);
1134                 Transition *transition = (Transition *) m_dragItem;
1135                 transition->updateTransitionEndTrack(getPreviousVideoTrack(m_dragItem->track()));
1136                 m_document->renderer()->mltMoveTransition(transition->transitionTag(), (int)(m_tracksList.count() - m_dragItemInfo.track), (int)(m_tracksList.count() - m_dragItem->track()), transition->transitionEndTrack(), m_dragItemInfo.startPos, m_dragItemInfo.endPos, info.startPos, info.endPos);
1137             }
1138         } else {
1139             // Moving several clips. We need to delete them and readd them to new position,
1140             // or they might overlap each other during the move
1141
1142             GenTime timeOffset = info.startPos - m_dragItemInfo.startPos;
1143             int trackOffset = info.track - m_dragItemInfo.track;
1144             if (timeOffset != GenTime() || trackOffset != 0) {
1145                 QUndoCommand *moveClips = new QUndoCommand();
1146                 moveClips->setText("Move clips");
1147                 // remove items in MLT playlist
1148                 for (int i = 0; i < m_selectedClipList.count(); i++) {
1149                     AbstractClipItem *item = m_selectedClipList.at(i);
1150                     ItemInfo info = item->info();
1151                     info.startPos = info.startPos - timeOffset;
1152                     info.endPos = info.endPos - timeOffset;
1153                     info.track = info.track - trackOffset;
1154                     if (item->type() == AVWIDGET) {
1155                         ClipItem *clip = static_cast <ClipItem*>(item);
1156                         new AddTimelineClipCommand(this, clip->xml(), clip->clipProducer(), info, clip->effectList(), false, true, moveClips);
1157                         m_document->renderer()->mltRemoveClip(m_tracksList.count() - info.track, info.startPos);
1158                     } else {
1159                         Transition *tr = static_cast <Transition*>(item);
1160                         new AddTransitionCommand(this, info, tr->transitionEndTrack(), tr->toXML(), false, true, moveClips);
1161                         m_document->renderer()->mltDeleteTransition(tr->transitionTag(), tr->transitionEndTrack(), m_tracksList.count() - info.track, info.startPos, info.endPos, tr->toXML());
1162                     }
1163                 }
1164
1165                 for (int i = 0; i < m_selectedClipList.count(); i++) {
1166                     // re-add items in correct place
1167                     AbstractClipItem *item = m_selectedClipList.at(i);
1168                     if (item->type() == AVWIDGET) {
1169                         ClipItem *clip = static_cast <ClipItem*>(item);
1170                         new AddTimelineClipCommand(this, clip->xml(), clip->clipProducer(), item->info(), clip->effectList(), false, false, moveClips);
1171                         ItemInfo info = item->info();
1172                         info.track = m_tracksList.count() - item->track();
1173                         m_document->renderer()->mltInsertClip(info, clip->xml(), clip->baseClip()->producer());
1174                     } else {
1175                         Transition *tr = static_cast <Transition*>(item);
1176                         ItemInfo transitionInfo = tr->info();
1177                         new AddTransitionCommand(this, info, tr->transitionEndTrack(), tr->toXML(), false, false, moveClips);
1178                         m_document->renderer()->mltAddTransition(tr->transitionTag(), tr->transitionEndTrack() + trackOffset, m_tracksList.count() - transitionInfo.track, transitionInfo.startPos, transitionInfo.endPos, tr->toXML());
1179                     }
1180                 }
1181                 m_commandStack->push(moveClips);
1182             }
1183         }
1184
1185     } else if (m_operationMode == RESIZESTART && m_dragItem->startPos() != m_dragItemInfo.startPos) {
1186         // resize start
1187         if (m_dragItem->type() == AVWIDGET) {
1188             ItemInfo resizeinfo = m_dragItemInfo;
1189             resizeinfo.track = m_tracksList.count() - resizeinfo.track;
1190             bool success = m_document->renderer()->mltResizeClipStart(resizeinfo, m_dragItem->startPos() - m_dragItemInfo.startPos);
1191             if (success) {
1192                 updateClipFade((ClipItem *) m_dragItem);
1193                 ResizeClipCommand *command = new ResizeClipCommand(this, m_dragItemInfo, info, false);
1194                 m_commandStack->push(command);
1195             } else {
1196                 m_dragItem->resizeStart((int) m_dragItemInfo.startPos.frames(m_document->fps()), m_scale);
1197                 emit displayMessage(i18n("Error when resizing clip"), ErrorMessage);
1198             }
1199         } else if (m_dragItem->type() == TRANSITIONWIDGET) {
1200             MoveTransitionCommand *command = new MoveTransitionCommand(this, m_dragItemInfo, info, false);
1201             m_commandStack->push(command);
1202             Transition *transition = (Transition *) m_dragItem;
1203             m_document->renderer()->mltMoveTransition(transition->transitionTag(), (int)(m_tracksList.count() - m_dragItemInfo.track), (int)(m_tracksList.count() - m_dragItemInfo.track), 0, m_dragItemInfo.startPos, m_dragItemInfo.endPos, info.startPos, info.endPos);
1204         }
1205
1206         //m_document->renderer()->doRefresh();
1207     } else if (m_operationMode == RESIZEEND && m_dragItem->endPos() != m_dragItemInfo.endPos) {
1208         // resize end
1209         if (m_dragItem->type() == AVWIDGET) {
1210             ItemInfo resizeinfo = info;
1211             resizeinfo.track = m_tracksList.count() - resizeinfo.track;
1212             bool success = m_document->renderer()->mltResizeClipEnd(resizeinfo, resizeinfo.endPos - resizeinfo.startPos);
1213             if (success) {
1214                 ResizeClipCommand *command = new ResizeClipCommand(this, m_dragItemInfo, info, false);
1215                 m_commandStack->push(command);
1216             } else {
1217                 m_dragItem->resizeEnd((int) m_dragItemInfo.endPos.frames(m_document->fps()), m_scale);
1218                 emit displayMessage(i18n("Error when resizing clip"), ErrorMessage);
1219             }
1220         } else if (m_dragItem->type() == TRANSITIONWIDGET) {
1221             MoveTransitionCommand *command = new MoveTransitionCommand(this, m_dragItemInfo, info, false);
1222             m_commandStack->push(command);
1223             Transition *transition = (Transition *) m_dragItem;
1224 //             m_document->renderer()->mltMoveTransition(transition->transitionTag(), (int)(m_tracksList.count() - m_dragItemInfo.track), (int)(m_tracksList.count() - m_dragItemInfo.track), 0, m_dragItemInfo.startPos, m_dragItemInfo.endPos, info.startPos, info.endPos);
1225         }
1226         //m_document->renderer()->doRefresh();
1227     } else if (m_operationMode == FADEIN) {
1228         // resize fade in effect
1229         ClipItem * item = (ClipItem *) m_dragItem;
1230         QStringList clipeffects = item->effectNames();
1231         if (clipeffects.contains(i18n("Fade in"))) {
1232             int ix = clipeffects.indexOf(i18n("Fade in"));
1233             QDomElement oldeffect = item->effectAt(ix);
1234             int start = item->cropStart().frames(m_document->fps());
1235             int end = item->fadeIn();
1236             if (end == 0) {
1237                 slotDeleteEffect(item, oldeffect);
1238             } else {
1239                 end += start;
1240                 QDomElement effect = MainWindow::audioEffects.getEffectByName("Fade in");
1241                 EffectsList::setParameter(effect, "in", QString::number(start));
1242                 EffectsList::setParameter(effect, "out", QString::number(end));
1243                 slotUpdateClipEffect(item, oldeffect, effect, ix);
1244             }
1245         } else if (item->fadeIn() != 0) {
1246             QDomElement effect = MainWindow::audioEffects.getEffectByName("Fade in");
1247             int start = item->cropStart().frames(m_document->fps());
1248             int end = item->fadeIn() + start;
1249             EffectsList::setParameter(effect, "in", QString::number(start));
1250             EffectsList::setParameter(effect, "out", QString::number(end));
1251             slotAddEffect(effect, m_dragItem->startPos(), m_dragItem->track());
1252         }
1253     } else if (m_operationMode == FADEOUT) {
1254         // resize fade in effect
1255         ClipItem * item = (ClipItem *) m_dragItem;
1256         QStringList clipeffects = item->effectNames();
1257         if (clipeffects.contains(i18n("Fade out"))) {
1258             int ix = clipeffects.indexOf(i18n("Fade out"));
1259             QDomElement oldeffect = item->effectAt(ix);
1260             int end = (item->duration() + item->cropStart()).frames(m_document->fps());
1261             int start = item->fadeOut();
1262             if (start == 0) {
1263                 slotDeleteEffect(item, oldeffect);
1264             } else {
1265                 start = end - start;
1266                 QDomElement effect = MainWindow::audioEffects.getEffectByName("Fade out");
1267                 EffectsList::setParameter(effect, "in", QString::number(start));
1268                 EffectsList::setParameter(effect, "out", QString::number(end));
1269                 slotUpdateClipEffect(item, oldeffect, effect, ix);
1270             }
1271         } else if (item->fadeOut() != 0) {
1272             QDomElement effect = MainWindow::audioEffects.getEffectByName("Fade out");
1273             int end = (item->duration() + item->cropStart()).frames(m_document->fps());
1274             int start = end - item->fadeOut();
1275             EffectsList::setParameter(effect, "in", QString::number(start));
1276             EffectsList::setParameter(effect, "out", QString::number(end));
1277             slotAddEffect(effect, m_dragItem->startPos(), m_dragItem->track());
1278         }
1279     } else if (m_operationMode == KEYFRAME) {
1280         // update the MLT effect
1281         ClipItem * item = (ClipItem *) m_dragItem;
1282         QString previous = item->keyframes(item->selectedEffectIndex());
1283         item->updateKeyframeEffect();
1284         QString next = item->keyframes(item->selectedEffectIndex());
1285         EditKeyFrameCommand *command = new EditKeyFrameCommand(this, item->track(), item->startPos(), item->selectedEffectIndex(), previous, next, false);
1286         m_commandStack->push(command);
1287         updateEffect(m_tracksList.count() - item->track(), item->startPos(), item->selectedEffect(), item->selectedEffectIndex());
1288     }
1289
1290     emit transitionItemSelected((m_dragItem && m_dragItem->type() == TRANSITIONWIDGET) ? (Transition*) m_dragItem : NULL);
1291     m_document->setModified(true);
1292     m_operationMode = NONE;
1293 }
1294
1295 void CustomTrackView::deleteClip(ItemInfo info) {
1296     ClipItem *item = getClipItemAt((int) info.startPos.frames(m_document->fps()) + 1, info.track);
1297     if (!item) {
1298         kDebug() << "----------------  ERROR, CANNOT find clip to delete at...";// << rect.x();
1299         return;
1300     }
1301     if (item->isSelected()) emit clipItemSelected(NULL);
1302     item->baseClip()->removeReference();
1303     m_document->updateClip(item->baseClip()->getId());
1304     scene()->removeItem(item);
1305     delete item;
1306     m_document->renderer()->mltRemoveClip(m_tracksList.count() - info.track, info.startPos);
1307     m_document->renderer()->doRefresh();
1308 }
1309
1310 void CustomTrackView::deleteSelectedClips() {
1311     QList<QGraphicsItem *> itemList = scene()->selectedItems();
1312     if (itemList.count() == 0) {
1313         emit displayMessage(i18n("Select clip to delete"), ErrorMessage);
1314         return;
1315     }
1316     QUndoCommand *deleteSelected = new QUndoCommand();
1317     deleteSelected->setText("Delete selected items");
1318     for (int i = 0; i < itemList.count(); i++) {
1319         if (itemList.at(i)->type() == AVWIDGET) {
1320             ClipItem *item = static_cast <ClipItem *>(itemList.at(i));
1321             new AddTimelineClipCommand(this, item->xml(), item->clipProducer(), item->info(), item->effectList(), true, true, deleteSelected);
1322         } else if (itemList.at(i)->type() == TRANSITIONWIDGET) {
1323             Transition *item = static_cast <Transition *>(itemList.at(i));
1324             ItemInfo info;
1325             info.startPos = item->startPos();
1326             info.endPos = item->endPos();
1327             info.track = item->track();
1328             new AddTransitionCommand(this, info, item->transitionEndTrack(), item->toXML(), true, true, deleteSelected);
1329         }
1330     }
1331     m_commandStack->push(deleteSelected);
1332 }
1333
1334 void CustomTrackView::changeClipSpeed() {
1335     QList<QGraphicsItem *> itemList = scene()->selectedItems();
1336     if (itemList.count() == 0) {
1337         emit displayMessage(i18n("Select clip to change speed"), ErrorMessage);
1338         return;
1339     }
1340     QUndoCommand *changeSelected = new QUndoCommand();
1341     changeSelected->setText("Edit clip speed");
1342     for (int i = 0; i < itemList.count(); i++) {
1343         if (itemList.at(i)->type() == AVWIDGET) {
1344             ClipItem *item = static_cast <ClipItem *>(itemList.at(i));
1345             ItemInfo info = item->info();
1346             int percent = QInputDialog::getInteger(this, i18n("Edit Clip Speed"), i18n("New speed (percents)"), 100, 1, 300);
1347             double speed = (double) percent / 100.0;
1348             if (item->speed() != speed)
1349                 new ChangeSpeedCommand(this, info, item->speed(), speed, item->clipProducer(), true, changeSelected);
1350         }
1351     }
1352     m_commandStack->push(changeSelected);
1353 }
1354
1355 void CustomTrackView::doChangeClipSpeed(ItemInfo info, double speed, int id) {
1356     DocClipBase *baseclip = m_document->clipManager()->getClipById(id);
1357     ClipItem *item = getClipItemAt((int) info.startPos.frames(m_document->fps()) + 1, info.track);
1358     info.track = m_tracksList.count() - item->track();
1359     m_document->renderer()->mltChangeClipSpeed(info, speed, baseclip->producer());
1360     item->setSpeed(speed);
1361     GenTime maxDuration = item->maxDuration();
1362     if (maxDuration < item->duration()) {
1363         info = item->info();
1364         ItemInfo endInfo = info;
1365         endInfo.endPos = info.startPos + maxDuration;
1366         ResizeClipCommand *command = new ResizeClipCommand(this, info, endInfo, true);
1367         m_commandStack->push(command);
1368     }
1369 }
1370
1371 void CustomTrackView::cutSelectedClips() {
1372     QList<QGraphicsItem *> itemList = scene()->selectedItems();
1373     GenTime currentPos = GenTime(m_cursorPos, m_document->fps());
1374     for (int i = 0; i < itemList.count(); i++) {
1375         if (itemList.at(i)->type() == AVWIDGET) {
1376             ClipItem *item = static_cast <ClipItem *>(itemList.at(i));
1377             if (currentPos > item->startPos() && currentPos <  item->endPos()) {
1378                 RazorClipCommand *command = new RazorClipCommand(this, item->info(), currentPos, true);
1379                 m_commandStack->push(command);
1380             }
1381         }
1382     }
1383 }
1384
1385 void CustomTrackView::addClip(QDomElement xml, int clipId, ItemInfo info, EffectsList effects) {
1386     DocClipBase *baseclip = m_document->clipManager()->getClipById(clipId);
1387     ClipItem *item = new ClipItem(baseclip, info, m_scale, m_document->fps());
1388     item->setEffectList(effects);
1389     scene()->addItem(item);
1390     baseclip->addReference();
1391     m_document->updateClip(baseclip->getId());
1392     info.track = m_tracksList.count() - info.track;
1393     m_document->renderer()->mltInsertClip(info, xml, baseclip->producer());
1394     for (int i = 0; i < item->effectsCount(); i++) {
1395         m_document->renderer()->mltAddEffect(info.track, info.startPos, item->getEffectArgs(item->effectAt(i)), false);
1396     }
1397     m_document->renderer()->doRefresh();
1398 }
1399
1400 void CustomTrackView::slotUpdateClip(int clipId) {
1401     QList<QGraphicsItem *> list = scene()->items();
1402     ClipItem *clip = NULL;
1403     for (int i = 0; i < list.size(); ++i) {
1404         if (list.at(i)->type() == AVWIDGET) {
1405             clip = static_cast <ClipItem *>(list.at(i));
1406             if (clip->clipProducer() == clipId) {
1407                 clip->refreshClip();
1408                 ItemInfo info = clip->info();
1409                 info.track = m_tracksList.count() - clip->track();
1410                 m_document->renderer()->mltUpdateClip(info, clip->xml(), clip->baseClip()->producer());
1411             }
1412         }
1413     }
1414 }
1415
1416 ClipItem *CustomTrackView::getClipItemAt(int pos, int track) {
1417     QList<QGraphicsItem *> list = scene()->items(QPointF(pos * m_scale, track * m_tracksHeight + m_tracksHeight / 2));
1418     ClipItem *clip = NULL;
1419     for (int i = 0; i < list.size(); ++i) {
1420         if (list.at(i)->type() == AVWIDGET) {
1421             clip = static_cast <ClipItem *>(list.at(i));
1422             break;
1423         }
1424     }
1425     return clip;
1426 }
1427
1428 ClipItem *CustomTrackView::getClipItemAt(GenTime pos, int track) {
1429     int framepos = (int)(pos.frames(m_document->fps()) * m_scale);
1430     return getClipItemAt(framepos, track);
1431 }
1432
1433 Transition *CustomTrackView::getTransitionItemAt(int pos, int track) {
1434     QList<QGraphicsItem *> list = scene()->items(QPointF(pos * m_scale, (track + 1) * m_tracksHeight));
1435     Transition *clip = NULL;
1436     for (int i = 0; i < list.size(); ++i) {
1437         if (list.at(i)->type() == TRANSITIONWIDGET) {
1438             clip = static_cast <Transition *>(list.at(i));
1439             break;
1440         }
1441     }
1442     return clip;
1443 }
1444
1445 Transition *CustomTrackView::getTransitionItemAt(GenTime pos, int track) {
1446     int framepos = (int)(pos.frames(m_document->fps()) * m_scale);
1447     return getTransitionItemAt(framepos, track);
1448 }
1449
1450 void CustomTrackView::moveClip(const ItemInfo start, const ItemInfo end) {
1451     ClipItem *item = getClipItemAt((int) start.startPos.frames(m_document->fps()) + 1, start.track);
1452     if (!item) {
1453         emit displayMessage(i18n("Cannot move clip at time: %1s on track %2", QString::number(start.startPos.seconds(), 'g', 2), start.track), ErrorMessage);
1454         kDebug() << "----------------  ERROR, CANNOT find clip to move at.. ";// << startPos.x() * m_scale * FRAME_SIZE + 1 << ", " << startPos.y() * m_tracksHeight + m_tracksHeight / 2;
1455         return;
1456     }
1457     //kDebug() << "----------------  Move CLIP FROM: " << startPos.x() << ", END:" << endPos.x() << ",TRACKS: " << startPos.y() << " TO " << endPos.y();
1458
1459     bool success = m_document->renderer()->mltMoveClip((int)(m_tracksList.count() - start.track), (int)(m_tracksList.count() - end.track), (int) start.startPos.frames(m_document->fps()), (int)end.startPos.frames(m_document->fps()));
1460     if (success) {
1461         item->moveTo((int) end.startPos.frames(m_document->fps()), m_scale, (int)((end.track - start.track) * m_tracksHeight), end.track);
1462     } else {
1463         // undo last move and emit error message
1464         emit displayMessage(i18n("Cannot move clip to position %1seconds", QString::number(end.startPos.seconds(), 'g', 2)), ErrorMessage);
1465     }
1466 }
1467
1468 void CustomTrackView::moveTransition(const ItemInfo start, const ItemInfo end) {
1469     Transition *item = getTransitionItemAt((int)start.startPos.frames(m_document->fps()) + 1, start.track);
1470     if (!item) {
1471         emit displayMessage(i18n("Cannot move transition at time: %1s on track %2", start.startPos.seconds(), start.track), ErrorMessage);
1472         kDebug() << "----------------  ERROR, CANNOT find transition to move... ";// << startPos.x() * m_scale * FRAME_SIZE + 1 << ", " << startPos.y() * m_tracksHeight + m_tracksHeight / 2;
1473         return;
1474     }
1475     //kDebug() << "----------------  Move TRANSITION FROM: " << startPos.x() << ", END:" << endPos.x() << ",TRACKS: " << oldtrack << " TO " << newtrack;
1476
1477     //kDebug()<<"///  RESIZE TRANS START: ("<< startPos.x()<<"x"<< startPos.y()<<") / ("<<endPos.x()<<"x"<< endPos.y()<<")";
1478     if (end.endPos - end.startPos == start.endPos - start.startPos) {
1479         // Transition was moved
1480         item->moveTo((int) end.startPos.frames(m_document->fps()), m_scale, (end.track - start.track) * m_tracksHeight, end.track);
1481     } else if (end.endPos == start.endPos) {
1482         // Transition start resize
1483         item->resizeStart((int) end.startPos.frames(m_document->fps()), m_scale);
1484     } else {
1485         // Transition end resize;
1486         item->resizeEnd((int) end.endPos.frames(m_document->fps()), m_scale);
1487     }
1488     //item->moveTransition(GenTime((int) (endPos.x() - startPos.x()), m_document->fps()));
1489     item->updateTransitionEndTrack(getPreviousVideoTrack(end.track));
1490     m_document->renderer()->mltMoveTransition(item->transitionTag(), m_tracksList.count() - start.track, m_tracksList.count() - end.track, item->transitionEndTrack(), start.startPos, start.endPos, end.startPos, end.endPos);
1491 }
1492
1493 void CustomTrackView::resizeClip(const ItemInfo start, const ItemInfo end) {
1494     int offset = 0;
1495     bool resizeClipStart = true;
1496     if (start.startPos == end.startPos) resizeClipStart = false;
1497     /*if (resizeClipStart) offset = 1;
1498     else offset = -1;*/
1499     ClipItem *item = getClipItemAt((int)(start.startPos.frames(m_document->fps()) + offset), start.track);
1500     if (!item) {
1501         emit displayMessage(i18n("Cannot move clip at time: %1s on track %2", start.startPos.seconds(), start.track), ErrorMessage);
1502         kDebug() << "----------------  ERROR, CANNOT find clip to resize at... "; // << startPos;
1503         return;
1504     }
1505     if (resizeClipStart) {
1506         ItemInfo clipinfo = item->info();
1507         clipinfo.track = m_tracksList.count() - clipinfo.track;
1508         bool success = m_document->renderer()->mltResizeClipStart(clipinfo, item->startPos() - end.startPos);
1509         if (success) {
1510             item->resizeStart((int) end.startPos.frames(m_document->fps()), m_scale);
1511             updateClipFade(item);
1512         } else emit displayMessage(i18n("Error when resizing clip"), ErrorMessage);
1513     } else {
1514         ItemInfo clipinfo = item->info();
1515         clipinfo.track = m_tracksList.count() - clipinfo.track;
1516         bool success = m_document->renderer()->mltResizeClipEnd(clipinfo, end.endPos - clipinfo.startPos);
1517         if (success) {
1518             item->resizeEnd((int) end.endPos.frames(m_document->fps()), m_scale);
1519             updateClipFade(item, true);
1520         } else emit displayMessage(i18n("Error when resizing clip"), ErrorMessage);
1521     }
1522     m_document->renderer()->doRefresh();
1523 }
1524
1525 void CustomTrackView::updateClipFade(ClipItem * item, bool updateFadeOut) {
1526     if (!updateFadeOut) {
1527         int end = item->fadeIn();
1528         if (end != 0) {
1529             // there is a fade in effect
1530             QStringList clipeffects = item->effectNames();
1531             QDomElement oldeffect = item->effectAt(clipeffects.indexOf("Fade in"));
1532             int start = item->cropStart().frames(m_document->fps());
1533             end += start;
1534             EffectsList::setParameter(oldeffect, "in", QString::number(start));
1535             EffectsList::setParameter(oldeffect, "out", QString::number(end));
1536             QMap <QString, QString> effectParams = item->getEffectArgs(oldeffect);
1537             if (!m_document->renderer()->mltEditEffect(m_tracksList.count() - item->track(), item->startPos(), effectParams))
1538                 emit displayMessage(i18n("Problem editing effect"), ErrorMessage);
1539         }
1540     } else {
1541         int start = item->fadeOut();
1542         if (start != 0) {
1543             // there is a fade in effect
1544             QStringList clipeffects = item->effectNames();
1545             QDomElement oldeffect = item->effectAt(clipeffects.indexOf("Fade out"));
1546             int end = (item->duration() - item->cropStart()).frames(m_document->fps());
1547             start = end - start;
1548             EffectsList::setParameter(oldeffect, "in", QString::number(start));
1549             EffectsList::setParameter(oldeffect, "out", QString::number(end));
1550             QMap <QString, QString> effectParams = item->getEffectArgs(oldeffect);
1551             if (m_document->renderer()->mltEditEffect(m_tracksList.count() - item->track(), item->startPos(), effectParams))
1552                 emit displayMessage(i18n("Problem editing effect"), ErrorMessage);
1553         }
1554     }
1555 }
1556
1557 double CustomTrackView::getSnapPointForPos(double pos) {
1558     for (int i = 0; i < m_snapPoints.size(); ++i) {
1559         if (abs((int)(pos - m_snapPoints.at(i).frames(m_document->fps()) * m_scale)) < 10) {
1560             //kDebug()<<" FOUND SNAP POINT AT: "<<m_snapPoints.at(i)<<", current pos: "<<pos / m_scale;
1561             return m_snapPoints.at(i).frames(m_document->fps()) * m_scale + 0.5;
1562         }
1563         if (m_snapPoints.at(i).frames(m_document->fps() * m_scale) > pos) break;
1564     }
1565     return pos;
1566 }
1567
1568 void CustomTrackView::updateSnapPoints(AbstractClipItem *selected) {
1569     m_snapPoints.clear();
1570     if (!KdenliveSettings::snaptopoints()) return;
1571     GenTime offset;
1572     if (selected) offset = selected->duration();
1573     QList<QGraphicsItem *> itemList = items();
1574     for (int i = 0; i < itemList.count(); i++) {
1575         if (itemList.at(i)->type() == AVWIDGET && itemList.at(i) != selected) {
1576             ClipItem *item = static_cast <ClipItem *>(itemList.at(i));
1577             GenTime start = item->startPos();
1578             GenTime end = item->endPos();
1579             m_snapPoints.append(start);
1580             m_snapPoints.append(end);
1581             QList < GenTime > markers = item->snapMarkers();
1582             for (int i = 0; i < markers.size(); ++i) {
1583                 GenTime t = markers.at(i);
1584                 m_snapPoints.append(t);
1585                 if (t > offset) m_snapPoints.append(t - offset);
1586             }
1587             if (offset != GenTime()) {
1588                 if (start > offset) m_snapPoints.append(start - offset);
1589                 if (end > offset) m_snapPoints.append(end - offset);
1590             }
1591         } else if (itemList.at(i)->type() == TRANSITIONWIDGET) {
1592             Transition *transition = static_cast <Transition*>(itemList.at(i));
1593             GenTime start = transition->startPos();
1594             GenTime end = transition->endPos();
1595             m_snapPoints.append(start);
1596             m_snapPoints.append(end);
1597             if (offset != GenTime()) {
1598                 if (start > offset) m_snapPoints.append(start - offset);
1599                 if (end > offset) m_snapPoints.append(end - offset);
1600             }
1601         }
1602     }
1603
1604     // add cursor position
1605     GenTime pos = GenTime(m_cursorPos, m_document->fps());
1606     m_snapPoints.append(pos);
1607     if (offset != GenTime()) m_snapPoints.append(pos - offset);
1608
1609     // add guides
1610     for (int i = 0; i < m_guides.count(); i++) {
1611         m_snapPoints.append(m_guides.at(i)->position());
1612         if (offset != GenTime()) m_snapPoints.append(m_guides.at(i)->position() - offset);
1613     }
1614
1615     qSort(m_snapPoints);
1616     //for (int i = 0; i < m_snapPoints.size(); ++i)
1617     //    kDebug() << "SNAP POINT: " << m_snapPoints.at(i).frames(25);
1618 }
1619
1620 void CustomTrackView::slotSeekToPreviousSnap() {
1621     updateSnapPoints(NULL);
1622     GenTime pos = GenTime(m_cursorPos, m_document->fps());
1623     GenTime res = GenTime();
1624     for (int i = 0; i < m_snapPoints.size(); ++i) {
1625         if (m_snapPoints.at(i) >= pos) {
1626             if (i == 0) i = 1;
1627             res = m_snapPoints.at(i - 1);
1628             break;
1629         }
1630     }
1631     setCursorPos((int) res.frames(m_document->fps()));
1632     checkScrolling();
1633 }
1634
1635 void CustomTrackView::slotSeekToNextSnap() {
1636     updateSnapPoints(NULL);
1637     GenTime pos = GenTime(m_cursorPos, m_document->fps());
1638     GenTime res = GenTime(m_projectDuration, m_document->fps());
1639     for (int i = 0; i < m_snapPoints.size(); ++i) {
1640         if (m_snapPoints.at(i) > pos) {
1641             res = m_snapPoints.at(i);
1642             break;
1643         }
1644     }
1645     setCursorPos((int) res.frames(m_document->fps()));
1646     checkScrolling();
1647 }
1648
1649 void CustomTrackView::clipStart() {
1650     QList<QGraphicsItem *> itemList = scene()->selectedItems();
1651     for (int i = 0; i < itemList.count(); i++) {
1652         if (itemList.at(i)->type() == AVWIDGET) {
1653             ClipItem *item = (ClipItem *) itemList.at(i);
1654             setCursorPos((int) item->startPos().frames(m_document->fps()));
1655             checkScrolling();
1656             break;
1657         }
1658     }
1659 }
1660
1661 void CustomTrackView::clipEnd() {
1662     QList<QGraphicsItem *> itemList = scene()->selectedItems();
1663     for (int i = 0; i < itemList.count(); i++) {
1664         if (itemList.at(i)->type() == AVWIDGET) {
1665             ClipItem *item = (ClipItem *) itemList.at(i);
1666             setCursorPos((int) item->endPos().frames(m_document->fps()));
1667             checkScrolling();
1668             break;
1669         }
1670     }
1671 }
1672
1673 void CustomTrackView::slotAddClipMarker() {
1674     QList<QGraphicsItem *> itemList = scene()->selectedItems();
1675     if (itemList.count() != 1) {
1676         emit displayMessage(i18n("Cannot add marker if more than one clip is selected"), ErrorMessage);
1677         kDebug() << "// CANNOT ADD MARKER IF MORE TAN ONE CLIP IS SELECTED....";
1678         return;
1679     }
1680     AbstractClipItem *item = (AbstractClipItem *)itemList.at(0);
1681     if (item->type() != AVWIDGET) return;
1682     GenTime pos = GenTime(m_cursorPos, m_document->fps());
1683     if (item->startPos() > pos || item->endPos() < pos) return;
1684     ClipItem *clip = (ClipItem *) item;
1685     int id = clip->baseClip()->getId();
1686     GenTime position = pos - item->startPos() + item->cropStart();
1687     CommentedTime marker(position, i18n("Marker"));
1688     MarkerDialog d(clip->baseClip(), marker, m_document->timecode(), this);
1689     if (d.exec() == QDialog::Accepted) {
1690         slotAddClipMarker(id, d.newMarker().time(), d.newMarker().comment());
1691     }
1692 }
1693
1694 void CustomTrackView::slotAddClipMarker(int id, GenTime t, QString c) {
1695     QString oldcomment = m_document->clipManager()->getClipById(id)->markerComment(t);
1696     AddMarkerCommand *command = new AddMarkerCommand(this, oldcomment, c, id, t, true);
1697     m_commandStack->push(command);
1698 }
1699
1700 void CustomTrackView::slotDeleteClipMarker() {
1701     QList<QGraphicsItem *> itemList = scene()->selectedItems();
1702     if (itemList.count() != 1) {
1703         emit displayMessage(i18n("Cannot delete marker if more than one clip is selected"), ErrorMessage);
1704         kDebug() << "// CANNOT DELETE MARKER IF MORE TAN ONE CLIP IS SELECTED....";
1705         return;
1706     }
1707     AbstractClipItem *item = (AbstractClipItem *)itemList.at(0);
1708     if (item->type() != AVWIDGET) {
1709         emit displayMessage(i18n("No clip selected"), ErrorMessage);
1710         return;
1711     }
1712     GenTime pos = GenTime(m_cursorPos, m_document->fps());
1713     if (item->startPos() > pos || item->endPos() < pos) {
1714         emit displayMessage(i18n("No selected clip at cursor time"), ErrorMessage);
1715         return;
1716     }
1717     ClipItem *clip = (ClipItem *) item;
1718     int id = clip->baseClip()->getId();
1719     GenTime position = pos - item->startPos() + item->cropStart();
1720     QString comment = clip->baseClip()->markerComment(position);
1721     if (comment.isEmpty()) {
1722         emit displayMessage(i18n("No marker found at cursor time"), ErrorMessage);
1723         return;
1724     }
1725     AddMarkerCommand *command = new AddMarkerCommand(this, comment, QString(), id, position, true);
1726     m_commandStack->push(command);
1727 }
1728
1729 void CustomTrackView::slotDeleteAllClipMarkers() {
1730     QList<QGraphicsItem *> itemList = scene()->selectedItems();
1731     if (itemList.count() != 1) {
1732         emit displayMessage(i18n("Cannot delete marker if more than one clip is selected"), ErrorMessage);
1733         kDebug() << "// CANNOT DELETE MARKER IF MORE TAN ONE CLIP IS SELECTED....";
1734         return;
1735     }
1736     AbstractClipItem *item = (AbstractClipItem *)itemList.at(0);
1737     if (item->type() != AVWIDGET) {
1738         emit displayMessage(i18n("No clip selected"), ErrorMessage);
1739         return;
1740     }
1741
1742     ClipItem *clip = static_cast <ClipItem *>(item);
1743     QList <CommentedTime> markers = clip->baseClip()->commentedSnapMarkers();
1744
1745     if (markers.isEmpty()) {
1746         emit displayMessage(i18n("Clip has no markers"), ErrorMessage);
1747         return;
1748     }
1749     int id = clip->baseClip()->getId();
1750     QUndoCommand *deleteMarkers = new QUndoCommand();
1751     deleteMarkers->setText("Delete clip markers");
1752
1753     for (int i = 0; i < markers.size(); i++) {
1754         new AddMarkerCommand(this, markers.at(i).comment(), QString(), id, markers.at(i).time(), true, deleteMarkers);
1755     }
1756     m_commandStack->push(deleteMarkers);
1757 }
1758
1759 void CustomTrackView::slotEditClipMarker() {
1760     QList<QGraphicsItem *> itemList = scene()->selectedItems();
1761     if (itemList.count() != 1) {
1762         emit displayMessage(i18n("Cannot edit marker if more than one clip is selected"), ErrorMessage);
1763         kDebug() << "// CANNOT DELETE MARKER IF MORE TAN ONE CLIP IS SELECTED....";
1764         return;
1765     }
1766     AbstractClipItem *item = (AbstractClipItem *)itemList.at(0);
1767     if (item->type() != AVWIDGET) {
1768         emit displayMessage(i18n("No clip at cursor time"), ErrorMessage);
1769         return;
1770     }
1771     GenTime pos = GenTime(m_cursorPos, m_document->fps());
1772     if (item->startPos() > pos || item->endPos() < pos) {
1773         emit displayMessage(i18n("No selected clip at cursor time"), ErrorMessage);
1774         return;
1775     }
1776     ClipItem *clip = (ClipItem *) item;
1777     int id = clip->baseClip()->getId();
1778     GenTime position = pos - item->startPos() + item->cropStart();
1779     QString oldcomment = clip->baseClip()->markerComment(position);
1780     if (oldcomment.isEmpty()) {
1781         emit displayMessage(i18n("No marker found at cursor time"), ErrorMessage);
1782         return;
1783     }
1784
1785     CommentedTime marker(position, oldcomment);
1786     MarkerDialog d(clip->baseClip(), marker, m_document->timecode(), this);
1787     if (d.exec() == QDialog::Accepted) {
1788         if (d.newMarker().time() == position) {
1789             // marker position was not changed, only text
1790             AddMarkerCommand *command = new AddMarkerCommand(this, oldcomment, d.newMarker().comment(), id, position, true);
1791             m_commandStack->push(command);
1792         } else {
1793             // marker text and position were changed, remove previous marker and add new one
1794             AddMarkerCommand *command1 = new AddMarkerCommand(this, oldcomment, QString(), id, position, true);
1795             AddMarkerCommand *command2 = new AddMarkerCommand(this, QString(), d.newMarker().comment(), id, d.newMarker().time(), true);
1796             m_commandStack->push(command1);
1797             m_commandStack->push(command2);
1798         }
1799     }
1800 }
1801
1802 void CustomTrackView::addMarker(const int id, const GenTime &pos, const QString comment) {
1803     DocClipBase *base = m_document->clipManager()->getClipById(id);
1804     if (!comment.isEmpty()) base->addSnapMarker(pos, comment);
1805     else base->deleteSnapMarker(pos);
1806     m_document->setModified(true);
1807     viewport()->update();
1808 }
1809
1810
1811
1812 void CustomTrackView::editGuide(const GenTime oldPos, const GenTime pos, const QString &comment) {
1813     if (oldPos > GenTime() && pos > GenTime()) {
1814         // move guide
1815         for (int i = 0; i < m_guides.count(); i++) {
1816             if (m_guides.at(i)->position() == oldPos) {
1817                 Guide *item = m_guides.at(i);
1818                 item->updateGuide(pos, comment);
1819                 break;
1820             }
1821         }
1822     } else if (pos > GenTime()) addGuide(pos, comment);
1823     else {
1824         // remove guide
1825         bool found = false;
1826         for (int i = 0; i < m_guides.count(); i++) {
1827             if (m_guides.at(i)->position() == oldPos) {
1828                 Guide *item = m_guides.takeAt(i);
1829                 delete item;
1830                 found = true;
1831                 break;
1832             }
1833         }
1834         if (!found) emit displayMessage(i18n("No guide at cursor time"), ErrorMessage);
1835     }
1836     m_document->syncGuides(m_guides);
1837 }
1838
1839 bool CustomTrackView::addGuide(const GenTime pos, const QString &comment) {
1840     for (int i = 0; i < m_guides.count(); i++) {
1841         if (m_guides.at(i)->position() == pos) {
1842             emit displayMessage(i18n("A guide already exists at that position"), ErrorMessage);
1843             return false;
1844         }
1845     }
1846     Guide *g = new Guide(this, pos, comment, m_scale, m_document->fps(), m_tracksHeight * m_tracksList.count());
1847     scene()->addItem(g);
1848     m_guides.append(g);
1849     m_document->syncGuides(m_guides);
1850     return true;
1851 }
1852
1853 void CustomTrackView::slotAddGuide() {
1854     CommentedTime marker(GenTime(m_cursorPos, m_document->fps()), i18n("Guide"));
1855     MarkerDialog d(NULL, marker, m_document->timecode(), this);
1856     if (d.exec() != QDialog::Accepted) return;
1857     if (addGuide(d.newMarker().time(), d.newMarker().comment())) {
1858         EditGuideCommand *command = new EditGuideCommand(this, GenTime(), QString(), d.newMarker().time(), d.newMarker().comment(), false);
1859         m_commandStack->push(command);
1860     }
1861 }
1862
1863 void CustomTrackView::slotEditGuide() {
1864     GenTime pos = GenTime(m_cursorPos, m_document->fps());
1865     bool found = false;
1866     for (int i = 0; i < m_guides.count(); i++) {
1867         if (m_guides.at(i)->position() == pos) {
1868             slotEditGuide(m_guides.at(i)->info());
1869             found = true;
1870             break;
1871         }
1872     }
1873     if (!found) emit displayMessage(i18n("No guide at cursor time"), ErrorMessage);
1874 }
1875
1876 void CustomTrackView::slotEditGuide(CommentedTime guide) {
1877     MarkerDialog d(NULL, guide, m_document->timecode(), this);
1878     if (d.exec() == QDialog::Accepted) {
1879         EditGuideCommand *command = new EditGuideCommand(this, guide.time(), guide.comment(), d.newMarker().time(), d.newMarker().comment(), true);
1880         m_commandStack->push(command);
1881     }
1882 }
1883
1884
1885 void CustomTrackView::slotDeleteGuide() {
1886     GenTime pos = GenTime(m_cursorPos, m_document->fps());
1887     bool found = false;
1888     for (int i = 0; i < m_guides.count(); i++) {
1889         if (m_guides.at(i)->position() == pos) {
1890             EditGuideCommand *command = new EditGuideCommand(this, m_guides.at(i)->position(), m_guides.at(i)->label(), GenTime(), QString(), true);
1891             m_commandStack->push(command);
1892             found = true;
1893             break;
1894         }
1895     }
1896     if (!found) emit displayMessage(i18n("No guide at cursor time"), ErrorMessage);
1897 }
1898
1899 void CustomTrackView::slotDeleteAllGuides() {
1900     QUndoCommand *deleteAll = new QUndoCommand();
1901     deleteAll->setText("Delete all guides");
1902     for (int i = 0; i < m_guides.count(); i++) {
1903         EditGuideCommand *command = new EditGuideCommand(this, m_guides.at(i)->position(), m_guides.at(i)->label(), GenTime(), QString(), true, deleteAll);
1904     }
1905     m_commandStack->push(deleteAll);
1906 }
1907
1908 void CustomTrackView::setTool(PROJECTTOOL tool) {
1909     m_tool = tool;
1910 }
1911
1912 void CustomTrackView::setScale(double scaleFactor) {
1913     //scale(scaleFactor, scaleFactor);
1914     m_animationTimer->stop();
1915     if (m_visualTip) {
1916         delete m_visualTip;
1917         m_visualTip = NULL;
1918     }
1919     if (m_animation) {
1920         delete m_animation;
1921         m_animation = NULL;
1922     }
1923     double pos = cursorPos() / m_scale;
1924     m_scale = scaleFactor;
1925     int vert = verticalScrollBar()->value();
1926     kDebug() << " HHHHHHHH  SCALING: " << m_scale;
1927     QList<QGraphicsItem *> itemList = items();
1928     for (int i = 0; i < itemList.count(); i++) {
1929         if (itemList.at(i)->type() == AVWIDGET || itemList.at(i)->type() == TRANSITIONWIDGET) {
1930             AbstractClipItem *clip = (AbstractClipItem *)itemList.at(i);
1931             clip->setRect(0, 0, (qreal) clip->duration().frames(m_document->fps()) * m_scale - .5, clip->rect().height());
1932             clip->setPos((qreal) clip->startPos().frames(m_document->fps()) * m_scale, clip->pos().y());
1933         }
1934     }
1935
1936     for (int i = 0; i < m_guides.count(); i++) {
1937         m_guides.at(i)->updatePosition(m_scale);
1938     }
1939
1940     setSceneRect(0, 0, (m_projectDuration + 100) * m_scale, sceneRect().height());
1941     updateCursorPos();
1942     centerOn(QPointF(cursorPos(), m_tracksHeight));
1943     verticalScrollBar()->setValue(vert);
1944 }
1945
1946 void CustomTrackView::slotRefreshGuides() {
1947     if (KdenliveSettings::showmarkers()) {
1948         kDebug() << "// refresh GUIDES";
1949         for (int i = 0; i < m_guides.count(); i++) {
1950             m_guides.at(i)->update();
1951         }
1952     }
1953 }
1954
1955 void CustomTrackView::drawBackground(QPainter * painter, const QRectF & rect) {
1956     QRect rectInView = viewport()->rect();
1957     rectInView.moveTo(horizontalScrollBar()->value(), verticalScrollBar()->value());
1958
1959     QColor base = palette().button().color();
1960     painter->setClipRect(rect);
1961     painter->drawLine(rectInView.left(), 0, rectInView.right(), 0);
1962     uint max = m_tracksList.count();
1963     for (uint i = 0; i < max;i++) {
1964         if (m_tracksList.at(max - i - 1).type == AUDIOTRACK) painter->fillRect(rectInView.left(), m_tracksHeight * i + 1, rectInView.right() - rectInView.left() + 1, m_tracksHeight - 1, QBrush(QColor(240, 240, 255)));
1965         painter->drawLine(rectInView.left(), m_tracksHeight * (i + 1), rectInView.right(), m_tracksHeight * (i + 1));
1966         //painter->drawText(QRectF(10, 50 * i, 100, 50 * i + 49), Qt::AlignLeft, i18n(" Track ") + QString::number(i + 1));
1967     }
1968     int lowerLimit = m_tracksHeight * m_tracksList.count() + 1;
1969     if (height() > lowerLimit)
1970         painter->fillRect(QRectF(rectInView.left(), lowerLimit, rectInView.width(), height() - lowerLimit), QBrush(base));
1971 }
1972
1973 bool CustomTrackView::findString(const QString &text) {
1974     QString marker;
1975     for (int i = 0; i < m_searchPoints.size(); ++i) {
1976         marker = m_searchPoints.at(i).comment();
1977         if (marker.contains(text, Qt::CaseInsensitive)) {
1978             setCursorPos(m_searchPoints.at(i).time().frames(m_document->fps()), true);
1979             int vert = verticalScrollBar()->value();
1980             int hor = cursorPos();
1981             ensureVisible(hor, vert + 10, 2, 2, 50, 0);
1982             m_findIndex = i;
1983             return true;
1984         }
1985     }
1986     return false;
1987 }
1988
1989 bool CustomTrackView::findNextString(const QString &text) {
1990     QString marker;
1991     for (int i = m_findIndex + 1; i < m_searchPoints.size(); ++i) {
1992         marker = m_searchPoints.at(i).comment();
1993         if (marker.contains(text, Qt::CaseInsensitive)) {
1994             setCursorPos(m_searchPoints.at(i).time().frames(m_document->fps()), true);
1995             int vert = verticalScrollBar()->value();
1996             int hor = cursorPos();
1997             ensureVisible(hor, vert + 10, 2, 2, 50, 0);
1998             m_findIndex = i;
1999             return true;
2000         }
2001     }
2002     m_findIndex = -1;
2003     return false;
2004 }
2005
2006 void CustomTrackView::initSearchStrings() {
2007     m_searchPoints.clear();
2008     QList<QGraphicsItem *> itemList = items();
2009     for (int i = 0; i < itemList.count(); i++) {
2010         // parse all clip names
2011         if (itemList.at(i)->type() == AVWIDGET) {
2012             ClipItem *item = static_cast <ClipItem *>(itemList.at(i));
2013             GenTime start = item->startPos();
2014             CommentedTime t(start, item->clipName());
2015             m_searchPoints.append(t);
2016             // add all clip markers
2017             QList < CommentedTime > markers = item->commentedSnapMarkers();
2018             m_searchPoints += markers;
2019         }
2020     }
2021
2022     // add guides
2023     for (int i = 0; i < m_guides.count(); i++) {
2024         m_searchPoints.append(m_guides.at(i)->info());
2025     }
2026
2027     qSort(m_searchPoints);
2028 }
2029
2030 void CustomTrackView::clearSearchStrings() {
2031     m_searchPoints.clear();
2032     m_findIndex = 0;
2033 }
2034
2035 void CustomTrackView::copyClip() {
2036     while (m_copiedItems.count() > 0) {
2037         delete m_copiedItems.takeFirst();
2038     }
2039     QList<QGraphicsItem *> itemList = scene()->selectedItems();
2040     if (itemList.count() == 0) {
2041         emit displayMessage(i18n("Select a clip before copying"), ErrorMessage);
2042         return;
2043     }
2044     for (int i = 0; i < itemList.count(); i++) {
2045         if (itemList.at(i)->type() == AVWIDGET) {
2046             ClipItem *dup = static_cast <ClipItem *>(itemList.at(i));
2047             m_copiedItems.append(dup->clone(m_scale, dup->info()));
2048         } else if (itemList.at(i)->type() == TRANSITIONWIDGET) {
2049             Transition *dup = static_cast <Transition *>(itemList.at(i));
2050             m_copiedItems.append(dup->clone(m_scale));
2051         }
2052     }
2053 }
2054
2055 bool CustomTrackView::canBePastedTo(ItemInfo info, int type) const {
2056     QRectF rect((double) info.startPos.frames(m_document->fps()) * m_scale, (double)(info.track * m_tracksHeight + 1), (double)(info.endPos - info.startPos).frames(m_document->fps()) * m_scale, (double)(m_tracksHeight - 1));
2057     QList<QGraphicsItem *> collisions = scene()->items(rect, Qt::IntersectsItemBoundingRect);
2058     for (int i = 0; i < collisions.count(); i++) {
2059         if (collisions.at(i)->type() == type) return false;
2060     }
2061     return true;
2062 }
2063
2064 bool CustomTrackView::canBePasted(QList<AbstractClipItem *> items, GenTime offset, int trackOffset) const {
2065     for (int i = 0; i < items.count(); i++) {
2066         ItemInfo info = items.at(i)->info();
2067         info.startPos += offset;
2068         info.endPos += offset;
2069         info.track += trackOffset;
2070         if (!canBePastedTo(info, items.at(i)->type())) return false;
2071     }
2072     return true;
2073 }
2074
2075 bool CustomTrackView::canBeMoved(QList<AbstractClipItem *> items, GenTime offset, int trackOffset) const {
2076     QPainterPath movePath;
2077     movePath.moveTo(0, 0);
2078
2079     for (int i = 0; i < items.count(); i++) {
2080         ItemInfo info = items.at(i)->info();
2081         info.startPos = info.startPos + offset;
2082         info.endPos = info.endPos + offset;
2083         info.track = info.track + trackOffset;
2084         if (info.startPos < GenTime()) {
2085             // No clip should go below 0
2086             return false;
2087         }
2088         QRectF rect((double) info.startPos.frames(m_document->fps()) * m_scale, (double)(info.track * m_tracksHeight + 1), (double)(info.endPos - info.startPos).frames(m_document->fps()) * m_scale, (double)(m_tracksHeight - 1));
2089         movePath.addRect(rect);
2090     }
2091     QList<QGraphicsItem *> collisions = scene()->items(movePath, Qt::IntersectsItemBoundingRect);
2092     for (int i = 0; i < collisions.count(); i++) {
2093         if ((collisions.at(i)->type() == AVWIDGET || collisions.at(i)->type() == TRANSITIONWIDGET) && !items.contains(static_cast <AbstractClipItem *>(collisions.at(i)))) {
2094             kDebug() << "  ////////////   CLIP COLLISION, MOVE NOT ALLOWED";
2095             return false;
2096         }
2097     }
2098     return true;
2099 }
2100
2101 void CustomTrackView::pasteClip() {
2102     if (m_copiedItems.count() == 0) {
2103         emit displayMessage(i18n("No clip copied"), ErrorMessage);
2104         return;
2105     }
2106     QPoint position;
2107     if (m_menuPosition.isNull()) position = mapFromGlobal(QCursor::pos());
2108     else position = m_menuPosition;
2109     GenTime pos = GenTime((int)(mapToScene(position).x() / m_scale), m_document->fps());
2110     int track = (int)(position.y() / m_tracksHeight);
2111     ItemInfo first = m_copiedItems.at(0)->info();
2112
2113     GenTime offset = pos - first.startPos;
2114     int trackOffset = track - first.track;
2115
2116     if (!canBePasted(m_copiedItems, offset, trackOffset)) {
2117         emit displayMessage(i18n("Cannot paste selected clips"), ErrorMessage);
2118         return;
2119     }
2120     QUndoCommand *pasteClips = new QUndoCommand();
2121     pasteClips->setText("Paste clips");
2122
2123     for (int i = 0; i < m_copiedItems.count(); i++) {
2124         // parse all clip names
2125         if (m_copiedItems.at(i) && m_copiedItems.at(i)->type() == AVWIDGET) {
2126             ClipItem *clip = static_cast <ClipItem *>(m_copiedItems.at(i));
2127             ItemInfo info;
2128             info.startPos = clip->startPos() + offset;
2129             info.endPos = clip->endPos() + offset;
2130             info.cropStart = clip->cropStart();
2131             info.track = clip->track() + trackOffset;
2132             if (canBePastedTo(info, AVWIDGET)) {
2133                 new AddTimelineClipCommand(this, clip->xml(), clip->clipProducer(), info, clip->effectList(), true, false, pasteClips);
2134             } else emit displayMessage(i18n("Cannot paste clip to selected place"), ErrorMessage);
2135         } else if (m_copiedItems.at(i) && m_copiedItems.at(i)->type() == TRANSITIONWIDGET) {
2136             Transition *tr = static_cast <Transition *>(m_copiedItems.at(i));
2137             ItemInfo info;
2138             info.startPos = tr->startPos() + offset;
2139             info.endPos = tr->endPos() + offset;
2140             info.track = tr->track() + trackOffset;
2141             if (canBePastedTo(info, TRANSITIONWIDGET)) {
2142                 new AddTransitionCommand(this, info, tr->transitionEndTrack() + trackOffset, tr->toXML(), false, true, pasteClips);
2143             } else emit displayMessage(i18n("Cannot paste transition to selected place"), ErrorMessage);
2144         }
2145     }
2146     m_commandStack->push(pasteClips);
2147 }
2148
2149 void CustomTrackView::pasteClipEffects() {
2150     if (m_copiedItems.count() != 1 || m_copiedItems.at(0)->type() != AVWIDGET) {
2151         emit displayMessage(i18n("You must copy exactly one clip before pasting effects"), ErrorMessage);
2152         return;
2153     }
2154     ClipItem *clip = static_cast < ClipItem *>(m_copiedItems.at(0));
2155     EffectsList effects = clip->effectList();
2156
2157     QUndoCommand *paste = new QUndoCommand();
2158     paste->setText("Paste effects");
2159
2160     QList<QGraphicsItem *> clips = scene()->selectedItems();
2161     for (int i = 0; i < clips.count(); ++i) {
2162         if (clips.at(i)->type() == AVWIDGET) {
2163             ClipItem *item = static_cast < ClipItem *>(clips.at(i));
2164             for (int i = 0; i < clip->effectsCount(); i++) {
2165                 new AddEffectCommand(this, m_tracksList.count() - item->track(), item->startPos(), clip->effectAt(i), true, paste);
2166             }
2167         }
2168     }
2169     m_commandStack->push(paste);
2170 }
2171
2172
2173 /*
2174 void CustomTrackView::drawForeground ( QPainter * painter, const QRectF & rect )
2175 {
2176   //kDebug()<<"/////  DRAWING FB: "<<rect.x()<<", width: "<<rect.width();
2177   painter->fillRect(rect, QColor(50, rand() % 250,50,100));
2178   painter->drawLine(m_cursorPos, rect.y(), m_cursorPos, rect.y() + rect.height());
2179 }
2180 */
2181 #include "customtrackview.moc"