]> git.sesse.net Git - kdenlive/blob - src/mainwindow.cpp
Fix http://www.kdenlive.org:80/mantis/view.php?id=251
[kdenlive] / src / mainwindow.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 <stdlib.h>
21
22 #include <QTextStream>
23 #include <QTimer>
24 #include <QAction>
25 #include <QtTest>
26 #include <QtCore>
27 #include <QKeyEvent>
28
29 #include <KApplication>
30 #include <KAction>
31 #include <KLocale>
32 #include <KGlobal>
33 #include <KActionCollection>
34 #include <KStandardAction>
35 #include <KFileDialog>
36 #include <KMessageBox>
37 #include <KDebug>
38 #include <KIO/NetAccess>
39 #include <KSaveFile>
40 #include <KRuler>
41 #include <KConfigDialog>
42 #include <KXMLGUIFactory>
43 #include <KStatusBar>
44 #include <kstandarddirs.h>
45 #include <KUrlRequesterDialog>
46 #include <KTemporaryFile>
47 #include <KActionMenu>
48 #include <KMenu>
49 #include <locale.h>
50 #include <ktogglefullscreenaction.h>
51 #include <KFileItem>
52 #include <KNotification>
53 #include <KNotifyConfigWidget>
54
55 #include <mlt++/Mlt.h>
56
57 #include "mainwindow.h"
58 #include "kdenlivesettings.h"
59 #include "kdenlivesettingsdialog.h"
60 #include "initeffects.h"
61 #include "profilesdialog.h"
62 #include "projectsettings.h"
63 #include "events.h"
64 #include "clipmanager.h"
65 #include "projectlist.h"
66 #include "monitor.h"
67 #include "recmonitor.h"
68 #include "monitormanager.h"
69 #include "kdenlivedoc.h"
70 #include "trackview.h"
71 #include "customtrackview.h"
72 #include "effectslistview.h"
73 #include "effectstackview.h"
74 #include "transitionsettings.h"
75 #include "renderwidget.h"
76 #include "renderer.h"
77 #include "jogshuttle.h"
78 #include "clipproperties.h"
79 #include "wizard.h"
80 #include "editclipcommand.h"
81 #include "titlewidget.h"
82
83 static const int ID_STATUS_MSG = 1;
84 static const int ID_EDITMODE_MSG = 2;
85 static const int ID_TIMELINE_MSG = 3;
86 static const int ID_TIMELINE_BUTTONS = 5;
87 static const int ID_TIMELINE_POS = 6;
88 static const int ID_TIMELINE_FORMAT = 7;
89
90 namespace Mlt {
91 class Producer;
92 };
93
94 EffectsList MainWindow::videoEffects;
95 EffectsList MainWindow::audioEffects;
96 EffectsList MainWindow::customEffects;
97 EffectsList MainWindow::transitions;
98
99 MainWindow::MainWindow(const QString &MltPath, QWidget *parent)
100         : KXmlGuiWindow(parent),
101         m_activeDocument(NULL), m_activeTimeline(NULL), m_renderWidget(NULL), m_jogProcess(NULL), m_findActivated(false), m_initialized(false) {
102     setlocale(LC_NUMERIC, "POSIX");
103     setFont(KGlobalSettings::toolBarFont());
104     parseProfiles(MltPath);
105     m_commandStack = new QUndoGroup;
106     m_timelineArea = new KTabWidget(this);
107     m_timelineArea->setTabReorderingEnabled(true);
108     m_timelineArea->setTabBarHidden(true);
109
110     QToolButton *closeTabButton = new QToolButton;
111     connect(closeTabButton, SIGNAL(clicked()), this, SLOT(closeCurrentDocument()));
112     closeTabButton->setIcon(KIcon("tab-close"));
113     closeTabButton->adjustSize();
114     closeTabButton->setToolTip(i18n("Close the current tab"));
115     m_timelineArea->setCornerWidget(closeTabButton);
116     connect(m_timelineArea, SIGNAL(currentChanged(int)), this, SLOT(activateDocument()));
117
118     connect(&m_findTimer, SIGNAL(timeout()), this, SLOT(findTimeout()));
119     m_findTimer.setSingleShot(true);
120
121     initEffects::parseEffectFiles();
122     //initEffects::parseCustomEffectsFile();
123
124     m_monitorManager = new MonitorManager();
125
126     projectListDock = new QDockWidget(i18n("Project Tree"), this);
127     projectListDock->setObjectName("project_tree");
128     m_projectList = new ProjectList(this);
129     projectListDock->setWidget(m_projectList);
130     addDockWidget(Qt::TopDockWidgetArea, projectListDock);
131
132     effectListDock = new QDockWidget(i18n("Effect List"), this);
133     effectListDock->setObjectName("effect_list");
134     m_effectList = new EffectsListView();
135
136     //m_effectList = new KListWidget(this);
137     effectListDock->setWidget(m_effectList);
138     addDockWidget(Qt::TopDockWidgetArea, effectListDock);
139
140     effectStackDock = new QDockWidget(i18n("Effect Stack"), this);
141     effectStackDock->setObjectName("effect_stack");
142     effectStack = new EffectStackView(this);
143     effectStackDock->setWidget(effectStack);
144     addDockWidget(Qt::TopDockWidgetArea, effectStackDock);
145
146     transitionConfigDock = new QDockWidget(i18n("Transition"), this);
147     transitionConfigDock->setObjectName("transition");
148     transitionConfig = new TransitionSettings(this);
149     transitionConfigDock->setWidget(transitionConfig);
150     addDockWidget(Qt::TopDockWidgetArea, transitionConfigDock);
151
152     KdenliveSettings::setCurrent_profile(KdenliveSettings::default_profile());
153     m_fileOpenRecent = KStandardAction::openRecent(this, SLOT(openFile(const KUrl &)),
154                        actionCollection());
155     readOptions();
156
157     clipMonitorDock = new QDockWidget(i18n("Clip Monitor"), this);
158     clipMonitorDock->setObjectName("clip_monitor");
159     m_clipMonitor = new Monitor("clip", m_monitorManager, this);
160     clipMonitorDock->setWidget(m_clipMonitor);
161     addDockWidget(Qt::TopDockWidgetArea, clipMonitorDock);
162     //m_clipMonitor->stop();
163
164     projectMonitorDock = new QDockWidget(i18n("Project Monitor"), this);
165     projectMonitorDock->setObjectName("project_monitor");
166     m_projectMonitor = new Monitor("project", m_monitorManager, this);
167     projectMonitorDock->setWidget(m_projectMonitor);
168     addDockWidget(Qt::TopDockWidgetArea, projectMonitorDock);
169
170     recMonitorDock = new QDockWidget(i18n("Record Monitor"), this);
171     recMonitorDock->setObjectName("record_monitor");
172     m_recMonitor = new RecMonitor("record", this);
173     recMonitorDock->setWidget(m_recMonitor);
174     addDockWidget(Qt::TopDockWidgetArea, recMonitorDock);
175
176     connect(m_recMonitor, SIGNAL(addProjectClip(KUrl)), this, SLOT(slotAddProjectClip(KUrl)));
177     connect(m_recMonitor, SIGNAL(showConfigDialog(int, int)), this, SLOT(slotPreferences(int, int)));
178
179     undoViewDock = new QDockWidget(i18n("Undo History"), this);
180     undoViewDock->setObjectName("undo_history");
181     m_undoView = new QUndoView(this);
182     m_undoView->setCleanIcon(KIcon("edit-clear"));
183     m_undoView->setEmptyLabel(i18n("Clean"));
184     undoViewDock->setWidget(m_undoView);
185     m_undoView->setGroup(m_commandStack);
186     addDockWidget(Qt::TopDockWidgetArea, undoViewDock);
187
188     //overviewDock = new QDockWidget(i18n("Project Overview"), this);
189     //overviewDock->setObjectName("project_overview");
190     //m_overView = new CustomTrackView(NULL, NULL, this);
191     //overviewDock->setWidget(m_overView);
192     //addDockWidget(Qt::TopDockWidgetArea, overviewDock);
193
194     setupActions();
195     //tabifyDockWidget(projectListDock, effectListDock);
196     tabifyDockWidget(projectListDock, effectStackDock);
197     tabifyDockWidget(projectListDock, transitionConfigDock);
198     //tabifyDockWidget(projectListDock, undoViewDock);
199
200
201     tabifyDockWidget(clipMonitorDock, projectMonitorDock);
202     tabifyDockWidget(clipMonitorDock, recMonitorDock);
203     setCentralWidget(m_timelineArea);
204
205     setupGUI();
206     //kDebug() << factory() << " " << factory()->container("video_effects_menu", this);
207
208     m_projectMonitor->setupMenu(static_cast<QMenu*>(factory()->container("monitor_go", this)));
209     m_clipMonitor->setupMenu(static_cast<QMenu*>(factory()->container("monitor_go", this)));
210
211     // build effects menus
212     QAction *action;
213     QMenu *videoEffectsMenu = static_cast<QMenu*>(factory()->container("video_effects_menu", this));
214
215     QStringList effectInfo;
216     QMap<QString, QStringList> effectsList;
217     for (int ix = 0; ix < videoEffects.count(); ix++) {
218         effectInfo = videoEffects.effectIdInfo(ix);
219         effectsList.insert(effectInfo.at(0).toLower(), effectInfo);
220     }
221
222     foreach(QStringList value, effectsList) {
223         action = new QAction(value.at(0), this);
224         action->setData(value);
225         videoEffectsMenu->addAction(action);
226     }
227
228     QMenu *audioEffectsMenu = static_cast<QMenu*>(factory()->container("audio_effects_menu", this));
229
230
231     effectsList.clear();
232     for (int ix = 0; ix < audioEffects.count(); ix++) {
233         effectInfo = audioEffects.effectIdInfo(ix);
234         effectsList.insert(effectInfo.at(0).toLower(), effectInfo);
235     }
236
237     foreach(QStringList value, effectsList) {
238         action = new QAction(value.at(0), this);
239         action->setData(value);
240         audioEffectsMenu->addAction(action);
241     }
242
243     m_customEffectsMenu = static_cast<QMenu*>(factory()->container("custom_effects_menu", this));
244
245     if (customEffects.isEmpty()) m_customEffectsMenu->setEnabled(false);
246     else m_customEffectsMenu->setEnabled(true);
247
248     effectsList.clear();
249     for (int ix = 0; ix < customEffects.count(); ix++) {
250         effectInfo = customEffects.effectIdInfo(ix);
251         effectsList.insert(effectInfo.at(0).toLower(), effectInfo);
252     }
253
254     foreach(QStringList value, effectsList) {
255         action = new QAction(value.at(0), this);
256         action->setData(value);
257         m_customEffectsMenu->addAction(action);
258     }
259
260     QMenu *newEffect = new QMenu(this);
261     newEffect->addMenu(videoEffectsMenu);
262     newEffect->addMenu(audioEffectsMenu);
263     newEffect->addMenu(m_customEffectsMenu);
264     effectStack->setMenu(newEffect);
265
266
267     QMenu *viewMenu = static_cast<QMenu*>(factory()->container("dockwindows", this));
268     const QList<QAction *> viewActions = createPopupMenu()->actions();
269     viewMenu->insertActions(NULL, viewActions);
270
271     connect(videoEffectsMenu, SIGNAL(triggered(QAction *)), this, SLOT(slotAddVideoEffect(QAction *)));
272     connect(audioEffectsMenu, SIGNAL(triggered(QAction *)), this, SLOT(slotAddAudioEffect(QAction *)));
273     connect(m_customEffectsMenu, SIGNAL(triggered(QAction *)), this, SLOT(slotAddCustomEffect(QAction *)));
274
275     m_timelineContextMenu = new QMenu(this);
276     m_timelineContextClipMenu = new QMenu(this);
277     m_timelineContextTransitionMenu = new QMenu(this);
278
279
280     QMenu *transitionsMenu = new QMenu(i18n("Add Transition"), this);
281     QStringList effects = transitions.effectNames();
282     foreach(const QString &name, effects) {
283         action = new QAction(name, this);
284         action->setData(name);
285         transitionsMenu->addAction(action);
286     }
287     connect(transitionsMenu, SIGNAL(triggered(QAction *)), this, SLOT(slotAddTransition(QAction *)));
288
289     m_timelineContextMenu->addAction(actionCollection()->action(KStandardAction::name(KStandardAction::Paste)));
290
291     m_timelineContextClipMenu->addAction(actionCollection()->action("delete_timeline_clip"));
292     m_timelineContextClipMenu->addAction(actionCollection()->action("change_clip_speed"));
293     m_timelineContextClipMenu->addAction(actionCollection()->action("cut_timeline_clip"));
294     m_timelineContextClipMenu->addAction(actionCollection()->action(KStandardAction::name(KStandardAction::Copy)));
295     m_timelineContextClipMenu->addAction(actionCollection()->action("paste_effects"));
296
297     QMenu *markersMenu = (QMenu*)(factory()->container("marker_menu", this));
298     m_timelineContextClipMenu->addMenu(markersMenu);
299     m_timelineContextClipMenu->addMenu(transitionsMenu);
300     m_timelineContextClipMenu->addMenu(videoEffectsMenu);
301     m_timelineContextClipMenu->addMenu(audioEffectsMenu);
302     //TODO: re-enable custom effects menu when it is implemented
303     m_timelineContextClipMenu->addMenu(m_customEffectsMenu);
304
305     m_timelineContextTransitionMenu->addAction(actionCollection()->action("delete_timeline_clip"));
306     m_timelineContextTransitionMenu->addAction(actionCollection()->action(KStandardAction::name(KStandardAction::Copy)));
307
308     connect(projectMonitorDock, SIGNAL(visibilityChanged(bool)), m_projectMonitor, SLOT(refreshMonitor(bool)));
309     connect(clipMonitorDock, SIGNAL(visibilityChanged(bool)), m_clipMonitor, SLOT(refreshMonitor(bool)));
310     //connect(m_monitorManager, SIGNAL(connectMonitors()), this, SLOT(slotConnectMonitors()));
311     connect(m_monitorManager, SIGNAL(raiseClipMonitor(bool)), this, SLOT(slotRaiseMonitor(bool)));
312     connect(m_effectList, SIGNAL(addEffect(QDomElement)), this, SLOT(slotAddEffect(QDomElement)));
313     connect(m_effectList, SIGNAL(reloadEffects()), this, SLOT(slotReloadEffects()));
314
315     m_monitorManager->initMonitors(m_clipMonitor, m_projectMonitor);
316     slotConnectMonitors();
317
318     if (KdenliveSettings::openlastproject()) {
319         openLastFile();
320     } else {
321         /*QList<KAutoSaveFile *> staleFiles = KAutoSaveFile::allStaleFiles();
322         if (!staleFiles.isEmpty()) {
323             if (KMessageBox::questionYesNo(this, i18n("Auto-saved files exist. Do you want to recover them now?"), i18n("File Recovery"), KGuiItem(i18n("Recover")), KGuiItem(i18n("Don't recover"))) == KMessageBox::Yes) {
324          recoverFiles(staleFiles);
325             }
326             else newFile();
327         }
328         else*/
329         newFile(false);
330     }
331
332     activateShuttleDevice();
333     projectListDock->raise();
334 }
335
336 void MainWindow::queryQuit() {
337     kDebug() << "----- SAVING CONFUIG";
338     if (queryClose()) kapp->quit();
339 }
340
341 //virtual
342 bool MainWindow::queryClose() {
343     saveOptions();
344     if (m_monitorManager) m_monitorManager->stopActiveMonitor();
345     if (m_activeDocument && m_activeDocument->isModified()) {
346         switch (KMessageBox::warningYesNoCancel(this, i18n("Save changes to document ?"))) {
347         case KMessageBox::Yes :
348             // save document here. If saving fails, return false;
349             saveFile();
350             return true;
351         case KMessageBox::No :
352             return true;
353         default: // cancel
354             return false;
355         }
356     }
357     return true;
358 }
359
360 void MainWindow::saveProperties(KConfig*) {
361     // save properties here,used by session management
362     saveFile();
363 }
364
365
366 void MainWindow::readProperties(KConfig *config) {
367     // read properties here,used by session management
368     QString Lastproject = config->group("Recent Files").readPathEntry("File1", QString());
369     openFile(KUrl(Lastproject));
370 }
371
372 void MainWindow::slotReloadEffects() {
373     initEffects::parseCustomEffectsFile();
374     m_customEffectsMenu->clear();
375     const QStringList effects = customEffects.effectNames();
376     QAction *action;
377     if (effects.isEmpty()) m_customEffectsMenu->setEnabled(false);
378     else m_customEffectsMenu->setEnabled(true);
379
380     foreach(const QString &name, effects) {
381         action = new QAction(name, this);
382         action->setData(name);
383         m_customEffectsMenu->addAction(action);
384     }
385     m_effectList->reloadEffectList();
386 }
387
388 void MainWindow::activateShuttleDevice() {
389     if (m_jogProcess) delete m_jogProcess;
390     m_jogProcess = NULL;
391     if (KdenliveSettings::enableshuttle() == false) return;
392     m_jogProcess = new JogShuttle(KdenliveSettings::shuttledevice());
393     connect(m_jogProcess, SIGNAL(rewind1()), m_monitorManager, SLOT(slotRewindOneFrame()));
394     connect(m_jogProcess, SIGNAL(forward1()), m_monitorManager, SLOT(slotForwardOneFrame()));
395     connect(m_jogProcess, SIGNAL(rewind(double)), m_monitorManager, SLOT(slotRewind(double)));
396     connect(m_jogProcess, SIGNAL(forward(double)), m_monitorManager, SLOT(slotForward(double)));
397     connect(m_jogProcess, SIGNAL(stop()), m_monitorManager, SLOT(slotPlay()));
398     connect(m_jogProcess, SIGNAL(button(int)), this, SLOT(slotShuttleButton(int)));
399 }
400
401 void MainWindow::slotShuttleButton(int code) {
402     switch (code) {
403     case 5:
404         slotShuttleAction(KdenliveSettings::shuttle1());
405         break;
406     case 6:
407         slotShuttleAction(KdenliveSettings::shuttle2());
408         break;
409     case 7:
410         slotShuttleAction(KdenliveSettings::shuttle3());
411         break;
412     case 8:
413         slotShuttleAction(KdenliveSettings::shuttle4());
414         break;
415     case 9:
416         slotShuttleAction(KdenliveSettings::shuttle5());
417         break;
418     }
419 }
420
421 void MainWindow::slotShuttleAction(int code) {
422     switch (code) {
423     case 0:
424         return;
425     case 1:
426         m_monitorManager->slotPlay();
427         break;
428     default:
429         m_monitorManager->slotPlay();
430         break;
431     }
432 }
433
434 void MainWindow::configureNotifications() {
435     KNotifyConfigWidget::configure(this);
436 }
437
438 void MainWindow::slotFullScreen() {
439     //KToggleFullScreenAction::setFullScreen(this, actionCollection()->action("fullscreen")->isChecked());
440 }
441
442 void MainWindow::slotAddEffect(QDomElement effect, GenTime pos, int track) {
443     if (!m_activeDocument) return;
444     if (effect.isNull()) {
445         kDebug() << "--- ERROR, TRYING TO APPEND NULL EFFECT";
446         return;
447     }
448     TrackView *currentTimeLine = (TrackView *) m_timelineArea->currentWidget();
449     currentTimeLine->projectView()->slotAddEffect(effect.cloneNode().toElement(), pos, track);
450 }
451
452 void MainWindow::slotRaiseMonitor(bool clipMonitor) {
453     if (clipMonitor) clipMonitorDock->raise();
454     else projectMonitorDock->raise();
455 }
456
457 void MainWindow::slotSetClipDuration(const QString &id, int duration) {
458     if (!m_activeDocument) return;
459     m_activeDocument->setProducerDuration(id, duration);
460 }
461
462 void MainWindow::slotConnectMonitors() {
463
464     m_projectList->setRenderer(m_clipMonitor->render);
465     connect(m_projectList, SIGNAL(receivedClipDuration(const QString &, int)), this, SLOT(slotSetClipDuration(const QString &, int)));
466     connect(m_projectList, SIGNAL(showClipProperties(DocClipBase *)), this, SLOT(slotShowClipProperties(DocClipBase *)));
467     connect(m_projectList, SIGNAL(getFileProperties(const QDomElement &, const QString &)), m_clipMonitor->render, SLOT(getFileProperties(const QDomElement &, const QString &)));
468     connect(m_clipMonitor->render, SIGNAL(replyGetImage(const QString &, int, const QPixmap &, int, int)), m_projectList, SLOT(slotReplyGetImage(const QString &, int, const QPixmap &, int, int)));
469     connect(m_clipMonitor->render, SIGNAL(replyGetFileProperties(const QString &, Mlt::Producer*, const QMap < QString, QString > &, const QMap < QString, QString > &)), m_projectList, SLOT(slotReplyGetFileProperties(const QString &, Mlt::Producer*, const QMap < QString, QString > &, const QMap < QString, QString > &)));
470
471     connect(m_clipMonitor->render, SIGNAL(removeInvalidClip(const QString &)), m_projectList, SLOT(slotRemoveInvalidClip(const QString &)));
472
473     connect(m_clipMonitor, SIGNAL(refreshClipThumbnail(const QString &)), m_projectList, SLOT(slotRefreshClipThumbnail(const QString &)));
474
475     connect(m_clipMonitor, SIGNAL(adjustMonitorSize()), this, SLOT(slotAdjustClipMonitor()));
476     connect(m_projectMonitor, SIGNAL(adjustMonitorSize()), this, SLOT(slotAdjustProjectMonitor()));
477
478     connect(m_clipMonitor, SIGNAL(saveZone(Render *, QPoint)), this, SLOT(slotSaveZone(Render *, QPoint)));
479     connect(m_projectMonitor, SIGNAL(saveZone(Render *, QPoint)), this, SLOT(slotSaveZone(Render *, QPoint)));
480 }
481
482 void MainWindow::slotAdjustClipMonitor() {
483     clipMonitorDock->updateGeometry();
484     clipMonitorDock->adjustSize();
485     m_clipMonitor->resetSize();
486 }
487
488 void MainWindow::slotAdjustProjectMonitor() {
489     projectMonitorDock->updateGeometry();
490     projectMonitorDock->adjustSize();
491     m_projectMonitor->resetSize();
492 }
493
494 void MainWindow::setupActions() {
495
496     KActionCollection* collection = actionCollection();
497     m_timecodeFormat = new KComboBox(this);
498     m_timecodeFormat->addItem(i18n("hh:mm:ss::ff"));
499     m_timecodeFormat->addItem(i18n("Frames"));
500
501     statusProgressBar = new QProgressBar(this);
502     statusProgressBar->setMinimum(0);
503     statusProgressBar->setMaximum(100);
504     statusProgressBar->setMaximumWidth(150);
505     statusProgressBar->setVisible(false);
506
507     QWidget *w = new QWidget;
508
509     QHBoxLayout *layout = new QHBoxLayout;
510     w->setLayout(layout);
511     layout->setContentsMargins(5, 0, 5, 0);
512     QToolBar *toolbar = new QToolBar("statusToolBar", this);
513
514
515     m_toolGroup = new QActionGroup(this);
516
517     QString style1 = "QToolButton {background-color: rgba(230, 230, 230, 220); border-style: inset; border:1px solid #999999;border-radius: 3px;margin: 0px 3px;padding: 0px;} QToolButton:checked { background-color: rgba(224, 224, 0, 100); border-style: inset; border:1px solid #cc6666;border-radius: 3px;}";
518
519     m_buttonSelectTool = new KAction(KIcon("kdenlive-select-tool"), i18n("Selection tool"), this);
520     toolbar->addAction(m_buttonSelectTool);
521     m_buttonSelectTool->setCheckable(true);
522     m_buttonSelectTool->setChecked(true);
523
524     m_buttonRazorTool = new KAction(KIcon("edit-cut"), i18n("Razor tool"), this);
525     toolbar->addAction(m_buttonRazorTool);
526     m_buttonRazorTool->setCheckable(true);
527     m_buttonRazorTool->setChecked(false);
528
529     m_toolGroup->addAction(m_buttonSelectTool);
530     m_toolGroup->addAction(m_buttonRazorTool);
531     m_toolGroup->setExclusive(true);
532     toolbar->setToolButtonStyle(Qt::ToolButtonIconOnly);
533
534     QWidget * actionWidget;
535     actionWidget = toolbar->widgetForAction(m_buttonSelectTool);
536     actionWidget->setMaximumWidth(24);
537     actionWidget->setMinimumHeight(17);
538
539     actionWidget = toolbar->widgetForAction(m_buttonRazorTool);
540     actionWidget->setMaximumWidth(24);
541     actionWidget->setMinimumHeight(17);
542
543     toolbar->setStyleSheet(style1);
544     connect(m_toolGroup, SIGNAL(triggered(QAction *)), this, SLOT(slotChangeTool(QAction *)));
545
546     toolbar->addSeparator();
547     m_buttonFitZoom = new KAction(KIcon("zoom-fit-best"), i18n("Fit zoom to project"), this);
548     toolbar->addAction(m_buttonFitZoom);
549     m_buttonFitZoom->setCheckable(false);
550     connect(m_buttonFitZoom, SIGNAL(triggered()), this, SLOT(slotFitZoom()));
551
552     actionWidget = toolbar->widgetForAction(m_buttonFitZoom);
553     actionWidget->setMaximumWidth(24);
554     actionWidget->setMinimumHeight(17);
555
556     m_zoomSlider = new QSlider(Qt::Horizontal, this);
557     m_zoomSlider->setMaximum(13);
558     m_zoomSlider->setPageStep(1);
559
560     m_zoomSlider->setMaximumWidth(150);
561     m_zoomSlider->setMinimumWidth(100);
562
563     const int contentHeight = QFontMetrics(w->font()).height() + 8;
564
565     QString style = "QSlider::groove:horizontal { background-color: rgba(230, 230, 230, 220);border: 1px solid #999999;height: 8px;border-radius: 3px;margin-top:3px }";
566     style.append("QSlider::handle:horizontal {  background-color: white; border: 1px solid #999999;width: 9px;margin: -2px 0;border-radius: 3px; }");
567
568     m_zoomSlider->setStyleSheet(style);
569
570     //m_zoomSlider->height() + 5;
571     statusBar()->setMinimumHeight(contentHeight);
572
573
574     toolbar->addWidget(m_zoomSlider);
575
576     m_buttonVideoThumbs = new KAction(KIcon("kdenlive-show-videothumb"), i18n("Show video thumbnails"), this);
577     toolbar->addAction(m_buttonVideoThumbs);
578     m_buttonVideoThumbs->setCheckable(true);
579     m_buttonVideoThumbs->setChecked(KdenliveSettings::videothumbnails());
580     connect(m_buttonVideoThumbs, SIGNAL(triggered()), this, SLOT(slotSwitchVideoThumbs()));
581
582     m_buttonAudioThumbs = new KAction(KIcon("kdenlive-show-audiothumb"), i18n("Show audio thumbnails"), this);
583     toolbar->addAction(m_buttonAudioThumbs);
584     m_buttonAudioThumbs->setCheckable(true);
585     m_buttonAudioThumbs->setChecked(KdenliveSettings::audiothumbnails());
586     connect(m_buttonAudioThumbs, SIGNAL(triggered()), this, SLOT(slotSwitchAudioThumbs()));
587
588     m_buttonShowMarkers = new KAction(KIcon("kdenlive-show-markers"), i18n("Show markers comments"), this);
589     toolbar->addAction(m_buttonShowMarkers);
590     m_buttonShowMarkers->setCheckable(true);
591     m_buttonShowMarkers->setChecked(KdenliveSettings::showmarkers());
592     connect(m_buttonShowMarkers, SIGNAL(triggered()), this, SLOT(slotSwitchMarkersComments()));
593
594     m_buttonSnap = new KAction(KIcon("kdenlive-snap"), i18n("Snap"), this);
595     toolbar->addAction(m_buttonSnap);
596     m_buttonSnap->setCheckable(true);
597     m_buttonSnap->setChecked(KdenliveSettings::snaptopoints());
598     connect(m_buttonSnap, SIGNAL(triggered()), this, SLOT(slotSwitchSnap()));
599     layout->addWidget(toolbar);
600
601
602     actionWidget = toolbar->widgetForAction(m_buttonVideoThumbs);
603     actionWidget->setMaximumWidth(24);
604     actionWidget->setMinimumHeight(17);
605
606     actionWidget = toolbar->widgetForAction(m_buttonAudioThumbs);
607     actionWidget->setMaximumWidth(24);
608     actionWidget->setMinimumHeight(17);
609
610     actionWidget = toolbar->widgetForAction(m_buttonShowMarkers);
611     actionWidget->setMaximumWidth(24);
612     actionWidget->setMinimumHeight(17);
613
614     actionWidget = toolbar->widgetForAction(m_buttonSnap);
615     actionWidget->setMaximumWidth(24);
616     actionWidget->setMinimumHeight(17);
617
618     m_messageLabel = new StatusBarMessageLabel(this);
619     m_messageLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::MinimumExpanding);
620
621     statusBar()->addWidget(m_messageLabel, 10);
622     statusBar()->addWidget(statusProgressBar, 0);
623     statusBar()->insertPermanentWidget(ID_TIMELINE_BUTTONS, w);
624     statusBar()->insertPermanentFixedItem("00:00:00:00", ID_TIMELINE_POS);
625     statusBar()->insertPermanentWidget(ID_TIMELINE_FORMAT, m_timecodeFormat);
626     statusBar()->setMaximumHeight(statusBar()->font().pointSize() * 4);
627     m_messageLabel->hide();
628
629     collection->addAction("select_tool", m_buttonSelectTool);
630     collection->addAction("razor_tool", m_buttonRazorTool);
631
632     collection->addAction("show_video_thumbs", m_buttonVideoThumbs);
633     collection->addAction("show_audio_thumbs", m_buttonAudioThumbs);
634     collection->addAction("show_markers", m_buttonShowMarkers);
635     collection->addAction("snap", m_buttonSnap);
636     collection->addAction("zoom_fit", m_buttonFitZoom);
637
638     m_projectSearch = new KAction(KIcon("edit-find"), i18n("Find"), this);
639     collection->addAction("project_find", m_projectSearch);
640     connect(m_projectSearch, SIGNAL(triggered(bool)), this, SLOT(slotFind()));
641     m_projectSearch->setShortcut(Qt::Key_Slash);
642
643     m_projectSearchNext = new KAction(KIcon("go-down-search"), i18n("Find Next"), this);
644     collection->addAction("project_find_next", m_projectSearchNext);
645     connect(m_projectSearchNext, SIGNAL(triggered(bool)), this, SLOT(slotFindNext()));
646     m_projectSearchNext->setShortcut(Qt::Key_F3);
647     m_projectSearchNext->setEnabled(false);
648
649     KAction* profilesAction = new KAction(KIcon("document-new"), i18n("Manage Profiles"), this);
650     collection->addAction("manage_profiles", profilesAction);
651     connect(profilesAction, SIGNAL(triggered(bool)), this, SLOT(slotEditProfiles()));
652
653     KAction* projectAction = new KAction(KIcon("configure"), i18n("Project Settings"), this);
654     collection->addAction("project_settings", projectAction);
655     connect(projectAction, SIGNAL(triggered(bool)), this, SLOT(slotEditProjectSettings()));
656
657     KAction* projectRender = new KAction(KIcon("media-record"), i18n("Render"), this);
658     collection->addAction("project_render", projectRender);
659     projectRender->setShortcut(Qt::CTRL + Qt::Key_Return);
660     connect(projectRender, SIGNAL(triggered(bool)), this, SLOT(slotRenderProject()));
661
662     KAction* monitorPlay = new KAction(KIcon("media-playback-start"), i18n("Play"), this);
663     KShortcut playShortcut;
664     playShortcut.setPrimary(Qt::Key_Space);
665     playShortcut.setAlternate(Qt::Key_K);
666     monitorPlay->setShortcut(playShortcut);
667     collection->addAction("monitor_play", monitorPlay);
668     connect(monitorPlay, SIGNAL(triggered(bool)), m_monitorManager, SLOT(slotPlay()));
669
670     KAction *markIn = collection->addAction("mark_in");
671     markIn->setText(i18n("Set In Point"));
672     markIn->setShortcut(Qt::Key_I);
673     connect(markIn, SIGNAL(triggered(bool)), this, SLOT(slotSetInPoint()));
674
675     KAction *markOut = collection->addAction("mark_out");
676     markOut->setText(i18n("Set Out Point"));
677     markOut->setShortcut(Qt::Key_O);
678     connect(markOut, SIGNAL(triggered(bool)), this, SLOT(slotSetOutPoint()));
679
680     KAction* monitorSeekBackward = new KAction(KIcon("media-seek-backward"), i18n("Rewind"), this);
681     monitorSeekBackward->setShortcut(Qt::Key_J);
682     collection->addAction("monitor_seek_backward", monitorSeekBackward);
683     connect(monitorSeekBackward, SIGNAL(triggered(bool)), m_monitorManager, SLOT(slotRewind()));
684
685     KAction* monitorSeekBackwardOneFrame = new KAction(KIcon("media-skip-backward"), i18n("Rewind 1 Frame"), this);
686     monitorSeekBackwardOneFrame->setShortcut(Qt::Key_Left);
687     collection->addAction("monitor_seek_backward-one-frame", monitorSeekBackwardOneFrame);
688     connect(monitorSeekBackwardOneFrame, SIGNAL(triggered(bool)), m_monitorManager, SLOT(slotRewindOneFrame()));
689
690     KAction* monitorSeekSnapBackward = new KAction(KIcon("media-seek-backward"), i18n("Go to Previous Snap Point"), this);
691     monitorSeekSnapBackward->setShortcut(Qt::ALT + Qt::Key_Left);
692     collection->addAction("monitor_seek_snap_backward", monitorSeekSnapBackward);
693     connect(monitorSeekSnapBackward, SIGNAL(triggered(bool)), this, SLOT(slotSnapRewind()));
694
695     KAction* monitorSeekForward = new KAction(KIcon("media-seek-forward"), i18n("Forward"), this);
696     monitorSeekForward->setShortcut(Qt::Key_L);
697     collection->addAction("monitor_seek_forward", monitorSeekForward);
698     connect(monitorSeekForward, SIGNAL(triggered(bool)), m_monitorManager, SLOT(slotForward()));
699
700     KAction* clipStart = new KAction(KIcon("media-seek-backward"), i18n("Go to Clip Start"), this);
701     clipStart->setShortcut(Qt::Key_Home);
702     collection->addAction("seek_clip_start", clipStart);
703     connect(clipStart, SIGNAL(triggered(bool)), this, SLOT(slotClipStart()));
704
705     KAction* clipEnd = new KAction(KIcon("media-seek-forward"), i18n("Go to Clip End"), this);
706     clipEnd->setShortcut(Qt::Key_End);
707     collection->addAction("seek_clip_end", clipEnd);
708     connect(clipEnd, SIGNAL(triggered(bool)), this, SLOT(slotClipEnd()));
709
710     KAction* projectStart = new KAction(KIcon("go-first"), i18n("Go to Project Start"), this);
711     projectStart->setShortcut(Qt::CTRL + Qt::Key_Home);
712     collection->addAction("seek_start", projectStart);
713     connect(projectStart, SIGNAL(triggered(bool)), m_monitorManager, SLOT(slotStart()));
714
715     KAction* projectEnd = new KAction(KIcon("go-last"), i18n("Go to Project End"), this);
716     projectEnd->setShortcut(Qt::CTRL + Qt::Key_End);
717     collection->addAction("seek_end", projectEnd);
718     connect(projectEnd, SIGNAL(triggered(bool)), m_monitorManager, SLOT(slotEnd()));
719
720     KAction* monitorSeekForwardOneFrame = new KAction(KIcon("media-skip-forward"), i18n("Forward 1 Frame"), this);
721     monitorSeekForwardOneFrame->setShortcut(Qt::Key_Right);
722     collection->addAction("monitor_seek_forward-one-frame", monitorSeekForwardOneFrame);
723     connect(monitorSeekForwardOneFrame, SIGNAL(triggered(bool)), m_monitorManager, SLOT(slotForwardOneFrame()));
724
725     KAction* monitorSeekSnapForward = new KAction(KIcon("media-seek-forward"), i18n("Go to Next Snap Point"), this);
726     monitorSeekSnapForward->setShortcut(Qt::ALT + Qt::Key_Right);
727     collection->addAction("monitor_seek_snap_forward", monitorSeekSnapForward);
728     connect(monitorSeekSnapForward, SIGNAL(triggered(bool)), this, SLOT(slotSnapForward()));
729
730     KAction* deleteTimelineClip = new KAction(KIcon("edit-delete"), i18n("Delete Selected Item"), this);
731     deleteTimelineClip->setShortcut(Qt::Key_Delete);
732     collection->addAction("delete_timeline_clip", deleteTimelineClip);
733     connect(deleteTimelineClip, SIGNAL(triggered(bool)), this, SLOT(slotDeleteTimelineClip()));
734
735     KAction* editTimelineClipSpeed = new KAction(i18n("Change Clip Speed"), this);
736     collection->addAction("change_clip_speed", editTimelineClipSpeed);
737     connect(editTimelineClipSpeed, SIGNAL(triggered(bool)), this, SLOT(slotChangeClipSpeed()));
738
739     KAction* cutTimelineClip = new KAction(KIcon("edit-cut"), i18n("Cut Clip"), this);
740     cutTimelineClip->setShortcut(Qt::SHIFT + Qt::Key_R);
741     collection->addAction("cut_timeline_clip", cutTimelineClip);
742     connect(cutTimelineClip, SIGNAL(triggered(bool)), this, SLOT(slotCutTimelineClip()));
743
744     KAction* addClipMarker = new KAction(KIcon("bookmark-new"), i18n("Add Marker"), this);
745     collection->addAction("add_clip_marker", addClipMarker);
746     connect(addClipMarker, SIGNAL(triggered(bool)), this, SLOT(slotAddClipMarker()));
747
748     KAction* deleteClipMarker = new KAction(KIcon("edit-delete"), i18n("Delete Marker"), this);
749     collection->addAction("delete_clip_marker", deleteClipMarker);
750     connect(deleteClipMarker, SIGNAL(triggered(bool)), this, SLOT(slotDeleteClipMarker()));
751
752     KAction* deleteAllClipMarkers = new KAction(KIcon("edit-delete"), i18n("Delete All Markers"), this);
753     collection->addAction("delete_all_clip_markers", deleteAllClipMarkers);
754     connect(deleteAllClipMarkers, SIGNAL(triggered(bool)), this, SLOT(slotDeleteAllClipMarkers()));
755
756     KAction* editClipMarker = new KAction(KIcon("document-properties"), i18n("Edit Marker"), this);
757     collection->addAction("edit_clip_marker", editClipMarker);
758     connect(editClipMarker, SIGNAL(triggered(bool)), this, SLOT(slotEditClipMarker()));
759
760     KAction *addGuide = new KAction(KIcon("document-new"), i18n("Add Guide"), this);
761     collection->addAction("add_guide", addGuide);
762     connect(addGuide, SIGNAL(triggered()), this, SLOT(slotAddGuide()));
763
764     QAction *delGuide = new KAction(KIcon("edit-delete"), i18n("Delete Guide"), this);
765     collection->addAction("delete_guide", delGuide);
766     connect(delGuide, SIGNAL(triggered()), this, SLOT(slotDeleteGuide()));
767
768     QAction *editGuide = new KAction(KIcon("document-properties"), i18n("Edit Guide"), this);
769     collection->addAction("edit_guide", editGuide);
770     connect(editGuide, SIGNAL(triggered()), this, SLOT(slotEditGuide()));
771
772     QAction *delAllGuides = new KAction(KIcon("edit-delete"), i18n("Delete All Guides"), this);
773     collection->addAction("delete_all_guides", delAllGuides);
774     connect(delAllGuides, SIGNAL(triggered()), this, SLOT(slotDeleteAllGuides()));
775
776     QAction *pasteEffects = new KAction(KIcon("edit-paste"), i18n("Paste Effects"), this);
777     collection->addAction("paste_effects", pasteEffects);
778     connect(pasteEffects , SIGNAL(triggered()), this, SLOT(slotPasteEffects()));
779
780     m_closeAction = KStandardAction::close(this, SLOT(closeCurrentDocument()), collection);
781
782     KStandardAction::quit(this, SLOT(queryQuit()), collection);
783
784     KStandardAction::open(this, SLOT(openFile()), collection);
785
786     m_saveAction = KStandardAction::save(this, SLOT(saveFile()), collection);
787
788     KStandardAction::saveAs(this, SLOT(saveFileAs()), collection);
789
790     KStandardAction::openNew(this, SLOT(newFile()), collection);
791
792     KStandardAction::preferences(this, SLOT(slotPreferences()), collection);
793
794     KStandardAction::configureNotifications(this , SLOT(configureNotifications()), collection);
795
796     KStandardAction::copy(this, SLOT(slotCopy()), collection);
797
798     KStandardAction::paste(this, SLOT(slotPaste()), collection);
799
800     KAction *undo = KStandardAction::undo(m_commandStack, SLOT(undo()), collection);
801     undo->setEnabled(false);
802     connect(m_commandStack, SIGNAL(canUndoChanged(bool)), undo, SLOT(setEnabled(bool)));
803
804     KAction *redo = KStandardAction::redo(m_commandStack, SLOT(redo()), collection);
805     redo->setEnabled(false);
806     connect(m_commandStack, SIGNAL(canRedoChanged(bool)), redo, SLOT(setEnabled(bool)));
807
808     KStandardAction::fullScreen(this, SLOT(slotFullScreen()), this, collection);
809
810     connect(collection, SIGNAL(actionHovered(QAction*)),
811             this, SLOT(slotDisplayActionMessage(QAction*)));
812     //connect(collection, SIGNAL( clearStatusText() ),
813     //statusBar(), SLOT( clear() ) );
814 }
815
816 void MainWindow::slotDisplayActionMessage(QAction *a) {
817     statusBar()->showMessage(a->data().toString(), 3000);
818 }
819
820 void MainWindow::saveOptions() {
821     KdenliveSettings::self()->writeConfig();
822     KSharedConfigPtr config = KGlobal::config();
823     m_fileOpenRecent->saveEntries(KConfigGroup(config, "Recent Files"));
824     config->sync();
825 }
826
827 void MainWindow::readOptions() {
828     KSharedConfigPtr config = KGlobal::config();
829     m_fileOpenRecent->loadEntries(KConfigGroup(config, "Recent Files"));
830     KConfigGroup initialGroup(config, "version");
831     if (!initialGroup.exists()) {
832         // this is our first run, show Wizard
833         Wizard *w = new Wizard(this);
834         if (w->exec() == QDialog::Accepted && w->isOk()) {
835             w->adjustSettings();
836             initialGroup.writeEntry("version", "0.7");
837             delete w;
838         } else {
839             ::exit(1);
840         }
841     }
842 }
843
844 void MainWindow::newFile(bool showProjectSettings) {
845     QString profileName;
846     KUrl projectFolder;
847     QPoint projectTracks(3, 2);
848     if (!showProjectSettings && m_timelineArea->count() == 0) {
849         if (!KdenliveSettings::activatetabs()) closeCurrentDocument();
850         profileName = KdenliveSettings::default_profile();
851     } else {
852         ProjectSettings *w = new ProjectSettings;
853         if (w->exec() != QDialog::Accepted) return;
854         if (!KdenliveSettings::activatetabs()) closeCurrentDocument();
855         profileName = w->selectedProfile();
856         projectFolder = w->selectedFolder();
857         projectTracks = w->tracks();
858         delete w;
859     }
860     KdenliveDoc *doc = new KdenliveDoc(KUrl(), projectFolder, m_commandStack, profileName, projectTracks,  this);
861     doc->m_autosave = new KAutoSaveFile(KUrl(), doc);
862     TrackView *trackView = new TrackView(doc, this);
863     m_timelineArea->addTab(trackView, KIcon("kdenlive"), doc->description());
864     if (m_timelineArea->count() == 1) {
865         connectDocumentInfo(doc);
866         connectDocument(trackView, doc);
867     } else m_timelineArea->setTabBarHidden(false);
868     m_closeAction->setEnabled(m_timelineArea->count() > 1);
869 }
870
871 void MainWindow::activateDocument() {
872     if (m_timelineArea->currentWidget() == NULL) return;
873     TrackView *currentTab = (TrackView *) m_timelineArea->currentWidget();
874     KdenliveDoc *currentDoc = currentTab->document();
875     connectDocumentInfo(currentDoc);
876     connectDocument(currentTab, currentDoc);
877 }
878
879 void MainWindow::closeCurrentDocument() {
880     QWidget *w = m_timelineArea->currentWidget();
881     if (!w) return;
882     // closing current document
883     int ix = m_timelineArea->currentIndex() + 1;
884     if (ix == m_timelineArea->count()) ix = 0;
885     m_timelineArea->setCurrentIndex(ix);
886     TrackView *tabToClose = (TrackView *) w;
887     KdenliveDoc *docToClose = tabToClose->document();
888     if (docToClose && docToClose->isModified()) {
889         switch (KMessageBox::warningYesNoCancel(this, i18n("Save changes to document ?"))) {
890         case KMessageBox::Yes :
891             // save document here. If saving fails, return false;
892             saveFile();
893             break;
894         case KMessageBox::Cancel :
895             return;
896         default:
897             break;
898         }
899     }
900     m_timelineArea->removeTab(m_timelineArea->indexOf(w));
901     if (m_timelineArea->count() == 1) m_timelineArea->setTabBarHidden(true);
902     delete docToClose;
903     delete w;
904     if (m_timelineArea->count() == 0) {
905         m_activeDocument = NULL;
906         effectStack->clear();
907         transitionConfig->slotTransitionItemSelected(NULL);
908     }
909 }
910
911 void MainWindow::saveFileAs(const QString &outputFileName) {
912     m_projectMonitor->saveSceneList(outputFileName, m_activeDocument->documentInfoXml());
913     m_activeDocument->setUrl(KUrl(outputFileName));
914     if (m_activeDocument->m_autosave == NULL) {
915         m_activeDocument->m_autosave = new KAutoSaveFile(KUrl(outputFileName), this);
916     } else m_activeDocument->m_autosave->setManagedFile(KUrl(outputFileName));
917     setCaption(m_activeDocument->description());
918     m_timelineArea->setTabText(m_timelineArea->currentIndex(), m_activeDocument->description());
919     m_timelineArea->setTabToolTip(m_timelineArea->currentIndex(), m_activeDocument->url().path());
920     m_activeDocument->setModified(false);
921     m_fileOpenRecent->addUrl(KUrl(outputFileName));
922 }
923
924 void MainWindow::saveFileAs() {
925     QString outputFile = KFileDialog::getSaveFileName(KUrl(), "*.kdenlive|Kdenlive project files (*.kdenlive)");
926     if (QFile::exists(outputFile)) {
927         if (KMessageBox::questionYesNo(this, i18n("File already exists.\nDo you want to overwrite it ?")) == KMessageBox::No) return;
928     }
929     saveFileAs(outputFile);
930 }
931
932 void MainWindow::saveFile() {
933     if (!m_activeDocument) return;
934     if (m_activeDocument->url().isEmpty()) {
935         saveFileAs();
936     } else {
937         saveFileAs(m_activeDocument->url().path());
938         m_activeDocument->m_autosave->resize(0);
939     }
940 }
941
942 void MainWindow::openFile() {
943     KUrl url = KFileDialog::getOpenUrl(KUrl(), "*.kdenlive|Kdenlive project files (*.kdenlive)\n*.westley|MLT project files (*.westley)");
944     if (url.isEmpty()) return;
945     m_fileOpenRecent->addUrl(url);
946     openFile(url);
947 }
948
949 void MainWindow::openLastFile() {
950     KSharedConfigPtr config = KGlobal::config();
951     KUrl::List urls = m_fileOpenRecent->urls();
952     if (urls.isEmpty()) newFile(false);
953     else openFile(urls.last());
954 }
955
956 void MainWindow::openFile(const KUrl &url) {
957     // Check if the document is already opened
958     const int ct = m_timelineArea->count();
959     bool isOpened = false;
960     int i;
961     for (i = 0; i < ct; i++) {
962         TrackView *tab = (TrackView *) m_timelineArea->widget(i);
963         KdenliveDoc *doc = tab->document();
964         if (doc->url() == url) {
965             isOpened = true;
966             break;
967         }
968     }
969     if (isOpened) {
970         m_timelineArea->setCurrentIndex(i);
971         return;
972     }
973
974     // Check for backup file
975     QList<KAutoSaveFile *> staleFiles = KAutoSaveFile::staleFiles(url);
976     if (!staleFiles.isEmpty()) {
977         if (KMessageBox::questionYesNo(this,
978                                        i18n("Auto-saved files exist. Do you want to recover them now?"),
979                                        i18n("File Recovery"),
980                                        KGuiItem(i18n("Recover")), KGuiItem(i18n("Don't recover"))) == KMessageBox::Yes) {
981             recoverFiles(staleFiles);
982             return;
983         } else {
984             // remove the stale files
985             foreach(KAutoSaveFile *stale, staleFiles) {
986                 stale->open(QIODevice::ReadWrite);
987                 delete stale;
988             }
989         }
990     }
991     if (!KdenliveSettings::activatetabs()) closeCurrentDocument();
992     doOpenFile(url, NULL);
993 }
994
995 void MainWindow::doOpenFile(const KUrl &url, KAutoSaveFile *stale) {
996     KdenliveDoc *doc;
997     doc = new KdenliveDoc(url, KUrl(), m_commandStack, QString(), QPoint(3, 2), this);
998     if (stale == NULL) {
999         stale = new KAutoSaveFile(url, doc);
1000         doc->m_autosave = stale;
1001     } else {
1002         doc->m_autosave = stale;
1003         doc->setUrl(stale->managedFile());
1004         doc->setModified(true);
1005         stale->setParent(doc);
1006     }
1007     connectDocumentInfo(doc);
1008     TrackView *trackView = new TrackView(doc, this);
1009     m_timelineArea->setCurrentIndex(m_timelineArea->addTab(trackView, KIcon("kdenlive"), doc->description()));
1010     m_timelineArea->setTabToolTip(m_timelineArea->currentIndex(), doc->url().path());
1011     if (m_timelineArea->count() > 1) m_timelineArea->setTabBarHidden(false);
1012     slotGotProgressInfo(QString(), -1);
1013     m_clipMonitor->refreshMonitor(true);
1014 }
1015
1016 void MainWindow::recoverFiles(QList<KAutoSaveFile *> staleFiles) {
1017     if (!KdenliveSettings::activatetabs()) closeCurrentDocument();
1018     foreach(KAutoSaveFile *stale, staleFiles) {
1019         /*if (!stale->open(QIODevice::QIODevice::ReadOnly)) {
1020                   // show an error message; we could not steal the lockfile
1021                   // maybe another application got to the file before us?
1022                   delete stale;
1023                   continue;
1024         }*/
1025         kDebug() << "// OPENING RECOVERY: " << stale->fileName() << "\nMANAGED: " << stale->managedFile().path();
1026         // the stalefiles also contain ".lock" files so we must ignore them... bug in KAutoSaveFile ?
1027         if (!stale->fileName().endsWith(".lock")) doOpenFile(KUrl(stale->fileName()), stale);
1028         else KIO::NetAccess::del(KUrl(stale->fileName()), this);
1029     }
1030 }
1031
1032
1033 void MainWindow::parseProfiles(const QString &mltPath) {
1034     //kdDebug()<<" + + YOUR MLT INSTALL WAS FOUND IN: "<< MLT_PREFIX <<endl;
1035
1036     //KdenliveSettings::setDefaulttmpfolder();
1037     if (!mltPath.isEmpty()) {
1038         KdenliveSettings::setMltpath(mltPath + "/share/mlt/profiles/");
1039         KdenliveSettings::setRendererpath(mltPath + "/bin/inigo");
1040     }
1041
1042     if (KdenliveSettings::mltpath().isEmpty()) {
1043         KdenliveSettings::setMltpath(QString(MLT_PREFIX) + QString("/share/mlt/profiles/"));
1044     }
1045     if (KdenliveSettings::rendererpath().isEmpty()) {
1046         QString inigoPath = QString(MLT_PREFIX) + QString("/bin/inigo");
1047         if (!QFile::exists(inigoPath))
1048             inigoPath = KStandardDirs::findExe("inigo");
1049         else KdenliveSettings::setRendererpath(inigoPath);
1050     }
1051     QStringList profilesFilter;
1052     profilesFilter << "*";
1053     QStringList profilesList = QDir(KdenliveSettings::mltpath()).entryList(profilesFilter, QDir::Files);
1054
1055     if (profilesList.isEmpty()) {
1056         // Cannot find MLT path, try finding inigo
1057         QString profilePath = KdenliveSettings::rendererpath();
1058         if (!profilePath.isEmpty()) {
1059             profilePath = profilePath.section('/', 0, -3);
1060             KdenliveSettings::setMltpath(profilePath + "/share/mlt/profiles/");
1061             QStringList profilesList = QDir(KdenliveSettings::mltpath()).entryList(profilesFilter, QDir::Files);
1062         }
1063
1064         if (profilesList.isEmpty()) {
1065             // Cannot find the MLT profiles, ask for location
1066             KUrlRequesterDialog *getUrl = new KUrlRequesterDialog(KdenliveSettings::mltpath(), i18n("Cannot find your Mlt profiles, please give the path"), this);
1067             getUrl->fileDialog()->setMode(KFile::Directory);
1068             if (getUrl->exec() == QDialog::Rejected) {
1069                 ::exit(0);
1070             }
1071             KUrl mltPath = getUrl->selectedUrl();
1072             delete getUrl;
1073             if (mltPath.isEmpty()) ::exit(0);
1074             KdenliveSettings::setMltpath(mltPath.path());
1075             QStringList profilesList = QDir(KdenliveSettings::mltpath()).entryList(profilesFilter, QDir::Files);
1076         }
1077     }
1078
1079     if (KdenliveSettings::rendererpath().isEmpty()) {
1080         // Cannot find the MLT inigo renderer, ask for location
1081         KUrlRequesterDialog *getUrl = new KUrlRequesterDialog(QString(), i18n("Cannot find the inigo program required for rendering (part of Mlt)"), this);
1082         if (getUrl->exec() == QDialog::Rejected) {
1083             ::exit(0);
1084         }
1085         KUrl rendererPath = getUrl->selectedUrl();
1086         delete getUrl;
1087         if (rendererPath.isEmpty()) ::exit(0);
1088         KdenliveSettings::setRendererpath(rendererPath.path());
1089     }
1090
1091     kDebug() << "RESULTING MLT PATH: " << KdenliveSettings::mltpath();
1092
1093     // Parse MLT profiles to build a list of available video formats
1094     if (profilesList.isEmpty()) parseProfiles();
1095 }
1096
1097
1098 void MainWindow::slotEditProfiles() {
1099     ProfilesDialog *w = new ProfilesDialog;
1100     w->exec();
1101     delete w;
1102 }
1103
1104 void MainWindow::slotEditProjectSettings() {
1105     ProjectSettings *w = new ProjectSettings;
1106     if (w->exec() == QDialog::Accepted) {
1107         QString profile = w->selectedProfile();
1108         m_activeDocument->setProfilePath(profile);
1109         KdenliveSettings::setCurrent_profile(profile);
1110         KdenliveSettings::setProject_fps(m_activeDocument->fps());
1111         setCaption(m_activeDocument->description(), m_activeDocument->isModified());
1112         m_monitorManager->resetProfiles(m_activeDocument->timecode());
1113         if (m_renderWidget) m_renderWidget->setDocumentStandard(m_activeDocument->getDocumentStandard());
1114         m_timelineArea->setTabText(m_timelineArea->currentIndex(), m_activeDocument->description());
1115
1116         // We need to desactivate & reactivate monitors to get a refresh
1117         m_monitorManager->switchMonitors();
1118     }
1119     delete w;
1120 }
1121
1122 void MainWindow::slotRenderProject() {
1123     if (!m_renderWidget) {
1124         m_renderWidget = new RenderWidget(this);
1125         connect(m_renderWidget, SIGNAL(doRender(const QString&, const QString&, const QStringList &, const QStringList &, bool, bool, double, double)), this, SLOT(slotDoRender(const QString&, const QString&, const QStringList &, const QStringList &, bool, bool, double, double)));
1126         if (m_activeDocument) m_renderWidget->setGuides(m_activeDocument->guidesXml(), m_activeDocument->projectDuration());
1127     }
1128     /*TrackView *currentTab = (TrackView *) m_timelineArea->currentWidget();
1129     if (currentTab) m_renderWidget->setTimeline(currentTab);
1130     m_renderWidget->setDocument(m_activeDocument);*/
1131     m_renderWidget->show();
1132 }
1133
1134 void MainWindow::slotDoRender(const QString &dest, const QString &render, const QStringList &overlay_args, const QStringList &avformat_args, bool zoneOnly, bool playAfter, double guideStart, double guideEnd) {
1135     if (dest.isEmpty()) return;
1136     int in;
1137     int out;
1138     TrackView *currentTab = (TrackView *) m_timelineArea->currentWidget();
1139     if (currentTab && zoneOnly) {
1140         in = currentTab->inPoint();
1141         out = currentTab->outPoint();
1142     }
1143     KTemporaryFile temp;
1144     temp.setAutoRemove(false);
1145     temp.setSuffix(".westley");
1146     if (temp.open()) {
1147         m_projectMonitor->saveSceneList(temp.fileName());
1148         QStringList args;
1149         args << "-erase";
1150         if (zoneOnly) args << "in=" + QString::number(in) << "out=" + QString::number(out);
1151         else if (guideStart != -1) {
1152             args << "in=" + QString::number(GenTime(guideStart).frames(m_activeDocument->fps())) << "out=" + QString::number(GenTime(guideEnd).frames(m_activeDocument->fps()));
1153         }
1154         if (!overlay_args.isEmpty()) args << "preargs=" + overlay_args.join(" ");
1155         QString videoPlayer = "-";
1156         if (playAfter) {
1157             videoPlayer = KdenliveSettings::defaultplayerapp();
1158             if (videoPlayer.isEmpty()) KMessageBox::sorry(this, i18n("Cannot play video after rendering because the default video player application is not set.\nPlease define it in Kdenlive settings dialog."));
1159         }
1160         if (!QFile::exists(KdenliveSettings::rendererpath())) {
1161             KMessageBox::sorry(this, i18n("Cannot find the inigo program required for rendering (part of Mlt)"));
1162             return;
1163         }
1164         args << KdenliveSettings::rendererpath() << m_activeDocument->profilePath() << render << videoPlayer << temp.fileName() << dest << avformat_args;
1165         QString renderer = QCoreApplication::applicationDirPath() + QString("/kdenlive_render");
1166         if (!QFile::exists(renderer)) renderer = "kdenlive_render";
1167         QProcess::startDetached(renderer, args);
1168
1169         KNotification::event("RenderStarted", i18n("Rendering <i>%1</i> started", dest), QPixmap(), this);
1170     }
1171 }
1172
1173 void MainWindow::slotUpdateMousePosition(int pos) {
1174     if (m_activeDocument)
1175         switch (m_timecodeFormat->currentIndex()) {
1176         case 0:
1177             statusBar()->changeItem(m_activeDocument->timecode().getTimecodeFromFrames(pos), ID_TIMELINE_POS);
1178             break;
1179         default:
1180             statusBar()->changeItem(QString::number(pos), ID_TIMELINE_POS);
1181         }
1182 }
1183
1184 void MainWindow::slotUpdateDocumentState(bool modified) {
1185     setCaption(m_activeDocument->description(), modified);
1186     m_saveAction->setEnabled(modified);
1187     if (modified) {
1188         m_timelineArea->setTabTextColor(m_timelineArea->currentIndex(), palette().color(QPalette::Link));
1189         m_timelineArea->setTabIcon(m_timelineArea->currentIndex(), KIcon("document-save"));
1190     } else {
1191         m_timelineArea->setTabTextColor(m_timelineArea->currentIndex(), palette().color(QPalette::Text));
1192         m_timelineArea->setTabIcon(m_timelineArea->currentIndex(), KIcon("kdenlive"));
1193     }
1194 }
1195
1196 void MainWindow::connectDocumentInfo(KdenliveDoc *doc) {
1197     if (m_activeDocument) {
1198         if (m_activeDocument == doc) return;
1199         disconnect(m_activeDocument, SIGNAL(progressInfo(const QString &, int)), this, SLOT(slotGotProgressInfo(const QString &, int)));
1200     }
1201     connect(doc, SIGNAL(progressInfo(const QString &, int)), this, SLOT(slotGotProgressInfo(const QString &, int)));
1202 }
1203
1204 void MainWindow::connectDocument(TrackView *trackView, KdenliveDoc *doc) { //changed
1205     //m_projectMonitor->stop();
1206     m_closeAction->setEnabled(m_timelineArea->count() > 1);
1207     kDebug() << "///////////////////   CONNECTING DOC TO PROJECT VIEW ////////////////";
1208     if (m_activeDocument) {
1209         if (m_activeDocument == doc) return;
1210         m_activeDocument->backupMltPlaylist();
1211         if (m_activeTimeline) {
1212             disconnect(m_projectMonitor, SIGNAL(renderPosition(int)), m_activeTimeline, SLOT(moveCursorPos(int)));
1213             disconnect(m_projectMonitor, SIGNAL(zoneUpdated(QPoint)), m_activeTimeline, SLOT(slotSetZone(QPoint)));
1214             disconnect(m_projectMonitor, SIGNAL(durationChanged(int)), m_activeTimeline, SLOT(setDuration(int)));
1215             disconnect(m_projectList, SIGNAL(projectModified()), m_activeDocument, SLOT(setModified()));
1216             disconnect(m_activeDocument, SIGNAL(guidesUpdated()), this, SLOT(slotGuidesUpdated()));
1217             disconnect(m_activeDocument, SIGNAL(addProjectClip(DocClipBase *)), m_projectList, SLOT(slotAddClip(DocClipBase *)));
1218             disconnect(m_activeDocument, SIGNAL(addProjectFolder(const QString, const QString &, bool, bool)), m_projectList, SLOT(slotAddFolder(const QString, const QString &, bool, bool)));
1219             disconnect(m_activeDocument, SIGNAL(signalDeleteProjectClip(const QString &)), m_projectList, SLOT(slotDeleteClip(const QString &)));
1220             disconnect(m_activeDocument, SIGNAL(updateClipDisplay(const QString &)), m_projectList, SLOT(slotUpdateClip(const QString &)));
1221             disconnect(m_activeDocument, SIGNAL(selectLastAddedClip(const QString &)), m_projectList, SLOT(slotSelectClip(const QString &)));
1222             disconnect(m_activeDocument, SIGNAL(deleteTimelineClip(const QString &)), m_activeTimeline, SLOT(slotDeleteClip(const QString &)));
1223             disconnect(m_activeTimeline, SIGNAL(clipItemSelected(ClipItem*)), effectStack, SLOT(slotClipItemSelected(ClipItem*)));
1224             disconnect(m_activeTimeline, SIGNAL(clipItemSelected(ClipItem*)), this, SLOT(slotActivateEffectStackView()));
1225             disconnect(m_activeTimeline, SIGNAL(transitionItemSelected(Transition*)), transitionConfig, SLOT(slotTransitionItemSelected(Transition*)));
1226             disconnect(m_activeTimeline, SIGNAL(transitionItemSelected(Transition*)), this, SLOT(slotActivateTransitionView()));
1227             disconnect(m_zoomSlider, SIGNAL(valueChanged(int)), m_activeTimeline, SLOT(slotChangeZoom(int)));
1228             disconnect(m_activeTimeline->projectView(), SIGNAL(displayMessage(const QString&, MessageType)), m_messageLabel, SLOT(setMessage(const QString&, MessageType)));
1229             disconnect(m_activeTimeline->projectView(), SIGNAL(showClipFrame(DocClipBase *, const int)), m_clipMonitor, SLOT(slotSetXml(DocClipBase *, const int)));
1230
1231             disconnect(m_activeDocument, SIGNAL(docModified(bool)), this, SLOT(slotUpdateDocumentState(bool)));
1232             disconnect(effectStack, SIGNAL(updateClipEffect(ClipItem*, QDomElement, QDomElement, int)), m_activeTimeline->projectView(), SLOT(slotUpdateClipEffect(ClipItem*, QDomElement, QDomElement, int)));
1233             disconnect(effectStack, SIGNAL(removeEffect(ClipItem*, QDomElement)), m_activeTimeline->projectView(), SLOT(slotDeleteEffect(ClipItem*, QDomElement)));
1234             disconnect(effectStack, SIGNAL(changeEffectState(ClipItem*, int, bool)), m_activeTimeline->projectView(), SLOT(slotChangeEffectState(ClipItem*, int, bool)));
1235             disconnect(effectStack, SIGNAL(changeEffectPosition(ClipItem*, int, int)), m_activeTimeline->projectView(), SLOT(slotChangeEffectPosition(ClipItem*, int, int)));
1236             disconnect(effectStack, SIGNAL(refreshEffectStack(ClipItem*)), m_activeTimeline->projectView(), SLOT(slotRefreshEffects(ClipItem*)));
1237             disconnect(effectStack, SIGNAL(reloadEffects()), this, SLOT(slotReloadEffects()));
1238             disconnect(transitionConfig, SIGNAL(transitionUpdated(Transition *, QDomElement)), m_activeTimeline->projectView() , SLOT(slotTransitionUpdated(Transition *, QDomElement)));
1239             disconnect(transitionConfig, SIGNAL(seekTimeline(int)), m_activeTimeline->projectView() , SLOT(setCursorPos(int)));
1240             disconnect(m_activeTimeline->projectView(), SIGNAL(activateDocumentMonitor()), m_projectMonitor, SLOT(activateMonitor()));
1241             disconnect(m_activeTimeline, SIGNAL(zoneMoved(int, int)), m_projectMonitor, SLOT(slotZoneMoved(int, int)));
1242             disconnect(m_projectList, SIGNAL(loadingIsOver()), m_activeTimeline->projectView(), SLOT(slotUpdateAllThumbs()));
1243             effectStack->clear();
1244         }
1245         m_activeDocument->setRenderer(NULL);
1246         disconnect(m_projectList, SIGNAL(clipSelected(DocClipBase *)), m_clipMonitor, SLOT(slotSetXml(DocClipBase *)));
1247         m_clipMonitor->stop();
1248     }
1249     KdenliveSettings::setCurrent_profile(doc->profilePath());
1250     KdenliveSettings::setProject_fps(doc->fps());
1251     m_monitorManager->resetProfiles(doc->timecode());
1252     m_projectList->setDocument(doc);
1253     transitionConfig->updateProjectFormat(doc->mltProfile());
1254     effectStack->updateProjectFormat(doc->mltProfile());
1255     connect(m_projectList, SIGNAL(clipSelected(DocClipBase *)), m_clipMonitor, SLOT(slotSetXml(DocClipBase *)));
1256     connect(m_projectList, SIGNAL(projectModified()), doc, SLOT(setModified()));
1257     connect(trackView, SIGNAL(cursorMoved()), m_projectMonitor, SLOT(activateMonitor()));
1258     connect(trackView, SIGNAL(mousePosition(int)), this, SLOT(slotUpdateMousePosition(int)));
1259     connect(m_projectMonitor, SIGNAL(renderPosition(int)), trackView, SLOT(moveCursorPos(int)));
1260     connect(m_projectMonitor, SIGNAL(zoneUpdated(QPoint)), trackView, SLOT(slotSetZone(QPoint)));
1261     connect(m_projectMonitor, SIGNAL(durationChanged(int)), trackView, SLOT(setDuration(int)));
1262     connect(doc, SIGNAL(addProjectClip(DocClipBase *)), m_projectList, SLOT(slotAddClip(DocClipBase *)));
1263     connect(doc, SIGNAL(addProjectFolder(const QString, const QString &, bool, bool)), m_projectList, SLOT(slotAddFolder(const QString, const QString &, bool, bool)));
1264     connect(doc, SIGNAL(signalDeleteProjectClip(const QString &)), m_projectList, SLOT(slotDeleteClip(const QString &)));
1265     connect(doc, SIGNAL(updateClipDisplay(const QString &)), m_projectList, SLOT(slotUpdateClip(const QString &)));
1266     connect(doc, SIGNAL(selectLastAddedClip(const QString &)), m_projectList, SLOT(slotSelectClip(const QString &)));
1267
1268     connect(doc, SIGNAL(deleteTimelineClip(const QString &)), trackView, SLOT(slotDeleteClip(const QString &)));
1269     connect(doc, SIGNAL(docModified(bool)), this, SLOT(slotUpdateDocumentState(bool)));
1270     connect(doc, SIGNAL(guidesUpdated()), this, SLOT(slotGuidesUpdated()));
1271
1272
1273     connect(trackView, SIGNAL(clipItemSelected(ClipItem*)), effectStack, SLOT(slotClipItemSelected(ClipItem*)));
1274     connect(trackView, SIGNAL(clipItemSelected(ClipItem*)), this, SLOT(slotActivateEffectStackView()));
1275     connect(trackView, SIGNAL(transitionItemSelected(Transition*)), transitionConfig, SLOT(slotTransitionItemSelected(Transition*)));
1276     connect(trackView, SIGNAL(transitionItemSelected(Transition*)), this, SLOT(slotActivateTransitionView()));
1277     m_zoomSlider->setValue(doc->zoom());
1278     connect(m_zoomSlider, SIGNAL(valueChanged(int)), trackView, SLOT(slotChangeZoom(int)));
1279     connect(trackView->projectView(), SIGNAL(zoomIn()), this, SLOT(slotZoomIn()));
1280     connect(trackView->projectView(), SIGNAL(zoomOut()), this, SLOT(slotZoomOut()));
1281     connect(trackView->projectView(), SIGNAL(displayMessage(const QString&, MessageType)), m_messageLabel, SLOT(setMessage(const QString&, MessageType)));
1282
1283     connect(trackView->projectView(), SIGNAL(showClipFrame(DocClipBase *, const int)), m_clipMonitor, SLOT(slotSetXml(DocClipBase *, const int)));
1284
1285
1286     connect(effectStack, SIGNAL(updateClipEffect(ClipItem*, QDomElement, QDomElement, int)), trackView->projectView(), SLOT(slotUpdateClipEffect(ClipItem*, QDomElement, QDomElement, int)));
1287     connect(effectStack, SIGNAL(removeEffect(ClipItem*, QDomElement)), trackView->projectView(), SLOT(slotDeleteEffect(ClipItem*, QDomElement)));
1288     connect(effectStack, SIGNAL(changeEffectState(ClipItem*, int, bool)), trackView->projectView(), SLOT(slotChangeEffectState(ClipItem*, int, bool)));
1289     connect(effectStack, SIGNAL(changeEffectPosition(ClipItem*, int, int)), trackView->projectView(), SLOT(slotChangeEffectPosition(ClipItem*, int, int)));
1290     connect(effectStack, SIGNAL(refreshEffectStack(ClipItem*)), trackView->projectView(), SLOT(slotRefreshEffects(ClipItem*)));
1291     connect(transitionConfig, SIGNAL(transitionUpdated(Transition *, QDomElement)), trackView->projectView() , SLOT(slotTransitionUpdated(Transition *, QDomElement)));
1292     connect(transitionConfig, SIGNAL(seekTimeline(int)), trackView->projectView() , SLOT(setCursorPos(int)));
1293     connect(effectStack, SIGNAL(reloadEffects()), this, SLOT(slotReloadEffects()));
1294
1295     connect(trackView->projectView(), SIGNAL(activateDocumentMonitor()), m_projectMonitor, SLOT(activateMonitor()));
1296     connect(trackView, SIGNAL(zoneMoved(int, int)), m_projectMonitor, SLOT(slotZoneMoved(int, int)));
1297     connect(m_projectList, SIGNAL(loadingIsOver()), trackView->projectView(), SLOT(slotUpdateAllThumbs()));
1298
1299     trackView->projectView()->setContextMenu(m_timelineContextMenu, m_timelineContextClipMenu, m_timelineContextTransitionMenu);
1300     m_activeTimeline = trackView;
1301     if (m_renderWidget) m_renderWidget->setDocumentStandard(doc->getDocumentStandard());
1302     doc->setRenderer(m_projectMonitor->render);
1303     m_commandStack->setActiveStack(doc->commandStack());
1304     KdenliveSettings::setProject_display_ratio(doc->dar());
1305     m_projectList->updateAllClips();
1306     //doc->clipManager()->checkAudioThumbs();
1307
1308     //m_overView->setScene(trackView->projectScene());
1309     //m_overView->scale(m_overView->width() / trackView->duration(), m_overView->height() / (50 * trackView->tracksNumber()));
1310     //m_overView->fitInView(m_overView->itemAt(0, 50), Qt::KeepAspectRatio);
1311
1312     setCaption(doc->description(), doc->isModified());
1313     m_saveAction->setEnabled(doc->isModified());
1314     m_activeDocument = doc;
1315 }
1316
1317 void MainWindow::slotGuidesUpdated() {
1318     if (m_renderWidget) m_renderWidget->setGuides(m_activeDocument->guidesXml(), m_activeDocument->projectDuration());
1319 }
1320
1321 void MainWindow::slotPreferences(int page, int option) {
1322     //An instance of your dialog could be already created and could be
1323     // cached, in which case you want to display the cached dialog
1324     // instead of creating another one
1325     if (KConfigDialog::showDialog("settings")) {
1326         if (page != -1) static_cast <KdenliveSettingsDialog*>(KConfigDialog::exists("settings"))->showPage(page, option);
1327         return;
1328     }
1329
1330     // KConfigDialog didn't find an instance of this dialog, so lets
1331     // create it :
1332     KdenliveSettingsDialog* dialog = new KdenliveSettingsDialog(this);
1333     connect(dialog, SIGNAL(settingsChanged(const QString&)), this, SLOT(updateConfiguration()));
1334     connect(dialog, SIGNAL(doResetProfile()), m_monitorManager, SLOT(slotResetProfiles()));
1335     dialog->show();
1336     if (page != -1) dialog->showPage(page, option);
1337 }
1338
1339 void MainWindow::updateConfiguration() {
1340     //TODO: we should apply settings to all projects, not only the current one
1341     if (m_activeTimeline) {
1342         m_activeTimeline->refresh();
1343         m_activeTimeline->projectView()->checkAutoScroll();
1344         m_activeTimeline->projectView()->checkTrackHeight();
1345         if (m_activeDocument) m_activeDocument->clipManager()->checkAudioThumbs();
1346     }
1347     m_buttonAudioThumbs->setChecked(KdenliveSettings::audiothumbnails());
1348     m_buttonVideoThumbs->setChecked(KdenliveSettings::videothumbnails());
1349     activateShuttleDevice();
1350
1351 }
1352
1353 void MainWindow::slotSwitchVideoThumbs() {
1354     KdenliveSettings::setVideothumbnails(!KdenliveSettings::videothumbnails());
1355     if (m_activeTimeline) {
1356         m_activeTimeline->refresh();
1357     }
1358     m_buttonVideoThumbs->setChecked(KdenliveSettings::videothumbnails());
1359 }
1360
1361 void MainWindow::slotSwitchAudioThumbs() {
1362     KdenliveSettings::setAudiothumbnails(!KdenliveSettings::audiothumbnails());
1363     if (m_activeTimeline) {
1364         m_activeTimeline->refresh();
1365         m_activeTimeline->projectView()->checkAutoScroll();
1366         if (m_activeDocument) m_activeDocument->clipManager()->checkAudioThumbs();
1367     }
1368     m_buttonAudioThumbs->setChecked(KdenliveSettings::audiothumbnails());
1369 }
1370
1371 void MainWindow::slotSwitchMarkersComments() {
1372     KdenliveSettings::setShowmarkers(!KdenliveSettings::showmarkers());
1373     if (m_activeTimeline) {
1374         m_activeTimeline->refresh();
1375     }
1376     m_buttonShowMarkers->setChecked(KdenliveSettings::showmarkers());
1377 }
1378
1379 void MainWindow::slotSwitchSnap() {
1380     KdenliveSettings::setSnaptopoints(!KdenliveSettings::snaptopoints());
1381     m_buttonSnap->setChecked(KdenliveSettings::snaptopoints());
1382 }
1383
1384
1385 void MainWindow::slotDeleteTimelineClip() {
1386     if (QApplication::focusWidget()->parentWidget()->parentWidget() == projectListDock) m_projectList->slotRemoveClip();
1387     else if (m_activeTimeline) {
1388         m_activeTimeline->projectView()->deleteSelectedClips();
1389     }
1390 }
1391
1392 void MainWindow::slotChangeClipSpeed() {
1393     if (m_activeTimeline) {
1394         m_activeTimeline->projectView()->changeClipSpeed();
1395     }
1396 }
1397
1398 void MainWindow::slotAddClipMarker() {
1399     if (m_activeTimeline) {
1400         m_activeTimeline->projectView()->slotAddClipMarker();
1401     }
1402 }
1403
1404 void MainWindow::slotDeleteClipMarker() {
1405     if (m_activeTimeline) {
1406         m_activeTimeline->projectView()->slotDeleteClipMarker();
1407     }
1408 }
1409
1410 void MainWindow::slotDeleteAllClipMarkers() {
1411     if (m_activeTimeline) {
1412         m_activeTimeline->projectView()->slotDeleteAllClipMarkers();
1413     }
1414 }
1415
1416 void MainWindow::slotEditClipMarker() {
1417     if (m_activeTimeline) {
1418         m_activeTimeline->projectView()->slotEditClipMarker();
1419     }
1420 }
1421
1422 void MainWindow::slotAddGuide() {
1423     if (m_activeTimeline)
1424         m_activeTimeline->projectView()->slotAddGuide();
1425 }
1426
1427 void MainWindow::slotEditGuide() {
1428     if (m_activeTimeline)
1429         m_activeTimeline->projectView()->slotEditGuide();
1430 }
1431
1432 void MainWindow::slotDeleteGuide() {
1433     if (m_activeTimeline)
1434         m_activeTimeline->projectView()->slotDeleteGuide();
1435 }
1436
1437 void MainWindow::slotDeleteAllGuides() {
1438     if (m_activeTimeline)
1439         m_activeTimeline->projectView()->slotDeleteAllGuides();
1440 }
1441
1442 void MainWindow::slotCutTimelineClip() {
1443     if (m_activeTimeline) {
1444         m_activeTimeline->projectView()->cutSelectedClips();
1445     }
1446 }
1447
1448 void MainWindow::slotAddProjectClip(KUrl url) {
1449     if (m_activeDocument)
1450         m_activeDocument->slotAddClipFile(url, QString());
1451 }
1452
1453 void MainWindow::slotAddTransition(QAction *result) {
1454     if (!result) return;
1455     QDomElement effect = transitions.getEffectByName(result->data().toString());
1456     if (m_activeTimeline) {
1457         m_activeTimeline->projectView()->slotAddTransitionToSelectedClips(effect);
1458     }
1459 }
1460
1461 void MainWindow::slotAddVideoEffect(QAction *result) {
1462     if (!result) return;
1463     QStringList info = result->data().toStringList();
1464     if (info.isEmpty()) return;
1465     QDomElement effect = videoEffects.getEffectByTag(info.at(1), info.at(2));
1466     slotAddEffect(effect);
1467 }
1468
1469 void MainWindow::slotAddAudioEffect(QAction *result) {
1470     if (!result) return;
1471     QStringList info = result->data().toStringList();
1472     if (info.isEmpty()) return;
1473     QDomElement effect = audioEffects.getEffectByTag(info.at(1), info.at(2));
1474     slotAddEffect(effect);
1475 }
1476
1477 void MainWindow::slotAddCustomEffect(QAction *result) {
1478     if (!result) return;
1479     QStringList info = result->data().toStringList();
1480     if (info.isEmpty()) return;
1481     QDomElement effect = customEffects.getEffectByTag(info.at(1), info.at(2));
1482     slotAddEffect(effect);
1483 }
1484
1485 void MainWindow::slotZoomIn() {
1486     m_zoomSlider->setValue(m_zoomSlider->value() - 1);
1487 }
1488
1489 void MainWindow::slotZoomOut() {
1490     m_zoomSlider->setValue(m_zoomSlider->value() + 1);
1491 }
1492
1493 void MainWindow::slotFitZoom() {
1494     if (m_activeTimeline) {
1495         m_zoomSlider->setValue(m_activeTimeline->fitZoom());
1496     }
1497 }
1498
1499 void MainWindow::slotGotProgressInfo(const QString &message, int progress) {
1500     statusProgressBar->setValue(progress);
1501     if (progress >= 0) {
1502         if (!message.isEmpty()) m_messageLabel->setMessage(message, InformationMessage);//statusLabel->setText(message);
1503         statusProgressBar->setVisible(true);
1504     } else {
1505         m_messageLabel->setMessage(QString(), DefaultMessage);
1506         statusProgressBar->setVisible(false);
1507     }
1508 }
1509
1510 void MainWindow::slotShowClipProperties(DocClipBase *clip) {
1511     if (clip->clipType() == TEXT) {
1512         QString titlepath = m_activeDocument->projectFolder().path() + "/titles/";
1513         QString path = clip->getProperty("resource");
1514         TitleWidget *dia_ui = new TitleWidget(KUrl(), titlepath, m_projectMonitor->render, this);
1515         QDomDocument doc;
1516         doc.setContent(clip->getProperty("xmldata"));
1517         dia_ui->setXml(doc);
1518         if (dia_ui->exec() == QDialog::Accepted) {
1519             QPixmap pix = dia_ui->renderedPixmap();
1520             pix.save(path);
1521             //slotAddClipFile(KUrl("/tmp/kdenlivetitle.png"), QString(), -1);
1522             //m_clipManager->slotEditTextClipFile(id, dia_ui->xml().toString());
1523             QMap <QString, QString> newprops;
1524             newprops.insert("xmldata", dia_ui->xml().toString());
1525             EditClipCommand *command = new EditClipCommand(m_projectList, clip->getId(), clip->properties(), newprops, true);
1526             m_activeDocument->commandStack()->push(command);
1527             m_clipMonitor->refreshMonitor(true);
1528             m_activeDocument->setModified(true);
1529         }
1530         delete dia_ui;
1531
1532         //m_activeDocument->editTextClip(clip->getProperty("xml"), clip->getId());
1533         return;
1534     }
1535     ClipProperties dia(clip, m_activeDocument->timecode(), m_activeDocument->fps(), this);
1536     connect(&dia, SIGNAL(addMarker(const QString &, GenTime, QString)), m_activeTimeline->projectView(), SLOT(slotAddClipMarker(const QString &, GenTime, QString)));
1537     if (dia.exec() == QDialog::Accepted) {
1538         EditClipCommand *command = new EditClipCommand(m_projectList, dia.clipId(), clip->properties(), dia.properties(), true);
1539         m_activeDocument->commandStack()->push(command);
1540
1541         //m_projectList->slotUpdateClipProperties(dia.clipId(), dia.properties());
1542         if (dia.needsTimelineRefresh()) {
1543             // update clip occurences in timeline
1544             m_activeTimeline->projectView()->slotUpdateClip(dia.clipId());
1545         }
1546     }
1547 }
1548
1549 void MainWindow::customEvent(QEvent* e) {
1550     if (e->type() == QEvent::User) {
1551         // The timeline playing position changed...
1552         kDebug() << "RECIEVED JOG EVEMNT!!!";
1553     }
1554 }
1555 void MainWindow::slotActivateEffectStackView() {
1556     effectStack->raiseWindow(effectStackDock);
1557 }
1558
1559 void MainWindow::slotActivateTransitionView() {
1560     transitionConfig->raiseWindow(transitionConfigDock);
1561 }
1562
1563 void MainWindow::slotSnapRewind() {
1564     if (m_projectMonitor->isActive()) {
1565         if (m_activeTimeline)
1566             m_activeTimeline->projectView()->slotSeekToPreviousSnap();
1567     }
1568 }
1569
1570 void MainWindow::slotSnapForward() {
1571     if (m_projectMonitor->isActive()) {
1572         if (m_activeTimeline)
1573             m_activeTimeline->projectView()->slotSeekToNextSnap();
1574     }
1575 }
1576
1577 void MainWindow::slotClipStart() {
1578     if (m_projectMonitor->isActive()) {
1579         if (m_activeTimeline)
1580             m_activeTimeline->projectView()->clipStart();
1581     }
1582 }
1583
1584 void MainWindow::slotClipEnd() {
1585     if (m_projectMonitor->isActive()) {
1586         if (m_activeTimeline)
1587             m_activeTimeline->projectView()->clipEnd();
1588     }
1589 }
1590
1591 void MainWindow::slotChangeTool(QAction * action) {
1592     if (action == m_buttonSelectTool) slotSetTool(SELECTTOOL);
1593     else if (action == m_buttonRazorTool) slotSetTool(RAZORTOOL);
1594 }
1595
1596 void MainWindow::slotSetTool(PROJECTTOOL tool) {
1597     if (m_activeDocument && m_activeTimeline) {
1598         //m_activeDocument->setTool(tool);
1599         m_activeTimeline->projectView()->setTool(tool);
1600     }
1601 }
1602
1603 void MainWindow::slotCopy() {
1604     if (!m_activeDocument || !m_activeTimeline) return;
1605     m_activeTimeline->projectView()->copyClip();
1606 }
1607
1608 void MainWindow::slotPaste() {
1609     if (!m_activeDocument || !m_activeTimeline) return;
1610     m_activeTimeline->projectView()->pasteClip();
1611 }
1612
1613 void MainWindow::slotPasteEffects() {
1614     if (!m_activeDocument || !m_activeTimeline) return;
1615     m_activeTimeline->projectView()->pasteClipEffects();
1616 }
1617
1618 void MainWindow::slotFind() {
1619     if (!m_activeDocument || !m_activeTimeline) return;
1620     m_projectSearch->setEnabled(false);
1621     m_findActivated = true;
1622     m_findString = QString();
1623     m_activeTimeline->projectView()->initSearchStrings();
1624     statusBar()->showMessage(i18n("Starting -- find text as you type"));
1625     m_findTimer.start(5000);
1626     qApp->installEventFilter(this);
1627 }
1628
1629 void MainWindow::slotFindNext() {
1630     if (m_activeTimeline && m_activeTimeline->projectView()->findNextString(m_findString)) {
1631         statusBar()->showMessage(i18n("Found : %1", m_findString));
1632     } else {
1633         statusBar()->showMessage(i18n("Reached end of project"));
1634     }
1635     m_findTimer.start(4000);
1636 }
1637
1638 void MainWindow::findAhead() {
1639     if (m_activeTimeline && m_activeTimeline->projectView()->findString(m_findString)) {
1640         m_projectSearchNext->setEnabled(true);
1641         statusBar()->showMessage(i18n("Found : %1", m_findString));
1642     } else {
1643         m_projectSearchNext->setEnabled(false);
1644         statusBar()->showMessage(i18n("Not found : %1", m_findString));
1645     }
1646 }
1647
1648 void MainWindow::findTimeout() {
1649     m_projectSearchNext->setEnabled(false);
1650     m_findActivated = false;
1651     m_findString = QString();
1652     statusBar()->showMessage(i18n("Find stopped"), 3000);
1653     if (m_activeTimeline) m_activeTimeline->projectView()->clearSearchStrings();
1654     m_projectSearch->setEnabled(true);
1655     removeEventFilter(this);
1656 }
1657
1658 void MainWindow::keyPressEvent(QKeyEvent *ke) {
1659     if (m_findActivated) {
1660         if (ke->key() == Qt::Key_Backspace) {
1661             m_findString = m_findString.left(m_findString.length() - 1);
1662
1663             if (!m_findString.isEmpty()) {
1664                 findAhead();
1665             } else {
1666                 findTimeout();
1667             }
1668
1669             m_findTimer.start(4000);
1670             ke->accept();
1671             return;
1672         } else if (ke->key() == Qt::Key_Escape) {
1673             findTimeout();
1674             ke->accept();
1675             return;
1676         } else if (ke->key() == Qt::Key_Space || !ke->text().trimmed().isEmpty()) {
1677             m_findString += ke->text();
1678
1679             findAhead();
1680
1681             m_findTimer.start(4000);
1682             ke->accept();
1683             return;
1684         }
1685     } else KXmlGuiWindow::keyPressEvent(ke);
1686 }
1687
1688 bool MainWindow::eventFilter(QObject *obj, QEvent *event) {
1689     if (m_findActivated) {
1690         if (event->type() == QEvent::ShortcutOverride) {
1691             QKeyEvent* ke = (QKeyEvent*) event;
1692             if (ke->text().trimmed().isEmpty()) return false;
1693             ke->accept();
1694             return true;
1695         } else return false;
1696     } else {
1697         // pass the event on to the parent class
1698         return QMainWindow::eventFilter(obj, event);
1699     }
1700 }
1701
1702 void MainWindow::slotSaveZone(Render *render, QPoint zone) {
1703     KDialog *dialog = new KDialog(this);
1704     dialog->setCaption("Save clip zone");
1705     dialog->setButtons(KDialog::Ok | KDialog::Cancel);
1706
1707     QWidget *widget = new QWidget(dialog);
1708     dialog->setMainWidget(widget);
1709
1710     QVBoxLayout *vbox = new QVBoxLayout(widget);
1711     QLabel *label1 = new QLabel(i18n("Save clip zone as:"), this);
1712     QString path = m_activeDocument->projectFolder().path();
1713     path.append("/");
1714     path.append("untitled.westley");
1715     KUrlRequester *url = new KUrlRequester(KUrl(path), this);
1716     url->setFilter("video/mlt-playlist");
1717     QLabel *label2 = new QLabel(i18n("Description:"), this);
1718     KLineEdit *edit = new KLineEdit(this);
1719     vbox->addWidget(label1);
1720     vbox->addWidget(url);
1721     vbox->addWidget(label2);
1722     vbox->addWidget(edit);
1723     if (dialog->exec() == QDialog::Accepted) render->saveZone(url->url(), edit->text(), zone);
1724
1725 }
1726
1727 void MainWindow::slotSetInPoint() {
1728     if (m_clipMonitor->isActive()) {
1729         m_clipMonitor->slotSetZoneStart();
1730     } else m_activeTimeline->projectView()->setInPoint();
1731 }
1732
1733 void MainWindow::slotSetOutPoint() {
1734     if (m_clipMonitor->isActive()) {
1735         m_clipMonitor->slotSetZoneEnd();
1736     } else m_activeTimeline->projectView()->setOutPoint();
1737 }
1738
1739 #include "mainwindow.moc"