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