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