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