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