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