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