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