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