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