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