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