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