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