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