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