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