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