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