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