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