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