]> git.sesse.net Git - kdenlive/blob - src/mainwindow.cpp
Fix custom effects multiplication:
[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
21 #include "mainwindow.h"
22 #include "mainwindowadaptor.h"
23 #include "kdenlivesettings.h"
24 #include "kdenlivesettingsdialog.h"
25 #include "initeffects.h"
26 #include "profilesdialog.h"
27 #include "projectsettings.h"
28 #include "events.h"
29 #include "clipmanager.h"
30 #include "projectlist.h"
31 #include "monitor.h"
32 #include "recmonitor.h"
33 #include "monitormanager.h"
34 #include "kdenlivedoc.h"
35 #include "trackview.h"
36 #include "customtrackview.h"
37 #include "effectslistview.h"
38 #include "effectstackview.h"
39 #include "transitionsettings.h"
40 #include "renderwidget.h"
41 #include "renderer.h"
42 #ifndef NO_JOGSHUTTLE
43 #include "jogshuttle.h"
44 #endif /* NO_JOGSHUTTLE */
45 #include "clipproperties.h"
46 #include "wizard.h"
47 #include "editclipcommand.h"
48 #include "titlewidget.h"
49 #include "markerdialog.h"
50 #include "clipitem.h"
51 #include "interfaces.h"
52 #include "kdenlive-config.h"
53 #include "cliptranscode.h"
54 #include "ui_templateclip_ui.h"
55
56 #include <KApplication>
57 #include <KAction>
58 #include <KLocale>
59 #include <KGlobal>
60 #include <KActionCollection>
61 #include <KStandardAction>
62 #include <KFileDialog>
63 #include <KMessageBox>
64 #include <KDebug>
65 #include <KIO/NetAccess>
66 #include <KSaveFile>
67 #include <KRuler>
68 #include <KConfigDialog>
69 #include <KXMLGUIFactory>
70 #include <KStatusBar>
71 #include <kstandarddirs.h>
72 #include <KUrlRequesterDialog>
73 #include <KTemporaryFile>
74 #include <KProcess>
75 #include <KActionMenu>
76 #include <KMenu>
77 #include <locale.h>
78 #include <ktogglefullscreenaction.h>
79 #include <KFileItem>
80 #include <KNotification>
81 #include <KNotifyConfigWidget>
82 #include <knewstuff2/engine.h>
83 #include <knewstuff2/ui/knewstuffaction.h>
84
85 #include <QTextStream>
86 #include <QTimer>
87 #include <QAction>
88 #include <QKeyEvent>
89 #include <QInputDialog>
90
91 #include <stdlib.h>
92
93 static const char version[] = VERSION;
94
95 static const int ID_TIMELINE_POS = 0;
96
97 namespace Mlt
98 {
99 class Producer;
100 };
101
102 EffectsList MainWindow::videoEffects;
103 EffectsList MainWindow::audioEffects;
104 EffectsList MainWindow::customEffects;
105 EffectsList MainWindow::transitions;
106
107 MainWindow::MainWindow(const QString &MltPath, const KUrl & Url, QWidget *parent) :
108         KXmlGuiWindow(parent),
109         m_activeDocument(NULL),
110         m_activeTimeline(NULL),
111         m_renderWidget(NULL),
112 #ifndef NO_JOGSHUTTLE
113         m_jogProcess(NULL),
114 #endif /* NO_JOGSHUTTLE */
115         m_findActivated(false)
116 {
117
118     // Create DBus interface
119     new MainWindowAdaptor(this);
120     QDBusConnection dbus = QDBusConnection::sessionBus();
121     dbus.registerObject("/MainWindow", this);
122
123     setlocale(LC_NUMERIC, "POSIX");
124     setFont(KGlobalSettings::toolBarFont());
125     parseProfiles(MltPath);
126     m_commandStack = new QUndoGroup;
127     m_timelineArea = new KTabWidget(this);
128     m_timelineArea->setTabReorderingEnabled(true);
129     m_timelineArea->setTabBarHidden(true);
130
131     QToolButton *closeTabButton = new QToolButton;
132     connect(closeTabButton, SIGNAL(clicked()), this, SLOT(closeCurrentDocument()));
133     closeTabButton->setIcon(KIcon("tab-close"));
134     closeTabButton->adjustSize();
135     closeTabButton->setToolTip(i18n("Close the current tab"));
136     m_timelineArea->setCornerWidget(closeTabButton);
137     connect(m_timelineArea, SIGNAL(currentChanged(int)), this, SLOT(activateDocument()));
138
139     connect(&m_findTimer, SIGNAL(timeout()), this, SLOT(findTimeout()));
140     m_findTimer.setSingleShot(true);
141
142     // FIXME: the next call returns a newly allocated object, which leaks
143     initEffects::parseEffectFiles();
144     //initEffects::parseCustomEffectsFile();
145
146     m_monitorManager = new MonitorManager();
147
148     m_projectListDock = new QDockWidget(i18n("Project Tree"), this);
149     m_projectListDock->setObjectName("project_tree");
150     m_projectList = new ProjectList(this);
151     m_projectListDock->setWidget(m_projectList);
152     addDockWidget(Qt::TopDockWidgetArea, m_projectListDock);
153
154     m_shortcutRemoveFocus = new QShortcut(QKeySequence("Esc"), this);
155     connect(m_shortcutRemoveFocus, SIGNAL(activated()), this, SLOT(slotRemoveFocus()));
156
157     m_effectListDock = new QDockWidget(i18n("Effect List"), this);
158     m_effectListDock->setObjectName("effect_list");
159     m_effectList = new EffectsListView();
160
161     //m_effectList = new KListWidget(this);
162     m_effectListDock->setWidget(m_effectList);
163     addDockWidget(Qt::TopDockWidgetArea, m_effectListDock);
164
165     m_effectStackDock = new QDockWidget(i18n("Effect Stack"), this);
166     m_effectStackDock->setObjectName("effect_stack");
167     m_effectStack = new EffectStackView(this);
168     m_effectStackDock->setWidget(m_effectStack);
169     addDockWidget(Qt::TopDockWidgetArea, m_effectStackDock);
170
171     m_transitionConfigDock = new QDockWidget(i18n("Transition"), this);
172     m_transitionConfigDock->setObjectName("transition");
173     m_transitionConfig = new TransitionSettings(this);
174     m_transitionConfigDock->setWidget(m_transitionConfig);
175     addDockWidget(Qt::TopDockWidgetArea, m_transitionConfigDock);
176
177     KdenliveSettings::setCurrent_profile(KdenliveSettings::default_profile());
178     m_fileOpenRecent = KStandardAction::openRecent(this, SLOT(openFile(const KUrl &)),
179                        actionCollection());
180     readOptions();
181
182     //slotDetectAudioDriver();
183
184     m_clipMonitorDock = new QDockWidget(i18n("Clip Monitor"), this);
185     m_clipMonitorDock->setObjectName("clip_monitor");
186     m_clipMonitor = new Monitor("clip", m_monitorManager, this);
187     m_clipMonitorDock->setWidget(m_clipMonitor);
188     addDockWidget(Qt::TopDockWidgetArea, m_clipMonitorDock);
189     //m_clipMonitor->stop();
190
191     m_projectMonitorDock = new QDockWidget(i18n("Project Monitor"), this);
192     m_projectMonitorDock->setObjectName("project_monitor");
193     m_projectMonitor = new Monitor("project", m_monitorManager, this);
194     m_projectMonitorDock->setWidget(m_projectMonitor);
195     addDockWidget(Qt::TopDockWidgetArea, m_projectMonitorDock);
196
197     m_recMonitorDock = new QDockWidget(i18n("Record Monitor"), this);
198     m_recMonitorDock->setObjectName("record_monitor");
199     m_recMonitor = new RecMonitor("record", this);
200     m_recMonitorDock->setWidget(m_recMonitor);
201     addDockWidget(Qt::TopDockWidgetArea, m_recMonitorDock);
202
203     connect(m_recMonitor, SIGNAL(addProjectClip(KUrl)), this, SLOT(slotAddProjectClip(KUrl)));
204     connect(m_recMonitor, SIGNAL(showConfigDialog(int, int)), this, SLOT(slotPreferences(int, int)));
205
206     m_undoViewDock = new QDockWidget(i18n("Undo History"), this);
207     m_undoViewDock->setObjectName("undo_history");
208     m_undoView = new QUndoView(this);
209     m_undoView->setCleanIcon(KIcon("edit-clear"));
210     m_undoView->setEmptyLabel(i18n("Clean"));
211     m_undoViewDock->setWidget(m_undoView);
212     m_undoView->setGroup(m_commandStack);
213     addDockWidget(Qt::TopDockWidgetArea, m_undoViewDock);
214
215     //overviewDock = new QDockWidget(i18n("Project Overview"), this);
216     //overviewDock->setObjectName("project_overview");
217     //m_overView = new CustomTrackView(NULL, NULL, this);
218     //overviewDock->setWidget(m_overView);
219     //addDockWidget(Qt::TopDockWidgetArea, overviewDock);
220
221     setupActions();
222     //tabifyDockWidget(projectListDock, effectListDock);
223     tabifyDockWidget(m_projectListDock, m_effectStackDock);
224     tabifyDockWidget(m_projectListDock, m_transitionConfigDock);
225     //tabifyDockWidget(projectListDock, undoViewDock);
226
227
228     tabifyDockWidget(m_clipMonitorDock, m_projectMonitorDock);
229     tabifyDockWidget(m_clipMonitorDock, m_recMonitorDock);
230     setCentralWidget(m_timelineArea);
231
232
233     setupGUI();
234     /*ScriptingPart* sp = new ScriptingPart(this, QStringList());
235     guiFactory()->addClient(sp);*/
236
237     loadPlugins();
238     loadTranscoders();
239     //kDebug() << factory() << " " << factory()->container("video_effects_menu", this);
240
241     m_projectMonitor->setupMenu(static_cast<QMenu*>(factory()->container("monitor_go", this)), m_playZone, m_loopZone);
242     m_clipMonitor->setupMenu(static_cast<QMenu*>(factory()->container("monitor_go", this)), m_playZone, m_loopZone, static_cast<QMenu*>(factory()->container("marker_menu", this)));
243     m_projectList->setupGeneratorMenu(static_cast<QMenu*>(factory()->container("generators", this)), static_cast<QMenu*>(factory()->container("transcoders", this)));
244
245     // build effects menus
246     QAction *action;
247     QMenu *videoEffectsMenu = static_cast<QMenu*>(factory()->container("video_effects_menu", this));
248
249     QStringList effectInfo;
250     QMap<QString, QStringList> effectsList;
251     for (int ix = 0; ix < videoEffects.count(); ix++) {
252         effectInfo = videoEffects.effectIdInfo(ix);
253         effectsList.insert(effectInfo.at(0).toLower(), effectInfo);
254     }
255
256     foreach(const QStringList &value, effectsList) {
257         action = new QAction(value.at(0), this);
258         action->setData(value);
259         videoEffectsMenu->addAction(action);
260     }
261
262     QMenu *audioEffectsMenu = static_cast<QMenu*>(factory()->container("audio_effects_menu", this));
263
264
265     effectsList.clear();
266     for (int ix = 0; ix < audioEffects.count(); ix++) {
267         effectInfo = audioEffects.effectIdInfo(ix);
268         effectsList.insert(effectInfo.at(0).toLower(), effectInfo);
269     }
270
271     foreach(const QStringList &value, effectsList) {
272         action = new QAction(value.at(0), this);
273         action->setData(value);
274         audioEffectsMenu->addAction(action);
275     }
276
277     m_customEffectsMenu = static_cast<QMenu*>(factory()->container("custom_effects_menu", this));
278
279     if (customEffects.isEmpty()) m_customEffectsMenu->setEnabled(false);
280     else m_customEffectsMenu->setEnabled(true);
281
282     effectsList.clear();
283     for (int ix = 0; ix < customEffects.count(); ix++) {
284         effectInfo = customEffects.effectIdInfo(ix);
285         effectsList.insert(effectInfo.at(0).toLower(), effectInfo);
286     }
287
288     foreach(const QStringList &value, effectsList) {
289         action = new QAction(value.at(0), this);
290         action->setData(value);
291         m_customEffectsMenu->addAction(action);
292     }
293
294     QMenu *newEffect = new QMenu(this);
295     newEffect->addMenu(videoEffectsMenu);
296     newEffect->addMenu(audioEffectsMenu);
297     newEffect->addMenu(m_customEffectsMenu);
298     m_effectStack->setMenu(newEffect);
299
300
301     QMenu *viewMenu = static_cast<QMenu*>(factory()->container("dockwindows", this));
302     const QList<QAction *> viewActions = createPopupMenu()->actions();
303     viewMenu->insertActions(NULL, viewActions);
304
305     connect(videoEffectsMenu, SIGNAL(triggered(QAction *)), this, SLOT(slotAddVideoEffect(QAction *)));
306     connect(audioEffectsMenu, SIGNAL(triggered(QAction *)), this, SLOT(slotAddAudioEffect(QAction *)));
307     connect(m_customEffectsMenu, SIGNAL(triggered(QAction *)), this, SLOT(slotAddCustomEffect(QAction *)));
308
309     m_timelineContextMenu = new QMenu(this);
310     m_timelineContextClipMenu = new QMenu(this);
311     m_timelineContextTransitionMenu = new QMenu(this);
312
313
314     QMenu *transitionsMenu = new QMenu(i18n("Add Transition"), this);
315     QStringList effects = transitions.effectNames();
316
317     effectsList.clear();
318     for (int ix = 0; ix < transitions.count(); ix++) {
319         effectInfo = transitions.effectIdInfo(ix);
320         effectsList.insert(effectInfo.at(0).toLower(), effectInfo);
321     }
322     foreach(const QStringList &value, effectsList) {
323         action = new QAction(value.at(0), this);
324         action->setData(value);
325         transitionsMenu->addAction(action);
326     }
327     connect(transitionsMenu, SIGNAL(triggered(QAction *)), this, SLOT(slotAddTransition(QAction *)));
328
329     m_timelineContextMenu->addAction(actionCollection()->action("insert_space"));
330     m_timelineContextMenu->addAction(actionCollection()->action("delete_space"));
331     m_timelineContextMenu->addAction(actionCollection()->action(KStandardAction::name(KStandardAction::Paste)));
332
333     m_timelineContextClipMenu->addAction(actionCollection()->action("delete_timeline_clip"));
334     m_timelineContextClipMenu->addAction(actionCollection()->action("group_clip"));
335     m_timelineContextClipMenu->addAction(actionCollection()->action("ungroup_clip"));
336     m_timelineContextClipMenu->addAction(actionCollection()->action("cut_timeline_clip"));
337     m_timelineContextClipMenu->addAction(actionCollection()->action(KStandardAction::name(KStandardAction::Copy)));
338     m_timelineContextClipMenu->addAction(actionCollection()->action("paste_effects"));
339     m_timelineContextClipMenu->addAction(actionCollection()->action("split_audio"));
340
341     QMenu *markersMenu = (QMenu*)(factory()->container("marker_menu", this));
342     m_timelineContextClipMenu->addMenu(markersMenu);
343     m_timelineContextClipMenu->addMenu(transitionsMenu);
344     m_timelineContextClipMenu->addMenu(videoEffectsMenu);
345     m_timelineContextClipMenu->addMenu(audioEffectsMenu);
346     //TODO: re-enable custom effects menu when it is implemented
347     m_timelineContextClipMenu->addMenu(m_customEffectsMenu);
348
349     m_timelineContextTransitionMenu->addAction(actionCollection()->action("delete_timeline_clip"));
350     m_timelineContextTransitionMenu->addAction(actionCollection()->action(KStandardAction::name(KStandardAction::Copy)));
351
352     m_timelineContextTransitionMenu->addAction(actionCollection()->action("auto_transition"));
353
354     connect(m_projectMonitorDock, SIGNAL(visibilityChanged(bool)), m_projectMonitor, SLOT(refreshMonitor(bool)));
355     connect(m_clipMonitorDock, SIGNAL(visibilityChanged(bool)), m_clipMonitor, SLOT(refreshMonitor(bool)));
356     //connect(m_monitorManager, SIGNAL(connectMonitors()), this, SLOT(slotConnectMonitors()));
357     connect(m_monitorManager, SIGNAL(raiseClipMonitor(bool)), this, SLOT(slotRaiseMonitor(bool)));
358     connect(m_effectList, SIGNAL(addEffect(const QDomElement)), this, SLOT(slotAddEffect(const QDomElement)));
359     connect(m_effectList, SIGNAL(reloadEffects()), this, SLOT(slotReloadEffects()));
360
361     m_monitorManager->initMonitors(m_clipMonitor, m_projectMonitor);
362     slotConnectMonitors();
363
364     // Open or create a file.  Command line argument passed in Url has
365     // precedence, then "openlastproject", then just a plain empty file.
366     // If opening Url fails, openlastproject will _not_ be used.
367     if (!Url.isEmpty()) {
368         openFile(Url);
369     } else {
370         if (KdenliveSettings::openlastproject()) {
371             openLastFile();
372         }
373     }
374     if (m_timelineArea->count() == 0) {
375         newFile(false);
376     }
377
378 #ifndef NO_JOGSHUTTLE
379     activateShuttleDevice();
380 #endif /* NO_JOGSHUTTLE */
381     m_projectListDock->raise();
382 }
383
384 void MainWindow::queryQuit()
385 {
386     if (queryClose()) {
387         if (m_projectMonitor) m_projectMonitor->stop();
388         if (m_clipMonitor) m_clipMonitor->stop();
389         delete m_effectStack;
390         delete m_activeTimeline;
391         delete m_projectMonitor;
392         delete m_clipMonitor;
393         delete m_activeDocument;
394         delete m_shortcutRemoveFocus;
395         Mlt::Factory::close();
396         kapp->quit();
397     }
398 }
399
400 //virtual
401 bool MainWindow::queryClose()
402 {
403     if (m_renderWidget) {
404         int waitingJobs = m_renderWidget->waitingJobsCount();
405         if (waitingJobs > 0) {
406             switch (KMessageBox::warningYesNoCancel(this, i18n("You have %1 rendering jobs waiting in the queue.\nWhat do you want to do with these jobs?", waitingJobs), QString(), KGuiItem(i18n("Start them now")), KGuiItem(i18n("Delete them")))) {
407             case KMessageBox::Yes :
408                 // create script with waiting jobs and start it
409                 if (m_renderWidget->startWaitingRenderJobs() == false) return false;
410                 break;
411             case KMessageBox::No :
412                 // Don't do anything, jobs will be deleted
413                 break;
414             default:
415                 return false;
416             }
417         }
418     }
419     saveOptions();
420     if (m_monitorManager) m_monitorManager->stopActiveMonitor();
421     if (m_activeDocument && m_activeDocument->isModified()) {
422         switch (KMessageBox::warningYesNoCancel(this, i18n("Save changes to document?"))) {
423         case KMessageBox::Yes :
424             // save document here. If saving fails, return false;
425             return saveFile();
426         case KMessageBox::No :
427             // User does not want to save the changes, clear recovery files
428             m_activeDocument->m_autosave->resize(0);
429             return true;
430         default: // cancel
431             return false;
432         }
433     }
434     return true;
435 }
436
437
438 void MainWindow::loadPlugins()
439 {
440     foreach(QObject *plugin, QPluginLoader::staticInstances())
441     populateMenus(plugin);
442
443     QStringList directories = KGlobal::dirs()->findDirs("module", QString());
444     QStringList filters;
445     filters << "libkdenlive*";
446     foreach(const QString &folder, directories) {
447         kDebug() << "// PARSING FIOLER: " << folder;
448         QDir pluginsDir(folder);
449         foreach(const QString &fileName, pluginsDir.entryList(filters, QDir::Files)) {
450             kDebug() << "// FOUND PLUGIN: " << fileName << "= " << pluginsDir.absoluteFilePath(fileName);
451             QPluginLoader loader(pluginsDir.absoluteFilePath(fileName));
452             QObject *plugin = loader.instance();
453             if (plugin) {
454                 populateMenus(plugin);
455                 m_pluginFileNames += fileName;
456             } else kDebug() << "// ERROR LOADING PLUGIN: " << fileName << ", " << loader.errorString();
457         }
458     }
459     //exit(1);
460 }
461
462 void MainWindow::populateMenus(QObject *plugin)
463 {
464     QMenu *addMenu = static_cast<QMenu*>(factory()->container("generators", this));
465     ClipGenerator *iGenerator = qobject_cast<ClipGenerator *>(plugin);
466     if (iGenerator)
467         addToMenu(plugin, iGenerator->generators(KdenliveSettings::producerslist()), addMenu, SLOT(generateClip()),
468                   NULL);
469 }
470
471 void MainWindow::addToMenu(QObject *plugin, const QStringList &texts,
472                            QMenu *menu, const char *member,
473                            QActionGroup *actionGroup)
474 {
475     kDebug() << "// ADD to MENU" << texts;
476     foreach(const QString &text, texts) {
477         QAction *action = new QAction(text, plugin);
478         action->setData(text);
479         connect(action, SIGNAL(triggered()), this, member);
480         menu->addAction(action);
481
482         if (actionGroup) {
483             action->setCheckable(true);
484             actionGroup->addAction(action);
485         }
486     }
487 }
488
489 void MainWindow::aboutPlugins()
490 {
491     //PluginDialog dialog(pluginsDir.path(), m_pluginFileNames, this);
492     //dialog.exec();
493 }
494
495
496 void MainWindow::generateClip()
497 {
498     QAction *action = qobject_cast<QAction *>(sender());
499     ClipGenerator *iGenerator = qobject_cast<ClipGenerator *>(action->parent());
500
501     KUrl clipUrl = iGenerator->generatedClip(action->data().toString(), m_activeDocument->projectFolder(), QStringList(), QStringList(), 25, 720, 576);
502     if (!clipUrl.isEmpty()) {
503         m_projectList->slotAddClip(QList <QUrl> () << clipUrl);
504     }
505 }
506
507 void MainWindow::saveProperties(KConfigGroup &config)
508 {
509     // save properties here,used by session management
510     saveFile();
511     KMainWindow::saveProperties(config);
512 }
513
514
515 void MainWindow::readProperties(const KConfigGroup &config)
516 {
517     // read properties here,used by session management
518     KMainWindow::readProperties(config);
519     QString Lastproject = config.group("Recent Files").readPathEntry("File1", QString());
520     openFile(KUrl(Lastproject));
521 }
522
523 void MainWindow::slotReloadEffects()
524 {
525     kDebug()<<"START RELOAD; COUNR: "<<m_customEffectsMenu->actions().count();
526     m_customEffectsMenu->clear();
527     kDebug()<<"START RELOAD; CLR: "<<m_customEffectsMenu->actions().count();
528     initEffects::parseCustomEffectsFile();
529     const QStringList effects = customEffects.effectNames();
530     kDebug()<<"NEW EFFS: "<<effects;
531     QAction *action;
532     if (effects.isEmpty()) m_customEffectsMenu->setEnabled(false);
533     else m_customEffectsMenu->setEnabled(true);
534
535     foreach(const QString &name, effects) {
536         action = new QAction(name, this);
537         action->setData(name);
538         m_customEffectsMenu->addAction(action);
539     }
540     m_effectList->reloadEffectList();
541 }
542
543 #ifndef NO_JOGSHUTTLE
544 void MainWindow::activateShuttleDevice()
545 {
546     delete m_jogProcess;
547     m_jogProcess = NULL;
548     if (KdenliveSettings::enableshuttle() == false) return;
549     m_jogProcess = new JogShuttle(KdenliveSettings::shuttledevice());
550     connect(m_jogProcess, SIGNAL(rewind1()), m_monitorManager, SLOT(slotRewindOneFrame()));
551     connect(m_jogProcess, SIGNAL(forward1()), m_monitorManager, SLOT(slotForwardOneFrame()));
552     connect(m_jogProcess, SIGNAL(rewind(double)), m_monitorManager, SLOT(slotRewind(double)));
553     connect(m_jogProcess, SIGNAL(forward(double)), m_monitorManager, SLOT(slotForward(double)));
554     connect(m_jogProcess, SIGNAL(stop()), m_monitorManager, SLOT(slotPlay()));
555     connect(m_jogProcess, SIGNAL(button(int)), this, SLOT(slotShuttleButton(int)));
556 }
557
558 void MainWindow::slotShuttleButton(int code)
559 {
560     switch (code) {
561     case 5:
562         slotShuttleAction(KdenliveSettings::shuttle1());
563         break;
564     case 6:
565         slotShuttleAction(KdenliveSettings::shuttle2());
566         break;
567     case 7:
568         slotShuttleAction(KdenliveSettings::shuttle3());
569         break;
570     case 8:
571         slotShuttleAction(KdenliveSettings::shuttle4());
572         break;
573     case 9:
574         slotShuttleAction(KdenliveSettings::shuttle5());
575         break;
576     }
577 }
578
579 void MainWindow::slotShuttleAction(int code)
580 {
581     switch (code) {
582     case 0:
583         return;
584     case 1:
585         m_monitorManager->slotPlay();
586         break;
587     default:
588         m_monitorManager->slotPlay();
589         break;
590     }
591 }
592 #endif /* NO_JOGSHUTTLE */
593
594 void MainWindow::configureNotifications()
595 {
596     KNotifyConfigWidget::configure(this);
597 }
598
599 void MainWindow::slotFullScreen()
600 {
601     KToggleFullScreenAction::setFullScreen(this, actionCollection()->action("fullscreen")->isChecked());
602 }
603
604 void MainWindow::slotAddEffect(const QDomElement effect, GenTime pos, int track)
605 {
606     if (!m_activeDocument) return;
607     if (effect.isNull()) {
608         kDebug() << "--- ERROR, TRYING TO APPEND NULL EFFECT";
609         return;
610     }
611     QDomElement effectToAdd = effect.cloneNode().toElement();
612     m_activeTimeline->projectView()->slotAddEffect(effectToAdd, pos, track);
613 }
614
615 void MainWindow::slotRaiseMonitor(bool clipMonitor)
616 {
617     if (clipMonitor) m_clipMonitorDock->raise();
618     else m_projectMonitorDock->raise();
619 }
620
621 void MainWindow::slotUpdateClip(const QString &id)
622 {
623     if (!m_activeDocument) return;
624     m_activeTimeline->projectView()->slotUpdateClip(id);
625 }
626
627 void MainWindow::slotConnectMonitors()
628 {
629
630     m_projectList->setRenderer(m_projectMonitor->render);
631     connect(m_projectList, SIGNAL(receivedClipDuration(const QString &)), this, SLOT(slotUpdateClip(const QString &)));
632     connect(m_projectList, SIGNAL(showClipProperties(DocClipBase *)), this, SLOT(slotShowClipProperties(DocClipBase *)));
633     connect(m_projectList, SIGNAL(getFileProperties(const QDomElement, const QString &, bool)), m_projectMonitor->render, SLOT(getFileProperties(const QDomElement, const QString &, bool)));
634     connect(m_projectMonitor->render, SIGNAL(replyGetImage(const QString &, const QPixmap &)), m_projectList, SLOT(slotReplyGetImage(const QString &, const QPixmap &)));
635     connect(m_projectMonitor->render, SIGNAL(replyGetFileProperties(const QString &, Mlt::Producer*, const QMap < QString, QString > &, const QMap < QString, QString > &, bool)), m_projectList, SLOT(slotReplyGetFileProperties(const QString &, Mlt::Producer*, const QMap < QString, QString > &, const QMap < QString, QString > &, bool)));
636
637     connect(m_projectMonitor->render, SIGNAL(removeInvalidClip(const QString &, bool)), m_projectList, SLOT(slotRemoveInvalidClip(const QString &, bool)));
638
639     connect(m_clipMonitor, SIGNAL(refreshClipThumbnail(const QString &)), m_projectList, SLOT(slotRefreshClipThumbnail(const QString &)));
640
641     connect(m_clipMonitor, SIGNAL(adjustMonitorSize()), this, SLOT(slotAdjustClipMonitor()));
642     connect(m_projectMonitor, SIGNAL(adjustMonitorSize()), this, SLOT(slotAdjustProjectMonitor()));
643
644     connect(m_clipMonitor, SIGNAL(saveZone(Render *, QPoint)), this, SLOT(slotSaveZone(Render *, QPoint)));
645     connect(m_projectMonitor, SIGNAL(saveZone(Render *, QPoint)), this, SLOT(slotSaveZone(Render *, QPoint)));
646 }
647
648 void MainWindow::slotAdjustClipMonitor()
649 {
650     m_clipMonitorDock->updateGeometry();
651     m_clipMonitorDock->adjustSize();
652     m_clipMonitor->resetSize();
653 }
654
655 void MainWindow::slotAdjustProjectMonitor()
656 {
657     m_projectMonitorDock->updateGeometry();
658     m_projectMonitorDock->adjustSize();
659     m_projectMonitor->resetSize();
660 }
661
662 void MainWindow::setupActions()
663 {
664
665     KActionCollection* collection = actionCollection();
666     m_timecodeFormat = new KComboBox(this);
667     m_timecodeFormat->addItem(i18n("hh:mm:ss::ff"));
668     m_timecodeFormat->addItem(i18n("Frames"));
669     if (KdenliveSettings::frametimecode()) m_timecodeFormat->setCurrentIndex(1);
670     connect(m_timecodeFormat, SIGNAL(activated(int)), this, SLOT(slotUpdateTimecodeFormat(int)));
671
672     m_statusProgressBar = new QProgressBar(this);
673     m_statusProgressBar->setMinimum(0);
674     m_statusProgressBar->setMaximum(100);
675     m_statusProgressBar->setMaximumWidth(150);
676     m_statusProgressBar->setVisible(false);
677
678     QWidget *w = new QWidget;
679
680     QHBoxLayout *layout = new QHBoxLayout;
681     w->setLayout(layout);
682     layout->setContentsMargins(5, 0, 5, 0);
683     QToolBar *toolbar = new QToolBar("statusToolBar", this);
684
685
686     m_toolGroup = new QActionGroup(this);
687
688     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;}";
689
690     m_buttonSelectTool = new KAction(KIcon("kdenlive-select-tool"), i18n("Selection tool"), this);
691     m_buttonSelectTool->setShortcut(i18nc("Selection tool shortcut", "s"));
692     toolbar->addAction(m_buttonSelectTool);
693     m_buttonSelectTool->setCheckable(true);
694     m_buttonSelectTool->setChecked(true);
695
696     m_buttonRazorTool = new KAction(KIcon("edit-cut"), i18n("Razor tool"), this);
697     m_buttonRazorTool->setShortcut(i18nc("Razor tool shortcut", "x"));
698     toolbar->addAction(m_buttonRazorTool);
699     m_buttonRazorTool->setCheckable(true);
700     m_buttonRazorTool->setChecked(false);
701
702     m_buttonSpacerTool = new KAction(KIcon("kdenlive-spacer-tool"), i18n("Spacer tool"), this);
703     m_buttonSpacerTool->setShortcut(i18nc("Spacer tool shortcut", "m"));
704     toolbar->addAction(m_buttonSpacerTool);
705     m_buttonSpacerTool->setCheckable(true);
706     m_buttonSpacerTool->setChecked(false);
707
708     m_toolGroup->addAction(m_buttonSelectTool);
709     m_toolGroup->addAction(m_buttonRazorTool);
710     m_toolGroup->addAction(m_buttonSpacerTool);
711     m_toolGroup->setExclusive(true);
712     toolbar->setToolButtonStyle(Qt::ToolButtonIconOnly);
713
714     QWidget * actionWidget;
715     actionWidget = toolbar->widgetForAction(m_buttonSelectTool);
716     actionWidget->setMaximumWidth(24);
717     actionWidget->setMinimumHeight(18);
718
719     actionWidget = toolbar->widgetForAction(m_buttonRazorTool);
720     actionWidget->setMaximumWidth(24);
721     actionWidget->setMinimumHeight(18);
722
723     actionWidget = toolbar->widgetForAction(m_buttonSpacerTool);
724     actionWidget->setMaximumWidth(24);
725     actionWidget->setMinimumHeight(18);
726
727     toolbar->setStyleSheet(style1);
728     connect(m_toolGroup, SIGNAL(triggered(QAction *)), this, SLOT(slotChangeTool(QAction *)));
729
730     toolbar->addSeparator();
731     m_buttonFitZoom = new KAction(KIcon("zoom-fit-best"), i18n("Fit zoom to project"), this);
732     toolbar->addAction(m_buttonFitZoom);
733     m_buttonFitZoom->setCheckable(false);
734     connect(m_buttonFitZoom, SIGNAL(triggered()), this, SLOT(slotFitZoom()));
735
736     actionWidget = toolbar->widgetForAction(m_buttonFitZoom);
737     actionWidget->setMaximumWidth(24);
738     actionWidget->setMinimumHeight(18);
739
740     m_zoomSlider = new QSlider(Qt::Horizontal, this);
741     m_zoomSlider->setMaximum(13);
742     m_zoomSlider->setPageStep(1);
743
744     m_zoomSlider->setMaximumWidth(150);
745     m_zoomSlider->setMinimumWidth(100);
746
747     const int contentHeight = QFontMetrics(w->font()).height() + 8;
748
749     QString style = "QSlider::groove:horizontal { background-color: rgba(230, 230, 230, 220);border: 1px solid #999999;height: 8px;border-radius: 3px;margin-top:3px }";
750     style.append("QSlider::handle:horizontal {  background-color: white; border: 1px solid #999999;width: 9px;margin: -2px 0;border-radius: 3px; }");
751
752     m_zoomSlider->setStyleSheet(style);
753
754     //m_zoomSlider->height() + 5;
755     statusBar()->setMinimumHeight(contentHeight);
756
757
758     toolbar->addWidget(m_zoomSlider);
759
760     m_buttonVideoThumbs = new KAction(KIcon("kdenlive-show-videothumb"), i18n("Show video thumbnails"), this);
761     toolbar->addAction(m_buttonVideoThumbs);
762     m_buttonVideoThumbs->setCheckable(true);
763     m_buttonVideoThumbs->setChecked(KdenliveSettings::videothumbnails());
764     connect(m_buttonVideoThumbs, SIGNAL(triggered()), this, SLOT(slotSwitchVideoThumbs()));
765
766     m_buttonAudioThumbs = new KAction(KIcon("kdenlive-show-audiothumb"), i18n("Show audio thumbnails"), this);
767     toolbar->addAction(m_buttonAudioThumbs);
768     m_buttonAudioThumbs->setCheckable(true);
769     m_buttonAudioThumbs->setChecked(KdenliveSettings::audiothumbnails());
770     connect(m_buttonAudioThumbs, SIGNAL(triggered()), this, SLOT(slotSwitchAudioThumbs()));
771
772     m_buttonShowMarkers = new KAction(KIcon("kdenlive-show-markers"), i18n("Show markers comments"), this);
773     toolbar->addAction(m_buttonShowMarkers);
774     m_buttonShowMarkers->setCheckable(true);
775     m_buttonShowMarkers->setChecked(KdenliveSettings::showmarkers());
776     connect(m_buttonShowMarkers, SIGNAL(triggered()), this, SLOT(slotSwitchMarkersComments()));
777
778     m_buttonSnap = new KAction(KIcon("kdenlive-snap"), i18n("Snap"), this);
779     toolbar->addAction(m_buttonSnap);
780     m_buttonSnap->setCheckable(true);
781     m_buttonSnap->setChecked(KdenliveSettings::snaptopoints());
782     connect(m_buttonSnap, SIGNAL(triggered()), this, SLOT(slotSwitchSnap()));
783     layout->addWidget(toolbar);
784
785
786     actionWidget = toolbar->widgetForAction(m_buttonVideoThumbs);
787     actionWidget->setMaximumWidth(24);
788     actionWidget->setMinimumHeight(18);
789
790     actionWidget = toolbar->widgetForAction(m_buttonAudioThumbs);
791     actionWidget->setMaximumWidth(24);
792     actionWidget->setMinimumHeight(18);
793
794     actionWidget = toolbar->widgetForAction(m_buttonShowMarkers);
795     actionWidget->setMaximumWidth(24);
796     actionWidget->setMinimumHeight(18);
797
798     actionWidget = toolbar->widgetForAction(m_buttonSnap);
799     actionWidget->setMaximumWidth(24);
800     actionWidget->setMinimumHeight(18);
801
802     m_messageLabel = new StatusBarMessageLabel(this);
803     m_messageLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::MinimumExpanding);
804
805     statusBar()->addWidget(m_messageLabel, 10);
806     statusBar()->addWidget(m_statusProgressBar, 0);
807     statusBar()->addPermanentWidget(w);
808     statusBar()->insertPermanentFixedItem("00:00:00:00", ID_TIMELINE_POS);
809     statusBar()->addPermanentWidget(m_timecodeFormat);
810     statusBar()->setMaximumHeight(statusBar()->font().pointSize() * 4);
811
812     collection->addAction("select_tool", m_buttonSelectTool);
813     collection->addAction("razor_tool", m_buttonRazorTool);
814     collection->addAction("spacer_tool", m_buttonSpacerTool);
815
816     collection->addAction("show_video_thumbs", m_buttonVideoThumbs);
817     collection->addAction("show_audio_thumbs", m_buttonAudioThumbs);
818     collection->addAction("show_markers", m_buttonShowMarkers);
819     collection->addAction("snap", m_buttonSnap);
820     collection->addAction("zoom_fit", m_buttonFitZoom);
821
822     KAction* zoomIn = new KAction(KIcon("zoom-in"), i18n("Zoom In"), this);
823     collection->addAction("zoom_in", zoomIn);
824     connect(zoomIn, SIGNAL(triggered(bool)), this, SLOT(slotZoomIn()));
825     zoomIn->setShortcut(Qt::CTRL + Qt::Key_Plus);
826
827     KAction* zoomOut = new KAction(KIcon("zoom-out"), i18n("Zoom Out"), this);
828     collection->addAction("zoom_out", zoomOut);
829     connect(zoomOut, SIGNAL(triggered(bool)), this, SLOT(slotZoomOut()));
830     zoomOut->setShortcut(Qt::CTRL + Qt::Key_Minus);
831
832     m_projectSearch = new KAction(KIcon("edit-find"), i18n("Find"), this);
833     collection->addAction("project_find", m_projectSearch);
834     connect(m_projectSearch, SIGNAL(triggered(bool)), this, SLOT(slotFind()));
835     m_projectSearch->setShortcut(Qt::Key_Slash);
836
837     m_projectSearchNext = new KAction(KIcon("go-down-search"), i18n("Find Next"), this);
838     collection->addAction("project_find_next", m_projectSearchNext);
839     connect(m_projectSearchNext, SIGNAL(triggered(bool)), this, SLOT(slotFindNext()));
840     m_projectSearchNext->setShortcut(Qt::Key_F3);
841     m_projectSearchNext->setEnabled(false);
842
843     KAction* profilesAction = new KAction(KIcon("document-new"), i18n("Manage Project Profiles"), this);
844     collection->addAction("manage_profiles", profilesAction);
845     connect(profilesAction, SIGNAL(triggered(bool)), this, SLOT(slotEditProfiles()));
846
847     KNS::standardAction(i18n("Download New Wipes..."), this, SLOT(slotGetNewLumaStuff()), actionCollection(), "get_new_lumas");
848
849     KNS::standardAction(i18n("Download New Render Profiles..."), this, SLOT(slotGetNewRenderStuff()), actionCollection(), "get_new_profiles");
850
851     KNS::standardAction(i18n("Download New Project Profiles..."), this, SLOT(slotGetNewMltProfileStuff()), actionCollection(), "get_new_mlt_profiles");
852
853     KAction* wizAction = new KAction(KIcon("configure"), i18n("Run Config Wizard"), this);
854     collection->addAction("run_wizard", wizAction);
855     connect(wizAction, SIGNAL(triggered(bool)), this, SLOT(slotRunWizard()));
856
857     KAction* projectAction = new KAction(KIcon("configure"), i18n("Project Settings"), this);
858     collection->addAction("project_settings", projectAction);
859     connect(projectAction, SIGNAL(triggered(bool)), this, SLOT(slotEditProjectSettings()));
860
861     KAction* projectRender = new KAction(KIcon("media-record"), i18n("Render"), this);
862     collection->addAction("project_render", projectRender);
863     projectRender->setShortcut(Qt::CTRL + Qt::Key_Return);
864     connect(projectRender, SIGNAL(triggered(bool)), this, SLOT(slotRenderProject()));
865
866     KAction* monitorPlay = new KAction(KIcon("media-playback-start"), i18n("Play"), this);
867     KShortcut playShortcut;
868     playShortcut.setPrimary(Qt::Key_Space);
869     playShortcut.setAlternate(Qt::Key_K);
870     monitorPlay->setShortcut(playShortcut);
871     collection->addAction("monitor_play", monitorPlay);
872     connect(monitorPlay, SIGNAL(triggered(bool)), m_monitorManager, SLOT(slotPlay()));
873
874     m_playZone = new KAction(KIcon("media-playback-start"), i18n("Play Zone"), this);
875     m_playZone->setShortcut(Qt::CTRL + Qt::Key_Space);
876     collection->addAction("monitor_play_zone", m_playZone);
877     connect(m_playZone, SIGNAL(triggered(bool)), m_monitorManager, SLOT(slotPlayZone()));
878
879     m_loopZone = new KAction(KIcon("media-playback-start"), i18n("Loop Zone"), this);
880     m_loopZone->setShortcut(Qt::ALT + Qt::Key_Space);
881     collection->addAction("monitor_loop_zone", m_loopZone);
882     connect(m_loopZone, SIGNAL(triggered(bool)), m_monitorManager, SLOT(slotLoopZone()));
883
884     KAction *dvdWizard =  new KAction(KIcon("media-optical"), i18n("DVD Wizard"), this);
885     collection->addAction("dvd_wizard", dvdWizard);
886     connect(dvdWizard, SIGNAL(triggered(bool)), this, SLOT(slotDvdWizard()));
887
888     KAction *transcodeClip =  new KAction(KIcon("edit-copy"), i18n("Transcode Clip"), this);
889     collection->addAction("transcode_clip", transcodeClip);
890     connect(transcodeClip, SIGNAL(triggered(bool)), this, SLOT(slotTranscodeClip()));
891
892     KAction *markIn = collection->addAction("mark_in");
893     markIn->setText(i18n("Set In Point"));
894     markIn->setShortcut(Qt::Key_I);
895     connect(markIn, SIGNAL(triggered(bool)), this, SLOT(slotSetInPoint()));
896
897     KAction *markOut = collection->addAction("mark_out");
898     markOut->setText(i18n("Set Out Point"));
899     markOut->setShortcut(Qt::Key_O);
900     connect(markOut, SIGNAL(triggered(bool)), this, SLOT(slotSetOutPoint()));
901
902     KAction* monitorSeekBackward = new KAction(KIcon("media-seek-backward"), i18n("Rewind"), this);
903     monitorSeekBackward->setShortcut(Qt::Key_J);
904     collection->addAction("monitor_seek_backward", monitorSeekBackward);
905     connect(monitorSeekBackward, SIGNAL(triggered(bool)), m_monitorManager, SLOT(slotRewind()));
906
907     KAction* monitorSeekBackwardOneFrame = new KAction(KIcon("media-skip-backward"), i18n("Rewind 1 Frame"), this);
908     monitorSeekBackwardOneFrame->setShortcut(Qt::Key_Left);
909     collection->addAction("monitor_seek_backward-one-frame", monitorSeekBackwardOneFrame);
910     connect(monitorSeekBackwardOneFrame, SIGNAL(triggered(bool)), m_monitorManager, SLOT(slotRewindOneFrame()));
911
912     KAction* monitorSeekBackwardOneSecond = new KAction(KIcon("media-skip-backward"), i18n("Rewind 1 Second"), this);
913     monitorSeekBackwardOneSecond->setShortcut(Qt::SHIFT + Qt::Key_Left);
914     collection->addAction("monitor_seek_backward-one-second", monitorSeekBackwardOneSecond);
915     connect(monitorSeekBackwardOneSecond, SIGNAL(triggered(bool)), m_monitorManager, SLOT(slotRewindOneSecond()));
916
917     KAction* monitorSeekSnapBackward = new KAction(KIcon("media-seek-backward"), i18n("Go to Previous Snap Point"), this);
918     monitorSeekSnapBackward->setShortcut(Qt::ALT + Qt::Key_Left);
919     collection->addAction("monitor_seek_snap_backward", monitorSeekSnapBackward);
920     connect(monitorSeekSnapBackward, SIGNAL(triggered(bool)), this, SLOT(slotSnapRewind()));
921
922     KAction* monitorSeekForward = new KAction(KIcon("media-seek-forward"), i18n("Forward"), this);
923     monitorSeekForward->setShortcut(Qt::Key_L);
924     collection->addAction("monitor_seek_forward", monitorSeekForward);
925     connect(monitorSeekForward, SIGNAL(triggered(bool)), m_monitorManager, SLOT(slotForward()));
926
927     KAction* clipStart = new KAction(KIcon("media-seek-backward"), i18n("Go to Clip Start"), this);
928     clipStart->setShortcut(Qt::Key_Home);
929     collection->addAction("seek_clip_start", clipStart);
930     connect(clipStart, SIGNAL(triggered(bool)), this, SLOT(slotClipStart()));
931
932     KAction* clipEnd = new KAction(KIcon("media-seek-forward"), i18n("Go to Clip End"), this);
933     clipEnd->setShortcut(Qt::Key_End);
934     collection->addAction("seek_clip_end", clipEnd);
935     connect(clipEnd, SIGNAL(triggered(bool)), this, SLOT(slotClipEnd()));
936
937     KAction* projectStart = new KAction(KIcon("go-first"), i18n("Go to Project Start"), this);
938     projectStart->setShortcut(Qt::CTRL + Qt::Key_Home);
939     collection->addAction("seek_start", projectStart);
940     connect(projectStart, SIGNAL(triggered(bool)), m_monitorManager, SLOT(slotStart()));
941
942     KAction* projectEnd = new KAction(KIcon("go-last"), i18n("Go to Project End"), this);
943     projectEnd->setShortcut(Qt::CTRL + Qt::Key_End);
944     collection->addAction("seek_end", projectEnd);
945     connect(projectEnd, SIGNAL(triggered(bool)), m_monitorManager, SLOT(slotEnd()));
946
947     KAction* monitorSeekForwardOneFrame = new KAction(KIcon("media-skip-forward"), i18n("Forward 1 Frame"), this);
948     monitorSeekForwardOneFrame->setShortcut(Qt::Key_Right);
949     collection->addAction("monitor_seek_forward-one-frame", monitorSeekForwardOneFrame);
950     connect(monitorSeekForwardOneFrame, SIGNAL(triggered(bool)), m_monitorManager, SLOT(slotForwardOneFrame()));
951
952     KAction* monitorSeekForwardOneSecond = new KAction(KIcon("media-skip-forward"), i18n("Forward 1 Second"), this);
953     monitorSeekForwardOneSecond->setShortcut(Qt::SHIFT + Qt::Key_Right);
954     collection->addAction("monitor_seek_forward-one-second", monitorSeekForwardOneSecond);
955     connect(monitorSeekForwardOneSecond, SIGNAL(triggered(bool)), m_monitorManager, SLOT(slotForwardOneSecond()));
956
957     KAction* monitorSeekSnapForward = new KAction(KIcon("media-seek-forward"), i18n("Go to Next Snap Point"), this);
958     monitorSeekSnapForward->setShortcut(Qt::ALT + Qt::Key_Right);
959     collection->addAction("monitor_seek_snap_forward", monitorSeekSnapForward);
960     connect(monitorSeekSnapForward, SIGNAL(triggered(bool)), this, SLOT(slotSnapForward()));
961
962     KAction* deleteTimelineClip = new KAction(KIcon("edit-delete"), i18n("Delete Selected Item"), this);
963     deleteTimelineClip->setShortcut(Qt::Key_Delete);
964     collection->addAction("delete_timeline_clip", deleteTimelineClip);
965     connect(deleteTimelineClip, SIGNAL(triggered(bool)), this, SLOT(slotDeleteTimelineClip()));
966
967     /*KAction* editTimelineClipSpeed = new KAction(i18n("Change Clip Speed"), this);
968     collection->addAction("change_clip_speed", editTimelineClipSpeed);
969     editTimelineClipSpeed->setData("change_speed");
970     connect(editTimelineClipSpeed, SIGNAL(triggered(bool)), this, SLOT(slotChangeClipSpeed()));*/
971
972     KAction *stickTransition = collection->addAction("auto_transition");
973     stickTransition->setData(QString("auto"));
974     stickTransition->setCheckable(true);
975     stickTransition->setEnabled(false);
976     stickTransition->setText(i18n("Automatic Transition"));
977     connect(stickTransition, SIGNAL(triggered(bool)), this, SLOT(slotAutoTransition()));
978
979     KAction* groupClip = new KAction(KIcon("object-group"), i18n("Group Clips"), this);
980     groupClip->setShortcut(Qt::CTRL + Qt::Key_G);
981     collection->addAction("group_clip", groupClip);
982     connect(groupClip, SIGNAL(triggered(bool)), this, SLOT(slotGroupClips()));
983
984     KAction* ungroupClip = new KAction(KIcon("object-ungroup"), i18n("Ungroup Clips"), this);
985     collection->addAction("ungroup_clip", ungroupClip);
986     ungroupClip->setShortcut(Qt::CTRL + Qt::SHIFT + Qt::Key_G);
987     ungroupClip->setData("ungroup_clip");
988     connect(ungroupClip, SIGNAL(triggered(bool)), this, SLOT(slotUnGroupClips()));
989
990     KAction* cutTimelineClip = new KAction(KIcon("edit-cut"), i18n("Cut Clip"), this);
991     cutTimelineClip->setShortcut(Qt::SHIFT + Qt::Key_R);
992     collection->addAction("cut_timeline_clip", cutTimelineClip);
993     connect(cutTimelineClip, SIGNAL(triggered(bool)), this, SLOT(slotCutTimelineClip()));
994
995     KAction* addClipMarker = new KAction(KIcon("bookmark-new"), i18n("Add Marker"), this);
996     collection->addAction("add_clip_marker", addClipMarker);
997     connect(addClipMarker, SIGNAL(triggered(bool)), this, SLOT(slotAddClipMarker()));
998
999     KAction* deleteClipMarker = new KAction(KIcon("edit-delete"), i18n("Delete Marker"), this);
1000     collection->addAction("delete_clip_marker", deleteClipMarker);
1001     connect(deleteClipMarker, SIGNAL(triggered(bool)), this, SLOT(slotDeleteClipMarker()));
1002
1003     KAction* deleteAllClipMarkers = new KAction(KIcon("edit-delete"), i18n("Delete All Markers"), this);
1004     collection->addAction("delete_all_clip_markers", deleteAllClipMarkers);
1005     connect(deleteAllClipMarkers, SIGNAL(triggered(bool)), this, SLOT(slotDeleteAllClipMarkers()));
1006
1007     KAction* editClipMarker = new KAction(KIcon("document-properties"), i18n("Edit Marker"), this);
1008     collection->addAction("edit_clip_marker", editClipMarker);
1009     connect(editClipMarker, SIGNAL(triggered(bool)), this, SLOT(slotEditClipMarker()));
1010
1011     KAction* splitAudio = new KAction(KIcon("document-new"), i18n("Split Audio"), this);
1012     collection->addAction("split_audio", splitAudio);
1013     connect(splitAudio, SIGNAL(triggered(bool)), this, SLOT(slotSplitAudio()));
1014
1015     KAction* audioOnly = new KAction(KIcon("document-new"), i18n("Audio Only"), this);
1016     collection->addAction("clip_audio_only", audioOnly);
1017     audioOnly->setData("clip_audio_only");
1018     audioOnly->setCheckable(true);
1019
1020     KAction* videoOnly = new KAction(KIcon("document-new"), i18n("Video Only"), this);
1021     collection->addAction("clip_video_only", videoOnly);
1022     videoOnly->setData("clip_video_only");
1023     videoOnly->setCheckable(true);
1024
1025     KAction* audioAndVideo = new KAction(KIcon("document-new"), i18n("Audio and Video"), this);
1026     collection->addAction("clip_audio_and_video", audioAndVideo);
1027     audioAndVideo->setData("clip_audio_and_video");
1028     audioAndVideo->setCheckable(true);
1029
1030     m_clipTypeGroup = new QActionGroup(this);
1031     m_clipTypeGroup->addAction(audioOnly);
1032     m_clipTypeGroup->addAction(videoOnly);
1033     m_clipTypeGroup->addAction(audioAndVideo);
1034     connect(m_clipTypeGroup, SIGNAL(triggered(QAction *)), this, SLOT(slotUpdateClipType(QAction *)));
1035     m_clipTypeGroup->setEnabled(false);
1036
1037     KAction *insertSpace = new KAction(KIcon(), i18n("Insert Space"), this);
1038     collection->addAction("insert_space", insertSpace);
1039     connect(insertSpace, SIGNAL(triggered()), this, SLOT(slotInsertSpace()));
1040
1041     KAction *removeSpace = new KAction(KIcon(), i18n("Remove Space"), this);
1042     collection->addAction("delete_space", removeSpace);
1043     connect(removeSpace, SIGNAL(triggered()), this, SLOT(slotRemoveSpace()));
1044
1045     KAction *insertTrack = new KAction(KIcon(), i18n("Insert Track"), this);
1046     collection->addAction("insert_track", insertTrack);
1047     connect(insertTrack, SIGNAL(triggered()), this, SLOT(slotInsertTrack()));
1048
1049     KAction *deleteTrack = new KAction(KIcon(), i18n("Delete Track"), this);
1050     collection->addAction("delete_track", deleteTrack);
1051     connect(deleteTrack, SIGNAL(triggered()), this, SLOT(slotDeleteTrack()));
1052
1053     KAction *changeTrack = new KAction(KIcon(), i18n("Change Track"), this);
1054     collection->addAction("change_track", changeTrack);
1055     connect(changeTrack, SIGNAL(triggered()), this, SLOT(slotChangeTrack()));
1056
1057     KAction *addGuide = new KAction(KIcon("document-new"), i18n("Add Guide"), this);
1058     collection->addAction("add_guide", addGuide);
1059     connect(addGuide, SIGNAL(triggered()), this, SLOT(slotAddGuide()));
1060
1061     QAction *delGuide = new KAction(KIcon("edit-delete"), i18n("Delete Guide"), this);
1062     collection->addAction("delete_guide", delGuide);
1063     connect(delGuide, SIGNAL(triggered()), this, SLOT(slotDeleteGuide()));
1064
1065     QAction *editGuide = new KAction(KIcon("document-properties"), i18n("Edit Guide"), this);
1066     collection->addAction("edit_guide", editGuide);
1067     connect(editGuide, SIGNAL(triggered()), this, SLOT(slotEditGuide()));
1068
1069     QAction *delAllGuides = new KAction(KIcon("edit-delete"), i18n("Delete All Guides"), this);
1070     collection->addAction("delete_all_guides", delAllGuides);
1071     connect(delAllGuides, SIGNAL(triggered()), this, SLOT(slotDeleteAllGuides()));
1072
1073     QAction *pasteEffects = new KAction(KIcon("edit-paste"), i18n("Paste Effects"), this);
1074     collection->addAction("paste_effects", pasteEffects);
1075     pasteEffects->setData("paste_effects");
1076     connect(pasteEffects , SIGNAL(triggered()), this, SLOT(slotPasteEffects()));
1077
1078     QAction *showTimeline = new KAction(i18n("Show Timeline"), this);
1079     collection->addAction("show_timeline", showTimeline);
1080     showTimeline->setCheckable(true);
1081     showTimeline->setChecked(true);
1082     connect(showTimeline, SIGNAL(triggered(bool)), this, SLOT(slotShowTimeline(bool)));
1083
1084     /*QAction *maxCurrent = new KAction(i18n("Maximize Current Widget"), this);
1085     collection->addAction("maximize_current", maxCurrent);
1086     maxCurrent->setCheckable(true);
1087     maxCurrent->setChecked(false);
1088     connect(maxCurrent, SIGNAL(triggered(bool)), this, SLOT(slotMaximizeCurrent(bool)));*/
1089
1090
1091     m_closeAction = KStandardAction::close(this, SLOT(closeCurrentDocument()), collection);
1092
1093     KStandardAction::quit(this, SLOT(queryQuit()), collection);
1094
1095     KStandardAction::open(this, SLOT(openFile()), collection);
1096
1097     m_saveAction = KStandardAction::save(this, SLOT(saveFile()), collection);
1098
1099     KStandardAction::saveAs(this, SLOT(saveFileAs()), collection);
1100
1101     KStandardAction::openNew(this, SLOT(newFile()), collection);
1102
1103     KStandardAction::preferences(this, SLOT(slotPreferences()), collection);
1104
1105     KStandardAction::configureNotifications(this , SLOT(configureNotifications()), collection);
1106
1107     KStandardAction::copy(this, SLOT(slotCopy()), collection);
1108
1109     KStandardAction::paste(this, SLOT(slotPaste()), collection);
1110
1111     KAction *undo = KStandardAction::undo(m_commandStack, SLOT(undo()), collection);
1112     undo->setEnabled(false);
1113     connect(m_commandStack, SIGNAL(canUndoChanged(bool)), undo, SLOT(setEnabled(bool)));
1114
1115     KAction *redo = KStandardAction::redo(m_commandStack, SLOT(redo()), collection);
1116     redo->setEnabled(false);
1117     connect(m_commandStack, SIGNAL(canRedoChanged(bool)), redo, SLOT(setEnabled(bool)));
1118
1119     KStandardAction::fullScreen(this, SLOT(slotFullScreen()), this, collection);
1120
1121     /*
1122     //TODO: Add status tooltip to actions ?
1123     connect(collection, SIGNAL(actionHovered(QAction*)),
1124             this, SLOT(slotDisplayActionMessage(QAction*)));*/
1125
1126
1127     QAction *addClip = new KAction(KIcon("kdenlive-add-clip"), i18n("Add Clip"), this);
1128     collection->addAction("add_clip", addClip);
1129     connect(addClip , SIGNAL(triggered()), m_projectList, SLOT(slotAddClip()));
1130
1131     QAction *addColorClip = new KAction(KIcon("kdenlive-add-color-clip"), i18n("Add Color Clip"), this);
1132     collection->addAction("add_color_clip", addColorClip);
1133     connect(addColorClip , SIGNAL(triggered()), m_projectList, SLOT(slotAddColorClip()));
1134
1135     QAction *addSlideClip = new KAction(KIcon("kdenlive-add-slide-clip"), i18n("Add Slideshow Clip"), this);
1136     collection->addAction("add_slide_clip", addSlideClip);
1137     connect(addSlideClip , SIGNAL(triggered()), m_projectList, SLOT(slotAddSlideshowClip()));
1138
1139     QAction *addTitleClip = new KAction(KIcon("kdenlive-add-text-clip"), i18n("Add Title Clip"), this);
1140     collection->addAction("add_text_clip", addTitleClip);
1141     connect(addTitleClip , SIGNAL(triggered()), m_projectList, SLOT(slotAddTitleClip()));
1142
1143     QAction *addTitleTemplateClip = new KAction(KIcon("kdenlive-add-text-clip"), i18n("Add Template Title"), this);
1144     collection->addAction("add_text_template_clip", addTitleTemplateClip);
1145     connect(addTitleTemplateClip , SIGNAL(triggered()), m_projectList, SLOT(slotAddTitleTemplateClip()));
1146
1147     QAction *addFolderButton = new KAction(KIcon("folder-new"), i18n("Create Folder"), this);
1148     collection->addAction("add_folder", addFolderButton);
1149     connect(addFolderButton , SIGNAL(triggered()), m_projectList, SLOT(slotAddFolder()));
1150
1151     QAction *clipProperties = new KAction(KIcon("document-edit"), i18n("Clip Properties"), this);
1152     collection->addAction("clip_properties", clipProperties);
1153     clipProperties->setData("clip_properties");
1154     connect(clipProperties , SIGNAL(triggered()), m_projectList, SLOT(slotEditClip()));
1155     clipProperties->setEnabled(false);
1156
1157     QAction *openClip = new KAction(KIcon("document-open"), i18n("Edit Clip"), this);
1158     collection->addAction("edit_clip", openClip);
1159     openClip->setData("edit_clip");
1160     connect(openClip , SIGNAL(triggered()), m_projectList, SLOT(slotOpenClip()));
1161     openClip->setEnabled(false);
1162
1163     QAction *deleteClip = new KAction(KIcon("edit-delete"), i18n("Delete Clip"), this);
1164     collection->addAction("delete_clip", deleteClip);
1165     deleteClip->setData("delete_clip");
1166     connect(deleteClip , SIGNAL(triggered()), m_projectList, SLOT(slotRemoveClip()));
1167     deleteClip->setEnabled(false);
1168
1169     QAction *reloadClip = new KAction(KIcon("view-refresh"), i18n("Reload Clip"), this);
1170     collection->addAction("reload_clip", reloadClip);
1171     reloadClip->setData("reload_clip");
1172     connect(reloadClip , SIGNAL(triggered()), m_projectList, SLOT(slotReloadClip()));
1173     reloadClip->setEnabled(false);
1174
1175     QMenu *addClips = new QMenu();
1176     addClips->addAction(addClip);
1177     addClips->addAction(addColorClip);
1178     addClips->addAction(addSlideClip);
1179     addClips->addAction(addTitleClip);
1180     addClips->addAction(addTitleTemplateClip);
1181     addClips->addAction(addFolderButton);
1182
1183     addClips->addAction(reloadClip);
1184     addClips->addAction(clipProperties);
1185     addClips->addAction(openClip);
1186     addClips->addAction(deleteClip);
1187     m_projectList->setupMenu(addClips, addClip);
1188
1189     //connect(collection, SIGNAL( clearStatusText() ),
1190     //statusBar(), SLOT( clear() ) );
1191 }
1192
1193 void MainWindow::slotDisplayActionMessage(QAction *a)
1194 {
1195     statusBar()->showMessage(a->data().toString(), 3000);
1196 }
1197
1198 void MainWindow::saveOptions()
1199 {
1200     KdenliveSettings::self()->writeConfig();
1201     KSharedConfigPtr config = KGlobal::config();
1202     m_fileOpenRecent->saveEntries(KConfigGroup(config, "Recent Files"));
1203     KConfigGroup treecolumns(config, "Project Tree");
1204     treecolumns.writeEntry("columns", m_projectList->headerInfo());
1205     config->sync();
1206 }
1207
1208 void MainWindow::readOptions()
1209 {
1210     KSharedConfigPtr config = KGlobal::config();
1211     m_fileOpenRecent->loadEntries(KConfigGroup(config, "Recent Files"));
1212     KConfigGroup initialGroup(config, "version");
1213     bool upgrade = false;
1214     if (initialGroup.exists()) {
1215         if (initialGroup.readEntry("version", QString()).section(' ', 0, 0) != QString(version).section(' ', 0, 0)) {
1216             upgrade = true;
1217         }
1218
1219         if (initialGroup.readEntry("version") == "0.7") {
1220             //Add new settings from 0.7.1
1221             if (KdenliveSettings::defaultprojectfolder().isEmpty()) {
1222                 QString path = QDir::homePath() + "/kdenlive";
1223                 if (KStandardDirs::makeDir(path)  == false) {
1224                     kDebug() << "/// ERROR CREATING PROJECT FOLDER: " << path;
1225                 } else KdenliveSettings::setDefaultprojectfolder(path);
1226             }
1227         }
1228
1229     }
1230
1231     if (!initialGroup.exists() || upgrade) {
1232         // this is our first run, show Wizard
1233         Wizard *w = new Wizard(upgrade, this);
1234         if (w->exec() == QDialog::Accepted && w->isOk()) {
1235             w->adjustSettings();
1236             initialGroup.writeEntry("version", version);
1237             delete w;
1238         } else {
1239             ::exit(1);
1240         }
1241     }
1242     KConfigGroup treecolumns(config, "Project Tree");
1243     const QByteArray state = treecolumns.readEntry("columns", QByteArray());
1244     if (!state.isEmpty())
1245         m_projectList->setHeaderInfo(state);
1246 }
1247
1248 void MainWindow::slotRunWizard()
1249 {
1250     Wizard *w = new Wizard(false, this);
1251     if (w->exec() == QDialog::Accepted && w->isOk()) {
1252         w->adjustSettings();
1253     }
1254     delete w;
1255 }
1256
1257 void MainWindow::newFile(bool showProjectSettings)
1258 {
1259     if (!m_timelineArea->isEnabled()) return;
1260     QString profileName;
1261     KUrl projectFolder;
1262     QPoint projectTracks(KdenliveSettings::videotracks(), KdenliveSettings::audiotracks());
1263     if (!showProjectSettings && m_timelineArea->count() == 0) {
1264         if (!KdenliveSettings::activatetabs()) closeCurrentDocument();
1265         profileName = KdenliveSettings::default_profile();
1266         projectFolder = KdenliveSettings::defaultprojectfolder();
1267     } else {
1268         ProjectSettings *w = new ProjectSettings(projectTracks.x(), projectTracks.y(), KdenliveSettings::defaultprojectfolder(), false, this);
1269         if (w->exec() != QDialog::Accepted) return;
1270         if (!KdenliveSettings::activatetabs()) closeCurrentDocument();
1271         KdenliveSettings::setVideothumbnails(w->enableVideoThumbs());
1272         m_buttonVideoThumbs->setChecked(KdenliveSettings::videothumbnails());
1273         KdenliveSettings::setAudiothumbnails(w->enableAudioThumbs());
1274         m_buttonAudioThumbs->setChecked(KdenliveSettings::audiothumbnails());
1275         profileName = w->selectedProfile();
1276         projectFolder = w->selectedFolder();
1277         projectTracks = w->tracks();
1278         delete w;
1279     }
1280     KdenliveDoc *doc = new KdenliveDoc(KUrl(), projectFolder, m_commandStack, profileName, projectTracks, m_projectMonitor->render, this);
1281     doc->m_autosave = new KAutoSaveFile(KUrl(), doc);
1282     bool ok;
1283     TrackView *trackView = new TrackView(doc, &ok, this);
1284     m_timelineArea->addTab(trackView, KIcon("kdenlive"), doc->description());
1285     if (!ok) {
1286         // MLT is broken
1287         m_timelineArea->setEnabled(false);
1288         m_projectList->setEnabled(false);
1289         m_monitorManager->slotBlockMonitors();
1290         slotPreferences(6);
1291         return;
1292     }
1293     if (m_timelineArea->count() == 1) {
1294         connectDocumentInfo(doc);
1295         connectDocument(trackView, doc);
1296     } else m_timelineArea->setTabBarHidden(false);
1297     m_closeAction->setEnabled(m_timelineArea->count() > 1);
1298 }
1299
1300 void MainWindow::activateDocument()
1301 {
1302     if (m_timelineArea->currentWidget() == NULL || !m_timelineArea->isEnabled()) return;
1303     TrackView *currentTab = (TrackView *) m_timelineArea->currentWidget();
1304     KdenliveDoc *currentDoc = currentTab->document();
1305     connectDocumentInfo(currentDoc);
1306     connectDocument(currentTab, currentDoc);
1307 }
1308
1309 void MainWindow::closeCurrentDocument()
1310 {
1311     QWidget *w = m_timelineArea->currentWidget();
1312     if (!w) return;
1313     // closing current document
1314     int ix = m_timelineArea->currentIndex() + 1;
1315     if (ix == m_timelineArea->count()) ix = 0;
1316     m_timelineArea->setCurrentIndex(ix);
1317     TrackView *tabToClose = (TrackView *) w;
1318     KdenliveDoc *docToClose = tabToClose->document();
1319     if (docToClose && docToClose->isModified()) {
1320         switch (KMessageBox::warningYesNoCancel(this, i18n("Save changes to document?"))) {
1321         case KMessageBox::Yes :
1322             // save document here. If saving fails, return false;
1323             if (saveFile() == false) return;
1324             break;
1325         case KMessageBox::Cancel :
1326             return;
1327             break;
1328         default:
1329             break;
1330         }
1331     }
1332     m_timelineArea->removeTab(m_timelineArea->indexOf(w));
1333     if (m_timelineArea->count() == 1) {
1334         m_timelineArea->setTabBarHidden(true);
1335         m_closeAction->setEnabled(false);
1336     }
1337     if (docToClose == m_activeDocument) {
1338         delete m_activeDocument;
1339         m_activeDocument = NULL;
1340         m_effectStack->clear();
1341         m_transitionConfig->slotTransitionItemSelected(NULL, 0, QPoint(), false);
1342     } else delete docToClose;
1343     if (w == m_activeTimeline) {
1344         delete m_activeTimeline;
1345         m_activeTimeline = NULL;
1346     } else delete w;
1347 }
1348
1349 bool MainWindow::saveFileAs(const QString &outputFileName)
1350 {
1351     QString currentSceneList;
1352     if (KdenliveSettings::dropbframes()) {
1353         KdenliveSettings::setDropbframes(false);
1354         m_activeDocument->clipManager()->updatePreviewSettings();
1355         currentSceneList = m_projectMonitor->sceneList();
1356         KdenliveSettings::setDropbframes(true);
1357         m_activeDocument->clipManager()->updatePreviewSettings();
1358     } else currentSceneList = m_projectMonitor->sceneList();
1359
1360     if (m_activeDocument->saveSceneList(outputFileName, currentSceneList) == false)
1361         return false;
1362
1363     // Save timeline thumbnails
1364     m_activeTimeline->projectView()->saveThumbnails();
1365     m_activeDocument->setUrl(KUrl(outputFileName));
1366     if (m_activeDocument->m_autosave == NULL) {
1367         m_activeDocument->m_autosave = new KAutoSaveFile(KUrl(outputFileName), this);
1368     } else m_activeDocument->m_autosave->setManagedFile(KUrl(outputFileName));
1369     setCaption(m_activeDocument->description());
1370     m_timelineArea->setTabText(m_timelineArea->currentIndex(), m_activeDocument->description());
1371     m_timelineArea->setTabToolTip(m_timelineArea->currentIndex(), m_activeDocument->url().path());
1372     m_activeDocument->setModified(false);
1373     m_fileOpenRecent->addUrl(KUrl(outputFileName));
1374     return true;
1375 }
1376
1377 bool MainWindow::saveFileAs()
1378 {
1379     // Check that the Kdenlive mime type is correctly installed
1380     QString mimetype = "application/x-kdenlive";
1381     KMimeType::Ptr mime = KMimeType::mimeType(mimetype);
1382     if (!mime) mimetype = "*.kdenlive";
1383
1384     QString outputFile = KFileDialog::getSaveFileName(KUrl(), mimetype);
1385     if (outputFile.isEmpty()) return false;
1386     if (QFile::exists(outputFile)) {
1387         if (KMessageBox::questionYesNo(this, i18n("File already exists.\nDo you want to overwrite it?")) == KMessageBox::No) return false;
1388     }
1389     return saveFileAs(outputFile);
1390 }
1391
1392 bool MainWindow::saveFile()
1393 {
1394     if (!m_activeDocument) return true;
1395     if (m_activeDocument->url().isEmpty()) {
1396         return saveFileAs();
1397     } else {
1398         bool result = saveFileAs(m_activeDocument->url().path());
1399         m_activeDocument->m_autosave->resize(0);
1400         return result;
1401     }
1402 }
1403
1404 void MainWindow::openFile()
1405 {
1406     // Check that the Kdenlive mime type is correctly installed
1407     QString mimetype = "application/x-kdenlive";
1408     KMimeType::Ptr mime = KMimeType::mimeType(mimetype);
1409     if (!mime) mimetype = "*.kdenlive";
1410
1411     KUrl url = KFileDialog::getOpenUrl(KUrl("kfiledialog:///projectfolder"), mimetype);
1412     if (url.isEmpty()) return;
1413     m_fileOpenRecent->addUrl(url);
1414     openFile(url);
1415 }
1416
1417 void MainWindow::openLastFile()
1418 {
1419     KSharedConfigPtr config = KGlobal::config();
1420     KUrl::List urls = m_fileOpenRecent->urls();
1421     //WARNING: this is buggy, we get a random url, not the last one. Bug in KRecentFileAction?
1422     if (urls.isEmpty()) newFile(false);
1423     else openFile(urls.last());
1424 }
1425
1426 void MainWindow::openFile(const KUrl &url)
1427 {
1428     // Check if the document is already opened
1429     const int ct = m_timelineArea->count();
1430     bool isOpened = false;
1431     int i;
1432     for (i = 0; i < ct; i++) {
1433         TrackView *tab = (TrackView *) m_timelineArea->widget(i);
1434         KdenliveDoc *doc = tab->document();
1435         if (doc->url() == url) {
1436             isOpened = true;
1437             break;
1438         }
1439     }
1440     if (isOpened) {
1441         m_timelineArea->setCurrentIndex(i);
1442         return;
1443     }
1444
1445     // Check for backup file
1446     QList<KAutoSaveFile *> staleFiles = KAutoSaveFile::staleFiles(url);
1447     if (!staleFiles.isEmpty()) {
1448         if (KMessageBox::questionYesNo(this,
1449                                        i18n("Auto-saved files exist. Do you want to recover them now?"),
1450                                        i18n("File Recovery"),
1451                                        KGuiItem(i18n("Recover")), KGuiItem(i18n("Don't recover"))) == KMessageBox::Yes) {
1452             recoverFiles(staleFiles);
1453             return;
1454         } else {
1455             // remove the stale files
1456             foreach(KAutoSaveFile *stale, staleFiles) {
1457                 stale->open(QIODevice::ReadWrite);
1458                 delete stale;
1459             }
1460         }
1461     }
1462     if (!KdenliveSettings::activatetabs()) closeCurrentDocument();
1463     doOpenFile(url, NULL);
1464 }
1465
1466 void MainWindow::doOpenFile(const KUrl &url, KAutoSaveFile *stale)
1467 {
1468     if (!m_timelineArea->isEnabled()) return;
1469     KdenliveDoc *doc = new KdenliveDoc(url, KdenliveSettings::defaultprojectfolder(), m_commandStack, KdenliveSettings::default_profile(), QPoint(KdenliveSettings::videotracks(), KdenliveSettings::audiotracks()), m_projectMonitor->render, this);
1470     if (stale == NULL) {
1471         stale = new KAutoSaveFile(url, doc);
1472         doc->m_autosave = stale;
1473     } else {
1474         doc->m_autosave = stale;
1475         doc->setUrl(stale->managedFile());
1476         doc->setModified(true);
1477         stale->setParent(doc);
1478     }
1479     connectDocumentInfo(doc);
1480     bool ok;
1481     TrackView *trackView = new TrackView(doc, &ok, this);
1482     m_timelineArea->setCurrentIndex(m_timelineArea->addTab(trackView, KIcon("kdenlive"), doc->description()));
1483     if (!ok) {
1484         m_timelineArea->setEnabled(false);
1485         m_projectList->setEnabled(false);
1486         m_monitorManager->slotBlockMonitors();
1487         slotPreferences(6);
1488         return;
1489     }
1490     m_timelineArea->setTabToolTip(m_timelineArea->currentIndex(), doc->url().path());
1491     trackView->setDuration(trackView->duration());
1492     trackView->projectView()->initCursorPos(m_projectMonitor->render->seekPosition().frames(doc->fps()));
1493
1494     if (m_timelineArea->count() > 1) m_timelineArea->setTabBarHidden(false);
1495     slotGotProgressInfo(QString(), -1);
1496     m_clipMonitor->refreshMonitor(true);
1497     m_projectMonitor->adjustRulerSize(trackView->duration());
1498     m_projectMonitor->slotZoneMoved(trackView->inPoint(), trackView->outPoint());
1499 }
1500
1501 void MainWindow::recoverFiles(QList<KAutoSaveFile *> staleFiles)
1502 {
1503     if (!KdenliveSettings::activatetabs()) closeCurrentDocument();
1504     foreach(KAutoSaveFile *stale, staleFiles) {
1505         /*if (!stale->open(QIODevice::QIODevice::ReadOnly)) {
1506                   // show an error message; we could not steal the lockfile
1507                   // maybe another application got to the file before us?
1508                   delete stale;
1509                   continue;
1510         }*/
1511         kDebug() << "// OPENING RECOVERY: " << stale->fileName() << "\nMANAGED: " << stale->managedFile().path();
1512         // the stalefiles also contain ".lock" files so we must ignore them... bug in KAutoSaveFile?
1513         if (!stale->fileName().endsWith(".lock")) doOpenFile(KUrl(stale->fileName()), stale);
1514         else KIO::NetAccess::del(KUrl(stale->fileName()), this);
1515     }
1516 }
1517
1518
1519 void MainWindow::parseProfiles(const QString &mltPath)
1520 {
1521     // kDebug()<<" + + YOUR MLT INSTALL WAS FOUND IN: "<< MLT_PREFIX <<endl;
1522
1523     //KdenliveSettings::setDefaulttmpfolder();
1524     if (!mltPath.isEmpty()) {
1525         KdenliveSettings::setMltpath(mltPath + "/share/mlt/profiles/");
1526         KdenliveSettings::setRendererpath(mltPath + "/bin/melt");
1527     }
1528
1529     if (KdenliveSettings::mltpath().isEmpty()) {
1530         KdenliveSettings::setMltpath(QString(MLT_PREFIX) + QString("/share/mlt/profiles/"));
1531     }
1532     if (KdenliveSettings::rendererpath().isEmpty() || KdenliveSettings::rendererpath().endsWith("inigo")) {
1533         QString meltPath = QString(MLT_PREFIX) + QString("/bin/melt");
1534         if (!QFile::exists(meltPath))
1535             meltPath = KStandardDirs::findExe("melt");
1536         KdenliveSettings::setRendererpath(meltPath);
1537     }
1538     QStringList profilesFilter;
1539     profilesFilter << "*";
1540     QStringList profilesList = QDir(KdenliveSettings::mltpath()).entryList(profilesFilter, QDir::Files);
1541
1542     if (profilesList.isEmpty()) {
1543         // Cannot find MLT path, try finding melt
1544         QString profilePath = KdenliveSettings::rendererpath();
1545         if (!profilePath.isEmpty()) {
1546             profilePath = profilePath.section('/', 0, -3);
1547             KdenliveSettings::setMltpath(profilePath + "/share/mlt/profiles/");
1548             QStringList profilesList = QDir(KdenliveSettings::mltpath()).entryList(profilesFilter, QDir::Files);
1549         }
1550
1551         if (profilesList.isEmpty()) {
1552             // Cannot find the MLT profiles, ask for location
1553             KUrlRequesterDialog *getUrl = new KUrlRequesterDialog(KdenliveSettings::mltpath(), i18n("Cannot find your Mlt profiles, please give the path"), this);
1554             getUrl->fileDialog()->setMode(KFile::Directory);
1555             if (getUrl->exec() == QDialog::Rejected) {
1556                 ::exit(0);
1557             }
1558             KUrl mltPath = getUrl->selectedUrl();
1559             delete getUrl;
1560             if (mltPath.isEmpty()) ::exit(0);
1561             KdenliveSettings::setMltpath(mltPath.path(KUrl::AddTrailingSlash));
1562             QStringList profilesList = QDir(KdenliveSettings::mltpath()).entryList(profilesFilter, QDir::Files);
1563         }
1564     }
1565
1566     if (KdenliveSettings::rendererpath().isEmpty()) {
1567         // Cannot find the MLT melt renderer, ask for location
1568         KUrlRequesterDialog *getUrl = new KUrlRequesterDialog(QString(), i18n("Cannot find the melt program required for rendering (part of Mlt)"), this);
1569         if (getUrl->exec() == QDialog::Rejected) {
1570             ::exit(0);
1571         }
1572         KUrl rendererPath = getUrl->selectedUrl();
1573         delete getUrl;
1574         if (rendererPath.isEmpty()) ::exit(0);
1575         KdenliveSettings::setRendererpath(rendererPath.path());
1576     }
1577
1578     kDebug() << "RESULTING MLT PATH: " << KdenliveSettings::mltpath();
1579
1580     // Parse MLT profiles to build a list of available video formats
1581     if (profilesList.isEmpty()) parseProfiles();
1582 }
1583
1584
1585 void MainWindow::slotEditProfiles()
1586 {
1587     ProfilesDialog *w = new ProfilesDialog;
1588     if (w->exec() == QDialog::Accepted) {
1589         KdenliveSettingsDialog* d = static_cast <KdenliveSettingsDialog*>(KConfigDialog::exists("settings"));
1590         if (d) d->checkProfile();
1591     }
1592     delete w;
1593 }
1594
1595 void MainWindow::slotDetectAudioDriver()
1596 {
1597     /* WARNING: do not use this method because sometimes detects wrong driver (pulse instead of alsa),
1598     leading to no audio output, see bug #934 */
1599
1600     //decide which audio driver is really best, in some cases SDL is wrong
1601     if (KdenliveSettings::audiodrivername().isEmpty()) {
1602         QString driver;
1603         KProcess readProcess;
1604         //PulseAudio needs to be selected if it exists, the ALSA pulse pcm device is not fast enough.
1605         if (!KStandardDirs::findExe("pactl").isEmpty()) {
1606             readProcess.setOutputChannelMode(KProcess::OnlyStdoutChannel);
1607             readProcess.setProgram("pactl", QStringList() << "stat");
1608             readProcess.execute(2000); // Kill it after 2 seconds
1609
1610             QString result = QString(readProcess.readAllStandardOutput());
1611             kDebug() << "// / / / / / READING PACTL: ";
1612             kDebug() << result;
1613             if (!result.isEmpty()) {
1614                 driver = "pulse";
1615                 kDebug() << "// / / / / PULSEAUDIO DETECTED";
1616             }
1617         }
1618         //put others here
1619         KdenliveSettings::setAutoaudiodrivername(driver);
1620     }
1621 }
1622
1623 void MainWindow::slotEditProjectSettings()
1624 {
1625     QPoint p = m_activeDocument->getTracksCount();
1626     ProjectSettings *w = new ProjectSettings(p.x(), p.y(), m_activeDocument->projectFolder().path(), true, this);
1627
1628     if (w->exec() == QDialog::Accepted) {
1629         QString profile = w->selectedProfile();
1630         m_activeDocument->setProjectFolder(w->selectedFolder());
1631         if (m_renderWidget) m_renderWidget->setDocumentPath(w->selectedFolder().path(KUrl::AddTrailingSlash));
1632         if (m_activeDocument->profilePath() != profile) {
1633             // Profile was changed
1634             double dar = m_activeDocument->dar();
1635
1636             // Deselect current effect / transition
1637             m_effectStack->slotClipItemSelected(NULL, 0);
1638             m_transitionConfig->slotTransitionItemSelected(NULL, 0, QPoint(), false);
1639             m_clipMonitor->slotSetXml(NULL, 0);
1640             m_activeDocument->setProfilePath(profile);
1641             KdenliveSettings::setCurrent_profile(profile);
1642             KdenliveSettings::setProject_fps(m_activeDocument->fps());
1643             setCaption(m_activeDocument->description(), m_activeDocument->isModified());
1644
1645             m_activeDocument->clipManager()->clearUnusedProducers();
1646             m_monitorManager->resetProfiles(m_activeDocument->timecode());
1647
1648             m_transitionConfig->updateProjectFormat(m_activeDocument->mltProfile(), m_activeDocument->timecode(), m_activeTimeline->tracksNumber());
1649             m_effectStack->updateProjectFormat(m_activeDocument->mltProfile(), m_activeDocument->timecode());
1650             if (m_renderWidget) m_renderWidget->setProfile(m_activeDocument->mltProfile());
1651             m_timelineArea->setTabText(m_timelineArea->currentIndex(), m_activeDocument->description());
1652             //m_activeDocument->clipManager()->resetProducersList(m_projectMonitor->render->producersList());
1653             if (dar != m_activeDocument->dar()) m_projectList->reloadClipThumbnails();
1654             m_activeTimeline->updateProjectFps();
1655
1656             // We need to desactivate & reactivate monitors to get a refresh
1657             //m_monitorManager->switchMonitors();
1658         }
1659     }
1660     delete w;
1661 }
1662
1663 void MainWindow::slotRenderProject()
1664 {
1665     if (!m_renderWidget) {
1666         QString projectfolder = m_activeDocument ? m_activeDocument->projectFolder().path(KUrl::AddTrailingSlash) : KdenliveSettings::defaultprojectfolder();
1667         m_renderWidget = new RenderWidget(projectfolder, this);
1668         connect(m_renderWidget, SIGNAL(selectedRenderProfile(const QString &, const QString &, const QString&)), this, SLOT(slotSetDocumentRenderProfile(const QString &, const QString &, const QString&)));
1669         connect(m_renderWidget, SIGNAL(prepareRenderingData(bool, bool, const QString&)), this, SLOT(slotPrepareRendering(bool, bool, const QString&)));
1670         connect(m_renderWidget, SIGNAL(abortProcess(const QString &)), this, SIGNAL(abortRenderJob(const QString &)));
1671         connect(m_renderWidget, SIGNAL(openDvdWizard(const QString &, const QString &)), this, SLOT(slotDvdWizard(const QString &, const QString &)));
1672         if (m_activeDocument) {
1673             m_renderWidget->setProfile(m_activeDocument->mltProfile());
1674             m_renderWidget->setGuides(m_activeDocument->guidesXml(), m_activeDocument->projectDuration());
1675             m_renderWidget->setDocumentPath(m_activeDocument->projectFolder().path(KUrl::AddTrailingSlash));
1676             m_renderWidget->setRenderProfile(m_activeDocument->getDocumentProperty("renderdestination"), m_activeDocument->getDocumentProperty("renderprofile"), m_activeDocument->getDocumentProperty("renderurl"));
1677         }
1678     }
1679     /*TrackView *currentTab = (TrackView *) m_timelineArea->currentWidget();
1680     if (currentTab) m_renderWidget->setTimeline(currentTab);
1681     m_renderWidget->setDocument(m_activeDocument);*/
1682     m_renderWidget->show();
1683     m_renderWidget->showNormal();
1684 }
1685
1686 void MainWindow::setRenderingProgress(const QString &url, int progress)
1687 {
1688     if (m_renderWidget) m_renderWidget->setRenderJob(url, progress);
1689 }
1690
1691 void MainWindow::setRenderingFinished(const QString &url, int status, const QString &error)
1692 {
1693     if (m_renderWidget) m_renderWidget->setRenderStatus(url, status, error);
1694 }
1695
1696 void MainWindow::slotUpdateMousePosition(int pos)
1697 {
1698     if (m_activeDocument)
1699         switch (m_timecodeFormat->currentIndex()) {
1700         case 0:
1701             statusBar()->changeItem(m_activeDocument->timecode().getTimecodeFromFrames(pos), ID_TIMELINE_POS);
1702             break;
1703         default:
1704             statusBar()->changeItem(QString::number(pos), ID_TIMELINE_POS);
1705         }
1706 }
1707
1708 void MainWindow::slotUpdateDocumentState(bool modified)
1709 {
1710     if (!m_activeDocument) return;
1711     setCaption(m_activeDocument->description(), modified);
1712     m_saveAction->setEnabled(modified);
1713     if (modified) {
1714         m_timelineArea->setTabTextColor(m_timelineArea->currentIndex(), palette().color(QPalette::Link));
1715         m_timelineArea->setTabIcon(m_timelineArea->currentIndex(), KIcon("document-save"));
1716     } else {
1717         m_timelineArea->setTabTextColor(m_timelineArea->currentIndex(), palette().color(QPalette::Text));
1718         m_timelineArea->setTabIcon(m_timelineArea->currentIndex(), KIcon("kdenlive"));
1719     }
1720 }
1721
1722 void MainWindow::connectDocumentInfo(KdenliveDoc *doc)
1723 {
1724     if (m_activeDocument) {
1725         if (m_activeDocument == doc) return;
1726         disconnect(m_activeDocument, SIGNAL(progressInfo(const QString &, int)), this, SLOT(slotGotProgressInfo(const QString &, int)));
1727     }
1728     connect(doc, SIGNAL(progressInfo(const QString &, int)), this, SLOT(slotGotProgressInfo(const QString &, int)));
1729 }
1730
1731 void MainWindow::connectDocument(TrackView *trackView, KdenliveDoc *doc)   //changed
1732 {
1733     //m_projectMonitor->stop();
1734     m_closeAction->setEnabled(m_timelineArea->count() > 1);
1735     kDebug() << "///////////////////   CONNECTING DOC TO PROJECT VIEW ////////////////";
1736     if (m_activeDocument) {
1737         if (m_activeDocument == doc) return;
1738         if (m_activeTimeline) {
1739             disconnect(m_projectMonitor, SIGNAL(renderPosition(int)), m_activeTimeline, SLOT(moveCursorPos(int)));
1740             disconnect(m_projectMonitor, SIGNAL(zoneUpdated(QPoint)), m_activeTimeline, SLOT(slotSetZone(QPoint)));
1741             disconnect(m_projectMonitor, SIGNAL(durationChanged(int)), m_activeTimeline, SLOT(setDuration(int)));
1742             disconnect(m_projectList, SIGNAL(projectModified()), m_activeDocument, SLOT(setModified()));
1743             disconnect(m_projectMonitor->render, SIGNAL(refreshDocumentProducers()), m_activeDocument, SLOT(checkProjectClips()));
1744
1745             disconnect(m_activeDocument, SIGNAL(guidesUpdated()), this, SLOT(slotGuidesUpdated()));
1746             disconnect(m_activeDocument, SIGNAL(addProjectClip(DocClipBase *, bool)), m_projectList, SLOT(slotAddClip(DocClipBase *, bool)));
1747             disconnect(m_activeDocument, SIGNAL(resetProjectList()), m_projectList, SLOT(slotResetProjectList()));
1748             disconnect(m_activeDocument, SIGNAL(signalDeleteProjectClip(const QString &)), m_projectList, SLOT(slotDeleteClip(const QString &)));
1749             disconnect(m_activeDocument, SIGNAL(updateClipDisplay(const QString &)), m_projectList, SLOT(slotUpdateClip(const QString &)));
1750             disconnect(m_activeDocument, SIGNAL(selectLastAddedClip(const QString &)), m_projectList, SLOT(slotSelectClip(const QString &)));
1751             disconnect(m_activeDocument, SIGNAL(deleteTimelineClip(const QString &)), m_activeTimeline, SLOT(slotDeleteClip(const QString &)));
1752             disconnect(m_activeTimeline->projectView(), SIGNAL(clipItemSelected(ClipItem*, int)), m_effectStack, SLOT(slotClipItemSelected(ClipItem*, int)));
1753             disconnect(m_activeTimeline->projectView(), SIGNAL(clipItemSelected(ClipItem*, int)), this, SLOT(slotActivateEffectStackView()));
1754             disconnect(m_activeTimeline->projectView(), SIGNAL(transitionItemSelected(Transition*, int, QPoint, bool)), m_transitionConfig, SLOT(slotTransitionItemSelected(Transition*, int, QPoint, bool)));
1755             disconnect(m_activeTimeline->projectView(), SIGNAL(transitionItemSelected(Transition*, int, QPoint, bool)), this, SLOT(slotActivateTransitionView(Transition *)));
1756             disconnect(m_zoomSlider, SIGNAL(valueChanged(int)), m_activeTimeline, SLOT(slotChangeZoom(int)));
1757             disconnect(m_activeTimeline->projectView(), SIGNAL(displayMessage(const QString&, MessageType)), m_messageLabel, SLOT(setMessage(const QString&, MessageType)));
1758             disconnect(m_activeTimeline->projectView(), SIGNAL(showClipFrame(DocClipBase *, const int)), m_clipMonitor, SLOT(slotSetXml(DocClipBase *, const int)));
1759             disconnect(m_activeTimeline, SIGNAL(cursorMoved()), m_projectMonitor, SLOT(activateMonitor()));
1760             disconnect(m_activeTimeline, SIGNAL(insertTrack(int)), this, SLOT(slotInsertTrack(int)));
1761             disconnect(m_activeTimeline, SIGNAL(deleteTrack(int)), this, SLOT(slotDeleteTrack(int)));
1762             disconnect(m_activeTimeline, SIGNAL(changeTrack(int)), this, SLOT(slotChangeTrack(int)));
1763             disconnect(m_activeDocument, SIGNAL(docModified(bool)), this, SLOT(slotUpdateDocumentState(bool)));
1764             disconnect(m_effectStack, SIGNAL(updateClipEffect(ClipItem*, QDomElement, QDomElement, int)), m_activeTimeline->projectView(), SLOT(slotUpdateClipEffect(ClipItem*, QDomElement, QDomElement, int)));
1765             disconnect(m_effectStack, SIGNAL(removeEffect(ClipItem*, QDomElement)), m_activeTimeline->projectView(), SLOT(slotDeleteEffect(ClipItem*, QDomElement)));
1766             disconnect(m_effectStack, SIGNAL(changeEffectState(ClipItem*, int, bool)), m_activeTimeline->projectView(), SLOT(slotChangeEffectState(ClipItem*, int, bool)));
1767             disconnect(m_effectStack, SIGNAL(changeEffectPosition(ClipItem*, int, int)), m_activeTimeline->projectView(), SLOT(slotChangeEffectPosition(ClipItem*, int, int)));
1768             disconnect(m_effectStack, SIGNAL(refreshEffectStack(ClipItem*)), m_activeTimeline->projectView(), SLOT(slotRefreshEffects(ClipItem*)));
1769             disconnect(m_effectStack, SIGNAL(reloadEffects()), this, SLOT(slotReloadEffects()));
1770             disconnect(m_transitionConfig, SIGNAL(transitionUpdated(Transition *, QDomElement)), m_activeTimeline->projectView() , SLOT(slotTransitionUpdated(Transition *, QDomElement)));
1771             disconnect(m_transitionConfig, SIGNAL(seekTimeline(int)), m_activeTimeline->projectView() , SLOT(setCursorPos(int)));
1772             disconnect(m_activeTimeline->projectView(), SIGNAL(activateDocumentMonitor()), m_projectMonitor, SLOT(activateMonitor()));
1773             disconnect(m_activeTimeline, SIGNAL(zoneMoved(int, int)), this, SLOT(slotZoneMoved(int, int)));
1774             disconnect(m_projectList, SIGNAL(loadingIsOver()), m_activeTimeline->projectView(), SLOT(slotUpdateAllThumbs()));
1775             m_effectStack->clear();
1776         }
1777         //m_activeDocument->setRenderer(NULL);
1778         disconnect(m_projectList, SIGNAL(clipSelected(DocClipBase *)), m_clipMonitor, SLOT(slotSetXml(DocClipBase *)));
1779         disconnect(m_projectList, SIGNAL(refreshClip()), m_clipMonitor, SLOT(refreshMonitor()));
1780         m_clipMonitor->stop();
1781     }
1782     KdenliveSettings::setCurrent_profile(doc->profilePath());
1783     KdenliveSettings::setProject_fps(doc->fps());
1784     m_monitorManager->resetProfiles(doc->timecode());
1785     m_projectList->setDocument(doc);
1786     m_transitionConfig->updateProjectFormat(doc->mltProfile(), doc->timecode(), trackView->tracksNumber());
1787     m_effectStack->updateProjectFormat(doc->mltProfile(), doc->timecode());
1788     connect(m_projectList, SIGNAL(clipSelected(DocClipBase *)), m_clipMonitor, SLOT(slotSetXml(DocClipBase *)));
1789     connect(m_projectList, SIGNAL(refreshClip()), m_clipMonitor, SLOT(refreshMonitor()));
1790     connect(m_projectList, SIGNAL(projectModified()), doc, SLOT(setModified()));
1791     connect(m_projectList, SIGNAL(clipNameChanged(const QString, const QString)), trackView->projectView(), SLOT(clipNameChanged(const QString, const QString)));
1792
1793
1794     connect(trackView, SIGNAL(cursorMoved()), m_projectMonitor, SLOT(activateMonitor()));
1795     connect(trackView, SIGNAL(insertTrack(int)), this, SLOT(slotInsertTrack(int)));
1796     connect(trackView, SIGNAL(deleteTrack(int)), this, SLOT(slotDeleteTrack(int)));
1797     connect(trackView, SIGNAL(changeTrack(int)), this, SLOT(slotChangeTrack(int)));
1798     connect(trackView, SIGNAL(mousePosition(int)), this, SLOT(slotUpdateMousePosition(int)));
1799     connect(m_projectMonitor, SIGNAL(renderPosition(int)), trackView, SLOT(moveCursorPos(int)));
1800     connect(m_projectMonitor, SIGNAL(zoneUpdated(QPoint)), trackView, SLOT(slotSetZone(QPoint)));
1801     connect(m_projectMonitor, SIGNAL(durationChanged(int)), trackView, SLOT(setDuration(int)));
1802     connect(m_projectMonitor->render, SIGNAL(refreshDocumentProducers()), doc, SLOT(checkProjectClips()));
1803
1804     connect(doc, SIGNAL(addProjectClip(DocClipBase *, bool)), m_projectList, SLOT(slotAddClip(DocClipBase *, bool)));
1805     connect(doc, SIGNAL(resetProjectList()), m_projectList, SLOT(slotResetProjectList()));
1806     connect(doc, SIGNAL(signalDeleteProjectClip(const QString &)), m_projectList, SLOT(slotDeleteClip(const QString &)));
1807     connect(doc, SIGNAL(updateClipDisplay(const QString &)), m_projectList, SLOT(slotUpdateClip(const QString &)));
1808     connect(doc, SIGNAL(selectLastAddedClip(const QString &)), m_projectList, SLOT(slotSelectClip(const QString &)));
1809
1810     connect(doc, SIGNAL(deleteTimelineClip(const QString &)), trackView, SLOT(slotDeleteClip(const QString &)));
1811     connect(doc, SIGNAL(docModified(bool)), this, SLOT(slotUpdateDocumentState(bool)));
1812     connect(doc, SIGNAL(guidesUpdated()), this, SLOT(slotGuidesUpdated()));
1813
1814
1815     connect(trackView->projectView(), SIGNAL(clipItemSelected(ClipItem*, int)), m_effectStack, SLOT(slotClipItemSelected(ClipItem*, int)));
1816     connect(trackView->projectView(), SIGNAL(clipItemSelected(ClipItem*, int)), this, SLOT(slotActivateEffectStackView()));
1817     connect(trackView->projectView(), SIGNAL(transitionItemSelected(Transition*, int, QPoint, bool)), m_transitionConfig, SLOT(slotTransitionItemSelected(Transition*, int, QPoint, bool)));
1818     connect(trackView->projectView(), SIGNAL(transitionItemSelected(Transition*, int, QPoint, bool)), this, SLOT(slotActivateTransitionView(Transition *)));
1819     m_zoomSlider->setValue(doc->zoom().x());
1820     connect(m_zoomSlider, SIGNAL(valueChanged(int)), trackView, SLOT(slotChangeZoom(int)));
1821     connect(trackView->projectView(), SIGNAL(zoomIn()), this, SLOT(slotZoomIn()));
1822     connect(trackView->projectView(), SIGNAL(zoomOut()), this, SLOT(slotZoomOut()));
1823     connect(trackView->projectView(), SIGNAL(displayMessage(const QString&, MessageType)), m_messageLabel, SLOT(setMessage(const QString&, MessageType)));
1824
1825     connect(trackView->projectView(), SIGNAL(showClipFrame(DocClipBase *, const int)), m_clipMonitor, SLOT(slotSetXml(DocClipBase *, const int)));
1826
1827
1828     connect(m_effectStack, SIGNAL(updateClipEffect(ClipItem*, QDomElement, QDomElement, int)), trackView->projectView(), SLOT(slotUpdateClipEffect(ClipItem*, QDomElement, QDomElement, int)));
1829     connect(m_effectStack, SIGNAL(removeEffect(ClipItem*, QDomElement)), trackView->projectView(), SLOT(slotDeleteEffect(ClipItem*, QDomElement)));
1830     connect(m_effectStack, SIGNAL(changeEffectState(ClipItem*, int, bool)), trackView->projectView(), SLOT(slotChangeEffectState(ClipItem*, int, bool)));
1831     connect(m_effectStack, SIGNAL(changeEffectPosition(ClipItem*, int, int)), trackView->projectView(), SLOT(slotChangeEffectPosition(ClipItem*, int, int)));
1832     connect(m_effectStack, SIGNAL(refreshEffectStack(ClipItem*)), trackView->projectView(), SLOT(slotRefreshEffects(ClipItem*)));
1833     connect(m_transitionConfig, SIGNAL(transitionUpdated(Transition *, QDomElement)), trackView->projectView() , SLOT(slotTransitionUpdated(Transition *, QDomElement)));
1834     connect(m_transitionConfig, SIGNAL(seekTimeline(int)), trackView->projectView() , SLOT(setCursorPos(int)));
1835     connect(m_effectStack, SIGNAL(reloadEffects()), this, SLOT(slotReloadEffects()));
1836
1837     connect(trackView->projectView(), SIGNAL(activateDocumentMonitor()), m_projectMonitor, SLOT(activateMonitor()));
1838     connect(trackView, SIGNAL(zoneMoved(int, int)), this, SLOT(slotZoneMoved(int, int)));
1839     connect(m_projectList, SIGNAL(loadingIsOver()), trackView->projectView(), SLOT(slotUpdateAllThumbs()));
1840
1841     trackView->projectView()->setContextMenu(m_timelineContextMenu, m_timelineContextClipMenu, m_timelineContextTransitionMenu, m_clipTypeGroup);
1842     m_activeTimeline = trackView;
1843     if (m_renderWidget) {
1844         m_renderWidget->setProfile(doc->mltProfile());
1845         m_renderWidget->setGuides(doc->guidesXml(), doc->projectDuration());
1846         m_renderWidget->setDocumentPath(doc->projectFolder().path(KUrl::AddTrailingSlash));
1847         m_renderWidget->setRenderProfile(doc->getDocumentProperty("renderdestination"), doc->getDocumentProperty("renderprofile"), doc->getDocumentProperty("renderurl"));
1848     }
1849     //doc->setRenderer(m_projectMonitor->render);
1850     m_commandStack->setActiveStack(doc->commandStack());
1851     KdenliveSettings::setProject_display_ratio(doc->dar());
1852     //doc->clipManager()->checkAudioThumbs();
1853
1854     //m_overView->setScene(trackView->projectScene());
1855     //m_overView->scale(m_overView->width() / trackView->duration(), m_overView->height() / (50 * trackView->tracksNumber()));
1856     //m_overView->fitInView(m_overView->itemAt(0, 50), Qt::KeepAspectRatio);
1857
1858     setCaption(doc->description(), doc->isModified());
1859     m_saveAction->setEnabled(doc->isModified());
1860     m_activeDocument = doc;
1861     m_activeTimeline->updateProjectFps();
1862     m_projectList->updateAllClips();
1863     if (KdenliveSettings::dropbframes()) slotUpdatePreviewSettings();
1864
1865     // set tool to select tool
1866     m_buttonSelectTool->setChecked(true);
1867 }
1868
1869 void MainWindow::slotZoneMoved(int start, int end)
1870 {
1871     m_activeDocument->setZone(start, end);
1872     m_projectMonitor->slotZoneMoved(start, end);
1873 }
1874
1875 void MainWindow::slotGuidesUpdated()
1876 {
1877     if (m_renderWidget) m_renderWidget->setGuides(m_activeDocument->guidesXml(), m_activeDocument->projectDuration());
1878 }
1879
1880 void MainWindow::slotPreferences(int page, int option)
1881 {
1882     //An instance of your dialog could be already created and could be
1883     // cached, in which case you want to display the cached dialog
1884     // instead of creating another one
1885     if (KConfigDialog::showDialog("settings")) {
1886         KdenliveSettingsDialog* d = static_cast <KdenliveSettingsDialog*>(KConfigDialog::exists("settings"));
1887         if (page != -1) d->showPage(page, option);
1888         return;
1889     }
1890
1891     // KConfigDialog didn't find an instance of this dialog, so lets
1892     // create it :
1893     KdenliveSettingsDialog* dialog = new KdenliveSettingsDialog(this);
1894     connect(dialog, SIGNAL(settingsChanged(const QString&)), this, SLOT(updateConfiguration()));
1895     //connect(dialog, SIGNAL(doResetProfile()), this, SLOT(slotDetectAudioDriver()));
1896     connect(dialog, SIGNAL(doResetProfile()), m_monitorManager, SLOT(slotResetProfiles()));
1897     connect(dialog, SIGNAL(updatePreviewSettings()), this, SLOT(slotUpdatePreviewSettings()));
1898     connect(dialog, SIGNAL(updateCaptureFolder()), m_recMonitor, SLOT(slotUpdateCaptureFolder()));
1899     //connect(dialog, SIGNAL(updatePreviewSettings()), this, SLOT(slotUpdatePreviewSettings()));
1900     dialog->show();
1901     if (page != -1) dialog->showPage(page, option);
1902 }
1903
1904 void MainWindow::slotUpdatePreviewSettings()
1905 {
1906     if (m_activeDocument) {
1907         m_clipMonitor->slotSetXml(NULL, 0);
1908         m_activeDocument->updatePreviewSettings();
1909     }
1910 }
1911
1912 void MainWindow::updateConfiguration()
1913 {
1914     //TODO: we should apply settings to all projects, not only the current one
1915     if (m_activeTimeline) {
1916         m_activeTimeline->refresh();
1917         m_activeTimeline->projectView()->checkAutoScroll();
1918         m_activeTimeline->projectView()->checkTrackHeight();
1919         if (m_activeDocument) m_activeDocument->clipManager()->checkAudioThumbs();
1920     }
1921     m_buttonAudioThumbs->setChecked(KdenliveSettings::audiothumbnails());
1922     m_buttonVideoThumbs->setChecked(KdenliveSettings::videothumbnails());
1923
1924     // Update list of transcoding profiles
1925     loadTranscoders();
1926 #ifndef NO_JOGSHUTTLE
1927     activateShuttleDevice();
1928 #endif /* NO_JOGSHUTTLE */
1929
1930 }
1931
1932
1933 void MainWindow::slotSwitchVideoThumbs()
1934 {
1935     KdenliveSettings::setVideothumbnails(!KdenliveSettings::videothumbnails());
1936     if (m_activeTimeline) {
1937         m_activeTimeline->projectView()->slotUpdateAllThumbs();
1938     }
1939     m_buttonVideoThumbs->setChecked(KdenliveSettings::videothumbnails());
1940 }
1941
1942 void MainWindow::slotSwitchAudioThumbs()
1943 {
1944     KdenliveSettings::setAudiothumbnails(!KdenliveSettings::audiothumbnails());
1945     if (m_activeTimeline) {
1946         m_activeTimeline->refresh();
1947         m_activeTimeline->projectView()->checkAutoScroll();
1948         if (m_activeDocument) m_activeDocument->clipManager()->checkAudioThumbs();
1949     }
1950     m_buttonAudioThumbs->setChecked(KdenliveSettings::audiothumbnails());
1951 }
1952
1953 void MainWindow::slotSwitchMarkersComments()
1954 {
1955     KdenliveSettings::setShowmarkers(!KdenliveSettings::showmarkers());
1956     if (m_activeTimeline) {
1957         m_activeTimeline->refresh();
1958     }
1959     m_buttonShowMarkers->setChecked(KdenliveSettings::showmarkers());
1960 }
1961
1962 void MainWindow::slotSwitchSnap()
1963 {
1964     KdenliveSettings::setSnaptopoints(!KdenliveSettings::snaptopoints());
1965     m_buttonSnap->setChecked(KdenliveSettings::snaptopoints());
1966 }
1967
1968
1969 void MainWindow::slotDeleteTimelineClip()
1970 {
1971     if (QApplication::focusWidget()->parentWidget()->parentWidget() == m_projectListDock) m_projectList->slotRemoveClip();
1972     else if (m_activeTimeline) {
1973         m_activeTimeline->projectView()->deleteSelectedClips();
1974     }
1975 }
1976
1977 void MainWindow::slotAddClipMarker()
1978 {
1979     DocClipBase *clip = NULL;
1980     GenTime pos;
1981     if (m_projectMonitor->isActive()) {
1982         if (m_activeTimeline) {
1983             ClipItem *item = m_activeTimeline->projectView()->getActiveClipUnderCursor();
1984             if (item) {
1985                 pos = (m_projectMonitor->position() - item->startPos() + item->cropStart()) / item->speed();
1986                 clip = item->baseClip();
1987             }
1988         }
1989     } else {
1990         clip = m_clipMonitor->activeClip();
1991         pos = m_clipMonitor->position();
1992     }
1993     if (!clip) {
1994         m_messageLabel->setMessage(i18n("Cannot find clip to add marker"), ErrorMessage);
1995         return;
1996     }
1997     QString id = clip->getId();
1998     CommentedTime marker(pos, i18n("Marker"));
1999     MarkerDialog d(clip, marker, m_activeDocument->timecode(), i18n("Add Marker"), this);
2000     if (d.exec() == QDialog::Accepted) {
2001         m_activeTimeline->projectView()->slotAddClipMarker(id, d.newMarker().time(), d.newMarker().comment());
2002     }
2003     if (m_clipMonitor->isActive()) m_clipMonitor->checkOverlay();
2004 }
2005
2006 void MainWindow::slotDeleteClipMarker()
2007 {
2008     DocClipBase *clip = NULL;
2009     GenTime pos;
2010     if (m_projectMonitor->isActive()) {
2011         if (m_activeTimeline) {
2012             ClipItem *item = m_activeTimeline->projectView()->getActiveClipUnderCursor();
2013             if (item) {
2014                 pos = (m_projectMonitor->position() - item->startPos() + item->cropStart()) / item->speed();
2015                 clip = item->baseClip();
2016             }
2017         }
2018     } else {
2019         clip = m_clipMonitor->activeClip();
2020         pos = m_clipMonitor->position();
2021     }
2022     if (!clip) {
2023         m_messageLabel->setMessage(i18n("Cannot find clip to remove marker"), ErrorMessage);
2024         return;
2025     }
2026
2027     QString id = clip->getId();
2028     QString comment = clip->markerComment(pos);
2029     if (comment.isEmpty()) {
2030         m_messageLabel->setMessage(i18n("No marker found at cursor time"), ErrorMessage);
2031         return;
2032     }
2033     m_activeTimeline->projectView()->slotDeleteClipMarker(comment, id, pos);
2034     if (m_clipMonitor->isActive()) m_clipMonitor->checkOverlay();
2035
2036 }
2037
2038 void MainWindow::slotDeleteAllClipMarkers()
2039 {
2040     DocClipBase *clip = NULL;
2041     if (m_projectMonitor->isActive()) {
2042         if (m_activeTimeline) {
2043             ClipItem *item = m_activeTimeline->projectView()->getActiveClipUnderCursor();
2044             if (item) {
2045                 clip = item->baseClip();
2046             }
2047         }
2048     } else {
2049         clip = m_clipMonitor->activeClip();
2050     }
2051     if (!clip) {
2052         m_messageLabel->setMessage(i18n("Cannot find clip to remove marker"), ErrorMessage);
2053         return;
2054     }
2055     m_activeTimeline->projectView()->slotDeleteAllClipMarkers(clip->getId());
2056     if (m_clipMonitor->isActive()) m_clipMonitor->checkOverlay();
2057 }
2058
2059 void MainWindow::slotEditClipMarker()
2060 {
2061     DocClipBase *clip = NULL;
2062     GenTime pos;
2063     if (m_projectMonitor->isActive()) {
2064         if (m_activeTimeline) {
2065             ClipItem *item = m_activeTimeline->projectView()->getActiveClipUnderCursor();
2066             if (item) {
2067                 pos = (m_projectMonitor->position() - item->startPos() + item->cropStart()) / item->speed();
2068                 clip = item->baseClip();
2069             }
2070         }
2071     } else {
2072         clip = m_clipMonitor->activeClip();
2073         pos = m_clipMonitor->position();
2074     }
2075     if (!clip) {
2076         m_messageLabel->setMessage(i18n("Cannot find clip to remove marker"), ErrorMessage);
2077         return;
2078     }
2079
2080     QString id = clip->getId();
2081     QString oldcomment = clip->markerComment(pos);
2082     if (oldcomment.isEmpty()) {
2083         m_messageLabel->setMessage(i18n("No marker found at cursor time"), ErrorMessage);
2084         return;
2085     }
2086
2087     CommentedTime marker(pos, oldcomment);
2088     MarkerDialog d(clip, marker, m_activeDocument->timecode(), i18n("Edit Marker"), this);
2089     if (d.exec() == QDialog::Accepted) {
2090         m_activeTimeline->projectView()->slotAddClipMarker(id, d.newMarker().time(), d.newMarker().comment());
2091         if (d.newMarker().time() != pos) {
2092             // remove old marker
2093             m_activeTimeline->projectView()->slotAddClipMarker(id, pos, QString());
2094         }
2095         if (m_clipMonitor->isActive()) m_clipMonitor->checkOverlay();
2096     }
2097 }
2098
2099 void MainWindow::slotAddGuide()
2100 {
2101     if (m_activeTimeline)
2102         m_activeTimeline->projectView()->slotAddGuide();
2103 }
2104
2105 void MainWindow::slotInsertSpace()
2106 {
2107     if (m_activeTimeline)
2108         m_activeTimeline->projectView()->slotInsertSpace();
2109 }
2110
2111 void MainWindow::slotRemoveSpace()
2112 {
2113     if (m_activeTimeline)
2114         m_activeTimeline->projectView()->slotRemoveSpace();
2115 }
2116
2117 void MainWindow::slotInsertTrack(int ix)
2118 {
2119     m_projectMonitor->activateMonitor();
2120     if (m_activeTimeline)
2121         m_activeTimeline->projectView()->slotInsertTrack(ix);
2122 }
2123
2124 void MainWindow::slotDeleteTrack(int ix)
2125 {
2126     m_projectMonitor->activateMonitor();
2127     if (m_activeTimeline)
2128         m_activeTimeline->projectView()->slotDeleteTrack(ix);
2129 }
2130
2131 void MainWindow::slotChangeTrack(int ix)
2132 {
2133     m_projectMonitor->activateMonitor();
2134     if (m_activeTimeline)
2135         m_activeTimeline->projectView()->slotChangeTrack(ix);
2136 }
2137
2138 void MainWindow::slotEditGuide()
2139 {
2140     if (m_activeTimeline)
2141         m_activeTimeline->projectView()->slotEditGuide();
2142 }
2143
2144 void MainWindow::slotDeleteGuide()
2145 {
2146     if (m_activeTimeline)
2147         m_activeTimeline->projectView()->slotDeleteGuide();
2148 }
2149
2150 void MainWindow::slotDeleteAllGuides()
2151 {
2152     if (m_activeTimeline)
2153         m_activeTimeline->projectView()->slotDeleteAllGuides();
2154 }
2155
2156 void MainWindow::slotCutTimelineClip()
2157 {
2158     if (m_activeTimeline) {
2159         m_activeTimeline->projectView()->cutSelectedClips();
2160     }
2161 }
2162
2163 void MainWindow::slotGroupClips()
2164 {
2165     if (m_activeTimeline) {
2166         m_activeTimeline->projectView()->groupClips();
2167     }
2168 }
2169
2170 void MainWindow::slotUnGroupClips()
2171 {
2172     if (m_activeTimeline) {
2173         m_activeTimeline->projectView()->groupClips(false);
2174     }
2175 }
2176
2177 void MainWindow::slotAddProjectClip(KUrl url)
2178 {
2179     if (m_activeDocument)
2180         m_activeDocument->slotAddClipFile(url, QString());
2181 }
2182
2183 void MainWindow::slotAddTransition(QAction *result)
2184 {
2185     if (!result) return;
2186     QStringList info = result->data().toStringList();
2187     if (info.isEmpty()) return;
2188     QDomElement transition = transitions.getEffectByTag(info.at(1), info.at(2));
2189     if (m_activeTimeline && !transition.isNull()) {
2190         m_activeTimeline->projectView()->slotAddTransitionToSelectedClips(transition.cloneNode().toElement());
2191     }
2192 }
2193
2194 void MainWindow::slotAddVideoEffect(QAction *result)
2195 {
2196     if (!result) return;
2197     QStringList info = result->data().toStringList();
2198     if (info.isEmpty()) return;
2199     QDomElement effect = videoEffects.getEffectByTag(info.at(1), info.at(2));
2200     slotAddEffect(effect);
2201 }
2202
2203 void MainWindow::slotAddAudioEffect(QAction *result)
2204 {
2205     if (!result) return;
2206     QStringList info = result->data().toStringList();
2207     if (info.isEmpty()) return;
2208     QDomElement effect = audioEffects.getEffectByTag(info.at(1), info.at(2));
2209     slotAddEffect(effect);
2210 }
2211
2212 void MainWindow::slotAddCustomEffect(QAction *result)
2213 {
2214     if (!result) return;
2215     QStringList info = result->data().toStringList();
2216     if (info.isEmpty()) return;
2217     QDomElement effect = customEffects.getEffectByTag(info.at(1), info.at(2));
2218     slotAddEffect(effect);
2219 }
2220
2221 void MainWindow::slotZoomIn()
2222 {
2223     m_zoomSlider->setValue(m_zoomSlider->value() - 1);
2224 }
2225
2226 void MainWindow::slotZoomOut()
2227 {
2228     m_zoomSlider->setValue(m_zoomSlider->value() + 1);
2229 }
2230
2231 void MainWindow::slotFitZoom()
2232 {
2233     if (m_activeTimeline) {
2234         m_zoomSlider->setValue(m_activeTimeline->fitZoom());
2235     }
2236 }
2237
2238 void MainWindow::slotGotProgressInfo(const QString &message, int progress)
2239 {
2240     m_statusProgressBar->setValue(progress);
2241     if (progress >= 0) {
2242         if (!message.isEmpty()) m_messageLabel->setMessage(message, InformationMessage);//statusLabel->setText(message);
2243         m_statusProgressBar->setVisible(true);
2244     } else {
2245         m_messageLabel->setMessage(QString(), DefaultMessage);
2246         m_statusProgressBar->setVisible(false);
2247     }
2248 }
2249
2250 void MainWindow::slotShowClipProperties(DocClipBase *clip)
2251 {
2252     if (clip->clipType() == TEXT) {
2253         QString titlepath = m_activeDocument->projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
2254         if (!clip->getProperty("xmltemplate").isEmpty()) {
2255             // template text clip
2256
2257             // Get the list of existing templates
2258             QStringList filter;
2259             filter << "*.kdenlivetitle";
2260             QStringList templateFiles = QDir(titlepath).entryList(filter, QDir::Files);
2261
2262             QDialog *dia = new QDialog(this);
2263             Ui::TemplateClip_UI dia_ui;
2264             dia_ui.setupUi(dia);
2265             int ix = -1;
2266             const QString templatePath = clip->getProperty("xmltemplate");
2267             for (int i = 0; i < templateFiles.size(); ++i) {
2268                 dia_ui.template_list->comboBox()->addItem(templateFiles.at(i), titlepath + templateFiles.at(i));
2269                 if (templatePath == KUrl(titlepath + templateFiles.at(i)).path()) ix = i;
2270             }
2271             if (ix != -1) dia_ui.template_list->comboBox()->setCurrentIndex(ix);
2272             else dia_ui.template_list->comboBox()->insertItem(0, templatePath);
2273             dia_ui.template_list->fileDialog()->setFilter("*.kdenlivetitle");
2274             //warning: setting base directory doesn't work??
2275             KUrl startDir(titlepath);
2276             dia_ui.template_list->fileDialog()->setUrl(startDir);
2277             dia_ui.description->setText(clip->getProperty("description"));
2278             dia_ui.clone_clip->setChecked(true);
2279             if (dia->exec() == QDialog::Accepted) {
2280                 QString textTemplate = dia_ui.template_list->comboBox()->itemData(dia_ui.template_list->comboBox()->currentIndex()).toString();
2281                 if (textTemplate.isEmpty()) textTemplate = dia_ui.template_list->comboBox()->currentText();
2282
2283                 QMap <QString, QString> newprops;
2284
2285                 if (KUrl(textTemplate).path() != templatePath) {
2286                     // The template was changed
2287                     newprops.insert("xmltemplate", textTemplate);
2288                 }
2289
2290                 if (dia_ui.description->toPlainText() != clip->getProperty("description")) {
2291                     newprops.insert("description", dia_ui.description->toPlainText());
2292                 }
2293
2294                 QString newtemplate = newprops.value("xmltemplate");
2295                 if (newtemplate.isEmpty()) newtemplate = templatePath;
2296
2297                 // template modified we need to update xmldata
2298                 QString description = newprops.value("description");
2299                 if (description.isEmpty()) description = clip->getProperty("description");
2300                 newprops.insert("xmldata", m_projectList->generateTemplateXml(newtemplate, description).toString());
2301                 if (dia_ui.normal_clip->isChecked()) {
2302                     // Switch clip to normal clip
2303                     newprops.insert("xmltemplate", QString());
2304                 }
2305                 EditClipCommand *command = new EditClipCommand(m_projectList, clip->getId(), clip->properties(), newprops, true);
2306                 m_activeDocument->commandStack()->push(command);
2307             }
2308             return;
2309         }
2310         QString path = clip->getProperty("resource");
2311         TitleWidget *dia_ui = new TitleWidget(KUrl(), m_activeDocument->timecode(), titlepath, m_projectMonitor->render, this);
2312         QDomDocument doc;
2313         doc.setContent(clip->getProperty("xmldata"));
2314         dia_ui->setXml(doc);
2315         if (dia_ui->exec() == QDialog::Accepted) {
2316             QRect rect = dia_ui->renderedRect();
2317             QMap <QString, QString> newprops;
2318             newprops.insert("xmldata", dia_ui->xml().toString());
2319             newprops.insert("out", QString::number(dia_ui->duration()));
2320             newprops.insert("frame_size", QString::number(rect.width()) + 'x' + QString::number(rect.height()));
2321             EditClipCommand *command = new EditClipCommand(m_projectList, clip->getId(), clip->properties(), newprops, true);
2322             m_activeDocument->commandStack()->push(command);
2323             m_activeTimeline->projectView()->slotUpdateClip(clip->getId());
2324             m_activeDocument->setModified(true);
2325         }
2326         delete dia_ui;
2327
2328         //m_activeDocument->editTextClip(clip->getProperty("xml"), clip->getId());
2329         return;
2330     }
2331     ClipProperties dia(clip, m_activeDocument->timecode(), m_activeDocument->fps(), this);
2332     connect(&dia, SIGNAL(addMarker(const QString &, GenTime, QString)), m_activeTimeline->projectView(), SLOT(slotAddClipMarker(const QString &, GenTime, QString)));
2333     if (dia.exec() == QDialog::Accepted) {
2334         EditClipCommand *command = new EditClipCommand(m_projectList, clip->getId(), clip->properties(), dia.properties(), true);
2335         m_activeDocument->commandStack()->push(command);
2336
2337         //m_projectList->slotUpdateClipProperties(dia.clipId(), dia.properties());
2338         if (dia.needsTimelineRefresh()) {
2339             // update clip occurences in timeline
2340             m_activeTimeline->projectView()->slotUpdateClip(clip->getId());
2341         }
2342     }
2343 }
2344
2345 void MainWindow::customEvent(QEvent* e)
2346 {
2347     if (e->type() == QEvent::User) {
2348         m_messageLabel->setMessage(static_cast <MltErrorEvent *>(e)->message(), MltError);
2349     }
2350 }
2351 void MainWindow::slotActivateEffectStackView()
2352 {
2353     m_effectStack->raiseWindow(m_effectStackDock);
2354 }
2355
2356 void MainWindow::slotActivateTransitionView(Transition *t)
2357 {
2358     if (t) m_transitionConfig->raiseWindow(m_transitionConfigDock);
2359 }
2360
2361 void MainWindow::slotSnapRewind()
2362 {
2363     if (m_projectMonitor->isActive()) {
2364         if (m_activeTimeline)
2365             m_activeTimeline->projectView()->slotSeekToPreviousSnap();
2366     } else m_clipMonitor->slotSeekToPreviousSnap();
2367 }
2368
2369 void MainWindow::slotSnapForward()
2370 {
2371     if (m_projectMonitor->isActive()) {
2372         if (m_activeTimeline)
2373             m_activeTimeline->projectView()->slotSeekToNextSnap();
2374     } else m_clipMonitor->slotSeekToNextSnap();
2375 }
2376
2377 void MainWindow::slotClipStart()
2378 {
2379     if (m_projectMonitor->isActive()) {
2380         if (m_activeTimeline)
2381             m_activeTimeline->projectView()->clipStart();
2382     }
2383 }
2384
2385 void MainWindow::slotClipEnd()
2386 {
2387     if (m_projectMonitor->isActive()) {
2388         if (m_activeTimeline)
2389             m_activeTimeline->projectView()->clipEnd();
2390     }
2391 }
2392
2393 void MainWindow::slotChangeTool(QAction * action)
2394 {
2395     if (action == m_buttonSelectTool) slotSetTool(SELECTTOOL);
2396     else if (action == m_buttonRazorTool) slotSetTool(RAZORTOOL);
2397     else if (action == m_buttonSpacerTool) slotSetTool(SPACERTOOL);
2398 }
2399
2400 void MainWindow::slotSetTool(PROJECTTOOL tool)
2401 {
2402     if (m_activeDocument && m_activeTimeline) {
2403         //m_activeDocument->setTool(tool);
2404         m_activeTimeline->projectView()->setTool(tool);
2405     }
2406 }
2407
2408 void MainWindow::slotCopy()
2409 {
2410     if (!m_activeDocument || !m_activeTimeline) return;
2411     m_activeTimeline->projectView()->copyClip();
2412 }
2413
2414 void MainWindow::slotPaste()
2415 {
2416     if (!m_activeDocument || !m_activeTimeline) return;
2417     m_activeTimeline->projectView()->pasteClip();
2418 }
2419
2420 void MainWindow::slotPasteEffects()
2421 {
2422     if (!m_activeDocument || !m_activeTimeline) return;
2423     m_activeTimeline->projectView()->pasteClipEffects();
2424 }
2425
2426 void MainWindow::slotFind()
2427 {
2428     if (!m_activeDocument || !m_activeTimeline) return;
2429     m_projectSearch->setEnabled(false);
2430     m_findActivated = true;
2431     m_findString.clear();
2432     m_activeTimeline->projectView()->initSearchStrings();
2433     statusBar()->showMessage(i18n("Starting -- find text as you type"));
2434     m_findTimer.start(5000);
2435     qApp->installEventFilter(this);
2436 }
2437
2438 void MainWindow::slotFindNext()
2439 {
2440     if (m_activeTimeline && m_activeTimeline->projectView()->findNextString(m_findString)) {
2441         statusBar()->showMessage(i18n("Found: %1", m_findString));
2442     } else {
2443         statusBar()->showMessage(i18n("Reached end of project"));
2444     }
2445     m_findTimer.start(4000);
2446 }
2447
2448 void MainWindow::findAhead()
2449 {
2450     if (m_activeTimeline && m_activeTimeline->projectView()->findString(m_findString)) {
2451         m_projectSearchNext->setEnabled(true);
2452         statusBar()->showMessage(i18n("Found: %1", m_findString));
2453     } else {
2454         m_projectSearchNext->setEnabled(false);
2455         statusBar()->showMessage(i18n("Not found: %1", m_findString));
2456     }
2457 }
2458
2459 void MainWindow::findTimeout()
2460 {
2461     m_projectSearchNext->setEnabled(false);
2462     m_findActivated = false;
2463     m_findString.clear();
2464     statusBar()->showMessage(i18n("Find stopped"), 3000);
2465     if (m_activeTimeline) m_activeTimeline->projectView()->clearSearchStrings();
2466     m_projectSearch->setEnabled(true);
2467     removeEventFilter(this);
2468 }
2469
2470 void MainWindow::keyPressEvent(QKeyEvent *ke)
2471 {
2472     if (m_findActivated) {
2473         if (ke->key() == Qt::Key_Backspace) {
2474             m_findString = m_findString.left(m_findString.length() - 1);
2475
2476             if (!m_findString.isEmpty()) {
2477                 findAhead();
2478             } else {
2479                 findTimeout();
2480             }
2481
2482             m_findTimer.start(4000);
2483             ke->accept();
2484             return;
2485         } else if (ke->key() == Qt::Key_Escape) {
2486             findTimeout();
2487             ke->accept();
2488             return;
2489         } else if (ke->key() == Qt::Key_Space || !ke->text().trimmed().isEmpty()) {
2490             m_findString += ke->text();
2491
2492             findAhead();
2493
2494             m_findTimer.start(4000);
2495             ke->accept();
2496             return;
2497         }
2498     } else KXmlGuiWindow::keyPressEvent(ke);
2499 }
2500
2501
2502 /** Gets called when the window gets hidden */
2503 void MainWindow::hideEvent(QHideEvent */*event*/)
2504 {
2505     // kDebug() << "I was hidden";
2506     // issue http://www.kdenlive.org/mantis/view.php?id=231
2507     if (isMinimized()) {
2508         // kDebug() << "I am minimized";
2509         if (m_monitorManager) m_monitorManager->stopActiveMonitor();
2510     }
2511 }
2512
2513 bool MainWindow::eventFilter(QObject *obj, QEvent *event)
2514 {
2515     if (m_findActivated) {
2516         if (event->type() == QEvent::ShortcutOverride) {
2517             QKeyEvent* ke = (QKeyEvent*) event;
2518             if (ke->text().trimmed().isEmpty()) return false;
2519             ke->accept();
2520             return true;
2521         } else return false;
2522     } else {
2523         // pass the event on to the parent class
2524         return QMainWindow::eventFilter(obj, event);
2525     }
2526 }
2527
2528
2529 void MainWindow::slotSaveZone(Render *render, QPoint zone)
2530 {
2531     KDialog *dialog = new KDialog(this);
2532     dialog->setCaption("Save clip zone");
2533     dialog->setButtons(KDialog::Ok | KDialog::Cancel);
2534
2535     QWidget *widget = new QWidget(dialog);
2536     dialog->setMainWidget(widget);
2537
2538     QVBoxLayout *vbox = new QVBoxLayout(widget);
2539     QLabel *label1 = new QLabel(i18n("Save clip zone as:"), this);
2540     QString path = m_activeDocument->projectFolder().path();
2541     path.append("/");
2542     path.append("untitled.mlt");
2543     KUrlRequester *url = new KUrlRequester(KUrl(path), this);
2544     url->setFilter("video/mlt-playlist");
2545     QLabel *label2 = new QLabel(i18n("Description:"), this);
2546     KLineEdit *edit = new KLineEdit(this);
2547     vbox->addWidget(label1);
2548     vbox->addWidget(url);
2549     vbox->addWidget(label2);
2550     vbox->addWidget(edit);
2551     if (dialog->exec() == QDialog::Accepted) render->saveZone(url->url(), edit->text(), zone);
2552
2553 }
2554
2555 void MainWindow::slotSetInPoint()
2556 {
2557     if (m_clipMonitor->isActive()) {
2558         m_clipMonitor->slotSetZoneStart();
2559     } else m_activeTimeline->projectView()->setInPoint();
2560 }
2561
2562 void MainWindow::slotSetOutPoint()
2563 {
2564     if (m_clipMonitor->isActive()) {
2565         m_clipMonitor->slotSetZoneEnd();
2566     } else m_activeTimeline->projectView()->setOutPoint();
2567 }
2568
2569 void MainWindow::slotGetNewLumaStuff()
2570 {
2571     //KNS::Entry::List download();
2572     KNS::Entry::List entries = KNS::Engine::download();
2573     // list of changed entries
2574     kDebug() << "// PARSING KNS";
2575     foreach(KNS::Entry* entry, entries) {
2576         // care only about installed ones
2577         if (entry->status() == KNS::Entry::Installed) {
2578             foreach(const QString &file, entry->installedFiles()) {
2579                 kDebug() << "// CURRENTLY INSTALLED: " << file;
2580             }
2581         }
2582     }
2583     qDeleteAll(entries);
2584     initEffects::refreshLumas();
2585     m_activeTimeline->projectView()->reloadTransitionLumas();
2586 }
2587
2588 void MainWindow::slotGetNewRenderStuff()
2589 {
2590     //KNS::Entry::List download();
2591
2592     KNS::Engine engine(0);
2593     if (engine.init("kdenlive_render.knsrc")) {
2594         KNS::Entry::List entries = engine.downloadDialogModal(this);
2595
2596         if (entries.size() > 0) {
2597             foreach(KNS::Entry* entry, entries) {
2598                 // care only about installed ones
2599                 if (entry->status() == KNS::Entry::Installed) {
2600                     foreach(const QString &file, entry->installedFiles()) {
2601                         kDebug() << "// CURRENTLY INSTALLED: " << file;
2602                     }
2603                 }
2604             }
2605         }
2606         if (m_renderWidget) m_renderWidget->reloadProfiles();
2607     }
2608 }
2609
2610 void MainWindow::slotGetNewMltProfileStuff()
2611 {
2612     //KNS::Entry::List download();
2613
2614     KNS::Engine engine(0);
2615     if (engine.init("kdenlive_mltprofiles.knsrc")) {
2616         KNS::Entry::List entries = engine.downloadDialogModal(this);
2617
2618         if (entries.size() > 0) {
2619             foreach(KNS::Entry* entry, entries) {
2620                 // care only about installed ones
2621                 if (entry->status() == KNS::Entry::Installed) {
2622                     foreach(const QString &file, entry->installedFiles()) {
2623                         kDebug() << "// CURRENTLY INSTALLED: " << file;
2624                     }
2625                 }
2626             }
2627
2628             // update the list of profiles in settings dialog
2629             KdenliveSettingsDialog* d = static_cast <KdenliveSettingsDialog*>(KConfigDialog::exists("settings"));
2630             if (d) d->checkProfile();
2631         }
2632     }
2633 }
2634
2635 void MainWindow::slotAutoTransition()
2636 {
2637     if (m_activeTimeline) m_activeTimeline->projectView()->autoTransition();
2638 }
2639
2640 void MainWindow::slotSplitAudio()
2641 {
2642     if (m_activeTimeline) m_activeTimeline->projectView()->splitAudio();
2643 }
2644
2645 void MainWindow::slotUpdateClipType(QAction *action)
2646 {
2647     if (m_activeTimeline) {
2648         if (action->data().toString() == "clip_audio_only") m_activeTimeline->projectView()->setAudioOnly();
2649         else if (action->data().toString() == "clip_video_only") m_activeTimeline->projectView()->setVideoOnly();
2650         else m_activeTimeline->projectView()->setAudioAndVideo();
2651     }
2652 }
2653
2654 void MainWindow::slotDvdWizard(const QString &url, const QString &profile)
2655 {
2656     DvdWizard *w = new DvdWizard(url, profile, this);
2657     w->exec();
2658 }
2659
2660 void MainWindow::slotShowTimeline(bool show)
2661 {
2662     if (show == false) {
2663         m_timelineState = saveState();
2664         centralWidget()->setHidden(true);
2665     } else {
2666         centralWidget()->setHidden(false);
2667         restoreState(m_timelineState);
2668     }
2669 }
2670
2671 void MainWindow::slotMaximizeCurrent(bool /*show*/)
2672 {
2673     //TODO: is there a way to maximize current widget?
2674     //if (show == true)
2675     {
2676         m_timelineState = saveState();
2677         QWidget *par = focusWidget()->parentWidget();
2678         while (par->parentWidget() && par->parentWidget() != this) {
2679             par = par->parentWidget();
2680         }
2681         kDebug() << "CURRENT WIDGET: " << par->objectName();
2682     }
2683     /*else {
2684     //centralWidget()->setHidden(false);
2685     //restoreState(m_timelineState);
2686     }*/
2687 }
2688
2689 void MainWindow::loadTranscoders()
2690 {
2691     QMenu *transMenu = static_cast<QMenu*>(factory()->container("transcoders", this));
2692     transMenu->clear();
2693
2694     KSharedConfigPtr config = KSharedConfig::openConfig("kdenlivetranscodingrc");
2695     KConfigGroup transConfig(config, "Transcoding");
2696     // read the entries
2697     QMap< QString, QString > profiles = transConfig.entryMap();
2698     QMapIterator<QString, QString> i(profiles);
2699     while (i.hasNext()) {
2700         i.next();
2701         QAction *a = transMenu->addAction(i.key());
2702         a->setData(i.value());
2703         connect(a, SIGNAL(triggered()), this, SLOT(slotTranscode()));
2704     }
2705 }
2706
2707 void MainWindow::slotTranscode(KUrl::List urls)
2708 {
2709     QString params;
2710     if (urls.isEmpty()) {
2711         urls.append(m_projectList->currentClipUrl());
2712         QAction *action = qobject_cast<QAction *>(sender());
2713         params = action->data().toString();
2714     }
2715     if (urls.isEmpty()) return;
2716     ClipTranscode *d = new ClipTranscode(urls, params);
2717     connect(d, SIGNAL(addClip(KUrl)), this, SLOT(slotAddProjectClip(KUrl)));
2718     d->show();
2719     //QProcess::startDetached("ffmpeg", parameters);
2720 }
2721
2722 void MainWindow::slotTranscodeClip()
2723 {
2724     KUrl::List urls = KFileDialog::getOpenUrls(KUrl("kfiledialog:///projectfolder"));
2725     if (urls.isEmpty()) return;
2726     slotTranscode(urls);
2727 }
2728
2729 void MainWindow::slotSetDocumentRenderProfile(const QString &dest, const QString &name, const QString &file)
2730 {
2731     if (m_activeDocument == NULL) return;
2732     m_activeDocument->setDocumentProperty("renderdestination", dest);
2733     m_activeDocument->setDocumentProperty("renderprofile", name);
2734     m_activeDocument->setDocumentProperty("renderurl", file);
2735     m_activeDocument->setModified(true);
2736 }
2737
2738
2739 void MainWindow::slotPrepareRendering(bool scriptExport, bool zoneOnly, const QString &chapterFile)
2740 {
2741     if (m_activeDocument == NULL || m_renderWidget == NULL) return;
2742     QString scriptPath;
2743     QString playlistPath;
2744     if (scriptExport) {
2745         bool ok;
2746         QString scriptsFolder = m_activeDocument->projectFolder().path() + "/scripts/";
2747         QString path = m_renderWidget->getFreeScriptName();
2748         scriptPath = QInputDialog::getText(this, i18n("Create Render Script"), i18n("Script name (will be saved in: %1)", scriptsFolder), QLineEdit::Normal, KUrl(path).fileName(), &ok);
2749         if (!ok || scriptPath.isEmpty()) return;
2750         scriptPath.prepend(scriptsFolder);
2751         QFile f(scriptPath);
2752         if (f.exists()) {
2753             if (KMessageBox::warningYesNo(this, i18n("Script file already exists. Do you want to overwrite it?")) != KMessageBox::Yes)
2754                 return;
2755         }
2756         playlistPath = scriptPath + ".mlt";
2757         m_projectMonitor->saveSceneList(playlistPath);
2758     } else {
2759         KTemporaryFile temp;
2760         temp.setAutoRemove(false);
2761         temp.setSuffix(".mlt");
2762         temp.open();
2763         playlistPath = temp.fileName();
2764         m_projectMonitor->saveSceneList(playlistPath);
2765     }
2766
2767     if (!chapterFile.isEmpty()) {
2768         int in = 0;
2769         int out;
2770         if (!zoneOnly) out = (int) GenTime(m_activeDocument->projectDuration()).frames(m_activeDocument->fps());
2771         else {
2772             in = m_activeTimeline->inPoint();
2773             out = m_activeTimeline->outPoint();
2774         }
2775         QDomDocument doc;
2776         QDomElement chapters = doc.createElement("chapters");
2777         chapters.setAttribute("fps", m_activeDocument->fps());
2778         doc.appendChild(chapters);
2779
2780         QDomElement guidesxml = m_activeDocument->guidesXml();
2781         QDomNodeList nodes = guidesxml.elementsByTagName("guide");
2782         for (int i = 0; i < nodes.count(); i++) {
2783             QDomElement e = nodes.item(i).toElement();
2784             if (!e.isNull()) {
2785                 QString comment = e.attribute("comment");
2786                 int time = (int) GenTime(e.attribute("time").toDouble()).frames(m_activeDocument->fps());
2787                 if (time >= in && time < out) {
2788                     if (zoneOnly) time = time - in;
2789                     QDomElement chapter = doc.createElement("chapter");
2790                     chapters.appendChild(chapter);
2791                     chapter.setAttribute("title", comment);
2792                     chapter.setAttribute("time", time);
2793                 }
2794             }
2795         }
2796         if (chapters.childNodes().count() > 0) {
2797             if (m_activeTimeline->projectView()->hasGuide(out, 0) == -1) {
2798                 // Always insert a guide in pos 0
2799                 QDomElement chapter = doc.createElement("chapter");
2800                 chapters.insertBefore(chapter, QDomNode());
2801                 chapter.setAttribute("title", i18n("Start"));
2802                 chapter.setAttribute("time", "0");
2803             }
2804             // save chapters file
2805             QFile file(chapterFile);
2806             if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
2807                 kWarning() << "//////  ERROR writing DVD CHAPTER file: " << chapterFile;
2808             } else {
2809                 file.write(doc.toString().toUtf8());
2810                 if (file.error() != QFile::NoError) {
2811                     kWarning() << "//////  ERROR writing DVD CHAPTER file: " << chapterFile;
2812                 }
2813                 file.close();
2814             }
2815         }
2816     }
2817
2818     m_renderWidget->slotExport(scriptExport, m_activeTimeline->inPoint(), m_activeTimeline->outPoint(), playlistPath, scriptPath);
2819 }
2820
2821 void MainWindow::slotUpdateTimecodeFormat(int ix)
2822 {
2823     KdenliveSettings::setFrametimecode(ix == 1);
2824     m_clipMonitor->updateTimecodeFormat();
2825     m_projectMonitor->updateTimecodeFormat();
2826 }
2827
2828 void MainWindow::slotRemoveFocus()
2829 {
2830     statusBar()->setFocus();
2831     statusBar()->clearFocus();
2832 }
2833
2834
2835
2836
2837 #include "mainwindow.moc"