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