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