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