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