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