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