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