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