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