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