]> git.sesse.net Git - kdenlive/blob - src/mainwindow.cpp
Default layout simplified
[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 #include "audiosignal.h"
43 #ifndef NO_JOGSHUTTLE
44 #include "jogshuttle.h"
45 #include "jogaction.h"
46 #include "jogshuttleconfig.h"
47 #endif /* NO_JOGSHUTTLE */
48 #include "clipproperties.h"
49 #include "wizard.h"
50 #include "editclipcommand.h"
51 #include "titlewidget.h"
52 #include "markerdialog.h"
53 #include "clipitem.h"
54 #include "interfaces.h"
55 #include "kdenlive-config.h"
56 #include "cliptranscode.h"
57 #include "ui_templateclip_ui.h"
58 #include "colorscopes/vectorscope.h"
59 #include "colorscopes/waveform.h"
60 #include "colorscopes/rgbparade.h"
61 #include "colorscopes/histogram.h"
62 #include "audiospectrum.h"
63 #include "spectrogram.h"
64
65 #include <KApplication>
66 #include <KAction>
67 #include <KLocale>
68 #include <KGlobal>
69 #include <KActionCollection>
70 #include <KActionCategory>
71 #include <KStandardAction>
72 #include <KShortcutsDialog>
73 #include <KFileDialog>
74 #include <KMessageBox>
75 #include <KDebug>
76 #include <KIO/NetAccess>
77 #include <KSaveFile>
78 #include <KRuler>
79 #include <KConfigDialog>
80 #include <KXMLGUIFactory>
81 #include <KStatusBar>
82 #include <kstandarddirs.h>
83 #include <KUrlRequesterDialog>
84 #include <KTemporaryFile>
85 #include <KProcess>
86 #include <KActionMenu>
87 #include <KMenu>
88 #include <locale.h>
89 #include <ktogglefullscreenaction.h>
90 #include <KFileItem>
91 #include <KNotification>
92 #include <KNotifyConfigWidget>
93 #if KDE_IS_VERSION(4,3,80)
94 #include <knewstuff3/downloaddialog.h>
95 #include <knewstuff3/knewstuffaction.h>
96 #else
97 #include <knewstuff2/engine.h>
98 #include <knewstuff2/ui/knewstuffaction.h>
99 #define KNS3 KNS
100 #endif /* KDE_IS_VERSION(4,3,80) */
101 #include <KToolBar>
102 #include <KColorScheme>
103 #include <KProgressDialog>
104
105 #include <QTextStream>
106 #include <QTimer>
107 #include <QAction>
108 #include <QKeyEvent>
109 #include <QInputDialog>
110 #include <QDesktopWidget>
111 #include <QBitmap>
112
113 #include <stdlib.h>
114
115 // Uncomment for deeper debugging
116 //#define DEBUG_MAINW
117
118 #ifdef DEBUG_MAINW
119 #include <QDebug>
120 #endif
121
122 static const char version[] = VERSION;
123
124 static const int ID_TIMELINE_POS = 0;
125 namespace Mlt
126 {
127 class Producer;
128 };
129
130 Q_DECLARE_METATYPE(QVector<int16_t>)
131
132 EffectsList MainWindow::videoEffects;
133 EffectsList MainWindow::audioEffects;
134 EffectsList MainWindow::customEffects;
135 EffectsList MainWindow::transitions;
136
137 MainWindow::MainWindow(const QString &MltPath, const KUrl & Url, const QString & clipsToLoad, QWidget *parent) :
138     KXmlGuiWindow(parent),
139     m_activeDocument(NULL),
140     m_activeTimeline(NULL),
141     m_renderWidget(NULL),
142 #ifndef NO_JOGSHUTTLE
143     m_jogProcess(NULL),
144     m_jogShuttle(NULL),
145 #endif /* NO_JOGSHUTTLE */
146     m_findActivated(false),
147     m_stopmotion(NULL)
148 {
149     qRegisterMetaType<QVector<int16_t> > ();
150     // Create DBus interface
151     new MainWindowAdaptor(this);
152     QDBusConnection dbus = QDBusConnection::sessionBus();
153     dbus.registerObject("/MainWindow", this);
154
155     setlocale(LC_NUMERIC, "POSIX");
156     if (!KdenliveSettings::colortheme().isEmpty()) slotChangePalette(NULL, KdenliveSettings::colortheme());
157     setFont(KGlobalSettings::toolBarFont());
158     parseProfiles(MltPath);
159     KdenliveSettings::setCurrent_profile(KdenliveSettings::default_profile());
160     m_commandStack = new QUndoGroup;
161     setDockNestingEnabled(true);
162     m_timelineArea = new KTabWidget(this);
163     m_timelineArea->setTabReorderingEnabled(true);
164     m_timelineArea->setTabBarHidden(true);
165     m_timelineArea->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Preferred);
166     m_timelineArea->setMinimumHeight(200);
167
168     QToolButton *closeTabButton = new QToolButton;
169     connect(closeTabButton, SIGNAL(clicked()), this, SLOT(closeCurrentDocument()));
170     closeTabButton->setIcon(KIcon("tab-close"));
171     closeTabButton->adjustSize();
172     closeTabButton->setToolTip(i18n("Close the current tab"));
173     m_timelineArea->setCornerWidget(closeTabButton);
174     connect(m_timelineArea, SIGNAL(currentChanged(int)), this, SLOT(activateDocument()));
175
176     connect(&m_findTimer, SIGNAL(timeout()), this, SLOT(findTimeout()));
177     m_findTimer.setSingleShot(true);
178
179     // FIXME: the next call returns a newly allocated object, which leaks
180     initEffects::parseEffectFiles();
181     //initEffects::parseCustomEffectsFile();
182
183     m_monitorManager = new MonitorManager();
184
185     m_shortcutRemoveFocus = new QShortcut(QKeySequence("Esc"), this);
186     connect(m_shortcutRemoveFocus, SIGNAL(activated()), this, SLOT(slotRemoveFocus()));
187
188
189     /// Add Widgets ///
190
191     m_projectListDock = new QDockWidget(i18n("Project Tree"), this);
192     m_projectListDock->setObjectName("project_tree");
193     m_projectList = new ProjectList();
194     m_projectListDock->setWidget(m_projectList);
195     addDockWidget(Qt::TopDockWidgetArea, m_projectListDock);
196
197     m_clipMonitorDock = new QDockWidget(i18n("Clip Monitor"), this);
198     m_clipMonitorDock->setObjectName("clip_monitor");
199     m_clipMonitor = new Monitor("clip", m_monitorManager, QString(), m_timelineArea);
200     m_clipMonitorDock->setWidget(m_clipMonitor);
201
202     m_projectMonitorDock = new QDockWidget(i18n("Project Monitor"), this);
203     m_projectMonitorDock->setObjectName("project_monitor");
204     m_projectMonitor = new Monitor("project", m_monitorManager, QString());
205     m_projectMonitorDock->setWidget(m_projectMonitor);
206
207 #ifndef Q_WS_MAC
208     m_recMonitorDock = new QDockWidget(i18n("Record Monitor"), this);
209     m_recMonitorDock->setObjectName("record_monitor");
210     m_recMonitor = new RecMonitor("record");
211     m_recMonitorDock->setWidget(m_recMonitor);
212     connect(m_recMonitor, SIGNAL(addProjectClip(KUrl)), this, SLOT(slotAddProjectClip(KUrl)));
213     connect(m_recMonitor, SIGNAL(showConfigDialog(int, int)), this, SLOT(slotPreferences(int, int)));
214 #endif
215
216     m_notesDock = new QDockWidget(i18n("Project Notes"), this);
217     m_notesDock->setObjectName("notes_widget");
218     m_notesWidget = new KTextEdit();
219     m_notesWidget->setTabChangesFocus(true);
220 #if KDE_IS_VERSION(4,4,0)
221     m_notesWidget->setClickMessage(i18n("Enter your project notes here ..."));
222 #endif
223     m_notesDock->setWidget(m_notesWidget);
224     addDockWidget(Qt::TopDockWidgetArea, m_notesDock);
225
226     m_effectStackDock = new QDockWidget(i18n("Effect Stack"), this);
227     m_effectStackDock->setObjectName("effect_stack");
228     m_effectStack = new EffectStackView(m_projectMonitor);
229     m_effectStackDock->setWidget(m_effectStack);
230     addDockWidget(Qt::TopDockWidgetArea, m_effectStackDock);
231
232     m_transitionConfigDock = new QDockWidget(i18n("Transition"), this);
233     m_transitionConfigDock->setObjectName("transition");
234     m_transitionConfig = new TransitionSettings(m_projectMonitor);
235     m_transitionConfigDock->setWidget(m_transitionConfig);
236     addDockWidget(Qt::TopDockWidgetArea, m_transitionConfigDock);
237
238     m_effectListDock = new QDockWidget(i18n("Effect List"), this);
239     m_effectListDock->setObjectName("effect_list");
240     m_effectList = new EffectsListView();
241     m_effectListDock->setWidget(m_effectList);
242     addDockWidget(Qt::TopDockWidgetArea, m_effectListDock);
243
244     m_vectorscope = new Vectorscope(m_projectMonitor, m_clipMonitor);
245     m_vectorscopeDock = new QDockWidget(i18n("Vectorscope"), this);
246     m_vectorscopeDock->setObjectName(m_vectorscope->widgetName());
247     m_vectorscopeDock->setWidget(m_vectorscope);
248     addDockWidget(Qt::TopDockWidgetArea, m_vectorscopeDock);
249     connect(m_vectorscopeDock, SIGNAL(visibilityChanged(bool)), m_vectorscope, SLOT(forceUpdate(bool)));
250     connect(m_vectorscopeDock, SIGNAL(visibilityChanged(bool)), this, SLOT(slotUpdateGfxScopeFrameRequest()));
251     connect(m_vectorscope, SIGNAL(requestAutoRefresh(bool)), this, SLOT(slotUpdateGfxScopeFrameRequest()));
252     m_gfxScopesList.append(m_vectorscopeDock);
253
254     m_waveform = new Waveform(m_projectMonitor, m_clipMonitor);
255     m_waveformDock = new QDockWidget(i18n("Waveform"), this);
256     m_waveformDock->setObjectName(m_waveform->widgetName());
257     m_waveformDock->setWidget(m_waveform);
258     addDockWidget(Qt::TopDockWidgetArea, m_waveformDock);
259     connect(m_waveformDock, SIGNAL(visibilityChanged(bool)), m_waveform, SLOT(forceUpdate(bool)));
260     connect(m_waveformDock, SIGNAL(visibilityChanged(bool)), this, SLOT(slotUpdateGfxScopeFrameRequest()));
261     connect(m_waveform, SIGNAL(requestAutoRefresh(bool)), this, SLOT(slotUpdateGfxScopeFrameRequest()));
262     m_gfxScopesList.append(m_waveformDock);
263
264     m_RGBParade = new RGBParade(m_projectMonitor, m_clipMonitor);
265     m_RGBParadeDock = new QDockWidget(i18n("RGB Parade"), this);
266     m_RGBParadeDock->setObjectName(m_RGBParade->widgetName());
267     m_RGBParadeDock->setWidget(m_RGBParade);
268     addDockWidget(Qt::TopDockWidgetArea, m_RGBParadeDock);
269     connect(m_RGBParadeDock, SIGNAL(visibilityChanged(bool)), m_RGBParade, SLOT(forceUpdate(bool)));
270     connect(m_RGBParadeDock, SIGNAL(visibilityChanged(bool)), this, SLOT(slotUpdateGfxScopeFrameRequest()));
271     connect(m_RGBParade, SIGNAL(requestAutoRefresh(bool)), this, SLOT(slotUpdateGfxScopeFrameRequest()));
272     m_gfxScopesList.append(m_RGBParadeDock);
273
274     m_histogram = new Histogram(m_projectMonitor, m_clipMonitor);
275     m_histogramDock = new QDockWidget(i18n("Histogram"), this);
276     m_histogramDock->setObjectName(m_histogram->widgetName());
277     m_histogramDock->setWidget(m_histogram);
278     addDockWidget(Qt::TopDockWidgetArea, m_histogramDock);
279     connect(m_histogramDock, SIGNAL(visibilityChanged(bool)), m_histogram, SLOT(forceUpdate(bool)));
280     connect(m_histogramDock, SIGNAL(visibilityChanged(bool)), this, SLOT(slotUpdateGfxScopeFrameRequest()));
281     connect(m_histogram, SIGNAL(requestAutoRefresh(bool)), this, SLOT(slotUpdateGfxScopeFrameRequest()));
282     m_gfxScopesList.append(m_histogramDock);
283
284
285     m_audiosignal = new AudioSignal;
286     m_audiosignalDock = new QDockWidget(i18n("Audio Signal"), this);
287     m_audiosignalDock->setObjectName("audiosignal");
288     m_audiosignalDock->setWidget(m_audiosignal);
289     addDockWidget(Qt::TopDockWidgetArea, m_audiosignalDock);
290     connect(m_audiosignalDock, SIGNAL(visibilityChanged(bool)), this, SLOT(slotUpdateAudioScopeFrameRequest()));
291     connect(m_audiosignal, SIGNAL(updateAudioMonitoring()), this, SLOT(slotUpdateAudioScopeFrameRequest()));
292
293     m_audioSpectrum = new AudioSpectrum();
294     m_audioSpectrumDock = new QDockWidget(i18n("AudioSpectrum"), this);
295     m_audioSpectrumDock->setObjectName(m_audioSpectrum->widgetName());
296     m_audioSpectrumDock->setWidget(m_audioSpectrum);
297     addDockWidget(Qt::TopDockWidgetArea, m_audioSpectrumDock);
298     m_audioScopesList.append(m_audioSpectrum);
299     connect(m_audioSpectrumDock, SIGNAL(visibilityChanged(bool)), this, SLOT(slotUpdateAudioScopeFrameRequest()));
300     connect(m_audioSpectrum, SIGNAL(requestAutoRefresh(bool)), this, SLOT(slotUpdateAudioScopeFrameRequest()));
301
302     m_spectrogram = new Spectrogram();
303     m_spectrogramDock = new QDockWidget(i18n("Spectrogram"), this);
304     m_spectrogramDock->setObjectName(m_spectrogram->widgetName());
305     m_spectrogramDock->setWidget(m_spectrogram);
306     addDockWidget(Qt::TopDockWidgetArea, m_spectrogramDock);
307     m_audioScopesList.append(m_spectrogram);
308     connect(m_audioSpectrumDock, SIGNAL(visibilityChanged(bool)), this, SLOT(slotUpdateAudioScopeFrameRequest()));
309     connect(m_audioSpectrum, SIGNAL(requestAutoRefresh(bool)), this, SLOT(slotUpdateAudioScopeFrameRequest()));
310
311     // Connect the audio signal to the audio scope slots
312     bool b = true;
313     if (m_projectMonitor) {
314         qDebug() << "project monitor connected";
315         b &= connect(m_projectMonitor->render, SIGNAL(audioSamplesSignal(QVector<int16_t>, int, int, int)),
316                      m_audioSpectrum, SLOT(slotReceiveAudio(QVector<int16_t>, int, int, int)));
317         b &= connect(m_projectMonitor->render, SIGNAL(audioSamplesSignal(const QVector<int16_t>&, const int&, const int&, const int&)),
318                      m_audiosignal, SLOT(slotReceiveAudio(const QVector<int16_t>&, const int&, const int&, const int&)));
319         b &= connect(m_projectMonitor->render, SIGNAL(audioSamplesSignal(QVector<int16_t>,int,int,int)),
320                      m_spectrogram, SLOT(slotReceiveAudio(QVector<int16_t>,int,int,int)));
321     }
322     if (m_clipMonitor) {
323         qDebug() << "clip monitor connected";
324         b &= connect(m_clipMonitor->render, SIGNAL(audioSamplesSignal(QVector<int16_t>, int, int, int)),
325                      m_audioSpectrum, SLOT(slotReceiveAudio(QVector<int16_t>, int, int, int)));
326         b &= connect(m_clipMonitor->render, SIGNAL(audioSamplesSignal(const QVector<int16_t>&, int, int, int)),
327                      m_audiosignal, SLOT(slotReceiveAudio(const QVector<int16_t>&, int, int, int)));
328         b &= connect(m_clipMonitor->render, SIGNAL(audioSamplesSignal(QVector<int16_t>,int,int,int)),
329                      m_spectrogram, SLOT(slotReceiveAudio(QVector<int16_t>,int,int,int)));
330     }
331     // Ensure connections were set up correctly
332     Q_ASSERT(b);
333
334
335
336     // Add monitors here to keep them at the right of the window
337     addDockWidget(Qt::TopDockWidgetArea, m_clipMonitorDock);
338     addDockWidget(Qt::TopDockWidgetArea, m_projectMonitorDock);
339 #ifndef Q_WS_MAC
340     addDockWidget(Qt::TopDockWidgetArea, m_recMonitorDock);
341 #endif
342
343     m_undoViewDock = new QDockWidget(i18n("Undo History"), this);
344     m_undoViewDock->setObjectName("undo_history");
345     m_undoView = new QUndoView();
346     m_undoView->setCleanIcon(KIcon("edit-clear"));
347     m_undoView->setEmptyLabel(i18n("Clean"));
348     m_undoViewDock->setWidget(m_undoView);
349     m_undoView->setGroup(m_commandStack);
350     addDockWidget(Qt::TopDockWidgetArea, m_undoViewDock);
351
352
353     setupActions();
354
355
356     // Close non-general docks for the initial layout
357     // only show important ones
358     m_histogramDock->close();
359     m_RGBParadeDock->close();
360     m_waveformDock->close();
361     m_vectorscopeDock->close();
362
363     m_audioSpectrumDock->close();
364     m_spectrogramDock->close();
365     m_audiosignalDock->close();
366
367     m_undoViewDock->close();
368
369
370
371     /// Tabify Widgets ///
372     tabifyDockWidget(m_effectListDock, m_effectStackDock);
373     tabifyDockWidget(m_effectListDock, m_transitionConfigDock);
374     tabifyDockWidget(m_projectListDock, m_notesDock);
375
376     tabifyDockWidget(m_clipMonitorDock, m_projectMonitorDock);
377 #ifndef Q_WS_MAC
378     tabifyDockWidget(m_clipMonitorDock, m_recMonitorDock);
379 #endif
380
381
382
383
384     setCentralWidget(m_timelineArea);
385
386
387     m_fileOpenRecent = KStandardAction::openRecent(this, SLOT(openFile(const KUrl &)), actionCollection());
388     readOptions();
389     m_fileRevert = KStandardAction::revert(this, SLOT(slotRevert()), actionCollection());
390     m_fileRevert->setEnabled(false);
391
392     // Prepare layout actions
393     KActionCategory *layoutActions = new KActionCategory(i18n("Layouts"), actionCollection());
394     m_loadLayout = new KSelectAction(i18n("Load Layout"), actionCollection());
395     for (int i = 1; i < 5; i++) {
396         KAction *load = new KAction(KIcon(), i18n("Layout %1").arg(i), this);
397         load->setData("_" + QString::number(i));
398         layoutActions->addAction("load_layout" + QString::number(i), load);
399         m_loadLayout->addAction(load);
400         KAction *save = new KAction(KIcon(), i18n("Save As Layout %1").arg(i), this);
401         save->setData("_" + QString::number(i));
402         layoutActions->addAction("save_layout" + QString::number(i), save);
403     }
404     layoutActions->addAction("load_layouts", m_loadLayout);
405     connect(m_loadLayout, SIGNAL(triggered(QAction*)), this, SLOT(slotLoadLayout(QAction*)));
406
407     KAction *action;
408     // Stop motion actions. Beware of the order, we MUST use the same order in stopmotion/stopmotion.cpp
409     m_stopmotion_actions = new KActionCategory(i18n("Stop Motion"), actionCollection());
410     action = new KAction(KIcon("media-record"), i18n("Capture frame"), this);
411     //action->setShortcutContext(Qt::WidgetWithChildrenShortcut);
412     m_stopmotion_actions->addAction("stopmotion_capture", action);
413     action = new KAction(i18n("Switch live / captured frame"), this);
414     //action->setShortcutContext(Qt::WidgetWithChildrenShortcut);
415     m_stopmotion_actions->addAction("stopmotion_switch", action);
416     action = new KAction(KIcon("edit-paste"), i18n("Show last frame over video"), this);
417     action->setCheckable(true);
418     action->setChecked(false);
419     m_stopmotion_actions->addAction("stopmotion_overlay", action);
420
421     // Build effects menu
422     m_effectsMenu = new QMenu(i18n("Add Effect"));
423     m_effectActions = new KActionCategory(i18n("Effects"), actionCollection());
424     m_effectList->reloadEffectList(m_effectsMenu, m_effectActions);
425     m_effectsActionCollection->readSettings();
426     
427     setupGUI();
428
429
430     // Find QDockWidget tab bars and show / hide widget title bars on right click
431     QList <QTabBar *> tabs = findChildren<QTabBar *>();
432     for (int i = 0; i < tabs.count(); i++) {
433         tabs.at(i)->setContextMenuPolicy(Qt::CustomContextMenu);
434         connect(tabs.at(i), SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(slotSwitchTitles()));
435     }
436
437     /*ScriptingPart* sp = new ScriptingPart(this, QStringList());
438     guiFactory()->addClient(sp);*/
439
440     QMenu *saveLayout = (QMenu*)(factory()->container("layout_save_as", this));
441     if (saveLayout)
442         connect(saveLayout, SIGNAL(triggered(QAction*)), this, SLOT(slotSaveLayout(QAction*)));
443
444
445     // Load layout names from config file
446     loadLayouts();
447
448     loadPlugins();
449     loadTranscoders();
450     //kDebug() << factory() << " " << factory()->container("video_effects_menu", this);
451
452     m_projectMonitor->setupMenu(static_cast<QMenu*>(factory()->container("monitor_go", this)), m_playZone, m_loopZone, NULL, m_loopClip);
453     m_clipMonitor->setupMenu(static_cast<QMenu*>(factory()->container("monitor_go", this)), m_playZone, m_loopZone, static_cast<QMenu*>(factory()->container("marker_menu", this)));
454
455     QMenu *clipInTimeline = static_cast<QMenu*>(factory()->container("clip_in_timeline", this));
456     clipInTimeline->setIcon(KIcon("go-jump"));
457     m_projectList->setupGeneratorMenu(static_cast<QMenu*>(factory()->container("generators", this)),
458                                       static_cast<QMenu*>(factory()->container("transcoders", this)),
459                                       clipInTimeline);
460
461     // build themes menus
462     QMenu *themesMenu = static_cast<QMenu*>(factory()->container("themes_menu", this));
463     QActionGroup *themegroup = new QActionGroup(this);
464     themegroup->setExclusive(true);
465     action = new KAction(i18n("Default"), this);
466     action->setCheckable(true);
467     themegroup->addAction(action);
468     if (KdenliveSettings::colortheme().isEmpty()) action->setChecked(true);
469
470     const QStringList schemeFiles = KGlobal::dirs()->findAllResources("data", "color-schemes/*.colors", KStandardDirs::NoDuplicates);
471
472     for (int i = 0; i < schemeFiles.size(); ++i) {
473         // get the file name
474         const QString filename = schemeFiles.at(i);
475         const QFileInfo info(filename);
476
477         // add the entry
478         KSharedConfigPtr config = KSharedConfig::openConfig(filename);
479         QIcon icon = createSchemePreviewIcon(config);
480         KConfigGroup group(config, "General");
481         const QString name = group.readEntry("Name", info.baseName());
482         action = new KAction(name, this);
483         action->setData(filename);
484         action->setIcon(icon);
485         action->setCheckable(true);
486         themegroup->addAction(action);
487         if (KdenliveSettings::colortheme() == filename) action->setChecked(true);
488     }
489
490     /*KGlobal::dirs()->addResourceDir("themes", KStandardDirs::installPath("data") + QString("kdenlive/themes"));
491     QStringList themes = KGlobal::dirs()->findAllResources("themes", QString(), KStandardDirs::Recursive | KStandardDirs::NoDuplicates);
492     for (QStringList::const_iterator it = themes.constBegin(); it != themes.constEnd(); ++it)
493     {
494     QFileInfo fi(*it);
495         action = new QAction(fi.fileName(), this);
496         action->setData(*it);
497     action->setCheckable(true);
498     themegroup->addAction(action);
499     if (KdenliveSettings::colortheme() == *it) action->setChecked(true);
500     }*/
501     themesMenu->addActions(themegroup->actions());
502     connect(themesMenu, SIGNAL(triggered(QAction *)), this, SLOT(slotChangePalette(QAction*)));
503
504     // Setup and fill effects and transitions menus.
505
506
507     QMenu *m = static_cast<QMenu*>(factory()->container("video_effects_menu", this));
508     m = m_effectsMenu;
509
510
511     m_transitionsMenu = new QMenu(i18n("Add Transition"), this);
512     for (int i = 0; i < transitions.count(); ++i)
513         m_transitionsMenu->addAction(m_transitions[i]);
514
515     connect(m_effectsMenu, SIGNAL(triggered(QAction *)), this, SLOT(slotAddVideoEffect(QAction *)));
516     connect(m_transitionsMenu, SIGNAL(triggered(QAction *)), this, SLOT(slotAddTransition(QAction *)));
517
518     m_effectStack->setMenu(m_effectsMenu);
519
520     QMenu *viewMenu = static_cast<QMenu*>(factory()->container("dockwindows", this));
521     const QList<QAction *> viewActions = createPopupMenu()->actions();
522     viewMenu->insertActions(NULL, viewActions);
523
524     m_timelineContextMenu = new QMenu(this);
525     m_timelineContextClipMenu = new QMenu(this);
526     m_timelineContextTransitionMenu = new QMenu(this);
527
528     m_timelineContextMenu->addAction(actionCollection()->action("insert_space"));
529     m_timelineContextMenu->addAction(actionCollection()->action("delete_space"));
530     m_timelineContextMenu->addAction(actionCollection()->action(KStandardAction::name(KStandardAction::Paste)));
531
532     m_timelineContextClipMenu->addAction(actionCollection()->action("clip_in_project_tree"));
533     //m_timelineContextClipMenu->addAction(actionCollection()->action("clip_to_project_tree"));
534     m_timelineContextClipMenu->addAction(actionCollection()->action("edit_item_duration"));
535     m_timelineContextClipMenu->addAction(actionCollection()->action("delete_item"));
536     m_timelineContextClipMenu->addSeparator();
537     m_timelineContextClipMenu->addAction(actionCollection()->action("group_clip"));
538     m_timelineContextClipMenu->addAction(actionCollection()->action("ungroup_clip"));
539     m_timelineContextClipMenu->addAction(actionCollection()->action("split_audio"));
540     m_timelineContextClipMenu->addSeparator();
541     m_timelineContextClipMenu->addAction(actionCollection()->action("cut_timeline_clip"));
542     m_timelineContextClipMenu->addAction(actionCollection()->action(KStandardAction::name(KStandardAction::Copy)));
543     m_timelineContextClipMenu->addAction(actionCollection()->action("paste_effects"));
544     m_timelineContextClipMenu->addSeparator();
545
546     QMenu *markersMenu = (QMenu*)(factory()->container("marker_menu", this));
547     m_timelineContextClipMenu->addMenu(markersMenu);
548     m_timelineContextClipMenu->addSeparator();
549     m_timelineContextClipMenu->addMenu(m_transitionsMenu);
550     m_timelineContextClipMenu->addMenu(m_effectsMenu);
551
552     m_timelineContextTransitionMenu->addAction(actionCollection()->action("edit_item_duration"));
553     m_timelineContextTransitionMenu->addAction(actionCollection()->action("delete_item"));
554     m_timelineContextTransitionMenu->addAction(actionCollection()->action(KStandardAction::name(KStandardAction::Copy)));
555
556     m_timelineContextTransitionMenu->addAction(actionCollection()->action("auto_transition"));
557
558     connect(m_projectMonitorDock, SIGNAL(visibilityChanged(bool)), m_projectMonitor, SLOT(refreshMonitor(bool)));
559     connect(m_clipMonitorDock, SIGNAL(visibilityChanged(bool)), m_clipMonitor, SLOT(refreshMonitor(bool)));
560     //connect(m_monitorManager, SIGNAL(connectMonitors()), this, SLOT(slotConnectMonitors()));
561     connect(m_monitorManager, SIGNAL(raiseClipMonitor(bool)), this, SLOT(slotRaiseMonitor(bool)));
562     connect(m_monitorManager, SIGNAL(checkColorScopes()), this, SLOT(slotUpdateColorScopes()));
563     connect(m_effectList, SIGNAL(addEffect(const QDomElement)), this, SLOT(slotAddEffect(const QDomElement)));
564     connect(m_effectList, SIGNAL(reloadEffects()), this, SLOT(slotReloadEffects()));
565
566     m_monitorManager->initMonitors(m_clipMonitor, m_projectMonitor);
567     slotConnectMonitors();
568
569     // Open or create a file.  Command line argument passed in Url has
570     // precedence, then "openlastproject", then just a plain empty file.
571     // If opening Url fails, openlastproject will _not_ be used.
572     if (!Url.isEmpty()) {
573         // delay loading so that the window shows up
574         m_startUrl = Url;
575         QTimer::singleShot(500, this, SLOT(openFile()));
576     } else if (KdenliveSettings::openlastproject()) {
577         QTimer::singleShot(500, this, SLOT(openLastFile()));
578     } else { //if (m_timelineArea->count() == 0) {
579         newFile(false);
580     }
581
582     if (!clipsToLoad.isEmpty() && m_activeDocument) {
583         QStringList list = clipsToLoad.split(',');
584         QList <QUrl> urls;
585         foreach(QString path, list) {
586             kDebug() << QDir::current().absoluteFilePath(path);
587             urls << QUrl::fromLocalFile(QDir::current().absoluteFilePath(path));
588         }
589         m_projectList->slotAddClip(urls);
590     }
591
592 #ifndef NO_JOGSHUTTLE
593     activateShuttleDevice();
594 #endif /* NO_JOGSHUTTLE */
595     m_projectListDock->raise();
596
597     actionCollection()->addAssociatedWidget(m_clipMonitor->container());
598     actionCollection()->addAssociatedWidget(m_projectMonitor->container());
599 }
600
601 MainWindow::~MainWindow()
602 {
603     if (m_stopmotion) {
604         delete m_stopmotion;
605     }
606     m_effectStack->slotClipItemSelected(NULL, 0);
607     m_transitionConfig->slotTransitionItemSelected(NULL, 0, QPoint(), false);
608
609     if (m_projectMonitor) m_projectMonitor->stop();
610     if (m_clipMonitor) m_clipMonitor->stop();
611
612     delete m_activeTimeline;
613     delete m_effectStack;
614     delete m_transitionConfig;
615     delete m_activeDocument;
616     delete m_projectMonitor;
617     delete m_clipMonitor;
618     delete m_shortcutRemoveFocus;
619     Mlt::Factory::close();
620 }
621
622 //virtual
623 bool MainWindow::queryClose()
624 {
625     if (m_renderWidget) {
626         int waitingJobs = m_renderWidget->waitingJobsCount();
627         if (waitingJobs > 0) {
628             switch (KMessageBox::warningYesNoCancel(this, i18np("You have 1 rendering job waiting in the queue.\nWhat do you want to do with this job?", "You have %1 rendering jobs waiting in the queue.\nWhat do you want to do with these jobs?", waitingJobs), QString(), KGuiItem(i18n("Start them now")), KGuiItem(i18n("Delete them")))) {
629             case KMessageBox::Yes :
630                 // create script with waiting jobs and start it
631                 if (m_renderWidget->startWaitingRenderJobs() == false) return false;
632                 break;
633             case KMessageBox::No :
634                 // Don't do anything, jobs will be deleted
635                 break;
636             default:
637                 return false;
638             }
639         }
640     }
641     saveOptions();
642     if (m_monitorManager) m_monitorManager->stopActiveMonitor();
643     // warn the user to save if document is modified and we have clips in our project list
644     if (m_activeDocument && m_activeDocument->isModified() &&
645             ((m_projectList->documentClipList().isEmpty() && !m_activeDocument->url().isEmpty()) ||
646              !m_projectList->documentClipList().isEmpty())) {
647         raise();
648         activateWindow();
649         QString message;
650         if (m_activeDocument->url().fileName().isEmpty())
651             message = i18n("Save changes to document?");
652         else
653             message = i18n("The project <b>\"%1\"</b> has been changed.\nDo you want to save your changes?").arg(m_activeDocument->url().fileName());
654         switch (KMessageBox::warningYesNoCancel(this, message)) {
655         case KMessageBox::Yes :
656             // save document here. If saving fails, return false;
657             return saveFile();
658         case KMessageBox::No :
659             // User does not want to save the changes, clear recovery files
660             m_activeDocument->m_autosave->resize(0);
661             return true;
662         default: // cancel
663             return false;
664         }
665     }
666     return true;
667 }
668
669 void MainWindow::loadPlugins()
670 {
671     foreach(QObject * plugin, QPluginLoader::staticInstances()) {
672         populateMenus(plugin);
673     }
674
675     QStringList directories = KGlobal::dirs()->findDirs("module", QString());
676     QStringList filters;
677     filters << "libkdenlive*";
678     foreach(const QString & folder, directories) {
679         kDebug() << "Parsing plugin folder: " << folder;
680         QDir pluginsDir(folder);
681         foreach(const QString & fileName,
682                 pluginsDir.entryList(filters, QDir::Files)) {
683             /*
684              * Avoid loading the same plugin twice when there is more than one
685              * installation.
686              */
687             if (!m_pluginFileNames.contains(fileName)) {
688                 kDebug() << "Found plugin: " << fileName;
689                 QPluginLoader loader(pluginsDir.absoluteFilePath(fileName));
690                 QObject *plugin = loader.instance();
691                 if (plugin) {
692                     populateMenus(plugin);
693                     m_pluginFileNames += fileName;
694                 } else
695                     kDebug() << "Error loading plugin: " << fileName << ", " << loader.errorString();
696             }
697         }
698     }
699 }
700
701 void MainWindow::populateMenus(QObject *plugin)
702 {
703     QMenu *addMenu = static_cast<QMenu*>(factory()->container("generators", this));
704     ClipGenerator *iGenerator = qobject_cast<ClipGenerator *>(plugin);
705     if (iGenerator)
706         addToMenu(plugin, iGenerator->generators(KdenliveSettings::producerslist()), addMenu, SLOT(generateClip()),
707                   NULL);
708 }
709
710 void MainWindow::addToMenu(QObject *plugin, const QStringList &texts,
711                            QMenu *menu, const char *member,
712                            QActionGroup *actionGroup)
713 {
714     kDebug() << "// ADD to MENU" << texts;
715     foreach(const QString & text, texts) {
716         QAction *action = new QAction(text, plugin);
717         action->setData(text);
718         connect(action, SIGNAL(triggered()), this, member);
719         menu->addAction(action);
720
721         if (actionGroup) {
722             action->setCheckable(true);
723             actionGroup->addAction(action);
724         }
725     }
726 }
727
728 void MainWindow::aboutPlugins()
729 {
730     //PluginDialog dialog(pluginsDir.path(), m_pluginFileNames, this);
731     //dialog.exec();
732 }
733
734
735 void MainWindow::generateClip()
736 {
737     QAction *action = qobject_cast<QAction *>(sender());
738     ClipGenerator *iGenerator = qobject_cast<ClipGenerator *>(action->parent());
739
740     KUrl clipUrl = iGenerator->generatedClip(action->data().toString(), m_activeDocument->projectFolder(),
741                    QStringList(), QStringList(), m_activeDocument->fps(), m_activeDocument->width(), m_activeDocument->height());
742     if (!clipUrl.isEmpty()) {
743         m_projectList->slotAddClip(QList <QUrl> () << clipUrl);
744     }
745 }
746
747 void MainWindow::saveProperties(KConfigGroup &config)
748 {
749     // save properties here,used by session management
750     saveFile();
751     KMainWindow::saveProperties(config);
752 }
753
754
755 void MainWindow::readProperties(const KConfigGroup &config)
756 {
757     // read properties here,used by session management
758     KMainWindow::readProperties(config);
759     QString Lastproject = config.group("Recent Files").readPathEntry("File1", QString());
760     openFile(KUrl(Lastproject));
761 }
762
763 void MainWindow::slotReloadEffects()
764 {
765     initEffects::parseCustomEffectsFile();
766     m_effectList->reloadEffectList(m_effectsMenu, m_effectActions);
767 }
768
769 #ifndef NO_JOGSHUTTLE
770 void MainWindow::activateShuttleDevice()
771 {
772     delete m_jogShuttle;
773     m_jogShuttle = NULL;
774     delete m_jogProcess;
775     m_jogProcess = NULL;
776     if (KdenliveSettings::enableshuttle() == false) return;
777     
778     m_jogProcess = new JogShuttle(KdenliveSettings::shuttledevice());
779     m_jogShuttle = new JogShuttleAction(m_jogProcess, JogShuttleConfig::actionMap(KdenliveSettings::shuttlebuttons()));
780     
781     connect(m_jogShuttle, SIGNAL(rewindOneFrame()), m_monitorManager, SLOT(slotRewindOneFrame()));
782     connect(m_jogShuttle, SIGNAL(forwardOneFrame()), m_monitorManager, SLOT(slotForwardOneFrame()));
783     connect(m_jogShuttle, SIGNAL(rewind(double)), m_monitorManager, SLOT(slotRewind(double)));
784     connect(m_jogShuttle, SIGNAL(forward(double)), m_monitorManager, SLOT(slotForward(double)));
785     connect(m_jogShuttle, SIGNAL(action(const QString&)), this, SLOT(slotDoAction(const QString&)));
786 }
787 #endif /* NO_JOGSHUTTLE */
788
789 void MainWindow::slotDoAction(const QString& action_name)
790 {
791     QAction* action = actionCollection()->action(action_name);
792     if (!action) {
793         fprintf(stderr, "%s", QString("shuttle action '%1' unknown\n").arg(action_name).toAscii().constData());
794         return;
795     }
796     action->trigger();
797 }
798
799 void MainWindow::configureNotifications()
800 {
801     KNotifyConfigWidget::configure(this);
802 }
803
804 void MainWindow::slotFullScreen()
805 {
806     KToggleFullScreenAction::setFullScreen(this, actionCollection()->action("fullscreen")->isChecked());
807 }
808
809 void MainWindow::slotAddEffect(const QDomElement effect)
810 {
811     if (!m_activeDocument) return;
812     if (effect.isNull()) {
813         kDebug() << "--- ERROR, TRYING TO APPEND NULL EFFECT";
814         return;
815     }
816     QDomElement effectToAdd = effect.cloneNode().toElement();
817     bool ok;
818     int ix = m_effectStack->isTrackMode(&ok);
819     if (ok) m_activeTimeline->projectView()->slotAddTrackEffect(effectToAdd, m_activeDocument->tracksCount() - ix);
820     else m_activeTimeline->projectView()->slotAddEffect(effectToAdd, GenTime(), -1);
821 }
822
823 void MainWindow::slotRaiseMonitor(bool clipMonitor)
824 {
825     if (clipMonitor) m_clipMonitorDock->raise();
826     else m_projectMonitorDock->raise();
827 }
828
829 void MainWindow::slotUpdateClip(const QString &id)
830 {
831     if (!m_activeDocument) return;
832     m_activeTimeline->projectView()->slotUpdateClip(id);
833 }
834
835 void MainWindow::slotConnectMonitors()
836 {
837     m_projectList->setRenderer(m_projectMonitor->render);
838     //connect(m_projectList, SIGNAL(receivedClipDuration(const QString &)), this, SLOT(slotUpdateClip(const QString &)));
839     connect(m_projectList, SIGNAL(deleteProjectClips(QStringList, QMap<QString, QString>)), this, SLOT(slotDeleteProjectClips(QStringList, QMap<QString, QString>)));
840     connect(m_projectList, SIGNAL(showClipProperties(DocClipBase *)), this, SLOT(slotShowClipProperties(DocClipBase *)));
841     connect(m_projectList, SIGNAL(showClipProperties(QList <DocClipBase *>, QMap<QString, QString>)), this, SLOT(slotShowClipProperties(QList <DocClipBase *>, QMap<QString, QString>)));
842     connect(m_projectList, SIGNAL(getFileProperties(const QDomElement, const QString &, int, bool, bool)), m_projectMonitor->render, SLOT(getFileProperties(const QDomElement, const QString &, int, bool, bool)));
843     connect(m_projectMonitor->render, SIGNAL(replyGetImage(const QString &, const QPixmap &)), m_projectList, SLOT(slotReplyGetImage(const QString &, const QPixmap &)));
844     connect(m_projectMonitor->render, SIGNAL(replyGetFileProperties(const QString &, Mlt::Producer*, const QMap < QString, QString > &, const QMap < QString, QString > &, bool, bool)), m_projectList, SLOT(slotReplyGetFileProperties(const QString &, Mlt::Producer*, const QMap < QString, QString > &, const QMap < QString, QString > &, bool, bool)));
845
846     connect(m_projectMonitor->render, SIGNAL(removeInvalidClip(const QString &, bool)), m_projectList, SLOT(slotRemoveInvalidClip(const QString &, bool)));
847     connect(m_projectMonitor->render, SIGNAL(removeInvalidProxy(const QString &)), m_projectList, SLOT(slotRemoveInvalidProxy(const QString &)));
848
849     connect(m_clipMonitor, SIGNAL(refreshClipThumbnail(const QString &, bool)), m_projectList, SLOT(slotRefreshClipThumbnail(const QString &, bool)));
850
851     connect(m_clipMonitor, SIGNAL(adjustMonitorSize()), this, SLOT(slotAdjustClipMonitor()));
852     connect(m_projectMonitor, SIGNAL(adjustMonitorSize()), this, SLOT(slotAdjustProjectMonitor()));
853
854     connect(m_projectMonitor, SIGNAL(requestFrameForAnalysis(bool)), this, SLOT(slotMonitorRequestRenderFrame(bool)));
855
856     connect(m_clipMonitor, SIGNAL(saveZone(Render *, QPoint)), this, SLOT(slotSaveZone(Render *, QPoint)));
857     connect(m_projectMonitor, SIGNAL(saveZone(Render *, QPoint)), this, SLOT(slotSaveZone(Render *, QPoint)));
858 }
859
860 void MainWindow::slotAdjustClipMonitor()
861 {
862     m_clipMonitorDock->updateGeometry();
863     m_clipMonitorDock->adjustSize();
864     m_clipMonitor->resetSize();
865 }
866
867 void MainWindow::slotAdjustProjectMonitor()
868 {
869     m_projectMonitorDock->updateGeometry();
870     m_projectMonitorDock->adjustSize();
871     m_projectMonitor->resetSize();
872 }
873
874
875 class NameGrabbingKActionCollection {
876 public:
877   NameGrabbingKActionCollection(KActionCollection* collection, QStringList& action_names)
878     : m_collection(collection), m_action_names(action_names) {
879       m_action_names.clear();
880     }
881   KAction* addAction(const QString& action_name) {
882     m_action_names << action_name;
883     return m_collection->addAction(action_name);
884   }
885   void addAction(const QString& action_name, QAction* action) {
886     m_action_names << action_name;
887     m_collection->addAction(action_name, action);
888   }
889   operator KActionCollection*() { return m_collection; }
890   const QStringList& actionNames() const { return m_action_names; }
891 private:
892   KActionCollection* m_collection;
893   QStringList& m_action_names;
894 };
895
896 void MainWindow::setupActions()
897 {
898
899     NameGrabbingKActionCollection collection(actionCollection(), m_action_names);
900     m_timecodeFormat = new KComboBox(this);
901     m_timecodeFormat->addItem(i18n("hh:mm:ss:ff"));
902     m_timecodeFormat->addItem(i18n("Frames"));
903     if (KdenliveSettings::frametimecode()) m_timecodeFormat->setCurrentIndex(1);
904     connect(m_timecodeFormat, SIGNAL(activated(int)), this, SLOT(slotUpdateTimecodeFormat(int)));
905
906     m_statusProgressBar = new QProgressBar(this);
907     m_statusProgressBar->setMinimum(0);
908     m_statusProgressBar->setMaximum(100);
909     m_statusProgressBar->setMaximumWidth(150);
910     m_statusProgressBar->setVisible(false);
911
912     KToolBar *toolbar = new KToolBar("statusToolBar", this, Qt::BottomToolBarArea);
913     toolbar->setMovable(false);
914     KColorScheme scheme(palette().currentColorGroup(), KColorScheme::Window, KSharedConfig::openConfig(KdenliveSettings::colortheme()));
915     QColor buttonBg = scheme.background(KColorScheme::LinkBackground).color();
916     QColor buttonBord = scheme.foreground(KColorScheme::LinkText).color();
917     QColor buttonBord2 = scheme.shade(KColorScheme::LightShade);
918     statusBar()->setStyleSheet(QString("QStatusBar QLabel {font-size:%1pt;} QStatusBar::item { border: 0px; font-size:%1pt;padding:0px; }").arg(statusBar()->font().pointSize()));
919     QString style1 = QString("QToolBar { border: 0px } QToolButton { border-style: inset; border:1px solid transparent;border-radius: 3px;margin: 0px 3px;padding: 0px;} QToolButton:hover { background: rgb(%7, %8, %9);border-style: inset; border:1px solid rgb(%7, %8, %9);border-radius: 3px;} QToolButton:checked { background-color: rgb(%1, %2, %3); border-style: inset; border:1px solid rgb(%4, %5, %6);border-radius: 3px;}").arg(buttonBg.red()).arg(buttonBg.green()).arg(buttonBg.blue()).arg(buttonBord.red()).arg(buttonBord.green()).arg(buttonBord.blue()).arg(buttonBord2.red()).arg(buttonBord2.green()).arg(buttonBord2.blue());
920     QString styleBorderless = "QToolButton { border-width: 0px;margin: 1px 3px 0px;padding: 0px;}";
921
922     //create edit mode buttons
923     m_normalEditTool = new KAction(KIcon("kdenlive-normal-edit"), i18n("Normal mode"), this);
924     m_normalEditTool->setShortcut(i18nc("Normal editing", "n"));
925     toolbar->addAction(m_normalEditTool);
926     m_normalEditTool->setCheckable(true);
927     m_normalEditTool->setChecked(true);
928
929     m_overwriteEditTool = new KAction(KIcon("kdenlive-overwrite-edit"), i18n("Overwrite mode"), this);
930     //m_overwriteEditTool->setShortcut(i18nc("Overwrite mode shortcut", "o"));
931     toolbar->addAction(m_overwriteEditTool);
932     m_overwriteEditTool->setCheckable(true);
933     m_overwriteEditTool->setChecked(false);
934
935     m_insertEditTool = new KAction(KIcon("kdenlive-insert-edit"), i18n("Insert mode"), this);
936     //m_insertEditTool->setShortcut(i18nc("Insert mode shortcut", "i"));
937     toolbar->addAction(m_insertEditTool);
938     m_insertEditTool->setCheckable(true);
939     m_insertEditTool->setChecked(false);
940     // not implemented yet
941     m_insertEditTool->setEnabled(false);
942
943     QActionGroup *editGroup = new QActionGroup(this);
944     editGroup->addAction(m_normalEditTool);
945     editGroup->addAction(m_overwriteEditTool);
946     editGroup->addAction(m_insertEditTool);
947     editGroup->setExclusive(true);
948     connect(editGroup, SIGNAL(triggered(QAction *)), this, SLOT(slotChangeEdit(QAction *)));
949     //connect(m_overwriteEditTool, SIGNAL(toggled(bool)), this, SLOT(slotSetOverwriteMode(bool)));
950
951     toolbar->addSeparator();
952
953     // create tools buttons
954     m_buttonSelectTool = new KAction(KIcon("kdenlive-select-tool"), i18n("Selection tool"), this);
955     m_buttonSelectTool->setShortcut(i18nc("Selection tool shortcut", "s"));
956     toolbar->addAction(m_buttonSelectTool);
957     m_buttonSelectTool->setCheckable(true);
958     m_buttonSelectTool->setChecked(true);
959
960     m_buttonRazorTool = new KAction(KIcon("edit-cut"), i18n("Razor tool"), this);
961     m_buttonRazorTool->setShortcut(i18nc("Razor tool shortcut", "x"));
962     toolbar->addAction(m_buttonRazorTool);
963     m_buttonRazorTool->setCheckable(true);
964     m_buttonRazorTool->setChecked(false);
965
966     m_buttonSpacerTool = new KAction(KIcon("kdenlive-spacer-tool"), i18n("Spacer tool"), this);
967     m_buttonSpacerTool->setShortcut(i18nc("Spacer tool shortcut", "m"));
968     toolbar->addAction(m_buttonSpacerTool);
969     m_buttonSpacerTool->setCheckable(true);
970     m_buttonSpacerTool->setChecked(false);
971
972     QActionGroup *toolGroup = new QActionGroup(this);
973     toolGroup->addAction(m_buttonSelectTool);
974     toolGroup->addAction(m_buttonRazorTool);
975     toolGroup->addAction(m_buttonSpacerTool);
976     toolGroup->setExclusive(true);
977     toolbar->setToolButtonStyle(Qt::ToolButtonIconOnly);
978
979     QWidget * actionWidget;
980     int max = toolbar->iconSizeDefault() + 2;
981     actionWidget = toolbar->widgetForAction(m_normalEditTool);
982     actionWidget->setMaximumWidth(max);
983     actionWidget->setMaximumHeight(max - 4);
984
985     actionWidget = toolbar->widgetForAction(m_insertEditTool);
986     actionWidget->setMaximumWidth(max);
987     actionWidget->setMaximumHeight(max - 4);
988
989     actionWidget = toolbar->widgetForAction(m_overwriteEditTool);
990     actionWidget->setMaximumWidth(max);
991     actionWidget->setMaximumHeight(max - 4);
992
993     actionWidget = toolbar->widgetForAction(m_buttonSelectTool);
994     actionWidget->setMaximumWidth(max);
995     actionWidget->setMaximumHeight(max - 4);
996
997     actionWidget = toolbar->widgetForAction(m_buttonRazorTool);
998     actionWidget->setMaximumWidth(max);
999     actionWidget->setMaximumHeight(max - 4);
1000
1001     actionWidget = toolbar->widgetForAction(m_buttonSpacerTool);
1002     actionWidget->setMaximumWidth(max);
1003     actionWidget->setMaximumHeight(max - 4);
1004
1005     toolbar->setStyleSheet(style1);
1006     connect(toolGroup, SIGNAL(triggered(QAction *)), this, SLOT(slotChangeTool(QAction *)));
1007
1008     toolbar->addSeparator();
1009     m_buttonFitZoom = new KAction(KIcon("zoom-fit-best"), i18n("Fit zoom to project"), this);
1010     toolbar->addAction(m_buttonFitZoom);
1011     m_buttonFitZoom->setCheckable(false);
1012
1013     m_zoomOut = new KAction(KIcon("zoom-out"), i18n("Zoom Out"), this);
1014     toolbar->addAction(m_zoomOut);
1015     m_zoomOut->setShortcut(Qt::CTRL + Qt::Key_Minus);
1016
1017     m_zoomSlider = new QSlider(Qt::Horizontal, this);
1018     m_zoomSlider->setMaximum(13);
1019     m_zoomSlider->setPageStep(1);
1020     m_zoomSlider->setInvertedAppearance(true);
1021
1022     m_zoomSlider->setMaximumWidth(150);
1023     m_zoomSlider->setMinimumWidth(100);
1024     toolbar->addWidget(m_zoomSlider);
1025
1026     m_zoomIn = new KAction(KIcon("zoom-in"), i18n("Zoom In"), this);
1027     toolbar->addAction(m_zoomIn);
1028     m_zoomIn->setShortcut(Qt::CTRL + Qt::Key_Plus);
1029
1030     actionWidget = toolbar->widgetForAction(m_buttonFitZoom);
1031     actionWidget->setMaximumWidth(max);
1032     actionWidget->setMaximumHeight(max - 4);
1033     actionWidget->setStyleSheet(styleBorderless);
1034
1035     actionWidget = toolbar->widgetForAction(m_zoomIn);
1036     actionWidget->setMaximumWidth(max);
1037     actionWidget->setMaximumHeight(max - 4);
1038     actionWidget->setStyleSheet(styleBorderless);
1039
1040     actionWidget = toolbar->widgetForAction(m_zoomOut);
1041     actionWidget->setMaximumWidth(max);
1042     actionWidget->setMaximumHeight(max - 4);
1043     actionWidget->setStyleSheet(styleBorderless);
1044
1045     connect(m_zoomSlider, SIGNAL(valueChanged(int)), this, SLOT(slotSetZoom(int)));
1046     connect(m_zoomSlider, SIGNAL(sliderMoved(int)), this, SLOT(slotShowZoomSliderToolTip(int)));
1047     connect(m_buttonFitZoom, SIGNAL(triggered()), this, SLOT(slotFitZoom()));
1048     connect(m_zoomIn, SIGNAL(triggered(bool)), this, SLOT(slotZoomIn()));
1049     connect(m_zoomOut, SIGNAL(triggered(bool)), this, SLOT(slotZoomOut()));
1050
1051     toolbar->addSeparator();
1052
1053     //create automatic audio split button
1054     m_buttonAutomaticSplitAudio = new KAction(KIcon("kdenlive-split-audio"), i18n("Split audio and video automatically"), this);
1055     toolbar->addAction(m_buttonAutomaticSplitAudio);
1056     m_buttonAutomaticSplitAudio->setCheckable(true);
1057     m_buttonAutomaticSplitAudio->setChecked(KdenliveSettings::splitaudio());
1058     connect(m_buttonAutomaticSplitAudio, SIGNAL(triggered()), this, SLOT(slotSwitchSplitAudio()));
1059
1060     m_buttonVideoThumbs = new KAction(KIcon("kdenlive-show-videothumb"), i18n("Show video thumbnails"), this);
1061     toolbar->addAction(m_buttonVideoThumbs);
1062     m_buttonVideoThumbs->setCheckable(true);
1063     m_buttonVideoThumbs->setChecked(KdenliveSettings::videothumbnails());
1064     connect(m_buttonVideoThumbs, SIGNAL(triggered()), this, SLOT(slotSwitchVideoThumbs()));
1065
1066     m_buttonAudioThumbs = new KAction(KIcon("kdenlive-show-audiothumb"), i18n("Show audio thumbnails"), this);
1067     toolbar->addAction(m_buttonAudioThumbs);
1068     m_buttonAudioThumbs->setCheckable(true);
1069     m_buttonAudioThumbs->setChecked(KdenliveSettings::audiothumbnails());
1070     connect(m_buttonAudioThumbs, SIGNAL(triggered()), this, SLOT(slotSwitchAudioThumbs()));
1071
1072     m_buttonShowMarkers = new KAction(KIcon("kdenlive-show-markers"), i18n("Show markers comments"), this);
1073     toolbar->addAction(m_buttonShowMarkers);
1074     m_buttonShowMarkers->setCheckable(true);
1075     m_buttonShowMarkers->setChecked(KdenliveSettings::showmarkers());
1076     connect(m_buttonShowMarkers, SIGNAL(triggered()), this, SLOT(slotSwitchMarkersComments()));
1077
1078     m_buttonSnap = new KAction(KIcon("kdenlive-snap"), i18n("Snap"), this);
1079     toolbar->addAction(m_buttonSnap);
1080     m_buttonSnap->setCheckable(true);
1081     m_buttonSnap->setChecked(KdenliveSettings::snaptopoints());
1082     connect(m_buttonSnap, SIGNAL(triggered()), this, SLOT(slotSwitchSnap()));
1083
1084     actionWidget = toolbar->widgetForAction(m_buttonAutomaticSplitAudio);
1085     actionWidget->setMaximumWidth(max);
1086     actionWidget->setMaximumHeight(max - 4);
1087
1088     actionWidget = toolbar->widgetForAction(m_buttonVideoThumbs);
1089     actionWidget->setMaximumWidth(max);
1090     actionWidget->setMaximumHeight(max - 4);
1091
1092     actionWidget = toolbar->widgetForAction(m_buttonAudioThumbs);
1093     actionWidget->setMaximumWidth(max);
1094     actionWidget->setMaximumHeight(max - 4);
1095
1096     actionWidget = toolbar->widgetForAction(m_buttonShowMarkers);
1097     actionWidget->setMaximumWidth(max);
1098     actionWidget->setMaximumHeight(max - 4);
1099
1100     actionWidget = toolbar->widgetForAction(m_buttonSnap);
1101     actionWidget->setMaximumWidth(max);
1102     actionWidget->setMaximumHeight(max - 4);
1103
1104     m_messageLabel = new StatusBarMessageLabel(this);
1105     m_messageLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::MinimumExpanding);
1106
1107     statusBar()->addWidget(m_messageLabel, 10);
1108     statusBar()->addWidget(m_statusProgressBar, 0);
1109     statusBar()->addPermanentWidget(toolbar);
1110     statusBar()->insertPermanentFixedItem("00:00:00:00", ID_TIMELINE_POS);
1111     statusBar()->addPermanentWidget(m_timecodeFormat);
1112     //statusBar()->setMaximumHeight(statusBar()->font().pointSize() * 3);
1113
1114     collection.addAction("normal_mode", m_normalEditTool);
1115     collection.addAction("overwrite_mode", m_overwriteEditTool);
1116     collection.addAction("insert_mode", m_insertEditTool);
1117     collection.addAction("select_tool", m_buttonSelectTool);
1118     collection.addAction("razor_tool", m_buttonRazorTool);
1119     collection.addAction("spacer_tool", m_buttonSpacerTool);
1120
1121     collection.addAction("automatic_split_audio", m_buttonAutomaticSplitAudio);
1122     collection.addAction("show_video_thumbs", m_buttonVideoThumbs);
1123     collection.addAction("show_audio_thumbs", m_buttonAudioThumbs);
1124     collection.addAction("show_markers", m_buttonShowMarkers);
1125     collection.addAction("snap", m_buttonSnap);
1126     collection.addAction("zoom_fit", m_buttonFitZoom);
1127     collection.addAction("zoom_in", m_zoomIn);
1128     collection.addAction("zoom_out", m_zoomOut);
1129
1130     m_projectSearch = new KAction(KIcon("edit-find"), i18n("Find"), this);
1131     collection.addAction("project_find", m_projectSearch);
1132     connect(m_projectSearch, SIGNAL(triggered(bool)), this, SLOT(slotFind()));
1133     m_projectSearch->setShortcut(Qt::Key_Slash);
1134
1135     m_projectSearchNext = new KAction(KIcon("go-down-search"), i18n("Find Next"), this);
1136     collection.addAction("project_find_next", m_projectSearchNext);
1137     connect(m_projectSearchNext, SIGNAL(triggered(bool)), this, SLOT(slotFindNext()));
1138     m_projectSearchNext->setShortcut(Qt::Key_F3);
1139     m_projectSearchNext->setEnabled(false);
1140
1141     KAction* profilesAction = new KAction(KIcon("document-new"), i18n("Manage Project Profiles"), this);
1142     collection.addAction("manage_profiles", profilesAction);
1143     connect(profilesAction, SIGNAL(triggered(bool)), this, SLOT(slotEditProfiles()));
1144
1145     KNS3::standardAction(i18n("Download New Wipes..."),            this, SLOT(slotGetNewLumaStuff()),       actionCollection(), "get_new_lumas");
1146     KNS3::standardAction(i18n("Download New Render Profiles..."),  this, SLOT(slotGetNewRenderStuff()),     actionCollection(), "get_new_profiles");
1147     KNS3::standardAction(i18n("Download New Project Profiles..."), this, SLOT(slotGetNewMltProfileStuff()), actionCollection(), "get_new_mlt_profiles");
1148     KNS3::standardAction(i18n("Download New Title Templates..."),  this, SLOT(slotGetNewTitleStuff()),      actionCollection(), "get_new_titles");
1149
1150     KAction* wizAction = new KAction(KIcon("configure"), i18n("Run Config Wizard"), this);
1151     collection.addAction("run_wizard", wizAction);
1152     connect(wizAction, SIGNAL(triggered(bool)), this, SLOT(slotRunWizard()));
1153
1154     KAction* projectAction = new KAction(KIcon("configure"), i18n("Project Settings"), this);
1155     collection.addAction("project_settings", projectAction);
1156     connect(projectAction, SIGNAL(triggered(bool)), this, SLOT(slotEditProjectSettings()));
1157
1158     KAction* projectRender = new KAction(KIcon("media-record"), i18n("Render"), this);
1159     collection.addAction("project_render", projectRender);
1160     projectRender->setShortcut(Qt::CTRL + Qt::Key_Return);
1161     connect(projectRender, SIGNAL(triggered(bool)), this, SLOT(slotRenderProject()));
1162
1163     KAction* projectClean = new KAction(KIcon("edit-clear"), i18n("Clean Project"), this);
1164     collection.addAction("project_clean", projectClean);
1165     connect(projectClean, SIGNAL(triggered(bool)), this, SLOT(slotCleanProject()));
1166
1167     KAction* projectAdjust = new KAction(KIcon(), i18n("Adjust Profile to Current Clip"), this);
1168     collection.addAction("project_adjust_profile", projectAdjust);
1169     connect(projectAdjust, SIGNAL(triggered(bool)), m_projectList, SLOT(adjustProjectProfileToItem()));
1170
1171     KAction* monitorPlay = new KAction(KIcon("media-playback-start"), i18n("Play"), this);
1172     KShortcut playShortcut;
1173     playShortcut.setPrimary(Qt::Key_Space);
1174     playShortcut.setAlternate(Qt::Key_K);
1175     monitorPlay->setShortcut(playShortcut);
1176     collection.addAction("monitor_play", monitorPlay);
1177     connect(monitorPlay, SIGNAL(triggered(bool)), m_monitorManager, SLOT(slotPlay()));
1178
1179     KAction* monitorPause = new KAction(KIcon("media-playback-stop"), i18n("Pause"), this);
1180     collection.addAction("monitor_pause", monitorPause);
1181     connect(monitorPause, SIGNAL(triggered(bool)), m_monitorManager, SLOT(slotPause()));
1182
1183     m_playZone = new KAction(KIcon("media-playback-start"), i18n("Play Zone"), this);
1184     m_playZone->setShortcut(Qt::CTRL + Qt::Key_Space);
1185     collection.addAction("monitor_play_zone", m_playZone);
1186     connect(m_playZone, SIGNAL(triggered(bool)), m_monitorManager, SLOT(slotPlayZone()));
1187
1188     m_loopZone = new KAction(KIcon("media-playback-start"), i18n("Loop Zone"), this);
1189     m_loopZone->setShortcut(Qt::ALT + Qt::Key_Space);
1190     collection.addAction("monitor_loop_zone", m_loopZone);
1191     connect(m_loopZone, SIGNAL(triggered(bool)), m_monitorManager, SLOT(slotLoopZone()));
1192
1193     m_loopClip = new KAction(KIcon("media-playback-start"), i18n("Loop selected clip"), this);
1194     m_loopClip->setEnabled(false);
1195     collection.addAction("monitor_loop_clip", m_loopClip);
1196     connect(m_loopClip, SIGNAL(triggered(bool)), m_projectMonitor, SLOT(slotLoopClip()));
1197
1198     KAction *dvdWizard =  new KAction(KIcon("media-optical"), i18n("DVD Wizard"), this);
1199     collection.addAction("dvd_wizard", dvdWizard);
1200     connect(dvdWizard, SIGNAL(triggered(bool)), this, SLOT(slotDvdWizard()));
1201
1202     KAction *transcodeClip =  new KAction(KIcon("edit-copy"), i18n("Transcode Clips"), this);
1203     collection.addAction("transcode_clip", transcodeClip);
1204     connect(transcodeClip, SIGNAL(triggered(bool)), this, SLOT(slotTranscodeClip()));
1205
1206     KAction *markIn = collection.addAction("mark_in");
1207     markIn->setText(i18n("Set Zone In"));
1208     markIn->setShortcut(Qt::Key_I);
1209     connect(markIn, SIGNAL(triggered(bool)), this, SLOT(slotSetInPoint()));
1210
1211     KAction *markOut = collection.addAction("mark_out");
1212     markOut->setText(i18n("Set Zone Out"));
1213     markOut->setShortcut(Qt::Key_O);
1214     connect(markOut, SIGNAL(triggered(bool)), this, SLOT(slotSetOutPoint()));
1215
1216     KAction *switchMon = collection.addAction("switch_monitor");
1217     switchMon->setText(i18n("Switch monitor"));
1218     switchMon->setShortcut(Qt::Key_T);
1219     connect(switchMon, SIGNAL(triggered(bool)), this, SLOT(slotSwitchMonitors()));
1220
1221     KAction *fullMon = collection.addAction("monitor_fullscreen");
1222     fullMon->setText(i18n("Switch monitor fullscreen"));
1223     fullMon->setIcon(KIcon("view-fullscreen"));
1224     connect(fullMon, SIGNAL(triggered(bool)), this, SLOT(slotSwitchFullscreen()));
1225
1226     KAction *insertTree = collection.addAction("insert_project_tree");
1227     insertTree->setText(i18n("Insert zone in project tree"));
1228     insertTree->setShortcut(Qt::CTRL + Qt::Key_I);
1229     connect(insertTree, SIGNAL(triggered(bool)), this, SLOT(slotInsertZoneToTree()));
1230
1231     KAction *insertTimeline = collection.addAction("insert_timeline");
1232     insertTimeline->setText(i18n("Insert zone in timeline"));
1233     insertTimeline->setShortcut(Qt::SHIFT + Qt::CTRL + Qt::Key_I);
1234     connect(insertTimeline, SIGNAL(triggered(bool)), this, SLOT(slotInsertZoneToTimeline()));
1235
1236     KAction *resizeStart =  new KAction(KIcon(), i18n("Resize Item Start"), this);
1237     collection.addAction("resize_timeline_clip_start", resizeStart);
1238     resizeStart->setShortcut(Qt::Key_1);
1239     connect(resizeStart, SIGNAL(triggered(bool)), this, SLOT(slotResizeItemStart()));
1240
1241     KAction *resizeEnd =  new KAction(KIcon(), i18n("Resize Item End"), this);
1242     collection.addAction("resize_timeline_clip_end", resizeEnd);
1243     resizeEnd->setShortcut(Qt::Key_2);
1244     connect(resizeEnd, SIGNAL(triggered(bool)), this, SLOT(slotResizeItemEnd()));
1245
1246     KAction* monitorSeekBackward = new KAction(KIcon("media-seek-backward"), i18n("Rewind"), this);
1247     monitorSeekBackward->setShortcut(Qt::Key_J);
1248     collection.addAction("monitor_seek_backward", monitorSeekBackward);
1249     connect(monitorSeekBackward, SIGNAL(triggered(bool)), m_monitorManager, SLOT(slotRewind()));
1250
1251     KAction* monitorSeekBackwardOneFrame = new KAction(KIcon("media-skip-backward"), i18n("Rewind 1 Frame"), this);
1252     monitorSeekBackwardOneFrame->setShortcut(Qt::Key_Left);
1253     collection.addAction("monitor_seek_backward-one-frame", monitorSeekBackwardOneFrame);
1254     connect(monitorSeekBackwardOneFrame, SIGNAL(triggered(bool)), m_monitorManager, SLOT(slotRewindOneFrame()));
1255
1256     KAction* monitorSeekBackwardOneSecond = new KAction(KIcon("media-skip-backward"), i18n("Rewind 1 Second"), this);
1257     monitorSeekBackwardOneSecond->setShortcut(Qt::SHIFT + Qt::Key_Left);
1258     collection.addAction("monitor_seek_backward-one-second", monitorSeekBackwardOneSecond);
1259     connect(monitorSeekBackwardOneSecond, SIGNAL(triggered(bool)), m_monitorManager, SLOT(slotRewindOneSecond()));
1260
1261     KAction* monitorSeekSnapBackward = new KAction(KIcon("media-seek-backward"), i18n("Go to Previous Snap Point"), this);
1262     monitorSeekSnapBackward->setShortcut(Qt::ALT + Qt::Key_Left);
1263     collection.addAction("monitor_seek_snap_backward", monitorSeekSnapBackward);
1264     connect(monitorSeekSnapBackward, SIGNAL(triggered(bool)), this, SLOT(slotSnapRewind()));
1265
1266     KAction* monitorSeekForward = new KAction(KIcon("media-seek-forward"), i18n("Forward"), this);
1267     monitorSeekForward->setShortcut(Qt::Key_L);
1268     collection.addAction("monitor_seek_forward", monitorSeekForward);
1269     connect(monitorSeekForward, SIGNAL(triggered(bool)), m_monitorManager, SLOT(slotForward()));
1270
1271     KAction* clipStart = new KAction(KIcon("media-seek-backward"), i18n("Go to Clip Start"), this);
1272     clipStart->setShortcut(Qt::Key_Home);
1273     collection.addAction("seek_clip_start", clipStart);
1274     connect(clipStart, SIGNAL(triggered(bool)), this, SLOT(slotClipStart()));
1275
1276     KAction* clipEnd = new KAction(KIcon("media-seek-forward"), i18n("Go to Clip End"), this);
1277     clipEnd->setShortcut(Qt::Key_End);
1278     collection.addAction("seek_clip_end", clipEnd);
1279     connect(clipEnd, SIGNAL(triggered(bool)), this, SLOT(slotClipEnd()));
1280
1281     KAction* zoneStart = new KAction(KIcon("media-seek-backward"), i18n("Go to Zone Start"), this);
1282     zoneStart->setShortcut(Qt::SHIFT + Qt::Key_I);
1283     collection.addAction("seek_zone_start", zoneStart);
1284     connect(zoneStart, SIGNAL(triggered(bool)), this, SLOT(slotZoneStart()));
1285
1286     KAction* zoneEnd = new KAction(KIcon("media-seek-forward"), i18n("Go to Zone End"), this);
1287     zoneEnd->setShortcut(Qt::SHIFT + Qt::Key_O);
1288     collection.addAction("seek_zone_end", zoneEnd);
1289     connect(zoneEnd, SIGNAL(triggered(bool)), this, SLOT(slotZoneEnd()));
1290
1291     KAction* projectStart = new KAction(KIcon("go-first"), i18n("Go to Project Start"), this);
1292     projectStart->setShortcut(Qt::CTRL + Qt::Key_Home);
1293     collection.addAction("seek_start", projectStart);
1294     connect(projectStart, SIGNAL(triggered(bool)), m_monitorManager, SLOT(slotStart()));
1295
1296     KAction* projectEnd = new KAction(KIcon("go-last"), i18n("Go to Project End"), this);
1297     projectEnd->setShortcut(Qt::CTRL + Qt::Key_End);
1298     collection.addAction("seek_end", projectEnd);
1299     connect(projectEnd, SIGNAL(triggered(bool)), m_monitorManager, SLOT(slotEnd()));
1300
1301     KAction* monitorSeekForwardOneFrame = new KAction(KIcon("media-skip-forward"), i18n("Forward 1 Frame"), this);
1302     monitorSeekForwardOneFrame->setShortcut(Qt::Key_Right);
1303     collection.addAction("monitor_seek_forward-one-frame", monitorSeekForwardOneFrame);
1304     connect(monitorSeekForwardOneFrame, SIGNAL(triggered(bool)), m_monitorManager, SLOT(slotForwardOneFrame()));
1305
1306     KAction* monitorSeekForwardOneSecond = new KAction(KIcon("media-skip-forward"), i18n("Forward 1 Second"), this);
1307     monitorSeekForwardOneSecond->setShortcut(Qt::SHIFT + Qt::Key_Right);
1308     collection.addAction("monitor_seek_forward-one-second", monitorSeekForwardOneSecond);
1309     connect(monitorSeekForwardOneSecond, SIGNAL(triggered(bool)), m_monitorManager, SLOT(slotForwardOneSecond()));
1310
1311     KAction* monitorSeekSnapForward = new KAction(KIcon("media-seek-forward"), i18n("Go to Next Snap Point"), this);
1312     monitorSeekSnapForward->setShortcut(Qt::ALT + Qt::Key_Right);
1313     collection.addAction("monitor_seek_snap_forward", monitorSeekSnapForward);
1314     connect(monitorSeekSnapForward, SIGNAL(triggered(bool)), this, SLOT(slotSnapForward()));
1315
1316     KAction* deleteItem = new KAction(KIcon("edit-delete"), i18n("Delete Selected Item"), this);
1317     deleteItem->setShortcut(Qt::Key_Delete);
1318     collection.addAction("delete_timeline_clip", deleteItem);
1319     connect(deleteItem, SIGNAL(triggered(bool)), this, SLOT(slotDeleteItem()));
1320
1321     /*KAction* editTimelineClipSpeed = new KAction(i18n("Change Clip Speed"), this);
1322     collection.addAction("change_clip_speed", editTimelineClipSpeed);
1323     editTimelineClipSpeed->setData("change_speed");
1324     connect(editTimelineClipSpeed, SIGNAL(triggered(bool)), this, SLOT(slotChangeClipSpeed()));*/
1325
1326     KAction *stickTransition = collection.addAction("auto_transition");
1327     stickTransition->setData(QString("auto"));
1328     stickTransition->setCheckable(true);
1329     stickTransition->setEnabled(false);
1330     stickTransition->setText(i18n("Automatic Transition"));
1331     connect(stickTransition, SIGNAL(triggered(bool)), this, SLOT(slotAutoTransition()));
1332
1333     KAction* groupClip = new KAction(KIcon("object-group"), i18n("Group Clips"), this);
1334     groupClip->setShortcut(Qt::CTRL + Qt::Key_G);
1335     collection.addAction("group_clip", groupClip);
1336     connect(groupClip, SIGNAL(triggered(bool)), this, SLOT(slotGroupClips()));
1337
1338     KAction* ungroupClip = new KAction(KIcon("object-ungroup"), i18n("Ungroup Clips"), this);
1339     collection.addAction("ungroup_clip", ungroupClip);
1340     ungroupClip->setShortcut(Qt::CTRL + Qt::SHIFT + Qt::Key_G);
1341     ungroupClip->setData("ungroup_clip");
1342     connect(ungroupClip, SIGNAL(triggered(bool)), this, SLOT(slotUnGroupClips()));
1343
1344     KAction* editItemDuration = new KAction(KIcon("measure"), i18n("Edit Duration"), this);
1345     collection.addAction("edit_item_duration", editItemDuration);
1346     connect(editItemDuration, SIGNAL(triggered(bool)), this, SLOT(slotEditItemDuration()));
1347
1348     KAction* clipInProjectTree = new KAction(KIcon("go-jump-definition"), i18n("Clip in Project Tree"), this);
1349     collection.addAction("clip_in_project_tree", clipInProjectTree);
1350     connect(clipInProjectTree, SIGNAL(triggered(bool)), this, SLOT(slotClipInProjectTree()));
1351
1352     /*KAction* clipToProjectTree = new KAction(KIcon("go-jump-definition"), i18n("Add Clip to Project Tree"), this);
1353     collection.addAction("clip_to_project_tree", clipToProjectTree);
1354     connect(clipToProjectTree, SIGNAL(triggered(bool)), this, SLOT(slotClipToProjectTree()));*/
1355
1356     KAction* insertOvertwrite = new KAction(KIcon(), i18n("Insert Clip Zone in Timeline (Overwrite)"), this);
1357     insertOvertwrite->setShortcut(Qt::Key_V);
1358     collection.addAction("overwrite_to_in_point", insertOvertwrite);
1359     connect(insertOvertwrite, SIGNAL(triggered(bool)), this, SLOT(slotInsertClipOverwrite()));
1360
1361     KAction* selectTimelineClip = new KAction(KIcon("edit-select"), i18n("Select Clip"), this);
1362     selectTimelineClip->setShortcut(Qt::Key_Plus);
1363     collection.addAction("select_timeline_clip", selectTimelineClip);
1364     connect(selectTimelineClip, SIGNAL(triggered(bool)), this, SLOT(slotSelectTimelineClip()));
1365
1366     KAction* deselectTimelineClip = new KAction(KIcon("edit-select"), i18n("Deselect Clip"), this);
1367     deselectTimelineClip->setShortcut(Qt::Key_Minus);
1368     collection.addAction("deselect_timeline_clip", deselectTimelineClip);
1369     connect(deselectTimelineClip, SIGNAL(triggered(bool)), this, SLOT(slotDeselectTimelineClip()));
1370
1371     KAction* selectAddTimelineClip = new KAction(KIcon("edit-select"), i18n("Add Clip To Selection"), this);
1372     selectAddTimelineClip->setShortcut(Qt::ALT + Qt::Key_Plus);
1373     collection.addAction("select_add_timeline_clip", selectAddTimelineClip);
1374     connect(selectAddTimelineClip, SIGNAL(triggered(bool)), this, SLOT(slotSelectAddTimelineClip()));
1375
1376     KAction* selectTimelineTransition = new KAction(KIcon("edit-select"), i18n("Select Transition"), this);
1377     selectTimelineTransition->setShortcut(Qt::SHIFT + Qt::Key_Plus);
1378     collection.addAction("select_timeline_transition", selectTimelineTransition);
1379     connect(selectTimelineTransition, SIGNAL(triggered(bool)), this, SLOT(slotSelectTimelineTransition()));
1380
1381     KAction* deselectTimelineTransition = new KAction(KIcon("edit-select"), i18n("Deselect Transition"), this);
1382     deselectTimelineTransition->setShortcut(Qt::SHIFT + Qt::Key_Minus);
1383     collection.addAction("deselect_timeline_transition", deselectTimelineTransition);
1384     connect(deselectTimelineTransition, SIGNAL(triggered(bool)), this, SLOT(slotDeselectTimelineTransition()));
1385
1386     KAction* selectAddTimelineTransition = new KAction(KIcon("edit-select"), i18n("Add Transition To Selection"), this);
1387     selectAddTimelineTransition->setShortcut(Qt::ALT + Qt::SHIFT + Qt::Key_Plus);
1388     collection.addAction("select_add_timeline_transition", selectAddTimelineTransition);
1389     connect(selectAddTimelineTransition, SIGNAL(triggered(bool)), this, SLOT(slotSelectAddTimelineTransition()));
1390
1391     KAction* cutTimelineClip = new KAction(KIcon("edit-cut"), i18n("Cut Clip"), this);
1392     cutTimelineClip->setShortcut(Qt::SHIFT + Qt::Key_R);
1393     collection.addAction("cut_timeline_clip", cutTimelineClip);
1394     connect(cutTimelineClip, SIGNAL(triggered(bool)), this, SLOT(slotCutTimelineClip()));
1395
1396     KAction* addClipMarker = new KAction(KIcon("bookmark-new"), i18n("Add Marker"), this);
1397     collection.addAction("add_clip_marker", addClipMarker);
1398     connect(addClipMarker, SIGNAL(triggered(bool)), this, SLOT(slotAddClipMarker()));
1399
1400     KAction* deleteClipMarker = new KAction(KIcon("edit-delete"), i18n("Delete Marker"), this);
1401     collection.addAction("delete_clip_marker", deleteClipMarker);
1402     connect(deleteClipMarker, SIGNAL(triggered(bool)), this, SLOT(slotDeleteClipMarker()));
1403
1404     KAction* deleteAllClipMarkers = new KAction(KIcon("edit-delete"), i18n("Delete All Markers"), this);
1405     collection.addAction("delete_all_clip_markers", deleteAllClipMarkers);
1406     connect(deleteAllClipMarkers, SIGNAL(triggered(bool)), this, SLOT(slotDeleteAllClipMarkers()));
1407
1408     KAction* editClipMarker = new KAction(KIcon("document-properties"), i18n("Edit Marker"), this);
1409     editClipMarker->setData(QString("edit_marker"));
1410     collection.addAction("edit_clip_marker", editClipMarker);
1411     connect(editClipMarker, SIGNAL(triggered(bool)), this, SLOT(slotEditClipMarker()));
1412
1413     KAction *addMarkerGuideQuickly = new KAction(KIcon("bookmark-new"), i18n("Add Marker/Guide quickly"), this);
1414     addMarkerGuideQuickly->setShortcut(Qt::Key_Asterisk);
1415     collection.addAction("add_marker_guide_quickly", addMarkerGuideQuickly);
1416     connect(addMarkerGuideQuickly, SIGNAL(triggered(bool)), this, SLOT(slotAddMarkerGuideQuickly()));
1417
1418     KAction* splitAudio = new KAction(KIcon("document-new"), i18n("Split Audio"), this);
1419     collection.addAction("split_audio", splitAudio);
1420     connect(splitAudio, SIGNAL(triggered(bool)), this, SLOT(slotSplitAudio()));
1421
1422     KAction* audioOnly = new KAction(KIcon("document-new"), i18n("Audio Only"), this);
1423     collection.addAction("clip_audio_only", audioOnly);
1424     audioOnly->setData("clip_audio_only");
1425     audioOnly->setCheckable(true);
1426
1427     KAction* videoOnly = new KAction(KIcon("document-new"), i18n("Video Only"), this);
1428     collection.addAction("clip_video_only", videoOnly);
1429     videoOnly->setData("clip_video_only");
1430     videoOnly->setCheckable(true);
1431
1432     KAction* audioAndVideo = new KAction(KIcon("document-new"), i18n("Audio and Video"), this);
1433     collection.addAction("clip_audio_and_video", audioAndVideo);
1434     audioAndVideo->setData("clip_audio_and_video");
1435     audioAndVideo->setCheckable(true);
1436
1437     m_clipTypeGroup = new QActionGroup(this);
1438     m_clipTypeGroup->addAction(audioOnly);
1439     m_clipTypeGroup->addAction(videoOnly);
1440     m_clipTypeGroup->addAction(audioAndVideo);
1441     connect(m_clipTypeGroup, SIGNAL(triggered(QAction *)), this, SLOT(slotUpdateClipType(QAction *)));
1442     m_clipTypeGroup->setEnabled(false);
1443
1444     KAction *insertSpace = new KAction(KIcon(), i18n("Insert Space"), this);
1445     collection.addAction("insert_space", insertSpace);
1446     connect(insertSpace, SIGNAL(triggered()), this, SLOT(slotInsertSpace()));
1447
1448     KAction *removeSpace = new KAction(KIcon(), i18n("Remove Space"), this);
1449     collection.addAction("delete_space", removeSpace);
1450     connect(removeSpace, SIGNAL(triggered()), this, SLOT(slotRemoveSpace()));
1451
1452     KAction *insertTrack = new KAction(KIcon(), i18n("Insert Track"), this);
1453     collection.addAction("insert_track", insertTrack);
1454     connect(insertTrack, SIGNAL(triggered()), this, SLOT(slotInsertTrack()));
1455
1456     KAction *deleteTrack = new KAction(KIcon(), i18n("Delete Track"), this);
1457     collection.addAction("delete_track", deleteTrack);
1458     connect(deleteTrack, SIGNAL(triggered()), this, SLOT(slotDeleteTrack()));
1459
1460     KAction *configTracks = new KAction(KIcon("configure"), i18n("Configure Tracks"), this);
1461     collection.addAction("config_tracks", configTracks);
1462     connect(configTracks, SIGNAL(triggered()), this, SLOT(slotConfigTrack()));
1463
1464     KAction *addGuide = new KAction(KIcon("document-new"), i18n("Add Guide"), this);
1465     collection.addAction("add_guide", addGuide);
1466     connect(addGuide, SIGNAL(triggered()), this, SLOT(slotAddGuide()));
1467
1468     QAction *delGuide = new KAction(KIcon("edit-delete"), i18n("Delete Guide"), this);
1469     collection.addAction("delete_guide", delGuide);
1470     connect(delGuide, SIGNAL(triggered()), this, SLOT(slotDeleteGuide()));
1471
1472     QAction *editGuide = new KAction(KIcon("document-properties"), i18n("Edit Guide"), this);
1473     collection.addAction("edit_guide", editGuide);
1474     connect(editGuide, SIGNAL(triggered()), this, SLOT(slotEditGuide()));
1475
1476     QAction *delAllGuides = new KAction(KIcon("edit-delete"), i18n("Delete All Guides"), this);
1477     collection.addAction("delete_all_guides", delAllGuides);
1478     connect(delAllGuides, SIGNAL(triggered()), this, SLOT(slotDeleteAllGuides()));
1479
1480     QAction *pasteEffects = new KAction(KIcon("edit-paste"), i18n("Paste Effects"), this);
1481     collection.addAction("paste_effects", pasteEffects);
1482     pasteEffects->setData("paste_effects");
1483     connect(pasteEffects , SIGNAL(triggered()), this, SLOT(slotPasteEffects()));
1484
1485     QAction *showTimeline = new KAction(i18n("Show Timeline"), this);
1486     collection.addAction("show_timeline", showTimeline);
1487     showTimeline->setCheckable(true);
1488     showTimeline->setChecked(true);
1489     connect(showTimeline, SIGNAL(triggered(bool)), this, SLOT(slotShowTimeline(bool)));
1490
1491     QAction *showTitleBar = new KAction(i18n("Show Title Bars"), this);
1492     collection.addAction("show_titlebars", showTitleBar);
1493     showTitleBar->setCheckable(true);
1494     connect(showTitleBar, SIGNAL(triggered(bool)), this, SLOT(slotShowTitleBars(bool)));
1495     showTitleBar->setChecked(KdenliveSettings::showtitlebars());
1496     slotShowTitleBars(KdenliveSettings::showtitlebars());
1497
1498
1499     //const QByteArray state = layoutGroup.readEntry("layout1", QByteArray());
1500
1501     /*QAction *maxCurrent = new KAction(i18n("Maximize Current Widget"), this);
1502     collection.addAction("maximize_current", maxCurrent);
1503     maxCurrent->setCheckable(true);
1504     maxCurrent->setChecked(false);
1505     connect(maxCurrent, SIGNAL(triggered(bool)), this, SLOT(slotMaximizeCurrent(bool)));*/
1506
1507     m_closeAction = KStandardAction::close(this,  SLOT(closeCurrentDocument()),   collection);
1508     KStandardAction::quit(this,                   SLOT(close()),                  collection);
1509     KStandardAction::open(this,                   SLOT(openFile()),               collection);
1510     m_saveAction = KStandardAction::save(this,    SLOT(saveFile()),               collection);
1511     KStandardAction::saveAs(this,                 SLOT(saveFileAs()),             collection);
1512     KStandardAction::openNew(this,                SLOT(newFile()),                collection);
1513     // TODO: make the following connection to slotEditKeys work
1514     KStandardAction::keyBindings(this,            SLOT(slotEditKeys()),           collection);
1515     KStandardAction::preferences(this,            SLOT(slotPreferences()),        collection);
1516     KStandardAction::configureNotifications(this, SLOT(configureNotifications()), collection);
1517     KStandardAction::copy(this,                   SLOT(slotCopy()),               collection);
1518     KStandardAction::paste(this,                  SLOT(slotPaste()),              collection);
1519     KStandardAction::fullScreen(this,             SLOT(slotFullScreen()), this,   collection);
1520
1521     KAction *undo = KStandardAction::undo(m_commandStack, SLOT(undo()), collection);
1522     undo->setEnabled(false);
1523     connect(m_commandStack, SIGNAL(canUndoChanged(bool)), undo, SLOT(setEnabled(bool)));
1524
1525     KAction *redo = KStandardAction::redo(m_commandStack, SLOT(redo()), collection);
1526     redo->setEnabled(false);
1527     connect(m_commandStack, SIGNAL(canRedoChanged(bool)), redo, SLOT(setEnabled(bool)));
1528
1529     /*
1530     //TODO: Add status tooltip to actions ?
1531     connect(collection, SIGNAL(actionHovered(QAction*)),
1532             this, SLOT(slotDisplayActionMessage(QAction*)));*/
1533
1534
1535     QAction *addClip = new KAction(KIcon("kdenlive-add-clip"), i18n("Add Clip"), this);
1536     collection.addAction("add_clip", addClip);
1537     connect(addClip , SIGNAL(triggered()), m_projectList, SLOT(slotAddClip()));
1538
1539     QAction *addColorClip = new KAction(KIcon("kdenlive-add-color-clip"), i18n("Add Color Clip"), this);
1540     collection.addAction("add_color_clip", addColorClip);
1541     connect(addColorClip , SIGNAL(triggered()), m_projectList, SLOT(slotAddColorClip()));
1542
1543     QAction *addSlideClip = new KAction(KIcon("kdenlive-add-slide-clip"), i18n("Add Slideshow Clip"), this);
1544     collection.addAction("add_slide_clip", addSlideClip);
1545     connect(addSlideClip , SIGNAL(triggered()), m_projectList, SLOT(slotAddSlideshowClip()));
1546
1547     QAction *addTitleClip = new KAction(KIcon("kdenlive-add-text-clip"), i18n("Add Title Clip"), this);
1548     collection.addAction("add_text_clip", addTitleClip);
1549     connect(addTitleClip , SIGNAL(triggered()), m_projectList, SLOT(slotAddTitleClip()));
1550
1551     QAction *addTitleTemplateClip = new KAction(KIcon("kdenlive-add-text-clip"), i18n("Add Template Title"), this);
1552     collection.addAction("add_text_template_clip", addTitleTemplateClip);
1553     connect(addTitleTemplateClip , SIGNAL(triggered()), m_projectList, SLOT(slotAddTitleTemplateClip()));
1554
1555     QAction *addFolderButton = new KAction(KIcon("folder-new"), i18n("Create Folder"), this);
1556     collection.addAction("add_folder", addFolderButton);
1557     connect(addFolderButton , SIGNAL(triggered()), m_projectList, SLOT(slotAddFolder()));
1558
1559     QAction *clipProperties = new KAction(KIcon("document-edit"), i18n("Clip Properties"), this);
1560     collection.addAction("clip_properties", clipProperties);
1561     clipProperties->setData("clip_properties");
1562     connect(clipProperties , SIGNAL(triggered()), m_projectList, SLOT(slotEditClip()));
1563     clipProperties->setEnabled(false);
1564
1565     QAction *openClip = new KAction(KIcon("document-open"), i18n("Edit Clip"), this);
1566     collection.addAction("edit_clip", openClip);
1567     openClip->setData("edit_clip");
1568     connect(openClip , SIGNAL(triggered()), m_projectList, SLOT(slotOpenClip()));
1569     openClip->setEnabled(false);
1570
1571     QAction *deleteClip = new KAction(KIcon("edit-delete"), i18n("Delete Clip"), this);
1572     collection.addAction("delete_clip", deleteClip);
1573     deleteClip->setData("delete_clip");
1574     connect(deleteClip , SIGNAL(triggered()), m_projectList, SLOT(slotRemoveClip()));
1575     deleteClip->setEnabled(false);
1576
1577     QAction *reloadClip = new KAction(KIcon("view-refresh"), i18n("Reload Clip"), this);
1578     collection.addAction("reload_clip", reloadClip);
1579     reloadClip->setData("reload_clip");
1580     connect(reloadClip , SIGNAL(triggered()), m_projectList, SLOT(slotReloadClip()));
1581     reloadClip->setEnabled(false);
1582
1583     QAction *stopMotion = new KAction(KIcon("image-x-generic"), i18n("Stop Motion Capture"), this);
1584     collection.addAction("stopmotion", stopMotion);
1585     connect(stopMotion , SIGNAL(triggered()), this, SLOT(slotOpenStopmotion()));
1586
1587     QMenu *addClips = new QMenu();
1588     addClips->addAction(addClip);
1589     addClips->addAction(addColorClip);
1590     addClips->addAction(addSlideClip);
1591     addClips->addAction(addTitleClip);
1592     addClips->addAction(addTitleTemplateClip);
1593     addClips->addAction(addFolderButton);
1594
1595     addClips->addAction(reloadClip);
1596     addClips->addAction(clipProperties);
1597     addClips->addAction(openClip);
1598     addClips->addAction(deleteClip);
1599     m_projectList->setupMenu(addClips, addClip);
1600
1601     // Setup effects and transitions actions.
1602     m_effectsActionCollection = new KActionCollection(this, KGlobal::mainComponent());
1603     //KActionCategory *transitionActions = new KActionCategory(i18n("Transitions"), m_effectsActionCollection);
1604     KActionCategory *transitionActions = new KActionCategory(i18n("Transitions"), collection);
1605     m_transitions = new KAction*[transitions.count()];
1606     for (int i = 0; i < transitions.count(); i++) {
1607         QStringList effectInfo = transitions.effectIdInfo(i);
1608         m_transitions[i] = new KAction(effectInfo.at(0), this);
1609         m_transitions[i]->setData(effectInfo);
1610         m_transitions[i]->setIconVisibleInMenu(false);
1611         QString id = effectInfo.at(2);
1612         if (id.isEmpty()) id = effectInfo.at(1);
1613         transitionActions->addAction("transition_" + id, m_transitions[i]);
1614     }
1615     //m_effectsActionCollection->readSettings();
1616
1617     //connect(collection, SIGNAL( clearStatusText() ),
1618     //statusBar(), SLOT( clear() ) );
1619 }
1620
1621 void MainWindow::slotDisplayActionMessage(QAction *a)
1622 {
1623     statusBar()->showMessage(a->data().toString(), 3000);
1624 }
1625
1626 void MainWindow::loadLayouts()
1627 {
1628     QMenu *saveLayout = (QMenu*)(factory()->container("layout_save_as", this));
1629     if (m_loadLayout == NULL || saveLayout == NULL) return;
1630     KSharedConfigPtr config = KGlobal::config();
1631     KConfigGroup layoutGroup(config, "Layouts");
1632     QStringList entries = layoutGroup.keyList();
1633     QList<QAction *> loadActions = m_loadLayout->actions();
1634     QList<QAction *> saveActions = saveLayout->actions();
1635     for (int i = 1; i < 5; i++) {
1636         // Rename the layouts actions
1637         foreach(const QString & key, entries) {
1638             if (key.endsWith(QString("_%1").arg(i))) {
1639                 // Found previously saved layout
1640                 QString layoutName = key.section("_", 0, -2);
1641                 for (int j = 0; j < loadActions.count(); j++) {
1642                     if (loadActions.at(j)->data().toString().endsWith("_" + QString::number(i))) {
1643                         loadActions[j]->setText(layoutName);
1644                         loadActions[j]->setData(key);
1645                         break;
1646                     }
1647                 }
1648                 for (int j = 0; j < saveActions.count(); j++) {
1649                     if (saveActions.at(j)->data().toString().endsWith("_" + QString::number(i))) {
1650                         saveActions[j]->setText(i18n("Save as %1").arg(layoutName));
1651                         saveActions[j]->setData(key);
1652                         break;
1653                     }
1654                 }
1655             }
1656         }
1657     }
1658 }
1659
1660 void MainWindow::slotLoadLayout(QAction *action)
1661 {
1662     if (!action) return;
1663     QString layoutId = action->data().toString();
1664     if (layoutId.isEmpty()) return;
1665     KSharedConfigPtr config = KGlobal::config();
1666     KConfigGroup layouts(config, "Layouts");
1667     //QByteArray geom = QByteArray::fromBase64(layouts.readEntry(layoutId).toAscii());
1668     QByteArray state = QByteArray::fromBase64(layouts.readEntry(layoutId).toAscii());
1669     //restoreGeometry(geom);
1670     restoreState(state);
1671 }
1672
1673 void MainWindow::slotSaveLayout(QAction *action)
1674 {
1675     QString originallayoutName = action->data().toString();
1676     int layoutId = originallayoutName.section('_', -1).toInt();
1677
1678     QString layoutName = QInputDialog::getText(this, i18n("Save Layout"), i18n("Layout name:"), QLineEdit::Normal, originallayoutName.section('_', 0, -2));
1679     if (layoutName.isEmpty()) return;
1680     KSharedConfigPtr config = KGlobal::config();
1681     KConfigGroup layouts(config, "Layouts");
1682     layouts.deleteEntry(originallayoutName);
1683
1684     QByteArray st = saveState();
1685     layoutName.append("_" + QString::number(layoutId));
1686     layouts.writeEntry(layoutName, st.toBase64());
1687     loadLayouts();
1688 }
1689
1690 void MainWindow::saveOptions()
1691 {
1692     KdenliveSettings::self()->writeConfig();
1693     KSharedConfigPtr config = KGlobal::config();
1694     m_fileOpenRecent->saveEntries(KConfigGroup(config, "Recent Files"));
1695     KConfigGroup treecolumns(config, "Project Tree");
1696     treecolumns.writeEntry("columns", m_projectList->headerInfo());
1697     config->sync();
1698 }
1699
1700 void MainWindow::readOptions()
1701 {
1702     KSharedConfigPtr config = KGlobal::config();
1703     m_fileOpenRecent->loadEntries(KConfigGroup(config, "Recent Files"));
1704     KConfigGroup initialGroup(config, "version");
1705     bool upgrade = false;
1706     if (initialGroup.exists()) {
1707         if (initialGroup.readEntry("version", QString()).section(' ', 0, 0) != QString(version).section(' ', 0, 0)) {
1708             upgrade = true;
1709         }
1710
1711         if (initialGroup.readEntry("version") == "0.7") {
1712             //Add new settings from 0.7.1
1713             if (KdenliveSettings::defaultprojectfolder().isEmpty()) {
1714                 QString path = QDir::homePath() + "/kdenlive";
1715                 if (KStandardDirs::makeDir(path)  == false) {
1716                     kDebug() << "/// ERROR CREATING PROJECT FOLDER: " << path;
1717                 } else KdenliveSettings::setDefaultprojectfolder(path);
1718             }
1719         }
1720
1721     }
1722
1723     if (!initialGroup.exists() || upgrade) {
1724         // this is our first run, show Wizard
1725         Wizard *w = new Wizard(upgrade, this);
1726         if (w->exec() == QDialog::Accepted && w->isOk()) {
1727             w->adjustSettings();
1728             initialGroup.writeEntry("version", version);
1729             delete w;
1730         } else {
1731             ::exit(1);
1732         }
1733     }
1734     KConfigGroup treecolumns(config, "Project Tree");
1735     const QByteArray state = treecolumns.readEntry("columns", QByteArray());
1736     if (!state.isEmpty())
1737         m_projectList->setHeaderInfo(state);
1738 }
1739
1740 void MainWindow::slotRunWizard()
1741 {
1742     Wizard *w = new Wizard(false, this);
1743     if (w->exec() == QDialog::Accepted && w->isOk()) {
1744         w->adjustSettings();
1745     }
1746     delete w;
1747 }
1748
1749 void MainWindow::newFile(bool showProjectSettings, bool force)
1750 {
1751     if (!m_timelineArea->isEnabled() && !force)
1752         return;
1753     m_fileRevert->setEnabled(false);
1754     QString profileName = KdenliveSettings::default_profile();
1755     KUrl projectFolder = KdenliveSettings::defaultprojectfolder();
1756     QMap <QString, QString> documentProperties;
1757     QPoint projectTracks(KdenliveSettings::videotracks(), KdenliveSettings::audiotracks());
1758     if (!showProjectSettings) {
1759         // set up default properties
1760         documentProperties.insert("enableproxy", QString::number((int) KdenliveSettings::enableproxy()));
1761         documentProperties.insert("generateproxy", QString::number((int) KdenliveSettings::generateproxy()));
1762         documentProperties.insert("proxyminsize", QString::number(KdenliveSettings::proxyminsize()));
1763         documentProperties.insert("proxyparams", KdenliveSettings::proxyparams());
1764         documentProperties.insert("proxyextension", KdenliveSettings::proxyextension());
1765         documentProperties.insert("generateimageproxy", QString::number((int) KdenliveSettings::generateimageproxy()));
1766         documentProperties.insert("proxyimageminsize", QString::number(KdenliveSettings::proxyimageminsize()));
1767         if (!KdenliveSettings::activatetabs())
1768             if (!closeCurrentDocument())
1769                 return;
1770     } else {
1771         ProjectSettings *w = new ProjectSettings(NULL, QStringList(), projectTracks.x(), projectTracks.y(), KdenliveSettings::defaultprojectfolder(), false, true, this);
1772         if (w->exec() != QDialog::Accepted)
1773             return;
1774         if (!KdenliveSettings::activatetabs())
1775             if (!closeCurrentDocument())
1776                 return;
1777         if (KdenliveSettings::videothumbnails() != w->enableVideoThumbs())
1778             slotSwitchVideoThumbs();
1779         if (KdenliveSettings::audiothumbnails() != w->enableAudioThumbs())
1780             slotSwitchAudioThumbs();
1781         profileName = w->selectedProfile();
1782         projectFolder = w->selectedFolder();
1783         projectTracks = w->tracks();
1784         documentProperties.insert("enableproxy", QString::number((int) w->useProxy()));
1785         documentProperties.insert("generateproxy", QString::number((int) w->generateProxy()));
1786         documentProperties.insert("proxyminsize", QString::number(w->proxyMinSize()));
1787         documentProperties.insert("proxyparams", w->proxyParams());
1788         documentProperties.insert("proxyextension", w->proxyExtension());
1789         documentProperties.insert("generateimageproxy", QString::number((int) w->generateImageProxy()));
1790         documentProperties.insert("proxyimageminsize", QString::number(w->proxyImageMinSize()));
1791         delete w;
1792     }
1793     m_timelineArea->setEnabled(true);
1794     m_projectList->setEnabled(true);
1795     
1796     KdenliveDoc *doc = new KdenliveDoc(KUrl(), projectFolder, m_commandStack, profileName, documentProperties, projectTracks, m_projectMonitor->render, m_notesWidget, this);
1797     doc->m_autosave = new KAutoSaveFile(KUrl(), doc);
1798     bool ok;
1799     TrackView *trackView = new TrackView(doc, &ok, this);
1800     m_timelineArea->addTab(trackView, KIcon("kdenlive"), doc->description());
1801     if (!ok) {
1802         // MLT is broken
1803         //m_timelineArea->setEnabled(false);
1804         //m_projectList->setEnabled(false);
1805         slotPreferences(6);
1806         return;
1807     }
1808     if (m_timelineArea->count() == 1) {
1809         connectDocumentInfo(doc);
1810         connectDocument(trackView, doc);
1811     } else
1812         m_timelineArea->setTabBarHidden(false);
1813     m_monitorManager->activateMonitor("clip");
1814     m_closeAction->setEnabled(m_timelineArea->count() > 1);
1815 }
1816
1817 void MainWindow::activateDocument()
1818 {
1819     if (m_timelineArea->currentWidget() == NULL || !m_timelineArea->isEnabled()) return;
1820     TrackView *currentTab = (TrackView *) m_timelineArea->currentWidget();
1821     KdenliveDoc *currentDoc = currentTab->document();
1822     connectDocumentInfo(currentDoc);
1823     connectDocument(currentTab, currentDoc);
1824 }
1825
1826 bool MainWindow::closeCurrentDocument(bool saveChanges)
1827 {
1828     QWidget *w = m_timelineArea->currentWidget();
1829     if (!w) return true;
1830     // closing current document
1831     int ix = m_timelineArea->currentIndex() + 1;
1832     if (ix == m_timelineArea->count()) ix = 0;
1833     m_timelineArea->setCurrentIndex(ix);
1834     TrackView *tabToClose = (TrackView *) w;
1835     KdenliveDoc *docToClose = tabToClose->document();
1836     if (docToClose && docToClose->isModified() && saveChanges) {
1837         QString message;
1838         if (m_activeDocument->url().fileName().isEmpty())
1839             message = i18n("Save changes to document?");
1840         else
1841             message = i18n("The project <b>\"%1\"</b> has been changed.\nDo you want to save your changes?").arg(m_activeDocument->url().fileName());
1842         switch (KMessageBox::warningYesNoCancel(this, message)) {
1843         case KMessageBox::Yes :
1844             // save document here. If saving fails, return false;
1845             if (saveFile() == false) return false;
1846             break;
1847         case KMessageBox::Cancel :
1848             return false;
1849             break;
1850         default:
1851             break;
1852         }
1853     }
1854     m_clipMonitor->slotSetXml(NULL);
1855     m_timelineArea->removeTab(m_timelineArea->indexOf(w));
1856     if (m_timelineArea->count() == 1) {
1857         m_timelineArea->setTabBarHidden(true);
1858         m_closeAction->setEnabled(false);
1859     }
1860     if (docToClose == m_activeDocument) {
1861         delete m_activeDocument;
1862         m_activeDocument = NULL;
1863         m_effectStack->clear();
1864         m_transitionConfig->slotTransitionItemSelected(NULL, 0, QPoint(), false);
1865     } else {
1866         delete docToClose;
1867     }
1868     if (w == m_activeTimeline) {
1869         delete m_activeTimeline;
1870         m_activeTimeline = NULL;
1871     } else {
1872         delete w;
1873     }
1874     return true;
1875 }
1876
1877 bool MainWindow::saveFileAs(const QString &outputFileName)
1878 {
1879     QString currentSceneList;
1880     m_monitorManager->stopActiveMonitor();
1881
1882     if (m_activeDocument->saveSceneList(outputFileName, m_projectMonitor->sceneList(), m_projectList->expandedFolders()) == false)
1883         return false;
1884
1885     // Save timeline thumbnails
1886     m_activeTimeline->projectView()->saveThumbnails();
1887     m_activeDocument->setUrl(KUrl(outputFileName));
1888     if (m_activeDocument->m_autosave == NULL) {
1889         m_activeDocument->m_autosave = new KAutoSaveFile(KUrl(outputFileName), this);
1890     } else m_activeDocument->m_autosave->setManagedFile(KUrl(outputFileName));
1891     setCaption(m_activeDocument->description());
1892     m_timelineArea->setTabText(m_timelineArea->currentIndex(), m_activeDocument->description());
1893     m_timelineArea->setTabToolTip(m_timelineArea->currentIndex(), m_activeDocument->url().path());
1894     m_activeDocument->setModified(false);
1895     m_fileOpenRecent->addUrl(KUrl(outputFileName));
1896     m_fileRevert->setEnabled(true);
1897     return true;
1898 }
1899
1900 bool MainWindow::saveFileAs()
1901 {
1902     QString outputFile = KFileDialog::getSaveFileName(m_activeDocument->projectFolder(), getMimeType());
1903     if (outputFile.isEmpty()) {
1904         return false;
1905     }
1906     if (QFile::exists(outputFile)) {
1907         // Show the file dialog again if the user does not want to overwrite the file
1908         if (KMessageBox::questionYesNo(this, i18n("File %1 already exists.\nDo you want to overwrite it?", outputFile)) == KMessageBox::No)
1909             return saveFileAs();
1910     }
1911     return saveFileAs(outputFile);
1912 }
1913
1914 bool MainWindow::saveFile()
1915 {
1916     if (!m_activeDocument) return true;
1917     if (m_activeDocument->url().isEmpty()) {
1918         return saveFileAs();
1919     } else {
1920         bool result = saveFileAs(m_activeDocument->url().path());
1921         m_activeDocument->m_autosave->resize(0);
1922         return result;
1923     }
1924 }
1925
1926 void MainWindow::openFile()
1927 {
1928     if (!m_startUrl.isEmpty()) {
1929         openFile(m_startUrl);
1930         m_startUrl = KUrl();
1931         return;
1932     }
1933     KUrl url = KFileDialog::getOpenUrl(KUrl("kfiledialog:///projectfolder"), getMimeType());
1934     if (url.isEmpty()) return;
1935     m_fileOpenRecent->addUrl(url);
1936     openFile(url);
1937 }
1938
1939 void MainWindow::openLastFile()
1940 {
1941     KSharedConfigPtr config = KGlobal::config();
1942     KUrl::List urls = m_fileOpenRecent->urls();
1943     //WARNING: this is buggy, we get a random url, not the last one. Bug in KRecentFileAction?
1944     if (urls.isEmpty()) newFile(false);
1945     else openFile(urls.last());
1946 }
1947
1948 void MainWindow::openFile(const KUrl &url)
1949 {
1950     // Check if the document is already opened
1951     const int ct = m_timelineArea->count();
1952     bool isOpened = false;
1953     int i;
1954     for (i = 0; i < ct; i++) {
1955         TrackView *tab = (TrackView *) m_timelineArea->widget(i);
1956         KdenliveDoc *doc = tab->document();
1957         if (doc->url() == url) {
1958             isOpened = true;
1959             break;
1960         }
1961     }
1962     if (isOpened) {
1963         m_timelineArea->setCurrentIndex(i);
1964         return;
1965     }
1966
1967     if (!KdenliveSettings::activatetabs()) if (!closeCurrentDocument()) return;
1968
1969     // Check for backup file
1970     QList<KAutoSaveFile *> staleFiles = KAutoSaveFile::staleFiles(url);
1971     if (!staleFiles.isEmpty()) {
1972         if (KMessageBox::questionYesNo(this,
1973                                        i18n("Auto-saved files exist. Do you want to recover them now?"),
1974                                        i18n("File Recovery"),
1975                                        KGuiItem(i18n("Recover")), KGuiItem(i18n("Don't recover"))) == KMessageBox::Yes) {
1976             recoverFiles(staleFiles);
1977             return;
1978         } else {
1979             // remove the stale files
1980             foreach(KAutoSaveFile * stale, staleFiles) {
1981                 stale->open(QIODevice::ReadWrite);
1982                 delete stale;
1983             }
1984         }
1985     }
1986     m_messageLabel->setMessage(i18n("Opening file %1", url.path()), InformationMessage);
1987     m_messageLabel->repaint();
1988     doOpenFile(url, NULL);
1989 }
1990
1991 void MainWindow::doOpenFile(const KUrl &url, KAutoSaveFile *stale)
1992 {
1993     if (!m_timelineArea->isEnabled()) return;
1994     m_fileRevert->setEnabled(true);
1995
1996     // Recreate stopmotion widget on document change
1997     if (m_stopmotion) {
1998         delete m_stopmotion;
1999         m_stopmotion = NULL;
2000     }
2001
2002     KProgressDialog progressDialog(this, i18n("Loading project"), i18n("Loading project"));
2003     progressDialog.setAllowCancel(false);
2004     progressDialog.progressBar()->setMaximum(4);
2005     progressDialog.show();
2006     progressDialog.progressBar()->setValue(0);
2007     qApp->processEvents();
2008
2009     KdenliveDoc *doc = new KdenliveDoc(url, KdenliveSettings::defaultprojectfolder(), m_commandStack, KdenliveSettings::default_profile(), QMap <QString, QString> (), QPoint(KdenliveSettings::videotracks(), KdenliveSettings::audiotracks()), m_projectMonitor->render, m_notesWidget, this, &progressDialog);
2010
2011     progressDialog.progressBar()->setValue(1);
2012     progressDialog.progressBar()->setMaximum(4);
2013     progressDialog.setLabelText(i18n("Loading project"));
2014     qApp->processEvents();
2015
2016     if (stale == NULL) {
2017         stale = new KAutoSaveFile(url, doc);
2018         doc->m_autosave = stale;
2019     } else {
2020         doc->m_autosave = stale;
2021         doc->setUrl(stale->managedFile());
2022         doc->setModified(true);
2023         stale->setParent(doc);
2024     }
2025     connectDocumentInfo(doc);
2026
2027     progressDialog.progressBar()->setValue(2);
2028     qApp->processEvents();
2029
2030     bool ok;
2031     TrackView *trackView = new TrackView(doc, &ok, this);
2032
2033     progressDialog.progressBar()->setValue(3);
2034     qApp->processEvents();
2035
2036     m_timelineArea->setCurrentIndex(m_timelineArea->addTab(trackView, KIcon("kdenlive"), doc->description()));
2037     if (!ok) {
2038         m_timelineArea->setEnabled(false);
2039         m_projectList->setEnabled(false);
2040         KMessageBox::sorry(this, i18n("Cannot open file %1.\nProject is corrupted.", url.path()));
2041         slotGotProgressInfo(QString(), -1);
2042         newFile(false, true);
2043         return;
2044     }
2045     m_timelineArea->setTabToolTip(m_timelineArea->currentIndex(), doc->url().path());
2046     trackView->setDuration(trackView->duration());
2047     trackView->projectView()->initCursorPos(m_projectMonitor->render->seekPosition().frames(doc->fps()));
2048
2049     if (m_timelineArea->count() > 1) m_timelineArea->setTabBarHidden(false);
2050     slotGotProgressInfo(QString(), -1);
2051     m_projectMonitor->adjustRulerSize(trackView->duration());
2052     m_projectMonitor->slotZoneMoved(trackView->inPoint(), trackView->outPoint());
2053     m_clipMonitor->refreshMonitor(true);
2054
2055     progressDialog.progressBar()->setValue(4);
2056 }
2057
2058 void MainWindow::recoverFiles(QList<KAutoSaveFile *> staleFiles)
2059 {
2060     foreach(KAutoSaveFile * stale, staleFiles) {
2061         /*if (!stale->open(QIODevice::QIODevice::ReadOnly)) {
2062                   // show an error message; we could not steal the lockfile
2063                   // maybe another application got to the file before us?
2064                   delete stale;
2065                   continue;
2066         }*/
2067         kDebug() << "// OPENING RECOVERY: " << stale->fileName() << "\nMANAGED: " << stale->managedFile().path();
2068         // the stalefiles also contain ".lock" files so we must ignore them... bug in KAutoSaveFile?
2069         if (!stale->fileName().endsWith(".lock")) doOpenFile(KUrl(stale->fileName()), stale);
2070         else KIO::NetAccess::del(KUrl(stale->fileName()), this);
2071     }
2072 }
2073
2074 void MainWindow::parseProfiles(const QString &mltPath)
2075 {
2076     //KdenliveSettings::setDefaulttmpfolder();
2077     if (!mltPath.isEmpty()) {
2078         KdenliveSettings::setMltpath(mltPath + "/share/mlt/profiles/");
2079         KdenliveSettings::setRendererpath(mltPath + "/bin/melt");
2080     }
2081
2082     if (KdenliveSettings::mltpath().isEmpty())
2083         KdenliveSettings::setMltpath(QString(MLT_PREFIX) + QString("/share/mlt/profiles/"));
2084
2085     if (KdenliveSettings::rendererpath().isEmpty() || KdenliveSettings::rendererpath().endsWith("inigo")) {
2086         QString meltPath = QString(MLT_PREFIX) + QString("/bin/melt");
2087         if (!QFile::exists(meltPath))
2088             meltPath = KStandardDirs::findExe("melt");
2089         KdenliveSettings::setRendererpath(meltPath);
2090     }
2091
2092     if (KdenliveSettings::rendererpath().isEmpty()) {
2093         // Cannot find the MLT melt renderer, ask for location
2094         KUrlRequesterDialog *getUrl = new KUrlRequesterDialog(QString(), i18n("Cannot find the melt program required for rendering (part of MLT)"), this);
2095         if (getUrl->exec() == QDialog::Rejected) {
2096             ::exit(0);
2097         }
2098         KUrl rendererPath = getUrl->selectedUrl();
2099         delete getUrl;
2100         if (rendererPath.isEmpty()) ::exit(0);
2101         KdenliveSettings::setRendererpath(rendererPath.path());
2102     }
2103
2104     QStringList profilesFilter;
2105     profilesFilter << "*";
2106     QStringList profilesList = QDir(KdenliveSettings::mltpath()).entryList(profilesFilter, QDir::Files);
2107     if (profilesList.isEmpty()) {
2108         // Cannot find MLT path, try finding melt
2109         QString profilePath = KdenliveSettings::rendererpath();
2110         if (!profilePath.isEmpty()) {
2111             profilePath = profilePath.section('/', 0, -3);
2112             KdenliveSettings::setMltpath(profilePath + "/share/mlt/profiles/");
2113             profilesList = QDir(KdenliveSettings::mltpath()).entryList(profilesFilter, QDir::Files);
2114         }
2115         if (profilesList.isEmpty()) {
2116             // Cannot find the MLT profiles, ask for location
2117             KUrlRequesterDialog *getUrl = new KUrlRequesterDialog(KdenliveSettings::mltpath(), i18n("Cannot find your MLT profiles, please give the path"), this);
2118             getUrl->fileDialog()->setMode(KFile::Directory);
2119             if (getUrl->exec() == QDialog::Rejected) {
2120                 ::exit(0);
2121             }
2122             KUrl mltPath = getUrl->selectedUrl();
2123             delete getUrl;
2124             if (mltPath.isEmpty()) ::exit(0);
2125             KdenliveSettings::setMltpath(mltPath.path(KUrl::AddTrailingSlash));
2126             profilesList = QDir(KdenliveSettings::mltpath()).entryList(profilesFilter, QDir::Files);
2127         }
2128     }
2129
2130     kDebug() << "RESULTING MLT PATH: " << KdenliveSettings::mltpath();
2131
2132     // Parse again MLT profiles to build a list of available video formats
2133     if (profilesList.isEmpty()) parseProfiles();
2134 }
2135
2136
2137 void MainWindow::slotEditProfiles()
2138 {
2139     ProfilesDialog *w = new ProfilesDialog;
2140     if (w->exec() == QDialog::Accepted) {
2141         KdenliveSettingsDialog* d = static_cast <KdenliveSettingsDialog*>(KConfigDialog::exists("settings"));
2142         if (d) d->checkProfile();
2143     }
2144     delete w;
2145 }
2146
2147 void MainWindow::slotDetectAudioDriver()
2148 {
2149     /* WARNING: do not use this method because sometimes detects wrong driver (pulse instead of alsa),
2150     leading to no audio output, see bug #934 */
2151
2152     //decide which audio driver is really best, in some cases SDL is wrong
2153     if (KdenliveSettings::audiodrivername().isEmpty()) {
2154         QString driver;
2155         KProcess readProcess;
2156         //PulseAudio needs to be selected if it exists, the ALSA pulse pcm device is not fast enough.
2157         if (!KStandardDirs::findExe("pactl").isEmpty()) {
2158             readProcess.setOutputChannelMode(KProcess::OnlyStdoutChannel);
2159             readProcess.setProgram("pactl", QStringList() << "stat");
2160             readProcess.execute(2000); // Kill it after 2 seconds
2161
2162             QString result = QString(readProcess.readAllStandardOutput());
2163             kDebug() << "// / / / / / READING PACTL: ";
2164             kDebug() << result;
2165             if (!result.isEmpty()) {
2166                 driver = "pulse";
2167                 kDebug() << "// / / / / PULSEAUDIO DETECTED";
2168             }
2169         }
2170         //put others here
2171         KdenliveSettings::setAutoaudiodrivername(driver);
2172     }
2173 }
2174
2175 void MainWindow::slotEditProjectSettings()
2176 {
2177     QPoint p = m_activeDocument->getTracksCount();
2178     ProjectSettings *w = new ProjectSettings(m_projectList, m_activeTimeline->projectView()->extractTransitionsLumas(), p.x(), p.y(), m_activeDocument->projectFolder().path(), true, !m_activeDocument->isModified(), this);
2179
2180     if (w->exec() == QDialog::Accepted) {
2181         QString profile = w->selectedProfile();
2182         m_activeDocument->setProjectFolder(w->selectedFolder());
2183 #ifndef   Q_WS_MAC
2184         m_recMonitor->slotUpdateCaptureFolder(m_activeDocument->projectFolder().path(KUrl::AddTrailingSlash));
2185 #endif
2186         if (m_renderWidget) m_renderWidget->setDocumentPath(m_activeDocument->projectFolder().path(KUrl::AddTrailingSlash));
2187         if (KdenliveSettings::videothumbnails() != w->enableVideoThumbs()) slotSwitchVideoThumbs();
2188         if (KdenliveSettings::audiothumbnails() != w->enableAudioThumbs()) slotSwitchAudioThumbs();
2189         if (m_activeDocument->profilePath() != profile) slotUpdateProjectProfile(profile);
2190         if (m_activeDocument->getDocumentProperty("proxyparams") != w->proxyParams()) {
2191             m_activeDocument->setModified();
2192             m_activeDocument->setDocumentProperty("proxyparams", w->proxyParams());
2193             if (m_activeDocument->clipManager()->clipsCount() > 0 && KMessageBox::questionYesNo(this, i18n("You have changed the proxy parameters. Do you want to recreate all proxy clips for this project?")) == KMessageBox::Yes) {
2194                 //TODO: rebuild all proxies
2195                 //m_activeDocument->rebuildAllProxies();
2196             }
2197         }
2198         if (m_activeDocument->getDocumentProperty("proxyextension") != w->proxyExtension()) {
2199             m_activeDocument->setModified();
2200             m_activeDocument->setDocumentProperty("proxyextension", w->proxyExtension());
2201         }
2202         if (m_activeDocument->getDocumentProperty("generateproxy") != QString::number((int) w->generateProxy())) {
2203             m_activeDocument->setModified();
2204             m_activeDocument->setDocumentProperty("generateproxy", QString::number((int) w->generateProxy()));
2205         }
2206         if (m_activeDocument->getDocumentProperty("proxyminsize") != QString::number(w->proxyMinSize())) {
2207             m_activeDocument->setModified();
2208             m_activeDocument->setDocumentProperty("proxyminsize", QString::number(w->proxyMinSize()));
2209         }
2210         if (m_activeDocument->getDocumentProperty("generateimageproxy") != QString::number((int) w->generateImageProxy())) {
2211             m_activeDocument->setModified();
2212             m_activeDocument->setDocumentProperty("generateimageproxy", QString::number((int) w->generateImageProxy()));
2213         }
2214         if (m_activeDocument->getDocumentProperty("proxyimageminsize") != QString::number(w->proxyImageMinSize())) {
2215             m_activeDocument->setModified();
2216             m_activeDocument->setDocumentProperty("proxyimageminsize", QString::number(w->proxyImageMinSize()));
2217         }
2218         if (QString::number((int) w->useProxy()) != m_activeDocument->getDocumentProperty("enableproxy")) {
2219             m_activeDocument->setDocumentProperty("enableproxy", QString::number((int) w->useProxy()));
2220             m_activeDocument->setModified();
2221             slotUpdateProxySettings();
2222         }
2223     }
2224     delete w;
2225 }
2226
2227 void MainWindow::slotUpdateProjectProfile(const QString &profile)
2228 {
2229     double dar = m_activeDocument->dar();
2230
2231     // Recreate the stopmotion widget if profile changes
2232     if (m_stopmotion) {
2233         delete m_stopmotion;
2234         m_stopmotion = NULL;
2235     }
2236
2237     // Deselect current effect / transition
2238     m_effectStack->slotClipItemSelected(NULL, 0);
2239     m_transitionConfig->slotTransitionItemSelected(NULL, 0, QPoint(), false);
2240     m_clipMonitor->slotSetXml(NULL);
2241     bool updateFps = m_activeDocument->setProfilePath(profile);
2242     KdenliveSettings::setCurrent_profile(profile);
2243     KdenliveSettings::setProject_fps(m_activeDocument->fps());
2244     setCaption(m_activeDocument->description(), m_activeDocument->isModified());
2245
2246     m_activeDocument->clipManager()->clearUnusedProducers();
2247     m_monitorManager->resetProfiles(m_activeDocument->timecode());
2248     m_transitionConfig->updateProjectFormat(m_activeDocument->mltProfile(), m_activeDocument->timecode(), m_activeDocument->tracksList());
2249     m_effectStack->updateProjectFormat(m_activeDocument->mltProfile(), m_activeDocument->timecode());
2250     m_projectList->updateProjectFormat(m_activeDocument->timecode());
2251     if (m_renderWidget) m_renderWidget->setProfile(m_activeDocument->mltProfile());
2252     m_timelineArea->setTabText(m_timelineArea->currentIndex(), m_activeDocument->description());
2253     //m_activeDocument->clipManager()->resetProducersList(m_projectMonitor->render->producersList());
2254     if (dar != m_activeDocument->dar()) m_projectList->reloadClipThumbnails();
2255     if (updateFps) m_activeTimeline->updateProjectFps();
2256     m_activeDocument->setModified(true);
2257     m_commandStack->activeStack()->clear();
2258     //Update the mouse position display so it will display in DF/NDF format by default based on the project setting.
2259     slotUpdateMousePosition(0);
2260     // We need to desactivate & reactivate monitors to get a refresh
2261     //m_monitorManager->switchMonitors();
2262 }
2263
2264
2265 void MainWindow::slotRenderProject()
2266 {
2267     if (!m_renderWidget) {
2268         QString projectfolder = m_activeDocument ? m_activeDocument->projectFolder().path(KUrl::AddTrailingSlash) : KdenliveSettings::defaultprojectfolder();
2269         m_renderWidget = new RenderWidget(projectfolder, m_projectList->useProxy(), this);
2270         connect(m_renderWidget, SIGNAL(shutdown()), this, SLOT(slotShutdown()));
2271         connect(m_renderWidget, SIGNAL(selectedRenderProfile(QMap <QString, QString>)), this, SLOT(slotSetDocumentRenderProfile(QMap <QString, QString>)));
2272         connect(m_renderWidget, SIGNAL(prepareRenderingData(bool, bool, const QString&)), this, SLOT(slotPrepareRendering(bool, bool, const QString&)));
2273         connect(m_renderWidget, SIGNAL(abortProcess(const QString &)), this, SIGNAL(abortRenderJob(const QString &)));
2274         connect(m_renderWidget, SIGNAL(openDvdWizard(const QString &, const QString &)), this, SLOT(slotDvdWizard(const QString &, const QString &)));
2275         if (m_activeDocument) {
2276             m_renderWidget->setProfile(m_activeDocument->mltProfile());
2277             m_renderWidget->setGuides(m_activeDocument->guidesXml(), m_activeDocument->projectDuration());
2278             m_renderWidget->setDocumentPath(m_activeDocument->projectFolder().path(KUrl::AddTrailingSlash));
2279             m_renderWidget->setRenderProfile(m_activeDocument->getRenderProperties());
2280         }
2281     }
2282     slotCheckRenderStatus();
2283     m_renderWidget->show();
2284     m_renderWidget->showNormal();
2285
2286     // What are the following lines supposed to do?
2287     //m_activeTimeline->tracksNumber();
2288     //m_renderWidget->enableAudio(false);
2289     //m_renderWidget->export_audio;
2290 }
2291
2292 void MainWindow::slotCheckRenderStatus()
2293 {
2294     // Make sure there are no missing clips
2295     if (m_renderWidget)
2296         m_renderWidget->missingClips(m_projectList->hasMissingClips());
2297 }
2298
2299 void MainWindow::setRenderingProgress(const QString &url, int progress)
2300 {
2301     if (m_renderWidget)
2302         m_renderWidget->setRenderJob(url, progress);
2303 }
2304
2305 void MainWindow::setRenderingFinished(const QString &url, int status, const QString &error)
2306 {
2307     if (m_renderWidget)
2308         m_renderWidget->setRenderStatus(url, status, error);
2309 }
2310
2311 void MainWindow::slotCleanProject()
2312 {
2313     if (KMessageBox::warningContinueCancel(this, i18n("This will remove all unused clips from your project."), i18n("Clean up project")) == KMessageBox::Cancel) return;
2314     m_projectList->cleanup();
2315 }
2316
2317 void MainWindow::slotUpdateMousePosition(int pos)
2318 {
2319     if (m_activeDocument)
2320         switch (m_timecodeFormat->currentIndex()) {
2321         case 0:
2322             statusBar()->changeItem(m_activeDocument->timecode().getTimecodeFromFrames(pos), ID_TIMELINE_POS);
2323             break;
2324         default:
2325             statusBar()->changeItem(QString::number(pos), ID_TIMELINE_POS);
2326         }
2327 }
2328
2329 void MainWindow::slotUpdateDocumentState(bool modified)
2330 {
2331     if (!m_activeDocument) return;
2332     setCaption(m_activeDocument->description(), modified);
2333     m_saveAction->setEnabled(modified);
2334     if (modified) {
2335         m_timelineArea->setTabTextColor(m_timelineArea->currentIndex(), palette().color(QPalette::Link));
2336         m_timelineArea->setTabIcon(m_timelineArea->currentIndex(), KIcon("document-save"));
2337     } else {
2338         m_timelineArea->setTabTextColor(m_timelineArea->currentIndex(), palette().color(QPalette::Text));
2339         m_timelineArea->setTabIcon(m_timelineArea->currentIndex(), KIcon("kdenlive"));
2340     }
2341 }
2342
2343 void MainWindow::connectDocumentInfo(KdenliveDoc *doc)
2344 {
2345     if (m_activeDocument) {
2346         if (m_activeDocument == doc) return;
2347         disconnect(m_activeDocument, SIGNAL(progressInfo(const QString &, int)), this, SLOT(slotGotProgressInfo(const QString &, int)));
2348     }
2349     connect(doc, SIGNAL(progressInfo(const QString &, int)), this, SLOT(slotGotProgressInfo(const QString &, int)));
2350 }
2351
2352 void MainWindow::connectDocument(TrackView *trackView, KdenliveDoc *doc)   //changed
2353 {
2354     //m_projectMonitor->stop();
2355     m_closeAction->setEnabled(m_timelineArea->count() > 1);
2356     kDebug() << "///////////////////   CONNECTING DOC TO PROJECT VIEW ////////////////";
2357     if (m_activeDocument) {
2358         if (m_activeDocument == doc) return;
2359         if (m_activeTimeline) {
2360             disconnect(m_projectMonitor, SIGNAL(renderPosition(int)), m_activeTimeline, SLOT(moveCursorPos(int)));
2361             disconnect(m_projectMonitor, SIGNAL(zoneUpdated(QPoint)), m_activeTimeline, SLOT(slotSetZone(QPoint)));
2362             disconnect(m_projectMonitor, SIGNAL(durationChanged(int)), m_activeTimeline, SLOT(setDuration(int)));
2363             disconnect(m_projectMonitor, SIGNAL(zoneUpdated(QPoint)), m_activeDocument, SLOT(setModified()));
2364             disconnect(m_notesWidget, SIGNAL(textChanged()), m_activeDocument, SLOT(setModified()));
2365             disconnect(m_clipMonitor, SIGNAL(zoneUpdated(QPoint)), m_activeDocument, SLOT(setModified()));
2366             disconnect(m_projectList, SIGNAL(projectModified()), m_activeDocument, SLOT(setModified()));
2367             disconnect(m_projectList, SIGNAL(updateProfile(const QString &)), this, SLOT(slotUpdateProjectProfile(const QString &)));
2368
2369             disconnect(m_projectMonitor->render, SIGNAL(refreshDocumentProducers()), m_activeDocument, SLOT(checkProjectClips()));
2370
2371             disconnect(m_activeDocument, SIGNAL(guidesUpdated()), this, SLOT(slotGuidesUpdated()));
2372             disconnect(m_activeDocument, SIGNAL(addProjectClip(DocClipBase *, bool)), m_projectList, SLOT(slotAddClip(DocClipBase *, bool)));
2373             disconnect(m_activeDocument, SIGNAL(resetProjectList()), m_projectList, SLOT(slotResetProjectList()));
2374             disconnect(m_activeDocument, SIGNAL(signalDeleteProjectClip(const QString &)), this, SLOT(slotDeleteClip(const QString &)));
2375             disconnect(m_activeDocument, SIGNAL(updateClipDisplay(const QString &)), m_projectList, SLOT(slotUpdateClip(const QString &)));
2376             disconnect(m_activeDocument, SIGNAL(selectLastAddedClip(const QString &)), m_projectList, SLOT(slotSelectClip(const QString &)));
2377             disconnect(m_activeDocument, SIGNAL(deleteTimelineClip(const QString &)), m_activeTimeline, SLOT(slotDeleteClip(const QString &)));
2378             disconnect(m_activeTimeline->projectView(), SIGNAL(clipItemSelected(ClipItem*, int)), m_effectStack, SLOT(slotClipItemSelected(ClipItem*, int)));
2379             disconnect(m_activeTimeline->projectView(), SIGNAL(clipItemSelected(ClipItem*, int)), this, SLOT(slotActivateEffectStackView()));
2380             disconnect(m_activeTimeline->projectView(), SIGNAL(clipItemSelected(ClipItem*, int)), m_projectMonitor, SLOT(slotSetSelectedClip(ClipItem*)));
2381             disconnect(m_activeTimeline->projectView(), SIGNAL(transitionItemSelected(Transition*, int, QPoint, bool)), m_transitionConfig, SLOT(slotTransitionItemSelected(Transition*, int, QPoint, bool)));
2382             disconnect(m_activeTimeline->projectView(), SIGNAL(transitionItemSelected(Transition*, int, QPoint, bool)), this, SLOT(slotActivateTransitionView(Transition *)));
2383             disconnect(m_activeTimeline->projectView(), SIGNAL(transitionItemSelected(Transition*, int, QPoint, bool)), m_projectMonitor, SLOT(slotSetSelectedClip(Transition*)));
2384             disconnect(m_activeTimeline->projectView(), SIGNAL(playMonitor()), m_projectMonitor, SLOT(slotPlay()));
2385             disconnect(m_activeTimeline->projectView(), SIGNAL(displayMessage(const QString&, MessageType)), m_messageLabel, SLOT(setMessage(const QString&, MessageType)));
2386             disconnect(m_activeTimeline->projectView(), SIGNAL(showClipFrame(DocClipBase *, QPoint, const int)), m_clipMonitor, SLOT(slotSetXml(DocClipBase *, QPoint, const int)));
2387             disconnect(m_activeTimeline, SIGNAL(cursorMoved()), m_projectMonitor, SLOT(activateMonitor()));
2388             disconnect(m_activeTimeline, SIGNAL(insertTrack(int)), this, SLOT(slotInsertTrack(int)));
2389             disconnect(m_activeTimeline, SIGNAL(deleteTrack(int)), this, SLOT(slotDeleteTrack(int)));
2390             disconnect(m_activeTimeline, SIGNAL(configTrack(int)), this, SLOT(slotConfigTrack(int)));
2391             disconnect(m_activeDocument, SIGNAL(docModified(bool)), this, SLOT(slotUpdateDocumentState(bool)));
2392             disconnect(m_effectStack, SIGNAL(updateEffect(ClipItem*, int, QDomElement, QDomElement, int)), m_activeTimeline->projectView(), SLOT(slotUpdateClipEffect(ClipItem*, int, QDomElement, QDomElement, int)));
2393             disconnect(m_effectStack, SIGNAL(removeEffect(ClipItem*, int, QDomElement)), m_activeTimeline->projectView(), SLOT(slotDeleteEffect(ClipItem*, int, QDomElement)));
2394             disconnect(m_effectStack, SIGNAL(changeEffectState(ClipItem*, int, int, bool)), m_activeTimeline->projectView(), SLOT(slotChangeEffectState(ClipItem*, int, int, bool)));
2395             disconnect(m_effectStack, SIGNAL(changeEffectPosition(ClipItem*, int, int, int)), m_activeTimeline->projectView(), SLOT(slotChangeEffectPosition(ClipItem*, int, int, int)));
2396             disconnect(m_effectStack, SIGNAL(refreshEffectStack(ClipItem*)), m_activeTimeline->projectView(), SLOT(slotRefreshEffects(ClipItem*)));
2397             disconnect(m_effectStack, SIGNAL(reloadEffects()), this, SLOT(slotReloadEffects()));
2398             disconnect(m_effectStack, SIGNAL(displayMessage(const QString&, int)), this, SLOT(slotGotProgressInfo(const QString&, int)));
2399             disconnect(m_transitionConfig, SIGNAL(transitionUpdated(Transition *, QDomElement)), m_activeTimeline->projectView() , SLOT(slotTransitionUpdated(Transition *, QDomElement)));
2400             disconnect(m_transitionConfig, SIGNAL(seekTimeline(int)), m_activeTimeline->projectView() , SLOT(setCursorPos(int)));
2401             disconnect(m_activeTimeline->projectView(), SIGNAL(activateDocumentMonitor()), m_projectMonitor, SLOT(activateMonitor()));
2402             disconnect(m_activeTimeline, SIGNAL(zoneMoved(int, int)), this, SLOT(slotZoneMoved(int, int)));
2403             disconnect(m_projectList, SIGNAL(loadingIsOver()), m_activeTimeline->projectView(), SLOT(slotUpdateAllThumbs()));
2404             disconnect(m_projectList, SIGNAL(displayMessage(const QString&, int)), this, SLOT(slotGotProgressInfo(const QString&, int)));
2405             disconnect(m_projectList, SIGNAL(updateRenderStatus()), this, SLOT(slotCheckRenderStatus()));
2406             disconnect(m_projectList, SIGNAL(clipNeedsReload(const QString&, bool)), m_activeTimeline->projectView(), SLOT(slotUpdateClip(const QString &, bool)));
2407             disconnect(m_projectList, SIGNAL(refreshClip(const QString &)), m_activeTimeline->projectView(), SLOT(slotRefreshThumbs(const QString &)));
2408             m_effectStack->clear();
2409         }
2410         //m_activeDocument->setRenderer(NULL);
2411         disconnect(m_projectList, SIGNAL(clipSelected(DocClipBase *)), m_clipMonitor, SLOT(slotSetXml(DocClipBase *)));
2412         disconnect(m_projectList, SIGNAL(refreshClip(const QString &, bool)), m_monitorManager, SLOT(slotRefreshCurrentMonitor()));
2413         m_clipMonitor->stop();
2414     }
2415     KdenliveSettings::setCurrent_profile(doc->profilePath());
2416     KdenliveSettings::setProject_fps(doc->fps());
2417     m_monitorManager->resetProfiles(doc->timecode());
2418     m_projectList->setDocument(doc);
2419     m_transitionConfig->updateProjectFormat(doc->mltProfile(), doc->timecode(), doc->tracksList());
2420     m_effectStack->updateProjectFormat(doc->mltProfile(), doc->timecode());
2421     connect(m_projectList, SIGNAL(clipSelected(DocClipBase *, QPoint)), m_clipMonitor, SLOT(slotSetXml(DocClipBase *, QPoint)));
2422     connect(m_projectList, SIGNAL(refreshClip(const QString &, bool)), m_monitorManager, SLOT(slotRefreshCurrentMonitor()));
2423     connect(m_projectList, SIGNAL(refreshClip(const QString &, bool)), trackView->projectView(), SLOT(slotRefreshThumbs(const QString &, bool)));
2424     connect(m_projectList, SIGNAL(clipNeedsReload(const QString&, bool)), trackView->projectView(), SLOT(slotUpdateClip(const QString &, bool)));
2425
2426     connect(m_projectList, SIGNAL(projectModified()), doc, SLOT(setModified()));
2427     connect(m_projectList, SIGNAL(updateProfile(const QString &)), this, SLOT(slotUpdateProjectProfile(const QString &)));
2428     connect(m_projectList, SIGNAL(clipNameChanged(const QString, const QString)), trackView->projectView(), SLOT(clipNameChanged(const QString, const QString)));
2429
2430     connect(m_projectList, SIGNAL(findInTimeline(const QString&)), this, SLOT(slotClipInTimeline(const QString&)));
2431
2432
2433     connect(trackView, SIGNAL(cursorMoved()), m_projectMonitor, SLOT(activateMonitor()));
2434     connect(trackView, SIGNAL(insertTrack(int)), this, SLOT(slotInsertTrack(int)));
2435     connect(trackView, SIGNAL(deleteTrack(int)), this, SLOT(slotDeleteTrack(int)));
2436     connect(trackView, SIGNAL(configTrack(int)), this, SLOT(slotConfigTrack(int)));
2437     connect(trackView, SIGNAL(updateTracksInfo()), this, SLOT(slotUpdateTrackInfo()));
2438     connect(trackView, SIGNAL(mousePosition(int)), this, SLOT(slotUpdateMousePosition(int)));
2439     connect(trackView->projectView(), SIGNAL(forceClipProcessing(const QString &)), m_projectList, SLOT(slotForceProcessing(const QString &)));
2440     connect(m_projectMonitor, SIGNAL(renderPosition(int)), trackView, SLOT(moveCursorPos(int)));
2441     connect(m_projectMonitor, SIGNAL(zoneUpdated(QPoint)), trackView, SLOT(slotSetZone(QPoint)));
2442     connect(m_clipMonitor, SIGNAL(zoneUpdated(QPoint)), m_projectList, SLOT(slotUpdateClipCut(QPoint)));
2443     connect(m_projectMonitor, SIGNAL(zoneUpdated(QPoint)), doc, SLOT(setModified()));
2444     connect(m_clipMonitor, SIGNAL(zoneUpdated(QPoint)), doc, SLOT(setModified()));
2445     connect(m_projectMonitor, SIGNAL(durationChanged(int)), trackView, SLOT(setDuration(int)));
2446     connect(m_projectMonitor->render, SIGNAL(refreshDocumentProducers()), doc, SLOT(checkProjectClips()));
2447
2448     connect(doc, SIGNAL(addProjectClip(DocClipBase *, bool)), m_projectList, SLOT(slotAddClip(DocClipBase *, bool)));
2449     connect(doc, SIGNAL(resetProjectList()), m_projectList, SLOT(slotResetProjectList()));
2450     connect(doc, SIGNAL(signalDeleteProjectClip(const QString &)), this, SLOT(slotDeleteClip(const QString &)));
2451     connect(doc, SIGNAL(updateClipDisplay(const QString &)), m_projectList, SLOT(slotUpdateClip(const QString &)));
2452     connect(doc, SIGNAL(selectLastAddedClip(const QString &)), m_projectList, SLOT(slotSelectClip(const QString &)));
2453
2454     connect(doc, SIGNAL(deleteTimelineClip(const QString &)), trackView, SLOT(slotDeleteClip(const QString &)));
2455     connect(doc, SIGNAL(docModified(bool)), this, SLOT(slotUpdateDocumentState(bool)));
2456     connect(doc, SIGNAL(guidesUpdated()), this, SLOT(slotGuidesUpdated()));
2457     connect(m_notesWidget, SIGNAL(textChanged()), doc, SLOT(setModified()));
2458
2459     connect(trackView->projectView(), SIGNAL(clipItemSelected(ClipItem*, int)), m_effectStack, SLOT(slotClipItemSelected(ClipItem*, int)));
2460     connect(trackView->projectView(), SIGNAL(updateClipMarkers(DocClipBase *)), this, SLOT(slotUpdateClipMarkers(DocClipBase*)));
2461     connect(trackView, SIGNAL(showTrackEffects(int, TrackInfo)), m_effectStack, SLOT(slotTrackItemSelected(int, TrackInfo)));
2462     connect(trackView, SIGNAL(showTrackEffects(int, TrackInfo)), this, SLOT(slotActivateEffectStackView()));
2463
2464     connect(trackView->projectView(), SIGNAL(clipItemSelected(ClipItem*, int)), this, SLOT(slotActivateEffectStackView()));
2465     connect(trackView->projectView(), SIGNAL(transitionItemSelected(Transition*, int, QPoint, bool)), m_transitionConfig, SLOT(slotTransitionItemSelected(Transition*, int, QPoint, bool)));
2466     connect(trackView->projectView(), SIGNAL(transitionItemSelected(Transition*, int, QPoint, bool)), this, SLOT(slotActivateTransitionView(Transition *)));
2467     m_zoomSlider->setValue(doc->zoom().x());
2468     connect(trackView->projectView(), SIGNAL(zoomIn()), this, SLOT(slotZoomIn()));
2469     connect(trackView->projectView(), SIGNAL(zoomOut()), this, SLOT(slotZoomOut()));
2470     connect(trackView, SIGNAL(setZoom(int)), this, SLOT(slotSetZoom(int)));
2471     connect(trackView->projectView(), SIGNAL(displayMessage(const QString&, MessageType)), m_messageLabel, SLOT(setMessage(const QString&, MessageType)));
2472
2473     connect(trackView->projectView(), SIGNAL(showClipFrame(DocClipBase *, QPoint, const int)), m_clipMonitor, SLOT(slotSetXml(DocClipBase *, QPoint, const int)));
2474     connect(trackView->projectView(), SIGNAL(playMonitor()), m_projectMonitor, SLOT(slotPlay()));
2475
2476     connect(trackView->projectView(), SIGNAL(clipItemSelected(ClipItem*, int)), m_projectMonitor, SLOT(slotSetSelectedClip(ClipItem*)));
2477     connect(trackView->projectView(), SIGNAL(transitionItemSelected(Transition*, int, QPoint, bool)), m_projectMonitor, SLOT(slotSetSelectedClip(Transition*)));
2478
2479     connect(m_effectStack, SIGNAL(updateEffect(ClipItem*, int, QDomElement, QDomElement, int)), trackView->projectView(), SLOT(slotUpdateClipEffect(ClipItem*, int, QDomElement, QDomElement, int)));
2480     connect(m_effectStack, SIGNAL(updateClipRegion(ClipItem*, int, QString)), trackView->projectView(), SLOT(slotUpdateClipRegion(ClipItem*, int, QString)));
2481     connect(m_effectStack, SIGNAL(removeEffect(ClipItem*, int, QDomElement)), trackView->projectView(), SLOT(slotDeleteEffect(ClipItem*, int, QDomElement)));
2482     connect(m_effectStack, SIGNAL(changeEffectState(ClipItem*, int, int, bool)), trackView->projectView(), SLOT(slotChangeEffectState(ClipItem*, int, int, bool)));
2483     connect(m_effectStack, SIGNAL(changeEffectPosition(ClipItem*, int, int, int)), trackView->projectView(), SLOT(slotChangeEffectPosition(ClipItem*, int, int, int)));
2484     connect(m_effectStack, SIGNAL(refreshEffectStack(ClipItem*)), trackView->projectView(), SLOT(slotRefreshEffects(ClipItem*)));
2485     connect(m_transitionConfig, SIGNAL(transitionUpdated(Transition *, QDomElement)), trackView->projectView() , SLOT(slotTransitionUpdated(Transition *, QDomElement)));
2486     connect(m_transitionConfig, SIGNAL(seekTimeline(int)), trackView->projectView() , SLOT(setCursorPos(int)));
2487     connect(m_effectStack, SIGNAL(seekTimeline(int)), trackView->projectView() , SLOT(setCursorPos(int)));
2488     connect(m_effectStack, SIGNAL(reloadEffects()), this, SLOT(slotReloadEffects()));
2489     connect(m_effectStack, SIGNAL(displayMessage(const QString&, int)), this, SLOT(slotGotProgressInfo(const QString&, int)));
2490
2491     connect(trackView->projectView(), SIGNAL(activateDocumentMonitor()), m_projectMonitor, SLOT(activateMonitor()));
2492     connect(trackView, SIGNAL(zoneMoved(int, int)), this, SLOT(slotZoneMoved(int, int)));
2493     connect(m_projectList, SIGNAL(loadingIsOver()), trackView->projectView(), SLOT(slotUpdateAllThumbs()));
2494     connect(m_projectList, SIGNAL(displayMessage(const QString&, int)), this, SLOT(slotGotProgressInfo(const QString&, int)));
2495     connect(m_projectList, SIGNAL(updateRenderStatus()), this, SLOT(slotCheckRenderStatus()));
2496
2497
2498     trackView->projectView()->setContextMenu(m_timelineContextMenu, m_timelineContextClipMenu, m_timelineContextTransitionMenu, m_clipTypeGroup, (QMenu*)(factory()->container("marker_menu", this)));
2499     m_activeTimeline = trackView;
2500     if (m_renderWidget) {
2501         slotCheckRenderStatus();
2502         m_renderWidget->setProfile(doc->mltProfile());
2503         m_renderWidget->setGuides(doc->guidesXml(), doc->projectDuration());
2504         m_renderWidget->setDocumentPath(doc->projectFolder().path(KUrl::AddTrailingSlash));
2505         m_renderWidget->setRenderProfile(doc->getRenderProperties());
2506     }
2507     //doc->setRenderer(m_projectMonitor->render);
2508     m_commandStack->setActiveStack(doc->commandStack());
2509     KdenliveSettings::setProject_display_ratio(doc->dar());
2510     //doc->clipManager()->checkAudioThumbs();
2511
2512     //m_overView->setScene(trackView->projectScene());
2513     //m_overView->scale(m_overView->width() / trackView->duration(), m_overView->height() / (50 * trackView->tracksNumber()));
2514     //m_overView->fitInView(m_overView->itemAt(0, 50), Qt::KeepAspectRatio);
2515
2516     setCaption(doc->description(), doc->isModified());
2517     m_saveAction->setEnabled(doc->isModified());
2518     m_normalEditTool->setChecked(true);
2519     m_activeDocument = doc;
2520     m_activeTimeline->updateProjectFps();
2521     m_activeDocument->checkProjectClips();
2522 #ifndef   Q_WS_MAC
2523     m_recMonitor->slotUpdateCaptureFolder(m_activeDocument->projectFolder().path(KUrl::AddTrailingSlash));
2524 #endif
2525     //Update the mouse position display so it will display in DF/NDF format by default based on the project setting.
2526     slotUpdateMousePosition(0);
2527     // set tool to select tool
2528     m_buttonSelectTool->setChecked(true);
2529 }
2530
2531 void MainWindow::slotZoneMoved(int start, int end)
2532 {
2533     m_activeDocument->setZone(start, end);
2534     m_projectMonitor->slotZoneMoved(start, end);
2535 }
2536
2537 void MainWindow::slotGuidesUpdated()
2538 {
2539     if (m_renderWidget)
2540         m_renderWidget->setGuides(m_activeDocument->guidesXml(), m_activeDocument->projectDuration());
2541 }
2542
2543 void MainWindow::slotEditKeys()
2544 {
2545     KShortcutsDialog dialog(KShortcutsEditor::AllActions, KShortcutsEditor::LetterShortcutsAllowed, this);
2546     dialog.addCollection(actionCollection(), i18nc("general keyboard shortcuts", "General"));
2547     dialog.addCollection(m_effectsActionCollection, i18nc("effects and transitions keyboard shortcuts", "Effects & Transitions"));
2548     dialog.configure();
2549 }
2550
2551 void MainWindow::slotPreferences(int page, int option)
2552 {
2553     /*
2554      * An instance of your dialog could be already created and could be
2555      * cached, in which case you want to display the cached dialog
2556      * instead of creating another one
2557      */
2558     if (m_stopmotion) m_stopmotion->slotLive(false);
2559     if (KConfigDialog::showDialog("settings")) {
2560         KdenliveSettingsDialog* d = static_cast <KdenliveSettingsDialog*>(KConfigDialog::exists("settings"));
2561         if (page != -1) d->showPage(page, option);
2562         return;
2563     }
2564
2565     // KConfigDialog didn't find an instance of this dialog, so lets
2566     // create it :
2567     
2568     // Get the mappable actions in localized form
2569     QMap<QString, QString> actions;
2570     KActionCollection* collection = actionCollection();
2571     foreach (const QString& action_name, m_action_names) {
2572         actions[collection->action(action_name)->text()] = action_name;
2573     }
2574     
2575     KdenliveSettingsDialog* dialog = new KdenliveSettingsDialog(actions, this);
2576     connect(dialog, SIGNAL(settingsChanged(const QString&)), this, SLOT(updateConfiguration()));
2577     connect(dialog, SIGNAL(doResetProfile()), m_monitorManager, SLOT(slotResetProfiles()));
2578 #ifndef Q_WS_MAC
2579     connect(dialog, SIGNAL(updateCaptureFolder()), this, SLOT(slotUpdateCaptureFolder()));
2580 #endif
2581     dialog->show();
2582     if (page != -1) dialog->showPage(page, option);
2583 }
2584
2585 void MainWindow::slotUpdateCaptureFolder()
2586 {
2587
2588 #ifndef   Q_WS_MAC
2589     if (m_activeDocument) m_recMonitor->slotUpdateCaptureFolder(m_activeDocument->projectFolder().path(KUrl::AddTrailingSlash));
2590     else m_recMonitor->slotUpdateCaptureFolder(KdenliveSettings::defaultprojectfolder());
2591 #endif
2592 }
2593
2594 void MainWindow::updateConfiguration()
2595 {
2596     //TODO: we should apply settings to all projects, not only the current one
2597     if (m_activeTimeline) {
2598         m_activeTimeline->refresh();
2599         m_activeTimeline->projectView()->checkAutoScroll();
2600         m_activeTimeline->projectView()->checkTrackHeight();
2601         if (m_activeDocument)
2602             m_activeDocument->clipManager()->checkAudioThumbs();
2603     }
2604     m_buttonAudioThumbs->setChecked(KdenliveSettings::audiothumbnails());
2605     m_buttonVideoThumbs->setChecked(KdenliveSettings::videothumbnails());
2606     m_buttonShowMarkers->setChecked(KdenliveSettings::showmarkers());
2607     m_buttonAutomaticSplitAudio->setChecked(KdenliveSettings::splitaudio());
2608
2609     // Update list of transcoding profiles
2610     loadTranscoders();
2611 #ifndef NO_JOGSHUTTLE
2612     activateShuttleDevice();
2613 #endif /* NO_JOGSHUTTLE */
2614
2615 }
2616
2617 void MainWindow::slotSwitchSplitAudio()
2618 {
2619     KdenliveSettings::setSplitaudio(!KdenliveSettings::splitaudio());
2620     m_buttonAutomaticSplitAudio->setChecked(KdenliveSettings::splitaudio());
2621 }
2622
2623 void MainWindow::slotSwitchVideoThumbs()
2624 {
2625     KdenliveSettings::setVideothumbnails(!KdenliveSettings::videothumbnails());
2626     if (m_activeTimeline)
2627         m_activeTimeline->projectView()->slotUpdateAllThumbs();
2628     m_buttonVideoThumbs->setChecked(KdenliveSettings::videothumbnails());
2629 }
2630
2631 void MainWindow::slotSwitchAudioThumbs()
2632 {
2633     KdenliveSettings::setAudiothumbnails(!KdenliveSettings::audiothumbnails());
2634     if (m_activeTimeline) {
2635         m_activeTimeline->refresh();
2636         m_activeTimeline->projectView()->checkAutoScroll();
2637         if (m_activeDocument)
2638             m_activeDocument->clipManager()->checkAudioThumbs();
2639     }
2640     m_buttonAudioThumbs->setChecked(KdenliveSettings::audiothumbnails());
2641 }
2642
2643 void MainWindow::slotSwitchMarkersComments()
2644 {
2645     KdenliveSettings::setShowmarkers(!KdenliveSettings::showmarkers());
2646     if (m_activeTimeline)
2647         m_activeTimeline->refresh();
2648     m_buttonShowMarkers->setChecked(KdenliveSettings::showmarkers());
2649 }
2650
2651 void MainWindow::slotSwitchSnap()
2652 {
2653     KdenliveSettings::setSnaptopoints(!KdenliveSettings::snaptopoints());
2654     m_buttonSnap->setChecked(KdenliveSettings::snaptopoints());
2655 }
2656
2657
2658 void MainWindow::slotDeleteItem()
2659 {
2660     if (QApplication::focusWidget() &&
2661             QApplication::focusWidget()->parentWidget() &&
2662             QApplication::focusWidget()->parentWidget()->parentWidget() &&
2663             QApplication::focusWidget()->parentWidget()->parentWidget() == m_projectListDock) {
2664         m_projectList->slotRemoveClip();
2665
2666     } else {
2667         QWidget *widget = QApplication::focusWidget();
2668         while (widget) {
2669             if (widget == m_effectStackDock) {
2670                 m_effectStack->slotItemDel();
2671                 return;
2672             }
2673             widget = widget->parentWidget();
2674         }
2675
2676         // effect stack has no focus
2677         if (m_activeTimeline)
2678             m_activeTimeline->projectView()->deleteSelectedClips();
2679     }
2680 }
2681
2682 void MainWindow::slotUpdateClipMarkers(DocClipBase *clip)
2683 {
2684     if (m_clipMonitor->isActive())
2685         m_clipMonitor->checkOverlay();
2686     m_clipMonitor->updateMarkers(clip);
2687 }
2688
2689 void MainWindow::slotAddClipMarker()
2690 {
2691     DocClipBase *clip = NULL;
2692     GenTime pos;
2693     if (m_projectMonitor->isActive()) {
2694         if (m_activeTimeline) {
2695             ClipItem *item = m_activeTimeline->projectView()->getActiveClipUnderCursor();
2696             if (item) {
2697                 pos = GenTime((int)((m_projectMonitor->position() - item->startPos() + item->cropStart()).frames(m_activeDocument->fps()) * item->speed() + 0.5), m_activeDocument->fps());
2698                 clip = item->baseClip();
2699             }
2700         }
2701     } else {
2702         clip = m_clipMonitor->activeClip();
2703         pos = m_clipMonitor->position();
2704     }
2705     if (!clip) {
2706         m_messageLabel->setMessage(i18n("Cannot find clip to add marker"), ErrorMessage);
2707         return;
2708     }
2709     QString id = clip->getId();
2710     CommentedTime marker(pos, i18n("Marker"));
2711     MarkerDialog d(clip, marker, m_activeDocument->timecode(), i18n("Add Marker"), this);
2712     if (d.exec() == QDialog::Accepted)
2713         m_activeTimeline->projectView()->slotAddClipMarker(id, d.newMarker().time(), d.newMarker().comment());
2714 }
2715
2716 void MainWindow::slotDeleteClipMarker()
2717 {
2718     DocClipBase *clip = NULL;
2719     GenTime pos;
2720     if (m_projectMonitor->isActive()) {
2721         if (m_activeTimeline) {
2722             ClipItem *item = m_activeTimeline->projectView()->getActiveClipUnderCursor();
2723             if (item) {
2724                 pos = (m_projectMonitor->position() - item->startPos() + item->cropStart()) / item->speed();
2725                 clip = item->baseClip();
2726             }
2727         }
2728     } else {
2729         clip = m_clipMonitor->activeClip();
2730         pos = m_clipMonitor->position();
2731     }
2732     if (!clip) {
2733         m_messageLabel->setMessage(i18n("Cannot find clip to remove marker"), ErrorMessage);
2734         return;
2735     }
2736
2737     QString id = clip->getId();
2738     QString comment = clip->markerComment(pos);
2739     if (comment.isEmpty()) {
2740         m_messageLabel->setMessage(i18n("No marker found at cursor time"), ErrorMessage);
2741         return;
2742     }
2743     m_activeTimeline->projectView()->slotDeleteClipMarker(comment, id, pos);
2744 }
2745
2746 void MainWindow::slotDeleteAllClipMarkers()
2747 {
2748     DocClipBase *clip = NULL;
2749     if (m_projectMonitor->isActive()) {
2750         if (m_activeTimeline) {
2751             ClipItem *item = m_activeTimeline->projectView()->getActiveClipUnderCursor();
2752             if (item) {
2753                 clip = item->baseClip();
2754             }
2755         }
2756     } else {
2757         clip = m_clipMonitor->activeClip();
2758     }
2759     if (!clip) {
2760         m_messageLabel->setMessage(i18n("Cannot find clip to remove marker"), ErrorMessage);
2761         return;
2762     }
2763     m_activeTimeline->projectView()->slotDeleteAllClipMarkers(clip->getId());
2764 }
2765
2766 void MainWindow::slotEditClipMarker()
2767 {
2768     DocClipBase *clip = NULL;
2769     GenTime pos;
2770     if (m_projectMonitor->isActive()) {
2771         if (m_activeTimeline) {
2772             ClipItem *item = m_activeTimeline->projectView()->getActiveClipUnderCursor();
2773             if (item) {
2774                 pos = (m_projectMonitor->position() - item->startPos() + item->cropStart()) / item->speed();
2775                 clip = item->baseClip();
2776             }
2777         }
2778     } else {
2779         clip = m_clipMonitor->activeClip();
2780         pos = m_clipMonitor->position();
2781     }
2782     if (!clip) {
2783         m_messageLabel->setMessage(i18n("Cannot find clip to remove marker"), ErrorMessage);
2784         return;
2785     }
2786
2787     QString id = clip->getId();
2788     QString oldcomment = clip->markerComment(pos);
2789     if (oldcomment.isEmpty()) {
2790         m_messageLabel->setMessage(i18n("No marker found at cursor time"), ErrorMessage);
2791         return;
2792     }
2793
2794     CommentedTime marker(pos, oldcomment);
2795     MarkerDialog d(clip, marker, m_activeDocument->timecode(), i18n("Edit Marker"), this);
2796     if (d.exec() == QDialog::Accepted) {
2797         m_activeTimeline->projectView()->slotAddClipMarker(id, d.newMarker().time(), d.newMarker().comment());
2798         if (d.newMarker().time() != pos) {
2799             // remove old marker
2800             m_activeTimeline->projectView()->slotAddClipMarker(id, pos, QString());
2801         }
2802     }
2803 }
2804
2805 void MainWindow::slotAddMarkerGuideQuickly()
2806 {
2807     if (!m_activeTimeline || !m_activeDocument)
2808         return;
2809
2810     if (m_clipMonitor->isActive()) {
2811         DocClipBase *clip = m_clipMonitor->activeClip();
2812         GenTime pos = m_clipMonitor->position();
2813
2814         if (!clip) {
2815             m_messageLabel->setMessage(i18n("Cannot find clip to add marker"), ErrorMessage);
2816             return;
2817         }
2818
2819         m_activeTimeline->projectView()->slotAddClipMarker(clip->getId(), pos, m_activeDocument->timecode().getDisplayTimecode(pos, false));
2820     } else {
2821         m_activeTimeline->projectView()->slotAddGuide(false);
2822     }
2823 }
2824
2825 void MainWindow::slotAddGuide()
2826 {
2827     if (m_activeTimeline)
2828         m_activeTimeline->projectView()->slotAddGuide();
2829 }
2830
2831 void MainWindow::slotInsertSpace()
2832 {
2833     if (m_activeTimeline)
2834         m_activeTimeline->projectView()->slotInsertSpace();
2835 }
2836
2837 void MainWindow::slotRemoveSpace()
2838 {
2839     if (m_activeTimeline)
2840         m_activeTimeline->projectView()->slotRemoveSpace();
2841 }
2842
2843 void MainWindow::slotInsertTrack(int ix)
2844 {
2845     m_projectMonitor->activateMonitor();
2846     if (m_activeTimeline)
2847         m_activeTimeline->projectView()->slotInsertTrack(ix);
2848     if (m_activeDocument)
2849         m_transitionConfig->updateProjectFormat(m_activeDocument->mltProfile(), m_activeDocument->timecode(), m_activeDocument->tracksList());
2850 }
2851
2852 void MainWindow::slotDeleteTrack(int ix)
2853 {
2854     m_projectMonitor->activateMonitor();
2855     if (m_activeTimeline)
2856         m_activeTimeline->projectView()->slotDeleteTrack(ix);
2857     if (m_activeDocument)
2858         m_transitionConfig->updateProjectFormat(m_activeDocument->mltProfile(), m_activeDocument->timecode(), m_activeDocument->tracksList());
2859 }
2860
2861 void MainWindow::slotConfigTrack(int ix)
2862 {
2863     m_projectMonitor->activateMonitor();
2864     if (m_activeTimeline)
2865         m_activeTimeline->projectView()->slotConfigTracks(ix);
2866     if (m_activeDocument)
2867         m_transitionConfig->updateProjectFormat(m_activeDocument->mltProfile(), m_activeDocument->timecode(), m_activeDocument->tracksList());
2868 }
2869
2870 void MainWindow::slotEditGuide()
2871 {
2872     if (m_activeTimeline)
2873         m_activeTimeline->projectView()->slotEditGuide();
2874 }
2875
2876 void MainWindow::slotDeleteGuide()
2877 {
2878     if (m_activeTimeline)
2879         m_activeTimeline->projectView()->slotDeleteGuide();
2880 }
2881
2882 void MainWindow::slotDeleteAllGuides()
2883 {
2884     if (m_activeTimeline)
2885         m_activeTimeline->projectView()->slotDeleteAllGuides();
2886 }
2887
2888 void MainWindow::slotCutTimelineClip()
2889 {
2890     if (m_activeTimeline)
2891         m_activeTimeline->projectView()->cutSelectedClips();
2892 }
2893
2894 void MainWindow::slotInsertClipOverwrite()
2895 {
2896     if (m_activeTimeline) {
2897         QStringList data = m_clipMonitor->getZoneInfo();
2898         m_activeTimeline->projectView()->insertZoneOverwrite(data, m_activeTimeline->inPoint());
2899     }
2900 }
2901
2902 void MainWindow::slotSelectTimelineClip()
2903 {
2904     if (m_activeTimeline)
2905         m_activeTimeline->projectView()->selectClip(true);
2906 }
2907
2908 void MainWindow::slotSelectTimelineTransition()
2909 {
2910     if (m_activeTimeline)
2911         m_activeTimeline->projectView()->selectTransition(true);
2912 }
2913
2914 void MainWindow::slotDeselectTimelineClip()
2915 {
2916     if (m_activeTimeline)
2917         m_activeTimeline->projectView()->selectClip(false, true);
2918 }
2919
2920 void MainWindow::slotDeselectTimelineTransition()
2921 {
2922     if (m_activeTimeline)
2923         m_activeTimeline->projectView()->selectTransition(false, true);
2924 }
2925
2926 void MainWindow::slotSelectAddTimelineClip()
2927 {
2928     if (m_activeTimeline)
2929         m_activeTimeline->projectView()->selectClip(true, true);
2930 }
2931
2932 void MainWindow::slotSelectAddTimelineTransition()
2933 {
2934     if (m_activeTimeline)
2935         m_activeTimeline->projectView()->selectTransition(true, true);
2936 }
2937
2938 void MainWindow::slotGroupClips()
2939 {
2940     if (m_activeTimeline)
2941         m_activeTimeline->projectView()->groupClips();
2942 }
2943
2944 void MainWindow::slotUnGroupClips()
2945 {
2946     if (m_activeTimeline)
2947         m_activeTimeline->projectView()->groupClips(false);
2948 }
2949
2950 void MainWindow::slotEditItemDuration()
2951 {
2952     if (m_activeTimeline)
2953         m_activeTimeline->projectView()->editItemDuration();
2954 }
2955
2956 void MainWindow::slotAddProjectClip(KUrl url)
2957 {
2958     if (m_activeDocument)
2959         m_activeDocument->slotAddClipFile(url, QString());
2960 }
2961
2962 void MainWindow::slotAddTransition(QAction *result)
2963 {
2964     if (!result) return;
2965     QStringList info = result->data().toStringList();
2966     if (info.isEmpty()) return;
2967     QDomElement transition = transitions.getEffectByTag(info.at(1), info.at(2));
2968     if (m_activeTimeline && !transition.isNull()) {
2969         m_activeTimeline->projectView()->slotAddTransitionToSelectedClips(transition.cloneNode().toElement());
2970     }
2971 }
2972
2973 void MainWindow::slotAddVideoEffect(QAction *result)
2974 {
2975     if (!result) return;
2976     const int EFFECT_VIDEO = 1;
2977     const int EFFECT_AUDIO = 2;
2978     QStringList info = result->data().toStringList();
2979
2980     if (info.isEmpty() || info.size() < 3) return;
2981     QDomElement effect ;
2982     if (info.at(2) == QString::number((int) EFFECT_VIDEO))
2983             effect = videoEffects.getEffectByTag(info.at(0), info.at(1));
2984     else if (info.at(2) == QString::number((int) EFFECT_AUDIO))
2985             effect = audioEffects.getEffectByTag(info.at(0), info.at(1));
2986     else
2987             effect = customEffects.getEffectByTag(info.at(0), info.at(1));
2988     if (!effect.isNull()) slotAddEffect(effect);
2989     else m_messageLabel->setMessage(i18n("Cannot find effect %1 / %2").arg(info.at(0)).arg(info.at(1)), ErrorMessage);
2990 }
2991
2992 void MainWindow::slotAddAudioEffect(QAction *result)
2993 {
2994     if (!result) return;
2995     QStringList info = result->data().toStringList();
2996     if (info.isEmpty()) return;
2997     QDomElement effect = audioEffects.getEffectByTag(info.at(1), info.at(2));
2998     slotAddEffect(effect);
2999 }
3000
3001 void MainWindow::slotAddCustomEffect(QAction *result)
3002 {
3003     if (!result) return;
3004     QStringList info = result->data().toStringList();
3005     if (info.isEmpty()) return;
3006     QDomElement effect = customEffects.getEffectByTag(info.at(1), info.at(2));
3007     slotAddEffect(effect);
3008 }
3009
3010 void MainWindow::slotZoomIn()
3011 {
3012     m_zoomSlider->setValue(m_zoomSlider->value() - 1);
3013     slotShowZoomSliderToolTip();
3014 }
3015
3016 void MainWindow::slotZoomOut()
3017 {
3018     m_zoomSlider->setValue(m_zoomSlider->value() + 1);
3019     slotShowZoomSliderToolTip();
3020 }
3021
3022 void MainWindow::slotFitZoom()
3023 {
3024     if (m_activeTimeline)
3025         m_zoomSlider->setValue(m_activeTimeline->fitZoom());
3026 }
3027
3028 void MainWindow::slotSetZoom(int value)
3029 {
3030     value = qMax(m_zoomSlider->minimum(), value);
3031     value = qMin(m_zoomSlider->maximum(), value);
3032
3033     if (m_activeTimeline)
3034         m_activeTimeline->slotChangeZoom(value);
3035
3036     m_zoomOut->setEnabled(value < m_zoomSlider->maximum());
3037     m_zoomIn->setEnabled(value > m_zoomSlider->minimum());
3038     slotUpdateZoomSliderToolTip(value);
3039
3040     m_zoomSlider->blockSignals(true);
3041     m_zoomSlider->setValue(value);
3042     m_zoomSlider->blockSignals(false);
3043 }
3044
3045 void MainWindow::slotShowZoomSliderToolTip(int zoomlevel)
3046 {
3047     if (zoomlevel != -1)
3048         slotUpdateZoomSliderToolTip(zoomlevel);
3049
3050     QPoint global = m_zoomSlider->rect().topLeft();
3051     global.ry() += m_zoomSlider->height() / 2;
3052     QHelpEvent toolTipEvent(QEvent::ToolTip, QPoint(0, 0), m_zoomSlider->mapToGlobal(global));
3053     QApplication::sendEvent(m_zoomSlider, &toolTipEvent);
3054 }
3055
3056 void MainWindow::slotUpdateZoomSliderToolTip(int zoomlevel)
3057 {
3058     m_zoomSlider->setToolTip(i18n("Zoom Level: %1/13", (13 - zoomlevel)));
3059 }
3060
3061 void MainWindow::slotGotProgressInfo(const QString &message, int progress)
3062 {
3063     m_statusProgressBar->setValue(progress);
3064     if (progress >= 0) {
3065         if (!message.isEmpty())
3066             m_messageLabel->setMessage(message, InformationMessage);//statusLabel->setText(message);
3067         m_statusProgressBar->setVisible(true);
3068     } else if (progress == -2) {
3069         if (!message.isEmpty())
3070             m_messageLabel->setMessage(message, ErrorMessage);
3071         m_statusProgressBar->setVisible(false);
3072     } else {
3073         m_messageLabel->setMessage(QString(), DefaultMessage);
3074         m_statusProgressBar->setVisible(false);
3075     }
3076 }
3077
3078 void MainWindow::slotShowClipProperties(DocClipBase *clip)
3079 {
3080     if (clip->clipType() == TEXT) {
3081         QString titlepath = m_activeDocument->projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
3082         if (!clip->getProperty("resource").isEmpty() && clip->getProperty("xmldata").isEmpty()) {
3083             // template text clip
3084
3085             // Get the list of existing templates
3086             QStringList filter;
3087             filter << "*.kdenlivetitle";
3088             QStringList templateFiles = QDir(titlepath).entryList(filter, QDir::Files);
3089
3090             QDialog *dia = new QDialog(this);
3091             Ui::TemplateClip_UI dia_ui;
3092             dia_ui.setupUi(dia);
3093             int ix = -1;
3094             const QString templatePath = clip->getProperty("resource");
3095             for (int i = 0; i < templateFiles.size(); ++i) {
3096                 dia_ui.template_list->comboBox()->addItem(templateFiles.at(i), titlepath + templateFiles.at(i));
3097                 if (templatePath == KUrl(titlepath + templateFiles.at(i)).path()) ix = i;
3098             }
3099             if (ix != -1) dia_ui.template_list->comboBox()->setCurrentIndex(ix);
3100             else dia_ui.template_list->comboBox()->insertItem(0, templatePath);
3101             dia_ui.template_list->fileDialog()->setFilter("*.kdenlivetitle");
3102             //warning: setting base directory doesn't work??
3103             KUrl startDir(titlepath);
3104             dia_ui.template_list->fileDialog()->setUrl(startDir);
3105             dia_ui.description->setText(clip->getProperty("description"));
3106             if (dia->exec() == QDialog::Accepted) {
3107                 QString textTemplate = dia_ui.template_list->comboBox()->itemData(dia_ui.template_list->comboBox()->currentIndex()).toString();
3108                 if (textTemplate.isEmpty()) textTemplate = dia_ui.template_list->comboBox()->currentText();
3109
3110                 QMap <QString, QString> newprops;
3111
3112                 if (KUrl(textTemplate).path() != templatePath) {
3113                     // The template was changed
3114                     newprops.insert("resource", textTemplate);
3115                 }
3116
3117                 if (dia_ui.description->toPlainText() != clip->getProperty("description")) {
3118                     newprops.insert("description", dia_ui.description->toPlainText());
3119                 }
3120
3121                 QString newtemplate = newprops.value("xmltemplate");
3122                 if (newtemplate.isEmpty()) newtemplate = templatePath;
3123
3124                 // template modified we need to update xmldata
3125                 QString description = newprops.value("description");
3126                 if (description.isEmpty()) description = clip->getProperty("description");
3127                 else newprops.insert("templatetext", description);
3128                 //newprops.insert("xmldata", m_projectList->generateTemplateXml(newtemplate, description).toString());
3129                 if (!newprops.isEmpty()) {
3130                     EditClipCommand *command = new EditClipCommand(m_projectList, clip->getId(), clip->properties(), newprops, true);
3131                     m_activeDocument->commandStack()->push(command);
3132                 }
3133             }
3134             delete dia;
3135             return;
3136         }
3137         QString path = clip->getProperty("resource");
3138         TitleWidget *dia_ui = new TitleWidget(KUrl(), m_activeDocument->timecode(), titlepath, m_projectMonitor->render, this);
3139         QDomDocument doc;
3140         doc.setContent(clip->getProperty("xmldata"));
3141         dia_ui->setXml(doc);
3142         if (dia_ui->exec() == QDialog::Accepted) {
3143             QMap <QString, QString> newprops;
3144             newprops.insert("xmldata", dia_ui->xml().toString());
3145             if (dia_ui->outPoint() != clip->duration().frames(m_activeDocument->fps()) - 1) {
3146                 // duration changed, we need to update duration
3147                 newprops.insert("out", QString::number(dia_ui->outPoint()));
3148                 int currentLength = QString(clip->producerProperty("length")).toInt();
3149                 if (currentLength <= dia_ui->outPoint())
3150                         newprops.insert("length", QString::number(dia_ui->outPoint() + 1));
3151                 else newprops.insert("length", clip->producerProperty("length"));
3152             }
3153             if (!path.isEmpty()) {
3154                 // we are editing an external file, asked if we want to detach from that file or save the result to that title file.
3155                 if (KMessageBox::questionYesNo(this, i18n("You are editing an external title clip (%1). Do you want to save your changes to the title file or save the changes for this project only?", path), i18n("Save Title"), KGuiItem(i18n("Save to title file")), KGuiItem(i18n("Save in project only"))) == KMessageBox::Yes) {
3156                     // save to external file
3157                     dia_ui->saveTitle(path);
3158                 } else newprops.insert("resource", QString());
3159             }
3160             EditClipCommand *command = new EditClipCommand(m_projectList, clip->getId(), clip->properties(), newprops, true);
3161             m_activeDocument->commandStack()->push(command);
3162             //m_activeTimeline->projectView()->slotUpdateClip(clip->getId());
3163             m_activeDocument->setModified(true);
3164         }
3165         delete dia_ui;
3166
3167         //m_activeDocument->editTextClip(clip->getProperty("xml"), clip->getId());
3168         return;
3169     }
3170
3171     // any type of clip but a title
3172     ClipProperties *dia = new ClipProperties(clip, m_activeDocument->timecode(), m_activeDocument->fps(), this);
3173     connect(dia, SIGNAL(addMarker(const QString &, GenTime, QString)), m_activeTimeline->projectView(), SLOT(slotAddClipMarker(const QString &, GenTime, QString)));
3174     connect(dia, SIGNAL(applyNewClipProperties(const QString, QMap <QString, QString> , QMap <QString, QString> , bool, bool)), this, SLOT(slotApplyNewClipProperties(const QString, QMap <QString, QString> , QMap <QString, QString> , bool, bool)));
3175     dia->show();
3176 }
3177
3178
3179 void MainWindow::slotApplyNewClipProperties(const QString id, QMap <QString, QString> props, QMap <QString, QString> newprops, bool refresh, bool reload)
3180 {
3181     if (newprops.isEmpty()) return;
3182     EditClipCommand *command = new EditClipCommand(m_projectList, id, props, newprops, true);
3183     m_activeDocument->commandStack()->push(command);
3184     m_activeDocument->setModified();
3185
3186     if (refresh) {
3187         // update clip occurences in timeline
3188         m_activeTimeline->projectView()->slotUpdateClip(id, reload);
3189     }
3190 }
3191
3192
3193 void MainWindow::slotShowClipProperties(QList <DocClipBase *> cliplist, QMap<QString, QString> commonproperties)
3194 {
3195     ClipProperties dia(cliplist, m_activeDocument->timecode(), commonproperties, this);
3196     if (dia.exec() == QDialog::Accepted) {
3197         QUndoCommand *command = new QUndoCommand();
3198         command->setText(i18n("Edit clips"));
3199         QMap <QString, QString> newImageProps = dia.properties();
3200         // Transparency setting applies only for images
3201         QMap <QString, QString> newProps = newImageProps;
3202         newProps.remove("transparency");
3203
3204         for (int i = 0; i < cliplist.count(); i++) {
3205             DocClipBase *clip = cliplist.at(i);
3206             if (clip->clipType() == IMAGE)
3207                 new EditClipCommand(m_projectList, clip->getId(), clip->properties(), newImageProps, true, command);
3208             else 
3209                 new EditClipCommand(m_projectList, clip->getId(), clip->properties(), newProps, true, command);
3210         }
3211         m_activeDocument->commandStack()->push(command);
3212         for (int i = 0; i < cliplist.count(); i++)
3213             m_activeTimeline->projectView()->slotUpdateClip(cliplist.at(i)->getId(), dia.needsTimelineReload());
3214     }
3215 }
3216
3217 void MainWindow::customEvent(QEvent* e)
3218 {
3219     if (e->type() == QEvent::User)
3220         m_messageLabel->setMessage(static_cast <MltErrorEvent *>(e)->message(), MltError);
3221 }
3222 void MainWindow::slotActivateEffectStackView()
3223 {
3224     m_effectStack->raiseWindow(m_effectStackDock);
3225 }
3226
3227 void MainWindow::slotActivateTransitionView(Transition *t)
3228 {
3229     if (t)
3230         m_transitionConfig->raiseWindow(m_transitionConfigDock);
3231 }
3232
3233 void MainWindow::slotSnapRewind()
3234 {
3235     if (m_projectMonitor->isActive()) {
3236         if (m_activeTimeline)
3237             m_activeTimeline->projectView()->slotSeekToPreviousSnap();
3238     } else  {
3239         m_clipMonitor->slotSeekToPreviousSnap();
3240     }
3241 }
3242
3243 void MainWindow::slotSnapForward()
3244 {
3245     if (m_projectMonitor->isActive()) {
3246         if (m_activeTimeline)
3247             m_activeTimeline->projectView()->slotSeekToNextSnap();
3248     } else {
3249         m_clipMonitor->slotSeekToNextSnap();
3250     }
3251 }
3252
3253 void MainWindow::slotClipStart()
3254 {
3255     if (m_projectMonitor->isActive()) {
3256         if (m_activeTimeline)
3257             m_activeTimeline->projectView()->clipStart();
3258     }
3259 }
3260
3261 void MainWindow::slotClipEnd()
3262 {
3263     if (m_projectMonitor->isActive()) {
3264         if (m_activeTimeline)
3265             m_activeTimeline->projectView()->clipEnd();
3266     }
3267 }
3268
3269 void MainWindow::slotZoneStart()
3270 {
3271     if (m_projectMonitor->isActive())
3272         m_projectMonitor->slotZoneStart();
3273     else
3274         m_clipMonitor->slotZoneStart();
3275 }
3276
3277 void MainWindow::slotZoneEnd()
3278 {
3279     if (m_projectMonitor->isActive())
3280         m_projectMonitor->slotZoneEnd();
3281     else
3282         m_clipMonitor->slotZoneEnd();
3283 }
3284
3285 void MainWindow::slotChangeTool(QAction * action)
3286 {
3287     if (action == m_buttonSelectTool)
3288         slotSetTool(SELECTTOOL);
3289     else if (action == m_buttonRazorTool)
3290         slotSetTool(RAZORTOOL);
3291     else if (action == m_buttonSpacerTool)
3292         slotSetTool(SPACERTOOL);
3293 }
3294
3295 void MainWindow::slotChangeEdit(QAction * action)
3296 {
3297     if (!m_activeTimeline)
3298         return;
3299
3300     if (action == m_overwriteEditTool)
3301         m_activeTimeline->projectView()->setEditMode(OVERWRITEEDIT);
3302     else if (action == m_insertEditTool)
3303         m_activeTimeline->projectView()->setEditMode(INSERTEDIT);
3304     else
3305         m_activeTimeline->projectView()->setEditMode(NORMALEDIT);
3306 }
3307
3308 void MainWindow::slotSetTool(PROJECTTOOL tool)
3309 {
3310     if (m_activeDocument && m_activeTimeline) {
3311         //m_activeDocument->setTool(tool);
3312         QString message;
3313         switch (tool)  {
3314         case SPACERTOOL:
3315             message = i18n("Ctrl + click to use spacer on current track only");
3316             break;
3317         case RAZORTOOL:
3318             message = i18n("Click on a clip to cut it");
3319             break;
3320         default:
3321             message = i18n("Shift + click to create a selection rectangle, Ctrl + click to add an item to selection");
3322             break;
3323         }
3324         m_messageLabel->setMessage(message, InformationMessage);
3325         m_activeTimeline->projectView()->setTool(tool);
3326     }
3327 }
3328
3329 void MainWindow::slotCopy()
3330 {
3331     if (m_activeDocument && m_activeTimeline)
3332         m_activeTimeline->projectView()->copyClip();
3333 }
3334
3335 void MainWindow::slotPaste()
3336 {
3337     if (m_activeDocument && m_activeTimeline)
3338         m_activeTimeline->projectView()->pasteClip();
3339 }
3340
3341 void MainWindow::slotPasteEffects()
3342 {
3343     if (m_activeDocument && m_activeTimeline)
3344         m_activeTimeline->projectView()->pasteClipEffects();
3345 }
3346
3347 void MainWindow::slotFind()
3348 {
3349     if (!m_activeDocument || !m_activeTimeline) return;
3350     m_projectSearch->setEnabled(false);
3351     m_findActivated = true;
3352     m_findString.clear();
3353     m_activeTimeline->projectView()->initSearchStrings();
3354     statusBar()->showMessage(i18n("Starting -- find text as you type"));
3355     m_findTimer.start(5000);
3356     qApp->installEventFilter(this);
3357 }
3358
3359 void MainWindow::slotFindNext()
3360 {
3361     if (m_activeTimeline && m_activeTimeline->projectView()->findNextString(m_findString))
3362         statusBar()->showMessage(i18n("Found: %1", m_findString));
3363     else
3364         statusBar()->showMessage(i18n("Reached end of project"));
3365     m_findTimer.start(4000);
3366 }
3367
3368 void MainWindow::findAhead()
3369 {
3370     if (m_activeTimeline && m_activeTimeline->projectView()->findString(m_findString)) {
3371         m_projectSearchNext->setEnabled(true);
3372         statusBar()->showMessage(i18n("Found: %1", m_findString));
3373     } else {
3374         m_projectSearchNext->setEnabled(false);
3375         statusBar()->showMessage(i18n("Not found: %1", m_findString));
3376     }
3377 }
3378
3379 void MainWindow::findTimeout()
3380 {
3381     m_projectSearchNext->setEnabled(false);
3382     m_findActivated = false;
3383     m_findString.clear();
3384     statusBar()->showMessage(i18n("Find stopped"), 3000);
3385     if (m_activeTimeline) m_activeTimeline->projectView()->clearSearchStrings();
3386     m_projectSearch->setEnabled(true);
3387     removeEventFilter(this);
3388 }
3389
3390 void MainWindow::slotClipInTimeline(const QString &clipId)
3391 {
3392     if (m_activeTimeline && m_activeDocument) {
3393         QList<ItemInfo> matching = m_activeTimeline->projectView()->findId(clipId);
3394
3395         QMenu *inTimelineMenu = static_cast<QMenu*>(factory()->container("clip_in_timeline", this));
3396         inTimelineMenu->clear();
3397
3398         QList <QAction *> actionList;
3399
3400         for (int i = 0; i < matching.count(); ++i) {
3401             QString track = QString::number(matching.at(i).track);
3402             QString start = m_activeDocument->timecode().getTimecode(matching.at(i).startPos);
3403             int j = 0;
3404             QAction *a = new QAction(track + ": " + start, this);
3405             a->setData(QStringList() << track << start);
3406             connect(a, SIGNAL(triggered()), this, SLOT(slotSelectClipInTimeline()));
3407             while (j < actionList.count()) {
3408                 if (actionList.at(j)->text() > a->text()) break;
3409                 j++;
3410             }
3411             actionList.insert(j, a);
3412         }
3413         inTimelineMenu->addActions(actionList);
3414
3415         if (matching.empty())
3416             inTimelineMenu->setEnabled(false);
3417         else
3418             inTimelineMenu->setEnabled(true);
3419     }
3420 }
3421
3422 void MainWindow::slotClipInProjectTree()
3423 {
3424     if (m_activeTimeline) {
3425         const QStringList &clipIds = m_activeTimeline->projectView()->selectedClips();
3426         if (clipIds.isEmpty())
3427             return;
3428         m_projectListDock->raise();
3429         for (int i = 0; i < clipIds.count(); i++)
3430             m_projectList->selectItemById(clipIds.at(i));
3431         if (m_projectMonitor->isActive())
3432             slotSwitchMonitors();
3433     }
3434 }
3435
3436 /*void MainWindow::slotClipToProjectTree()
3437 {
3438     if (m_activeTimeline) {
3439     const QList<ClipItem *> clips =  m_activeTimeline->projectView()->selectedClipItems();
3440         if (clips.isEmpty()) return;
3441         for (int i = 0; i < clips.count(); i++) {
3442         m_projectList->slotAddXmlClip(clips.at(i)->itemXml());
3443         }
3444         //m_projectList->selectItemById(clipIds.at(i));
3445     }
3446 }*/
3447
3448 void MainWindow::slotSelectClipInTimeline()
3449 {
3450     if (m_activeTimeline) {
3451         QAction *action = qobject_cast<QAction *>(sender());
3452         QStringList data = action->data().toStringList();
3453         m_activeTimeline->projectView()->selectFound(data.at(0), data.at(1));
3454     }
3455 }
3456
3457 void MainWindow::keyPressEvent(QKeyEvent *ke)
3458 {
3459     if (m_findActivated) {
3460         if (ke->key() == Qt::Key_Backspace) {
3461             m_findString = m_findString.left(m_findString.length() - 1);
3462
3463             if (!m_findString.isEmpty())
3464                 findAhead();
3465             else
3466                 findTimeout();
3467
3468             m_findTimer.start(4000);
3469             ke->accept();
3470             return;
3471         } else if (ke->key() == Qt::Key_Escape) {
3472             findTimeout();
3473             ke->accept();
3474             return;
3475         } else if (ke->key() == Qt::Key_Space || !ke->text().trimmed().isEmpty()) {
3476             m_findString += ke->text();
3477
3478             findAhead();
3479
3480             m_findTimer.start(4000);
3481             ke->accept();
3482             return;
3483         }
3484     } else {
3485         KXmlGuiWindow::keyPressEvent(ke);
3486     }
3487 }
3488
3489
3490 /** Gets called when the window gets hidden */
3491 void MainWindow::hideEvent(QHideEvent */*event*/)
3492 {
3493     if (isMinimized() && m_monitorManager)
3494         m_monitorManager->stopActiveMonitor();
3495 }
3496
3497 bool MainWindow::eventFilter(QObject *obj, QEvent *event)
3498 {
3499     if (m_findActivated) {
3500         if (event->type() == QEvent::ShortcutOverride) {
3501             QKeyEvent* ke = (QKeyEvent*) event;
3502             if (ke->text().trimmed().isEmpty()) return false;
3503             ke->accept();
3504             return true;
3505         } else {
3506             return false;
3507         }
3508     } else {
3509         // pass the event on to the parent class
3510         return QMainWindow::eventFilter(obj, event);
3511     }
3512 }
3513
3514
3515 void MainWindow::slotSaveZone(Render *render, QPoint zone)
3516 {
3517     KDialog *dialog = new KDialog(this);
3518     dialog->setCaption("Save clip zone");
3519     dialog->setButtons(KDialog::Ok | KDialog::Cancel);
3520
3521     QWidget *widget = new QWidget(dialog);
3522     dialog->setMainWidget(widget);
3523
3524     QVBoxLayout *vbox = new QVBoxLayout(widget);
3525     QLabel *label1 = new QLabel(i18n("Save clip zone as:"), this);
3526     QString path = m_activeDocument->projectFolder().path(KUrl::AddTrailingSlash);
3527     path.append("untitled.mlt");
3528     KUrlRequester *url = new KUrlRequester(KUrl(path), this);
3529     url->setFilter("video/mlt-playlist");
3530     QLabel *label2 = new QLabel(i18n("Description:"), this);
3531     KLineEdit *edit = new KLineEdit(this);
3532     vbox->addWidget(label1);
3533     vbox->addWidget(url);
3534     vbox->addWidget(label2);
3535     vbox->addWidget(edit);
3536     if (dialog->exec() == QDialog::Accepted)
3537         render->saveZone(url->url(), edit->text(), zone);
3538
3539 }
3540
3541 void MainWindow::slotSetInPoint()
3542 {
3543     if (m_clipMonitor->isActive())
3544         m_clipMonitor->slotSetZoneStart();
3545     else
3546         m_projectMonitor->slotSetZoneStart();
3547     //else m_activeTimeline->projectView()->setInPoint();
3548 }
3549
3550 void MainWindow::slotSetOutPoint()
3551 {
3552     if (m_clipMonitor->isActive())
3553         m_clipMonitor->slotSetZoneEnd();
3554     else
3555         m_projectMonitor->slotSetZoneEnd();
3556     // else m_activeTimeline->projectView()->setOutPoint();
3557 }
3558
3559 void MainWindow::slotResizeItemStart()
3560 {
3561     if (m_activeTimeline)
3562         m_activeTimeline->projectView()->setInPoint();
3563 }
3564
3565 void MainWindow::slotResizeItemEnd()
3566 {
3567     if (m_activeTimeline)
3568         m_activeTimeline->projectView()->setOutPoint();
3569 }
3570
3571 int MainWindow::getNewStuff(const QString &configFile)
3572 {
3573     KNS3::Entry::List entries;
3574 #if KDE_IS_VERSION(4,3,80)
3575     KNS3::DownloadDialog dialog(configFile);
3576     dialog.exec();
3577     entries = dialog.changedEntries();
3578     foreach(const KNS3::Entry & entry, entries) {
3579         if (entry.status() == KNS3::Entry::Installed)
3580             kDebug() << "// Installed files: " << entry.installedFiles();
3581     }
3582 #else
3583     KNS::Engine engine(0);
3584     if (engine.init(configFile))
3585         entries = engine.downloadDialogModal(this);
3586     foreach(KNS::Entry * entry, entries) {
3587         if (entry->status() == KNS::Entry::Installed)
3588             kDebug() << "// Installed files: " << entry->installedFiles();
3589     }
3590 #endif /* KDE_IS_VERSION(4,3,80) */
3591     return entries.size();
3592 }
3593
3594 void MainWindow::slotGetNewTitleStuff()
3595 {
3596     if (getNewStuff("kdenlive_titles.knsrc") > 0)
3597         TitleWidget::refreshTitleTemplates();
3598 }
3599
3600 void MainWindow::slotGetNewLumaStuff()
3601 {
3602     if (getNewStuff("kdenlive_wipes.knsrc") > 0) {
3603         initEffects::refreshLumas();
3604         m_activeTimeline->projectView()->reloadTransitionLumas();
3605     }
3606 }
3607
3608 void MainWindow::slotGetNewRenderStuff()
3609 {
3610     if (getNewStuff("kdenlive_renderprofiles.knsrc") > 0)
3611         if (m_renderWidget)
3612             m_renderWidget->reloadProfiles();
3613 }
3614
3615 void MainWindow::slotGetNewMltProfileStuff()
3616 {
3617     if (getNewStuff("kdenlive_projectprofiles.knsrc") > 0) {
3618         // update the list of profiles in settings dialog
3619         KdenliveSettingsDialog* d = static_cast <KdenliveSettingsDialog*>(KConfigDialog::exists("settings"));
3620         if (d)
3621             d->checkProfile();
3622     }
3623 }
3624
3625 void MainWindow::slotAutoTransition()
3626 {
3627     if (m_activeTimeline)
3628         m_activeTimeline->projectView()->autoTransition();
3629 }
3630
3631 void MainWindow::slotSplitAudio()
3632 {
3633     if (m_activeTimeline)
3634         m_activeTimeline->projectView()->splitAudio();
3635 }
3636
3637 void MainWindow::slotUpdateClipType(QAction *action)
3638 {
3639     if (m_activeTimeline) {
3640         if (action->data().toString() == "clip_audio_only") m_activeTimeline->projectView()->setAudioOnly();
3641         else if (action->data().toString() == "clip_video_only") m_activeTimeline->projectView()->setVideoOnly();
3642         else m_activeTimeline->projectView()->setAudioAndVideo();
3643     }
3644 }
3645
3646 void MainWindow::slotDvdWizard(const QString &url, const QString &profile)
3647 {
3648     // We must stop the monitors since we create a new on in the dvd wizard
3649     m_clipMonitor->stop();
3650     m_projectMonitor->stop();
3651     DvdWizard w(url, profile, this);
3652     w.exec();
3653     m_projectMonitor->start();
3654 }
3655
3656 void MainWindow::slotShowTimeline(bool show)
3657 {
3658     if (show == false) {
3659         m_timelineState = saveState();
3660         centralWidget()->setHidden(true);
3661     } else {
3662         centralWidget()->setHidden(false);
3663         restoreState(m_timelineState);
3664     }
3665 }
3666
3667 void MainWindow::slotMaximizeCurrent(bool /*show*/)
3668 {
3669     //TODO: is there a way to maximize current widget?
3670     //if (show == true)
3671     {
3672         m_timelineState = saveState();
3673         QWidget *par = focusWidget()->parentWidget();
3674         while (par->parentWidget() && par->parentWidget() != this)
3675             par = par->parentWidget();
3676         kDebug() << "CURRENT WIDGET: " << par->objectName();
3677     }
3678     /*else {
3679     //centralWidget()->setHidden(false);
3680     //restoreState(m_timelineState);
3681     }*/
3682 }
3683
3684 void MainWindow::loadTranscoders()
3685 {
3686     QMenu *transMenu = static_cast<QMenu*>(factory()->container("transcoders", this));
3687     transMenu->clear();
3688
3689     KSharedConfigPtr config = KSharedConfig::openConfig("kdenlivetranscodingrc");
3690     KConfigGroup transConfig(config, "Transcoding");
3691     // read the entries
3692     QMap< QString, QString > profiles = transConfig.entryMap();
3693     QMapIterator<QString, QString> i(profiles);
3694     while (i.hasNext()) {
3695         i.next();
3696         QStringList data = i.value().split(";", QString::SkipEmptyParts);
3697         QAction *a = transMenu->addAction(i.key());
3698         a->setData(data);
3699         if (data.count() > 1)
3700             a->setToolTip(data.at(1));
3701         connect(a, SIGNAL(triggered()), this, SLOT(slotTranscode()));
3702     }
3703 }
3704
3705 void MainWindow::slotTranscode(KUrl::List urls)
3706 {
3707     QString params;
3708     QString desc;
3709     QString condition;
3710     if (urls.isEmpty()) {
3711         QAction *action = qobject_cast<QAction *>(sender());
3712         QStringList data = action->data().toStringList();
3713         params = data.at(0);
3714         if (data.count() > 1) desc = data.at(1);
3715         if (data.count() > 2) condition = data.at(2);
3716         urls << m_projectList->getConditionalUrls(condition);
3717         urls.removeAll(KUrl());
3718     }
3719     if (urls.isEmpty()) {
3720         m_messageLabel->setMessage(i18n("No clip to transcode"), ErrorMessage);
3721         return;
3722     }
3723     ClipTranscode *d = new ClipTranscode(urls, params, desc);
3724     connect(d, SIGNAL(addClip(KUrl)), this, SLOT(slotAddProjectClip(KUrl)));
3725     d->show();
3726     //QProcess::startDetached("ffmpeg", parameters);
3727 }
3728
3729 void MainWindow::slotTranscodeClip()
3730 {
3731     KUrl::List urls = KFileDialog::getOpenUrls(KUrl("kfiledialog:///projectfolder"));
3732     if (urls.isEmpty()) return;
3733     slotTranscode(urls);
3734 }
3735
3736 void MainWindow::slotSetDocumentRenderProfile(QMap <QString, QString> props)
3737 {
3738     if (m_activeDocument == NULL) return;
3739     QMapIterator<QString, QString> i(props);
3740     while (i.hasNext()) {
3741         i.next();
3742         m_activeDocument->setDocumentProperty(i.key(), i.value());
3743     }
3744     m_activeDocument->setModified(true);
3745 }
3746
3747
3748 void MainWindow::slotPrepareRendering(bool scriptExport, bool zoneOnly, const QString &chapterFile)
3749 {
3750     if (m_activeDocument == NULL || m_renderWidget == NULL) return;
3751     QString scriptPath;
3752     QString playlistPath;
3753     if (scriptExport) {
3754         bool ok;
3755         QString scriptsFolder = m_activeDocument->projectFolder().path(KUrl::AddTrailingSlash) + "scripts/";
3756         QString path = m_renderWidget->getFreeScriptName();
3757         scriptPath = QInputDialog::getText(this, i18n("Create Render Script"), i18n("Script name (will be saved in: %1)", scriptsFolder), QLineEdit::Normal, KUrl(path).fileName(), &ok);
3758         if (!ok || scriptPath.isEmpty()) return;
3759         scriptPath.prepend(scriptsFolder);
3760         QFile f(scriptPath);
3761         if (f.exists()) {
3762             if (KMessageBox::warningYesNo(this, i18n("Script file already exists. Do you want to overwrite it?")) != KMessageBox::Yes)
3763                 return;
3764         }
3765         playlistPath = scriptPath + ".mlt";
3766     } else {
3767         KTemporaryFile temp;
3768         temp.setAutoRemove(false);
3769         temp.setSuffix(".mlt");
3770         temp.open();
3771         playlistPath = temp.fileName();
3772     }
3773     QString playlistContent = m_projectMonitor->sceneList();
3774     if (!chapterFile.isEmpty()) {
3775         int in = 0;
3776         int out;
3777         if (!zoneOnly) out = (int) GenTime(m_activeDocument->projectDuration()).frames(m_activeDocument->fps());
3778         else {
3779             in = m_activeTimeline->inPoint();
3780             out = m_activeTimeline->outPoint();
3781         }
3782         QDomDocument doc;
3783         QDomElement chapters = doc.createElement("chapters");
3784         chapters.setAttribute("fps", m_activeDocument->fps());
3785         doc.appendChild(chapters);
3786
3787         QDomElement guidesxml = m_activeDocument->guidesXml();
3788         QDomNodeList nodes = guidesxml.elementsByTagName("guide");
3789         for (int i = 0; i < nodes.count(); i++) {
3790             QDomElement e = nodes.item(i).toElement();
3791             if (!e.isNull()) {
3792                 QString comment = e.attribute("comment");
3793                 int time = (int) GenTime(e.attribute("time").toDouble()).frames(m_activeDocument->fps());
3794                 if (time >= in && time < out) {
3795                     if (zoneOnly) time = time - in;
3796                     QDomElement chapter = doc.createElement("chapter");
3797                     chapters.appendChild(chapter);
3798                     chapter.setAttribute("title", comment);
3799                     chapter.setAttribute("time", time);
3800                 }
3801             }
3802         }
3803         if (chapters.childNodes().count() > 0) {
3804             if (m_activeTimeline->projectView()->hasGuide(out, 0) == -1) {
3805                 // Always insert a guide in pos 0
3806                 QDomElement chapter = doc.createElement("chapter");
3807                 chapters.insertBefore(chapter, QDomNode());
3808                 chapter.setAttribute("title", i18n("Start"));
3809                 chapter.setAttribute("time", "0");
3810             }
3811             // save chapters file
3812             QFile file(chapterFile);
3813             if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
3814                 kWarning() << "//////  ERROR writing DVD CHAPTER file: " << chapterFile;
3815             } else {
3816                 file.write(doc.toString().toUtf8());
3817                 if (file.error() != QFile::NoError) {
3818                     kWarning() << "//////  ERROR writing DVD CHAPTER file: " << chapterFile;
3819                 }
3820                 file.close();
3821             }
3822         }
3823     }
3824     bool exportAudio;
3825     if (m_renderWidget->automaticAudioExport()) {
3826         exportAudio = m_activeTimeline->checkProjectAudio();
3827     } else exportAudio = m_renderWidget->selectedAudioExport();
3828     
3829     // Do we want proxy rendering
3830     if (m_projectList->useProxy() && !m_renderWidget->proxyRendering()) {
3831         // replace proxy clips with originals
3832         QMap <QString, QString> proxies = m_projectList->getProxies();
3833         QMapIterator<QString, QString> i(proxies);
3834         while (i.hasNext()) {
3835             i.next();
3836             // Replace all keys with their values (proxy path with original path)
3837             playlistContent.replace(i.key(), i.value());
3838         }
3839     }
3840     
3841     // Do save scenelist
3842     QFile file(playlistPath);
3843     if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
3844         m_messageLabel->setMessage(i18n("Cannot write to file %1").arg(playlistPath), ErrorMessage);
3845         return;
3846     }
3847     file.write(playlistContent.toUtf8());
3848     if (file.error() != QFile::NoError) {
3849         m_messageLabel->setMessage(i18n("Cannot write to file %1").arg(playlistPath), ErrorMessage);
3850         file.close();
3851         return;
3852     }
3853     file.close();
3854     m_renderWidget->slotExport(scriptExport, m_activeTimeline->inPoint(), m_activeTimeline->outPoint(), playlistPath, scriptPath, exportAudio);
3855 }
3856
3857 void MainWindow::slotUpdateTimecodeFormat(int ix)
3858 {
3859     KdenliveSettings::setFrametimecode(ix == 1);
3860     m_clipMonitor->updateTimecodeFormat();
3861     m_projectMonitor->updateTimecodeFormat();
3862     m_transitionConfig->updateTimecodeFormat();
3863     m_effectStack->updateTimecodeFormat();
3864     //m_activeTimeline->projectView()->clearSelection();
3865     m_activeTimeline->updateRuler();
3866 }
3867
3868 void MainWindow::slotRemoveFocus()
3869 {
3870     statusBar()->setFocus();
3871     statusBar()->clearFocus();
3872 }
3873
3874 void MainWindow::slotRevert()
3875 {
3876     if (KMessageBox::warningContinueCancel(this, i18n("This will delete all changes made since you last saved your project. Are you sure you want to continue?"), i18n("Revert to last saved version")) == KMessageBox::Cancel) return;
3877     KUrl url = m_activeDocument->url();
3878     if (closeCurrentDocument(false))
3879         doOpenFile(url, NULL);
3880 }
3881
3882
3883 void MainWindow::slotShutdown()
3884 {
3885     if (m_activeDocument) m_activeDocument->setModified(false);
3886     // Call shutdown
3887     QDBusConnectionInterface* interface = QDBusConnection::sessionBus().interface();
3888     if (interface && interface->isServiceRegistered("org.kde.ksmserver")) {
3889         QDBusInterface smserver("org.kde.ksmserver", "/KSMServer", "org.kde.KSMServerInterface");
3890         smserver.call("logout", 1, 2, 2);
3891     } else if (interface && interface->isServiceRegistered("org.gnome.SessionManager")) {
3892         QDBusInterface smserver("org.gnome.SessionManager", "/org/gnome/SessionManager", "org.gnome.SessionManager");
3893         smserver.call("Shutdown");
3894     }
3895 }
3896
3897 void MainWindow::slotUpdateTrackInfo()
3898 {
3899     if (m_activeDocument)
3900         m_transitionConfig->updateProjectFormat(m_activeDocument->mltProfile(), m_activeDocument->timecode(), m_activeDocument->tracksList());
3901 }
3902
3903 void MainWindow::slotChangePalette(QAction *action, const QString &themename)
3904 {
3905     // Load the theme file
3906     QString theme;
3907     if (action == NULL) theme = themename;
3908     else theme = action->data().toString();
3909     KdenliveSettings::setColortheme(theme);
3910     // Make palette for all widgets.
3911     QPalette plt;
3912     if (theme.isEmpty()) {
3913         plt = QApplication::desktop()->palette();
3914     } else {
3915         KSharedConfigPtr config = KSharedConfig::openConfig(theme);
3916         plt = KGlobalSettings::createApplicationPalette(config);
3917     }
3918
3919     kapp->setPalette(plt);
3920     const QObjectList children = statusBar()->children();
3921
3922     foreach(QObject * child, children) {
3923         if (child->isWidgetType())
3924             ((QWidget*)child)->setPalette(plt);
3925         const QObjectList subchildren = child->children();
3926         foreach(QObject * subchild, subchildren) {
3927             if (subchild->isWidgetType())
3928                 ((QWidget*)subchild)->setPalette(plt);
3929         }
3930     }
3931     if (m_activeTimeline) {
3932         m_activeTimeline->projectView()->updatePalette();
3933     }
3934 }
3935
3936
3937 QPixmap MainWindow::createSchemePreviewIcon(const KSharedConfigPtr &config)
3938 {
3939     // code taken from kdebase/workspace/kcontrol/colors/colorscm.cpp
3940     const uchar bits1[] = { 0xff, 0xff, 0xff, 0x2c, 0x16, 0x0b };
3941     const uchar bits2[] = { 0x68, 0x34, 0x1a, 0xff, 0xff, 0xff };
3942     const QSize bitsSize(24, 2);
3943     const QBitmap b1 = QBitmap::fromData(bitsSize, bits1);
3944     const QBitmap b2 = QBitmap::fromData(bitsSize, bits2);
3945
3946     QPixmap pixmap(23, 16);
3947     pixmap.fill(Qt::black); // ### use some color other than black for borders?
3948
3949     KConfigGroup group(config, "WM");
3950     QPainter p(&pixmap);
3951     KColorScheme windowScheme(QPalette::Active, KColorScheme::Window, config);
3952     p.fillRect(1,  1, 7, 7, windowScheme.background());
3953     p.fillRect(2,  2, 5, 2, QBrush(windowScheme.foreground().color(), b1));
3954
3955     KColorScheme buttonScheme(QPalette::Active, KColorScheme::Button, config);
3956     p.fillRect(8,  1, 7, 7, buttonScheme.background());
3957     p.fillRect(9,  2, 5, 2, QBrush(buttonScheme.foreground().color(), b1));
3958
3959     p.fillRect(15,  1, 7, 7, group.readEntry("activeBackground", QColor(96, 148, 207)));
3960     p.fillRect(16,  2, 5, 2, QBrush(group.readEntry("activeForeground", QColor(255, 255, 255)), b1));
3961
3962     KColorScheme viewScheme(QPalette::Active, KColorScheme::View, config);
3963     p.fillRect(1,  8, 7, 7, viewScheme.background());
3964     p.fillRect(2, 12, 5, 2, QBrush(viewScheme.foreground().color(), b2));
3965
3966     KColorScheme selectionScheme(QPalette::Active, KColorScheme::Selection, config);
3967     p.fillRect(8,  8, 7, 7, selectionScheme.background());
3968     p.fillRect(9, 12, 5, 2, QBrush(selectionScheme.foreground().color(), b2));
3969
3970     p.fillRect(15,  8, 7, 7, group.readEntry("inactiveBackground", QColor(224, 223, 222)));
3971     p.fillRect(16, 12, 5, 2, QBrush(group.readEntry("inactiveForeground", QColor(20, 19, 18)), b2));
3972
3973     p.end();
3974     return pixmap;
3975 }
3976
3977 void MainWindow::slotSwitchMonitors()
3978 {
3979     m_monitorManager->slotSwitchMonitors(!m_clipMonitor->isActive());
3980     if (m_projectMonitor->isActive()) m_activeTimeline->projectView()->setFocus();
3981     else m_projectList->focusTree();
3982 }
3983
3984 void MainWindow::slotSwitchFullscreen()
3985 {
3986     if (m_projectMonitor->isActive()) m_projectMonitor->slotSwitchFullScreen();
3987     else m_clipMonitor->slotSwitchFullScreen();
3988 }
3989
3990 void MainWindow::slotInsertZoneToTree()
3991 {
3992     if (!m_clipMonitor->isActive() || m_clipMonitor->activeClip() == NULL) return;
3993     QStringList info = m_clipMonitor->getZoneInfo();
3994     m_projectList->slotAddClipCut(info.at(0), info.at(1).toInt(), info.at(2).toInt());
3995 }
3996
3997 void MainWindow::slotInsertZoneToTimeline()
3998 {
3999     if (m_activeTimeline == NULL || m_clipMonitor->activeClip() == NULL) return;
4000     QStringList info = m_clipMonitor->getZoneInfo();
4001     m_activeTimeline->projectView()->insertClipCut(m_clipMonitor->activeClip(), info.at(1).toInt(), info.at(2).toInt());
4002 }
4003
4004
4005 void MainWindow::slotDeleteProjectClips(QStringList ids, QMap<QString, QString> folderids)
4006 {
4007     if (m_activeDocument && m_activeTimeline) {
4008         if (!ids.isEmpty()) {
4009             for (int i = 0; i < ids.size(); ++i) {
4010                 m_activeTimeline->slotDeleteClip(ids.at(i));
4011             }
4012             m_activeDocument->clipManager()->slotDeleteClips(ids);
4013         }
4014         if (!folderids.isEmpty()) m_projectList->deleteProjectFolder(folderids);
4015         m_activeDocument->setModified(true);
4016     }
4017 }
4018
4019 void MainWindow::slotShowTitleBars(bool show)
4020 {
4021     QList <QDockWidget *> docks = findChildren<QDockWidget *>();
4022     for (int i = 0; i < docks.count(); i++) {
4023         QDockWidget* dock = docks.at(i);
4024         if (show) {
4025             dock->setTitleBarWidget(0);
4026         } else {
4027             if (!dock->isFloating()) {
4028                 dock->setTitleBarWidget(new QWidget);
4029             }
4030         }
4031     }
4032     KdenliveSettings::setShowtitlebars(show);
4033 }
4034
4035 void MainWindow::slotSwitchTitles()
4036 {
4037     slotShowTitleBars(!KdenliveSettings::showtitlebars());
4038 }
4039
4040 QString MainWindow::getMimeType()
4041 {
4042     QString mimetype = "application/x-kdenlive";
4043     KMimeType::Ptr mime = KMimeType::mimeType(mimetype);
4044     if (!mime) mimetype = "*.kdenlive";
4045     return mimetype;
4046 }
4047
4048 void MainWindow::slotMonitorRequestRenderFrame(bool request)
4049 {
4050     if (request) {
4051         m_projectMonitor->render->sendFrameForAnalysis = true;
4052         return;
4053     } else {
4054         for (int i = 0; i < m_gfxScopesList.count(); i++) {
4055             if (m_gfxScopesList.at(i)->isVisible() && tabifiedDockWidgets(m_gfxScopesList.at(i)).isEmpty() && static_cast<AbstractGfxScopeWidget *>(m_gfxScopesList.at(i)->widget())->autoRefreshEnabled()) {
4056                 request = true;
4057                 break;
4058             }
4059         }
4060     }
4061 #ifdef DEBUG_MAINW
4062     qDebug() << "Any scope accepting new frames? " << request;
4063 #endif
4064     if (!request) {
4065         m_projectMonitor->render->sendFrameForAnalysis = false;
4066     }
4067 }
4068
4069 void MainWindow::slotUpdateGfxScopeFrameRequest()
4070 {
4071     // We need a delay to make sure widgets are hidden after a close event for example
4072     QTimer::singleShot(500, this, SLOT(slotDoUpdateGfxScopeFrameRequest()));
4073 }
4074
4075 void MainWindow::slotDoUpdateGfxScopeFrameRequest()
4076 {
4077     // Check scopes
4078     bool request = false;
4079     for (int i = 0; i < m_gfxScopesList.count(); i++) {
4080         if (!m_gfxScopesList.at(i)->widget()->visibleRegion().isEmpty() && static_cast<AbstractGfxScopeWidget *>(m_gfxScopesList.at(i)->widget())->autoRefreshEnabled()) {
4081             kDebug() << "SCOPE VISIBLE: " << static_cast<AbstractGfxScopeWidget *>(m_gfxScopesList.at(i)->widget())->widgetName();
4082             request = true;
4083             break;
4084         }
4085     }
4086     if (!request) {
4087         if (!m_projectMonitor->effectSceneDisplayed()) {
4088             m_projectMonitor->render->sendFrameForAnalysis = false;
4089         }
4090         m_clipMonitor->render->sendFrameForAnalysis = false;
4091     } else {
4092         m_projectMonitor->render->sendFrameForAnalysis = true;
4093         m_clipMonitor->render->sendFrameForAnalysis = true;
4094     }
4095 }
4096
4097 void MainWindow::slotUpdateAudioScopeFrameRequest()
4098 {
4099     QTimer::singleShot(500, this, SLOT(slotDoUpdateAudioScopeFrameRequest()));
4100 }
4101
4102 void MainWindow::slotDoUpdateAudioScopeFrameRequest()
4103 {
4104     bool request = false;
4105     for (int i = 0; i < m_audioScopesList.count(); i++) {
4106         if (!m_audioScopesList.at(i)->visibleRegion().isEmpty() && m_audioScopesList.at(i)->autoRefreshEnabled()) {
4107             kDebug() << "AUDIO SCOPE VISIBLE: " << m_audioScopesList.at(i)->widgetName();
4108             request = true;
4109             break;
4110         }
4111     }
4112     // Handle audio signal separately (no common interface)
4113     if (!m_audiosignal->visibleRegion().isEmpty() && m_audiosignal->monitoringEnabled()) {
4114         kDebug() << "AUDIO SCOPE VISIBLE: " << "audiosignal";
4115         request = true;
4116     }
4117 #ifdef DEBUG_MAINW
4118     qDebug() << "Scopes Requesting Audio data: " << request;
4119 #endif
4120     KdenliveSettings::setMonitor_audio(request);
4121     m_monitorManager->slotUpdateAudioMonitoring();
4122 }
4123
4124 void MainWindow::slotUpdateColorScopes()
4125 {
4126     bool request = false;
4127     for (int i = 0; i < m_gfxScopesList.count(); i++) {
4128         // Check if we need the renderer to send a new frame for update
4129         if (!m_gfxScopesList.at(i)->widget()->visibleRegion().isEmpty() && !(static_cast<AbstractGfxScopeWidget *>(m_gfxScopesList.at(i)->widget())->autoRefreshEnabled())) request = true;
4130         static_cast<AbstractGfxScopeWidget *>(m_gfxScopesList.at(i)->widget())->slotActiveMonitorChanged(m_clipMonitor->isActive());
4131     }
4132     if (request) {
4133         if (m_clipMonitor->isActive()) m_clipMonitor->render->sendFrameUpdate();
4134         else m_projectMonitor->render->sendFrameUpdate();
4135     }
4136 }
4137
4138 void MainWindow::slotOpenStopmotion()
4139 {
4140     if (m_stopmotion == NULL) {
4141         m_stopmotion = new StopmotionWidget(m_activeDocument->projectFolder(), m_stopmotion_actions->actions(), this);
4142         connect(m_stopmotion, SIGNAL(addOrUpdateSequence(const QString)), m_projectList, SLOT(slotAddOrUpdateSequence(const QString)));
4143         for (int i = 0; i < m_gfxScopesList.count(); i++) {
4144             // Check if we need the renderer to send a new frame for update
4145             /*if (!m_scopesList.at(i)->widget()->visibleRegion().isEmpty() && !(static_cast<AbstractScopeWidget *>(m_scopesList.at(i)->widget())->autoRefreshEnabled())) request = true;*/
4146             connect(m_stopmotion, SIGNAL(gotFrame(QImage)), static_cast<AbstractGfxScopeWidget *>(m_gfxScopesList.at(i)->widget()), SLOT(slotRenderZoneUpdated(QImage)));
4147             //static_cast<AbstractScopeWidget *>(m_scopesList.at(i)->widget())->slotMonitorCapture();
4148         }
4149     }
4150     m_stopmotion->show();
4151 }
4152
4153 void MainWindow::slotDeleteClip(const QString &id)
4154 {
4155     QList <ClipProperties *> list = findChildren<ClipProperties *>();
4156     for (int i = 0; i < list.size(); ++i) {
4157         list.at(i)->disableClipId(id);
4158     }
4159     m_projectList->slotDeleteClip(id);
4160 }
4161
4162 void MainWindow::slotUpdateProxySettings()
4163 {
4164     if (m_renderWidget) m_renderWidget->updateProxyConfig(m_projectList->useProxy());
4165     if (KdenliveSettings::enableproxy())
4166         KStandardDirs::makeDir(m_activeDocument->projectFolder().path(KUrl::AddTrailingSlash) + "proxy/");
4167     m_projectList->updateProxyConfig();
4168 }
4169
4170 #include "mainwindow.moc"
4171
4172 #ifdef DEBUG_MAINW
4173 #undef DEBUG_MAINW
4174 #endif