]> git.sesse.net Git - kdenlive/blob - src/mainwindow.cpp
Correctly update monitor when changing a title clip duration
[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 "effectstackview.h"
39 #include "transitionsettings.h"
40 #include "renderwidget.h"
41 #include "renderer.h"
42 #ifndef NO_JOGSHUTTLE
43 #include "jogshuttle.h"
44 #endif /* NO_JOGSHUTTLE */
45 #include "clipproperties.h"
46 #include "wizard.h"
47 #include "editclipcommand.h"
48 #include "titlewidget.h"
49 #include "markerdialog.h"
50 #include "clipitem.h"
51 #include "interfaces.h"
52 #include "kdenlive-config.h"
53 #include "cliptranscode.h"
54 #include "ui_templateclip_ui.h"
55
56 #include <KApplication>
57 #include <KAction>
58 #include <KLocale>
59 #include <KGlobal>
60 #include <KActionCollection>
61 #include <KStandardAction>
62 #include <KFileDialog>
63 #include <KMessageBox>
64 #include <KDebug>
65 #include <KIO/NetAccess>
66 #include <KSaveFile>
67 #include <KRuler>
68 #include <KConfigDialog>
69 #include <KXMLGUIFactory>
70 #include <KStatusBar>
71 #include <kstandarddirs.h>
72 #include <KUrlRequesterDialog>
73 #include <KTemporaryFile>
74 #include <KProcess>
75 #include <KActionMenu>
76 #include <KMenu>
77 #include <locale.h>
78 #include <ktogglefullscreenaction.h>
79 #include <KFileItem>
80 #include <KNotification>
81 #include <KNotifyConfigWidget>
82 #include <knewstuff2/engine.h>
83 #include <knewstuff2/ui/knewstuffaction.h>
84 #include <KToolBar>
85
86 #include <QTextStream>
87 #include <QTimer>
88 #include <QAction>
89 #include <QKeyEvent>
90 #include <QInputDialog>
91
92 #include <stdlib.h>
93
94 static const char version[] = VERSION;
95
96 static const int ID_TIMELINE_POS = 0;
97
98 namespace Mlt
99 {
100 class Producer;
101 };
102
103 EffectsList MainWindow::videoEffects;
104 EffectsList MainWindow::audioEffects;
105 EffectsList MainWindow::customEffects;
106 EffectsList MainWindow::transitions;
107
108 MainWindow::MainWindow(const QString &MltPath, const KUrl & Url, QWidget *parent) :
109         KXmlGuiWindow(parent),
110         m_activeDocument(NULL),
111         m_activeTimeline(NULL),
112         m_renderWidget(NULL),
113 #ifndef NO_JOGSHUTTLE
114         m_jogProcess(NULL),
115 #endif /* NO_JOGSHUTTLE */
116         m_findActivated(false)
117 {
118
119     // Create DBus interface
120     new MainWindowAdaptor(this);
121     QDBusConnection dbus = QDBusConnection::sessionBus();
122     dbus.registerObject("/MainWindow", this);
123
124     setlocale(LC_NUMERIC, "POSIX");
125     setFont(KGlobalSettings::toolBarFont());
126     parseProfiles(MltPath);
127     m_commandStack = new QUndoGroup;
128     m_timelineArea = new KTabWidget(this);
129     m_timelineArea->setTabReorderingEnabled(true);
130     m_timelineArea->setTabBarHidden(true);
131
132     QToolButton *closeTabButton = new QToolButton;
133     connect(closeTabButton, SIGNAL(clicked()), this, SLOT(closeCurrentDocument()));
134     closeTabButton->setIcon(KIcon("tab-close"));
135     closeTabButton->adjustSize();
136     closeTabButton->setToolTip(i18n("Close the current tab"));
137     m_timelineArea->setCornerWidget(closeTabButton);
138     connect(m_timelineArea, SIGNAL(currentChanged(int)), this, SLOT(activateDocument()));
139
140     connect(&m_findTimer, SIGNAL(timeout()), this, SLOT(findTimeout()));
141     m_findTimer.setSingleShot(true);
142
143     // FIXME: the next call returns a newly allocated object, which leaks
144     initEffects::parseEffectFiles();
145     //initEffects::parseCustomEffectsFile();
146
147     m_monitorManager = new MonitorManager();
148
149     m_projectListDock = new QDockWidget(i18n("Project Tree"), this);
150     m_projectListDock->setObjectName("project_tree");
151     m_projectList = new ProjectList(this);
152     m_projectListDock->setWidget(m_projectList);
153     addDockWidget(Qt::TopDockWidgetArea, m_projectListDock);
154
155     m_shortcutRemoveFocus = new QShortcut(QKeySequence("Esc"), this);
156     connect(m_shortcutRemoveFocus, SIGNAL(activated()), this, SLOT(slotRemoveFocus()));
157
158     m_effectListDock = new QDockWidget(i18n("Effect List"), this);
159     m_effectListDock->setObjectName("effect_list");
160     m_effectList = new EffectsListView();
161
162     //m_effectList = new KListWidget(this);
163     m_effectListDock->setWidget(m_effectList);
164     addDockWidget(Qt::TopDockWidgetArea, m_effectListDock);
165
166     m_effectStackDock = new QDockWidget(i18n("Effect Stack"), this);
167     m_effectStackDock->setObjectName("effect_stack");
168     m_effectStack = new EffectStackView(this);
169     m_effectStackDock->setWidget(m_effectStack);
170     addDockWidget(Qt::TopDockWidgetArea, m_effectStackDock);
171
172     m_transitionConfigDock = new QDockWidget(i18n("Transition"), this);
173     m_transitionConfigDock->setObjectName("transition");
174     m_transitionConfig = new TransitionSettings(this);
175     m_transitionConfigDock->setWidget(m_transitionConfig);
176     addDockWidget(Qt::TopDockWidgetArea, m_transitionConfigDock);
177
178     KdenliveSettings::setCurrent_profile(KdenliveSettings::default_profile());
179     m_fileOpenRecent = KStandardAction::openRecent(this, SLOT(openFile(const KUrl &)), actionCollection());
180     readOptions();
181     m_fileRevert = KStandardAction::revert(this, SLOT(slotRevert()), actionCollection());
182     m_fileRevert->setEnabled(false);
183
184     //slotDetectAudioDriver();
185
186     m_clipMonitorDock = new QDockWidget(i18n("Clip Monitor"), this);
187     m_clipMonitorDock->setObjectName("clip_monitor");
188     m_clipMonitor = new Monitor("clip", m_monitorManager, QString(), this);
189     m_clipMonitorDock->setWidget(m_clipMonitor);
190     addDockWidget(Qt::TopDockWidgetArea, m_clipMonitorDock);
191     //m_clipMonitor->stop();
192
193     m_projectMonitorDock = new QDockWidget(i18n("Project Monitor"), this);
194     m_projectMonitorDock->setObjectName("project_monitor");
195     m_projectMonitor = new Monitor("project", m_monitorManager, QString(), this);
196     m_projectMonitorDock->setWidget(m_projectMonitor);
197     addDockWidget(Qt::TopDockWidgetArea, m_projectMonitorDock);
198
199 #ifndef Q_WS_MAC
200     m_recMonitorDock = new QDockWidget(i18n("Record Monitor"), this);
201     m_recMonitorDock->setObjectName("record_monitor");
202     m_recMonitor = new RecMonitor("record", this);
203     m_recMonitorDock->setWidget(m_recMonitor);
204     addDockWidget(Qt::TopDockWidgetArea, m_recMonitorDock);
205
206     connect(m_recMonitor, SIGNAL(addProjectClip(KUrl)), this, SLOT(slotAddProjectClip(KUrl)));
207     connect(m_recMonitor, SIGNAL(showConfigDialog(int, int)), this, SLOT(slotPreferences(int, int)));
208 #endif
209
210     m_undoViewDock = new QDockWidget(i18n("Undo History"), this);
211     m_undoViewDock->setObjectName("undo_history");
212     m_undoView = new QUndoView(this);
213     m_undoView->setCleanIcon(KIcon("edit-clear"));
214     m_undoView->setEmptyLabel(i18n("Clean"));
215     m_undoViewDock->setWidget(m_undoView);
216     m_undoView->setGroup(m_commandStack);
217     addDockWidget(Qt::TopDockWidgetArea, m_undoViewDock);
218
219     //overviewDock = new QDockWidget(i18n("Project Overview"), this);
220     //overviewDock->setObjectName("project_overview");
221     //m_overView = new CustomTrackView(NULL, NULL, this);
222     //overviewDock->setWidget(m_overView);
223     //addDockWidget(Qt::TopDockWidgetArea, overviewDock);
224
225     setupActions();
226     //tabifyDockWidget(projectListDock, effectListDock);
227     tabifyDockWidget(m_projectListDock, m_effectStackDock);
228     tabifyDockWidget(m_projectListDock, m_transitionConfigDock);
229     //tabifyDockWidget(projectListDock, undoViewDock);
230
231
232     tabifyDockWidget(m_clipMonitorDock, m_projectMonitorDock);
233 #ifndef Q_WS_MAC
234     tabifyDockWidget(m_clipMonitorDock, m_recMonitorDock);
235 #endif
236     setCentralWidget(m_timelineArea);
237
238
239     setupGUI();
240
241     /*ScriptingPart* sp = new ScriptingPart(this, QStringList());
242     guiFactory()->addClient(sp);*/
243
244     loadPlugins();
245     loadTranscoders();
246     //kDebug() << factory() << " " << factory()->container("video_effects_menu", this);
247
248     m_projectMonitor->setupMenu(static_cast<QMenu*>(factory()->container("monitor_go", this)), m_playZone, m_loopZone);
249     m_clipMonitor->setupMenu(static_cast<QMenu*>(factory()->container("monitor_go", this)), m_playZone, m_loopZone, static_cast<QMenu*>(factory()->container("marker_menu", this)));
250     m_projectList->setupGeneratorMenu(static_cast<QMenu*>(factory()->container("generators", this)), static_cast<QMenu*>(factory()->container("transcoders", this)));
251
252     // build effects menus
253     QAction *action;
254     QMenu *videoEffectsMenu = static_cast<QMenu*>(factory()->container("video_effects_menu", this));
255
256     QStringList effectInfo;
257     QMap<QString, QStringList> effectsList;
258     for (int ix = 0; ix < videoEffects.count(); ix++) {
259         effectInfo = videoEffects.effectIdInfo(ix);
260         effectsList.insert(effectInfo.at(0).toLower(), effectInfo);
261     }
262
263     foreach(const QStringList &value, effectsList) {
264         action = new QAction(value.at(0), this);
265         action->setData(value);
266         videoEffectsMenu->addAction(action);
267     }
268
269     QMenu *audioEffectsMenu = static_cast<QMenu*>(factory()->container("audio_effects_menu", this));
270
271
272     effectsList.clear();
273     for (int ix = 0; ix < audioEffects.count(); ix++) {
274         effectInfo = audioEffects.effectIdInfo(ix);
275         effectsList.insert(effectInfo.at(0).toLower(), effectInfo);
276     }
277
278     foreach(const QStringList &value, effectsList) {
279         action = new QAction(value.at(0), this);
280         action->setData(value);
281         audioEffectsMenu->addAction(action);
282     }
283
284     m_customEffectsMenu = static_cast<QMenu*>(factory()->container("custom_effects_menu", this));
285
286     if (customEffects.isEmpty()) m_customEffectsMenu->setEnabled(false);
287     else m_customEffectsMenu->setEnabled(true);
288
289     effectsList.clear();
290     for (int ix = 0; ix < customEffects.count(); ix++) {
291         effectInfo = customEffects.effectIdInfo(ix);
292         effectsList.insert(effectInfo.at(0).toLower(), effectInfo);
293     }
294
295     foreach(const QStringList &value, effectsList) {
296         action = new QAction(value.at(0), this);
297         action->setData(value);
298         m_customEffectsMenu->addAction(action);
299     }
300
301     QMenu *newEffect = new QMenu(this);
302     newEffect->addMenu(videoEffectsMenu);
303     newEffect->addMenu(audioEffectsMenu);
304     newEffect->addMenu(m_customEffectsMenu);
305     m_effectStack->setMenu(newEffect);
306
307
308     QMenu *viewMenu = static_cast<QMenu*>(factory()->container("dockwindows", this));
309     const QList<QAction *> viewActions = createPopupMenu()->actions();
310     viewMenu->insertActions(NULL, viewActions);
311
312     connect(videoEffectsMenu, SIGNAL(triggered(QAction *)), this, SLOT(slotAddVideoEffect(QAction *)));
313     connect(audioEffectsMenu, SIGNAL(triggered(QAction *)), this, SLOT(slotAddAudioEffect(QAction *)));
314     connect(m_customEffectsMenu, SIGNAL(triggered(QAction *)), this, SLOT(slotAddCustomEffect(QAction *)));
315
316     m_timelineContextMenu = new QMenu(this);
317     m_timelineContextClipMenu = new QMenu(this);
318     m_timelineContextTransitionMenu = new QMenu(this);
319
320
321     QMenu *transitionsMenu = new QMenu(i18n("Add Transition"), this);
322     QStringList effects = transitions.effectNames();
323
324     effectsList.clear();
325     for (int ix = 0; ix < transitions.count(); ix++) {
326         effectInfo = transitions.effectIdInfo(ix);
327         effectsList.insert(effectInfo.at(0).toLower(), effectInfo);
328     }
329     foreach(const QStringList &value, effectsList) {
330         action = new QAction(value.at(0), this);
331         action->setData(value);
332         transitionsMenu->addAction(action);
333     }
334     connect(transitionsMenu, SIGNAL(triggered(QAction *)), this, SLOT(slotAddTransition(QAction *)));
335
336     m_timelineContextMenu->addAction(actionCollection()->action("insert_space"));
337     m_timelineContextMenu->addAction(actionCollection()->action("delete_space"));
338     m_timelineContextMenu->addAction(actionCollection()->action(KStandardAction::name(KStandardAction::Paste)));
339
340     m_timelineContextClipMenu->addAction(actionCollection()->action("delete_timeline_clip"));
341     m_timelineContextClipMenu->addAction(actionCollection()->action("group_clip"));
342     m_timelineContextClipMenu->addAction(actionCollection()->action("ungroup_clip"));
343     m_timelineContextClipMenu->addAction(actionCollection()->action("cut_timeline_clip"));
344     m_timelineContextClipMenu->addAction(actionCollection()->action(KStandardAction::name(KStandardAction::Copy)));
345     m_timelineContextClipMenu->addAction(actionCollection()->action("paste_effects"));
346     m_timelineContextClipMenu->addAction(actionCollection()->action("split_audio"));
347
348     QMenu *markersMenu = (QMenu*)(factory()->container("marker_menu", this));
349     m_timelineContextClipMenu->addMenu(markersMenu);
350     m_timelineContextClipMenu->addMenu(transitionsMenu);
351     m_timelineContextClipMenu->addMenu(videoEffectsMenu);
352     m_timelineContextClipMenu->addMenu(audioEffectsMenu);
353     //TODO: re-enable custom effects menu when it is implemented
354     m_timelineContextClipMenu->addMenu(m_customEffectsMenu);
355
356     m_timelineContextTransitionMenu->addAction(actionCollection()->action("delete_timeline_clip"));
357     m_timelineContextTransitionMenu->addAction(actionCollection()->action(KStandardAction::name(KStandardAction::Copy)));
358
359     m_timelineContextTransitionMenu->addAction(actionCollection()->action("auto_transition"));
360
361     connect(m_projectMonitorDock, SIGNAL(visibilityChanged(bool)), m_projectMonitor, SLOT(refreshMonitor(bool)));
362     connect(m_clipMonitorDock, SIGNAL(visibilityChanged(bool)), m_clipMonitor, SLOT(refreshMonitor(bool)));
363     //connect(m_monitorManager, SIGNAL(connectMonitors()), this, SLOT(slotConnectMonitors()));
364     connect(m_monitorManager, SIGNAL(raiseClipMonitor(bool)), this, SLOT(slotRaiseMonitor(bool)));
365     connect(m_effectList, SIGNAL(addEffect(const QDomElement)), this, SLOT(slotAddEffect(const QDomElement)));
366     connect(m_effectList, SIGNAL(reloadEffects()), this, SLOT(slotReloadEffects()));
367
368     m_monitorManager->initMonitors(m_clipMonitor, m_projectMonitor);
369     slotConnectMonitors();
370
371     // Open or create a file.  Command line argument passed in Url has
372     // precedence, then "openlastproject", then just a plain empty file.
373     // If opening Url fails, openlastproject will _not_ be used.
374     if (!Url.isEmpty()) {
375         // delay loading so that the window shows up
376         m_startUrl = Url;
377         QTimer::singleShot(500, this, SLOT(openFile()));
378     } else if (KdenliveSettings::openlastproject()) {
379         QTimer::singleShot(500, this, SLOT(openLastFile()));
380     } else { //if (m_timelineArea->count() == 0) {
381         newFile(false);
382     }
383
384 #ifndef NO_JOGSHUTTLE
385     activateShuttleDevice();
386 #endif /* NO_JOGSHUTTLE */
387     m_projectListDock->raise();
388 }
389
390 void MainWindow::queryQuit()
391 {
392     if (queryClose()) {
393         if (m_projectMonitor) m_projectMonitor->stop();
394         if (m_clipMonitor) m_clipMonitor->stop();
395         delete m_effectStack;
396         delete m_activeTimeline;
397 #ifndef Q_WS_MAC
398         // This sometimes causes crash on exit on OS X for some reason.
399         delete m_projectMonitor;
400         delete m_clipMonitor;
401 #endif
402         delete m_activeDocument;
403         delete m_shortcutRemoveFocus;
404         Mlt::Factory::close();
405         kapp->quit();
406     }
407 }
408
409 //virtual
410 bool MainWindow::queryClose()
411 {
412     if (m_renderWidget) {
413         int waitingJobs = m_renderWidget->waitingJobsCount();
414         if (waitingJobs > 0) {
415             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")))) {
416             case KMessageBox::Yes :
417                 // create script with waiting jobs and start it
418                 if (m_renderWidget->startWaitingRenderJobs() == false) return false;
419                 break;
420             case KMessageBox::No :
421                 // Don't do anything, jobs will be deleted
422                 break;
423             default:
424                 return false;
425             }
426         }
427     }
428     saveOptions();
429     if (m_monitorManager) m_monitorManager->stopActiveMonitor();
430     if (m_activeDocument && m_activeDocument->isModified()) {
431         switch (KMessageBox::warningYesNoCancel(this, i18n("Save changes to document?"))) {
432         case KMessageBox::Yes :
433             // save document here. If saving fails, return false;
434             return saveFile();
435         case KMessageBox::No :
436             // User does not want to save the changes, clear recovery files
437             m_activeDocument->m_autosave->resize(0);
438             return true;
439         default: // cancel
440             return false;
441         }
442     }
443     return true;
444 }
445
446
447 void MainWindow::loadPlugins()
448 {
449     foreach(QObject *plugin, QPluginLoader::staticInstances())
450     populateMenus(plugin);
451
452     QStringList directories = KGlobal::dirs()->findDirs("module", QString());
453     QStringList filters;
454     filters << "libkdenlive*";
455     foreach(const QString &folder, directories) {
456         kDebug() << "// PARSING FIOLER: " << folder;
457         QDir pluginsDir(folder);
458         foreach(const QString &fileName, pluginsDir.entryList(filters, QDir::Files)) {
459             kDebug() << "// FOUND PLUGIN: " << fileName << "= " << pluginsDir.absoluteFilePath(fileName);
460             QPluginLoader loader(pluginsDir.absoluteFilePath(fileName));
461             QObject *plugin = loader.instance();
462             if (plugin) {
463                 populateMenus(plugin);
464                 m_pluginFileNames += fileName;
465             } else kDebug() << "// ERROR LOADING PLUGIN: " << fileName << ", " << loader.errorString();
466         }
467     }
468     //exit(1);
469 }
470
471 void MainWindow::populateMenus(QObject *plugin)
472 {
473     QMenu *addMenu = static_cast<QMenu*>(factory()->container("generators", this));
474     ClipGenerator *iGenerator = qobject_cast<ClipGenerator *>(plugin);
475     if (iGenerator)
476         addToMenu(plugin, iGenerator->generators(KdenliveSettings::producerslist()), addMenu, SLOT(generateClip()),
477                   NULL);
478 }
479
480 void MainWindow::addToMenu(QObject *plugin, const QStringList &texts,
481                            QMenu *menu, const char *member,
482                            QActionGroup *actionGroup)
483 {
484     kDebug() << "// ADD to MENU" << texts;
485     foreach(const QString &text, texts) {
486         QAction *action = new QAction(text, plugin);
487         action->setData(text);
488         connect(action, SIGNAL(triggered()), this, member);
489         menu->addAction(action);
490
491         if (actionGroup) {
492             action->setCheckable(true);
493             actionGroup->addAction(action);
494         }
495     }
496 }
497
498 void MainWindow::aboutPlugins()
499 {
500     //PluginDialog dialog(pluginsDir.path(), m_pluginFileNames, this);
501     //dialog.exec();
502 }
503
504
505 void MainWindow::generateClip()
506 {
507     QAction *action = qobject_cast<QAction *>(sender());
508     ClipGenerator *iGenerator = qobject_cast<ClipGenerator *>(action->parent());
509
510     KUrl clipUrl = iGenerator->generatedClip(action->data().toString(), m_activeDocument->projectFolder(), QStringList(), QStringList(), 25, 720, 576);
511     if (!clipUrl.isEmpty()) {
512         m_projectList->slotAddClip(QList <QUrl> () << clipUrl);
513     }
514 }
515
516 void MainWindow::saveProperties(KConfigGroup &config)
517 {
518     // save properties here,used by session management
519     saveFile();
520     KMainWindow::saveProperties(config);
521 }
522
523
524 void MainWindow::readProperties(const KConfigGroup &config)
525 {
526     // read properties here,used by session management
527     KMainWindow::readProperties(config);
528     QString Lastproject = config.group("Recent Files").readPathEntry("File1", QString());
529     openFile(KUrl(Lastproject));
530 }
531
532 void MainWindow::slotReloadEffects()
533 {
534     kDebug() << "START RELOAD; COUNR: " << m_customEffectsMenu->actions().count();
535     m_customEffectsMenu->clear();
536     kDebug() << "START RELOAD; CLR: " << m_customEffectsMenu->actions().count();
537     initEffects::parseCustomEffectsFile();
538     const QStringList effects = customEffects.effectNames();
539     kDebug() << "NEW EFFS: " << effects;
540     QAction *action;
541     if (effects.isEmpty()) m_customEffectsMenu->setEnabled(false);
542     else m_customEffectsMenu->setEnabled(true);
543
544     foreach(const QString &name, effects) {
545         action = new QAction(name, this);
546         action->setData(name);
547         m_customEffectsMenu->addAction(action);
548     }
549     m_effectList->reloadEffectList();
550 }
551
552 #ifndef NO_JOGSHUTTLE
553 void MainWindow::activateShuttleDevice()
554 {
555     delete m_jogProcess;
556     m_jogProcess = NULL;
557     if (KdenliveSettings::enableshuttle() == false) return;
558     m_jogProcess = new JogShuttle(KdenliveSettings::shuttledevice());
559     connect(m_jogProcess, SIGNAL(rewind1()), m_monitorManager, SLOT(slotRewindOneFrame()));
560     connect(m_jogProcess, SIGNAL(forward1()), m_monitorManager, SLOT(slotForwardOneFrame()));
561     connect(m_jogProcess, SIGNAL(rewind(double)), m_monitorManager, SLOT(slotRewind(double)));
562     connect(m_jogProcess, SIGNAL(forward(double)), m_monitorManager, SLOT(slotForward(double)));
563     connect(m_jogProcess, SIGNAL(stop()), m_monitorManager, SLOT(slotPlay()));
564     connect(m_jogProcess, SIGNAL(button(int)), this, SLOT(slotShuttleButton(int)));
565 }
566
567 void MainWindow::slotShuttleButton(int code)
568 {
569     switch (code) {
570     case 5:
571         slotShuttleAction(KdenliveSettings::shuttle1());
572         break;
573     case 6:
574         slotShuttleAction(KdenliveSettings::shuttle2());
575         break;
576     case 7:
577         slotShuttleAction(KdenliveSettings::shuttle3());
578         break;
579     case 8:
580         slotShuttleAction(KdenliveSettings::shuttle4());
581         break;
582     case 9:
583         slotShuttleAction(KdenliveSettings::shuttle5());
584         break;
585     }
586 }
587
588 void MainWindow::slotShuttleAction(int code)
589 {
590     switch (code) {
591     case 0:
592         return;
593     case 1:
594         m_monitorManager->slotPlay();
595         break;
596     default:
597         m_monitorManager->slotPlay();
598         break;
599     }
600 }
601 #endif /* NO_JOGSHUTTLE */
602
603 void MainWindow::configureNotifications()
604 {
605     KNotifyConfigWidget::configure(this);
606 }
607
608 void MainWindow::slotFullScreen()
609 {
610     KToggleFullScreenAction::setFullScreen(this, actionCollection()->action("fullscreen")->isChecked());
611 }
612
613 void MainWindow::slotAddEffect(const QDomElement effect, GenTime pos, int track)
614 {
615     if (!m_activeDocument) return;
616     if (effect.isNull()) {
617         kDebug() << "--- ERROR, TRYING TO APPEND NULL EFFECT";
618         return;
619     }
620     QDomElement effectToAdd = effect.cloneNode().toElement();
621     m_activeTimeline->projectView()->slotAddEffect(effectToAdd, pos, track);
622 }
623
624 void MainWindow::slotRaiseMonitor(bool clipMonitor)
625 {
626     if (clipMonitor) m_clipMonitorDock->raise();
627     else m_projectMonitorDock->raise();
628 }
629
630 void MainWindow::slotUpdateClip(const QString &id)
631 {
632     if (!m_activeDocument) return;
633     m_activeTimeline->projectView()->slotUpdateClip(id);
634 }
635
636 void MainWindow::slotConnectMonitors()
637 {
638
639     m_projectList->setRenderer(m_projectMonitor->render);
640     //connect(m_projectList, SIGNAL(receivedClipDuration(const QString &)), this, SLOT(slotUpdateClip(const QString &)));
641     connect(m_projectList, SIGNAL(showClipProperties(DocClipBase *)), this, SLOT(slotShowClipProperties(DocClipBase *)));
642     connect(m_projectList, SIGNAL(getFileProperties(const QDomElement, const QString &, bool)), m_projectMonitor->render, SLOT(getFileProperties(const QDomElement, const QString &, bool)));
643     connect(m_projectMonitor->render, SIGNAL(replyGetImage(const QString &, const QPixmap &)), m_projectList, SLOT(slotReplyGetImage(const QString &, const QPixmap &)));
644     connect(m_projectMonitor->render, SIGNAL(replyGetFileProperties(const QString &, Mlt::Producer*, const QMap < QString, QString > &, const QMap < QString, QString > &, bool)), m_projectList, SLOT(slotReplyGetFileProperties(const QString &, Mlt::Producer*, const QMap < QString, QString > &, const QMap < QString, QString > &, bool)));
645
646     connect(m_projectMonitor->render, SIGNAL(removeInvalidClip(const QString &, bool)), m_projectList, SLOT(slotRemoveInvalidClip(const QString &, bool)));
647
648     connect(m_clipMonitor, SIGNAL(refreshClipThumbnail(const QString &)), m_projectList, SLOT(slotRefreshClipThumbnail(const QString &)));
649
650     connect(m_clipMonitor, SIGNAL(adjustMonitorSize()), this, SLOT(slotAdjustClipMonitor()));
651     connect(m_projectMonitor, SIGNAL(adjustMonitorSize()), this, SLOT(slotAdjustProjectMonitor()));
652
653     connect(m_clipMonitor, SIGNAL(saveZone(Render *, QPoint)), this, SLOT(slotSaveZone(Render *, QPoint)));
654     connect(m_projectMonitor, SIGNAL(saveZone(Render *, QPoint)), this, SLOT(slotSaveZone(Render *, QPoint)));
655 }
656
657 void MainWindow::slotAdjustClipMonitor()
658 {
659     m_clipMonitorDock->updateGeometry();
660     m_clipMonitorDock->adjustSize();
661     m_clipMonitor->resetSize();
662 }
663
664 void MainWindow::slotAdjustProjectMonitor()
665 {
666     m_projectMonitorDock->updateGeometry();
667     m_projectMonitorDock->adjustSize();
668     m_projectMonitor->resetSize();
669 }
670
671 void MainWindow::setupActions()
672 {
673
674     KActionCollection* collection = actionCollection();
675     m_timecodeFormat = new KComboBox(this);
676     m_timecodeFormat->addItem(i18n("hh:mm:ss::ff"));
677     m_timecodeFormat->addItem(i18n("Frames"));
678     if (KdenliveSettings::frametimecode()) m_timecodeFormat->setCurrentIndex(1);
679     connect(m_timecodeFormat, SIGNAL(activated(int)), this, SLOT(slotUpdateTimecodeFormat(int)));
680
681     m_statusProgressBar = new QProgressBar(this);
682     m_statusProgressBar->setMinimum(0);
683     m_statusProgressBar->setMaximum(100);
684     m_statusProgressBar->setMaximumWidth(150);
685     m_statusProgressBar->setVisible(false);
686
687     KToolBar *toolbar = new KToolBar("statusToolBar", this, Qt::BottomToolBarArea);
688     toolbar->setMovable(false);
689     m_toolGroup = new QActionGroup(this);
690     statusBar()->setStyleSheet(QString("QStatusBar QLabel {font-size:%1pt;} QStatusBar::item { border: 0px; font-size:%1pt;padding:0px; }").arg(statusBar()->font().pointSize()));
691     QString style1 = "QToolBar { border: 0px } QToolButton {background-color: rgba(230, 230, 230, 220); border-style: inset; border:1px solid #999999;border-radius: 3px;margin: 0px 3px;padding: 0px;} QToolButton:checked { background-color: rgba(224, 224, 0, 100); border-style: inset; border:1px solid #cc6666;border-radius: 3px;}";
692
693     m_buttonSelectTool = new KAction(KIcon("kdenlive-select-tool"), i18n("Selection tool"), this);
694     m_buttonSelectTool->setShortcut(i18nc("Selection tool shortcut", "s"));
695     toolbar->addAction(m_buttonSelectTool);
696     m_buttonSelectTool->setCheckable(true);
697     m_buttonSelectTool->setChecked(true);
698
699     m_buttonRazorTool = new KAction(KIcon("edit-cut"), i18n("Razor tool"), this);
700     m_buttonRazorTool->setShortcut(i18nc("Razor tool shortcut", "x"));
701     toolbar->addAction(m_buttonRazorTool);
702     m_buttonRazorTool->setCheckable(true);
703     m_buttonRazorTool->setChecked(false);
704
705     m_buttonSpacerTool = new KAction(KIcon("kdenlive-spacer-tool"), i18n("Spacer tool"), this);
706     m_buttonSpacerTool->setShortcut(i18nc("Spacer tool shortcut", "m"));
707     toolbar->addAction(m_buttonSpacerTool);
708     m_buttonSpacerTool->setCheckable(true);
709     m_buttonSpacerTool->setChecked(false);
710
711     m_toolGroup->addAction(m_buttonSelectTool);
712     m_toolGroup->addAction(m_buttonRazorTool);
713     m_toolGroup->addAction(m_buttonSpacerTool);
714     m_toolGroup->setExclusive(true);
715     toolbar->setToolButtonStyle(Qt::ToolButtonIconOnly);
716
717     QWidget * actionWidget;
718     int max = toolbar->iconSizeDefault() + 2;
719     actionWidget = toolbar->widgetForAction(m_buttonSelectTool);
720     actionWidget->setMaximumWidth(max);
721     actionWidget->setMaximumHeight(max - 4);
722
723     actionWidget = toolbar->widgetForAction(m_buttonRazorTool);
724     actionWidget->setMaximumWidth(max);
725     actionWidget->setMaximumHeight(max - 4);
726
727     actionWidget = toolbar->widgetForAction(m_buttonSpacerTool);
728     actionWidget->setMaximumWidth(max);
729     actionWidget->setMaximumHeight(max - 4);
730
731     toolbar->setStyleSheet(style1);
732     connect(m_toolGroup, SIGNAL(triggered(QAction *)), this, SLOT(slotChangeTool(QAction *)));
733
734     toolbar->addSeparator();
735     m_buttonFitZoom = new KAction(KIcon("zoom-fit-best"), i18n("Fit zoom to project"), this);
736     toolbar->addAction(m_buttonFitZoom);
737     m_buttonFitZoom->setCheckable(false);
738     connect(m_buttonFitZoom, SIGNAL(triggered()), this, SLOT(slotFitZoom()));
739
740     actionWidget = toolbar->widgetForAction(m_buttonFitZoom);
741     actionWidget->setMaximumWidth(max);
742     actionWidget->setMaximumHeight(max - 4);
743
744     m_zoomSlider = new QSlider(Qt::Horizontal, this);
745     m_zoomSlider->setMaximum(13);
746     m_zoomSlider->setPageStep(1);
747
748     m_zoomSlider->setMaximumWidth(150);
749     m_zoomSlider->setMinimumWidth(100);
750     toolbar->addWidget(m_zoomSlider);
751
752     m_buttonVideoThumbs = new KAction(KIcon("kdenlive-show-videothumb"), i18n("Show video thumbnails"), this);
753     toolbar->addAction(m_buttonVideoThumbs);
754     m_buttonVideoThumbs->setCheckable(true);
755     m_buttonVideoThumbs->setChecked(KdenliveSettings::videothumbnails());
756     connect(m_buttonVideoThumbs, SIGNAL(triggered()), this, SLOT(slotSwitchVideoThumbs()));
757
758     m_buttonAudioThumbs = new KAction(KIcon("kdenlive-show-audiothumb"), i18n("Show audio thumbnails"), this);
759     toolbar->addAction(m_buttonAudioThumbs);
760     m_buttonAudioThumbs->setCheckable(true);
761     m_buttonAudioThumbs->setChecked(KdenliveSettings::audiothumbnails());
762     connect(m_buttonAudioThumbs, SIGNAL(triggered()), this, SLOT(slotSwitchAudioThumbs()));
763
764     m_buttonShowMarkers = new KAction(KIcon("kdenlive-show-markers"), i18n("Show markers comments"), this);
765     toolbar->addAction(m_buttonShowMarkers);
766     m_buttonShowMarkers->setCheckable(true);
767     m_buttonShowMarkers->setChecked(KdenliveSettings::showmarkers());
768     connect(m_buttonShowMarkers, SIGNAL(triggered()), this, SLOT(slotSwitchMarkersComments()));
769
770     m_buttonSnap = new KAction(KIcon("kdenlive-snap"), i18n("Snap"), this);
771     toolbar->addAction(m_buttonSnap);
772     m_buttonSnap->setCheckable(true);
773     m_buttonSnap->setChecked(KdenliveSettings::snaptopoints());
774     connect(m_buttonSnap, SIGNAL(triggered()), this, SLOT(slotSwitchSnap()));
775
776     actionWidget = toolbar->widgetForAction(m_buttonVideoThumbs);
777     actionWidget->setMaximumWidth(max);
778     actionWidget->setMaximumHeight(max - 4);
779
780     actionWidget = toolbar->widgetForAction(m_buttonAudioThumbs);
781     actionWidget->setMaximumWidth(max);
782     actionWidget->setMaximumHeight(max - 4);
783
784     actionWidget = toolbar->widgetForAction(m_buttonShowMarkers);
785     actionWidget->setMaximumWidth(max);
786     actionWidget->setMaximumHeight(max - 4);
787
788     actionWidget = toolbar->widgetForAction(m_buttonSnap);
789     actionWidget->setMaximumWidth(max);
790     actionWidget->setMaximumHeight(max - 4);
791
792     m_messageLabel = new StatusBarMessageLabel(this);
793     m_messageLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::MinimumExpanding);
794
795     statusBar()->addWidget(m_messageLabel, 10);
796     statusBar()->addWidget(m_statusProgressBar, 0);
797     statusBar()->addPermanentWidget(toolbar);
798     statusBar()->insertPermanentFixedItem("00:00:00:00", ID_TIMELINE_POS);
799     statusBar()->addPermanentWidget(m_timecodeFormat);
800     //statusBar()->setMaximumHeight(statusBar()->font().pointSize() * 3);
801
802     collection->addAction("select_tool", m_buttonSelectTool);
803     collection->addAction("razor_tool", m_buttonRazorTool);
804     collection->addAction("spacer_tool", m_buttonSpacerTool);
805
806     collection->addAction("show_video_thumbs", m_buttonVideoThumbs);
807     collection->addAction("show_audio_thumbs", m_buttonAudioThumbs);
808     collection->addAction("show_markers", m_buttonShowMarkers);
809     collection->addAction("snap", m_buttonSnap);
810     collection->addAction("zoom_fit", m_buttonFitZoom);
811
812     KAction* zoomIn = new KAction(KIcon("zoom-in"), i18n("Zoom In"), this);
813     collection->addAction("zoom_in", zoomIn);
814     connect(zoomIn, SIGNAL(triggered(bool)), this, SLOT(slotZoomIn()));
815     zoomIn->setShortcut(Qt::CTRL + Qt::Key_Plus);
816
817     KAction* zoomOut = new KAction(KIcon("zoom-out"), i18n("Zoom Out"), this);
818     collection->addAction("zoom_out", zoomOut);
819     connect(zoomOut, SIGNAL(triggered(bool)), this, SLOT(slotZoomOut()));
820     zoomOut->setShortcut(Qt::CTRL + Qt::Key_Minus);
821
822     m_projectSearch = new KAction(KIcon("edit-find"), i18n("Find"), this);
823     collection->addAction("project_find", m_projectSearch);
824     connect(m_projectSearch, SIGNAL(triggered(bool)), this, SLOT(slotFind()));
825     m_projectSearch->setShortcut(Qt::Key_Slash);
826
827     m_projectSearchNext = new KAction(KIcon("go-down-search"), i18n("Find Next"), this);
828     collection->addAction("project_find_next", m_projectSearchNext);
829     connect(m_projectSearchNext, SIGNAL(triggered(bool)), this, SLOT(slotFindNext()));
830     m_projectSearchNext->setShortcut(Qt::Key_F3);
831     m_projectSearchNext->setEnabled(false);
832
833     KAction* profilesAction = new KAction(KIcon("document-new"), i18n("Manage Project Profiles"), this);
834     collection->addAction("manage_profiles", profilesAction);
835     connect(profilesAction, SIGNAL(triggered(bool)), this, SLOT(slotEditProfiles()));
836
837     KNS::standardAction(i18n("Download New Wipes..."), this, SLOT(slotGetNewLumaStuff()), actionCollection(), "get_new_lumas");
838
839     KNS::standardAction(i18n("Download New Render Profiles..."), this, SLOT(slotGetNewRenderStuff()), actionCollection(), "get_new_profiles");
840
841     KNS::standardAction(i18n("Download New Project Profiles..."), this, SLOT(slotGetNewMltProfileStuff()), actionCollection(), "get_new_mlt_profiles");
842
843     KAction* wizAction = new KAction(KIcon("configure"), i18n("Run Config Wizard"), this);
844     collection->addAction("run_wizard", wizAction);
845     connect(wizAction, SIGNAL(triggered(bool)), this, SLOT(slotRunWizard()));
846
847     KAction* projectAction = new KAction(KIcon("configure"), i18n("Project Settings"), this);
848     collection->addAction("project_settings", projectAction);
849     connect(projectAction, SIGNAL(triggered(bool)), this, SLOT(slotEditProjectSettings()));
850
851     KAction* projectRender = new KAction(KIcon("media-record"), i18n("Render"), this);
852     collection->addAction("project_render", projectRender);
853     projectRender->setShortcut(Qt::CTRL + Qt::Key_Return);
854     connect(projectRender, SIGNAL(triggered(bool)), this, SLOT(slotRenderProject()));
855
856     KAction* projectClean = new KAction(KIcon("edit-clear"), i18n("Clean Project"), this);
857     collection->addAction("project_clean", projectClean);
858     connect(projectClean, SIGNAL(triggered(bool)), this, SLOT(slotCleanProject()));
859
860     KAction* monitorPlay = new KAction(KIcon("media-playback-start"), i18n("Play"), this);
861     KShortcut playShortcut;
862     playShortcut.setPrimary(Qt::Key_Space);
863     playShortcut.setAlternate(Qt::Key_K);
864     monitorPlay->setShortcut(playShortcut);
865     collection->addAction("monitor_play", monitorPlay);
866     connect(monitorPlay, SIGNAL(triggered(bool)), m_monitorManager, SLOT(slotPlay()));
867
868     m_playZone = new KAction(KIcon("media-playback-start"), i18n("Play Zone"), this);
869     m_playZone->setShortcut(Qt::CTRL + Qt::Key_Space);
870     collection->addAction("monitor_play_zone", m_playZone);
871     connect(m_playZone, SIGNAL(triggered(bool)), m_monitorManager, SLOT(slotPlayZone()));
872
873     m_loopZone = new KAction(KIcon("media-playback-start"), i18n("Loop Zone"), this);
874     m_loopZone->setShortcut(Qt::ALT + Qt::Key_Space);
875     collection->addAction("monitor_loop_zone", m_loopZone);
876     connect(m_loopZone, SIGNAL(triggered(bool)), m_monitorManager, SLOT(slotLoopZone()));
877
878     KAction *dvdWizard =  new KAction(KIcon("media-optical"), i18n("DVD Wizard"), this);
879     collection->addAction("dvd_wizard", dvdWizard);
880     connect(dvdWizard, SIGNAL(triggered(bool)), this, SLOT(slotDvdWizard()));
881
882     KAction *transcodeClip =  new KAction(KIcon("edit-copy"), i18n("Transcode Clips"), this);
883     collection->addAction("transcode_clip", transcodeClip);
884     connect(transcodeClip, SIGNAL(triggered(bool)), this, SLOT(slotTranscodeClip()));
885
886     KAction *markIn = collection->addAction("mark_in");
887     markIn->setText(i18n("Set In Point"));
888     markIn->setShortcut(Qt::Key_I);
889     connect(markIn, SIGNAL(triggered(bool)), this, SLOT(slotSetInPoint()));
890
891     KAction *markOut = collection->addAction("mark_out");
892     markOut->setText(i18n("Set Out Point"));
893     markOut->setShortcut(Qt::Key_O);
894     connect(markOut, SIGNAL(triggered(bool)), this, SLOT(slotSetOutPoint()));
895
896     KAction* monitorSeekBackward = new KAction(KIcon("media-seek-backward"), i18n("Rewind"), this);
897     monitorSeekBackward->setShortcut(Qt::Key_J);
898     collection->addAction("monitor_seek_backward", monitorSeekBackward);
899     connect(monitorSeekBackward, SIGNAL(triggered(bool)), m_monitorManager, SLOT(slotRewind()));
900
901     KAction* monitorSeekBackwardOneFrame = new KAction(KIcon("media-skip-backward"), i18n("Rewind 1 Frame"), this);
902     monitorSeekBackwardOneFrame->setShortcut(Qt::Key_Left);
903     collection->addAction("monitor_seek_backward-one-frame", monitorSeekBackwardOneFrame);
904     connect(monitorSeekBackwardOneFrame, SIGNAL(triggered(bool)), m_monitorManager, SLOT(slotRewindOneFrame()));
905
906     KAction* monitorSeekBackwardOneSecond = new KAction(KIcon("media-skip-backward"), i18n("Rewind 1 Second"), this);
907     monitorSeekBackwardOneSecond->setShortcut(Qt::SHIFT + Qt::Key_Left);
908     collection->addAction("monitor_seek_backward-one-second", monitorSeekBackwardOneSecond);
909     connect(monitorSeekBackwardOneSecond, SIGNAL(triggered(bool)), m_monitorManager, SLOT(slotRewindOneSecond()));
910
911     KAction* monitorSeekSnapBackward = new KAction(KIcon("media-seek-backward"), i18n("Go to Previous Snap Point"), this);
912     monitorSeekSnapBackward->setShortcut(Qt::ALT + Qt::Key_Left);
913     collection->addAction("monitor_seek_snap_backward", monitorSeekSnapBackward);
914     connect(monitorSeekSnapBackward, SIGNAL(triggered(bool)), this, SLOT(slotSnapRewind()));
915
916     KAction* monitorSeekForward = new KAction(KIcon("media-seek-forward"), i18n("Forward"), this);
917     monitorSeekForward->setShortcut(Qt::Key_L);
918     collection->addAction("monitor_seek_forward", monitorSeekForward);
919     connect(monitorSeekForward, SIGNAL(triggered(bool)), m_monitorManager, SLOT(slotForward()));
920
921     KAction* clipStart = new KAction(KIcon("media-seek-backward"), i18n("Go to Clip Start"), this);
922     clipStart->setShortcut(Qt::Key_Home);
923     collection->addAction("seek_clip_start", clipStart);
924     connect(clipStart, SIGNAL(triggered(bool)), this, SLOT(slotClipStart()));
925
926     KAction* clipEnd = new KAction(KIcon("media-seek-forward"), i18n("Go to Clip End"), this);
927     clipEnd->setShortcut(Qt::Key_End);
928     collection->addAction("seek_clip_end", clipEnd);
929     connect(clipEnd, SIGNAL(triggered(bool)), this, SLOT(slotClipEnd()));
930
931     KAction* projectStart = new KAction(KIcon("go-first"), i18n("Go to Project Start"), this);
932     projectStart->setShortcut(Qt::CTRL + Qt::Key_Home);
933     collection->addAction("seek_start", projectStart);
934     connect(projectStart, SIGNAL(triggered(bool)), m_monitorManager, SLOT(slotStart()));
935
936     KAction* projectEnd = new KAction(KIcon("go-last"), i18n("Go to Project End"), this);
937     projectEnd->setShortcut(Qt::CTRL + Qt::Key_End);
938     collection->addAction("seek_end", projectEnd);
939     connect(projectEnd, SIGNAL(triggered(bool)), m_monitorManager, SLOT(slotEnd()));
940
941     KAction* monitorSeekForwardOneFrame = new KAction(KIcon("media-skip-forward"), i18n("Forward 1 Frame"), this);
942     monitorSeekForwardOneFrame->setShortcut(Qt::Key_Right);
943     collection->addAction("monitor_seek_forward-one-frame", monitorSeekForwardOneFrame);
944     connect(monitorSeekForwardOneFrame, SIGNAL(triggered(bool)), m_monitorManager, SLOT(slotForwardOneFrame()));
945
946     KAction* monitorSeekForwardOneSecond = new KAction(KIcon("media-skip-forward"), i18n("Forward 1 Second"), this);
947     monitorSeekForwardOneSecond->setShortcut(Qt::SHIFT + Qt::Key_Right);
948     collection->addAction("monitor_seek_forward-one-second", monitorSeekForwardOneSecond);
949     connect(monitorSeekForwardOneSecond, SIGNAL(triggered(bool)), m_monitorManager, SLOT(slotForwardOneSecond()));
950
951     KAction* monitorSeekSnapForward = new KAction(KIcon("media-seek-forward"), i18n("Go to Next Snap Point"), this);
952     monitorSeekSnapForward->setShortcut(Qt::ALT + Qt::Key_Right);
953     collection->addAction("monitor_seek_snap_forward", monitorSeekSnapForward);
954     connect(monitorSeekSnapForward, SIGNAL(triggered(bool)), this, SLOT(slotSnapForward()));
955
956     KAction* deleteTimelineClip = new KAction(KIcon("edit-delete"), i18n("Delete Selected Item"), this);
957     deleteTimelineClip->setShortcut(Qt::Key_Delete);
958     collection->addAction("delete_timeline_clip", deleteTimelineClip);
959     connect(deleteTimelineClip, SIGNAL(triggered(bool)), this, SLOT(slotDeleteTimelineClip()));
960
961     /*KAction* editTimelineClipSpeed = new KAction(i18n("Change Clip Speed"), this);
962     collection->addAction("change_clip_speed", editTimelineClipSpeed);
963     editTimelineClipSpeed->setData("change_speed");
964     connect(editTimelineClipSpeed, SIGNAL(triggered(bool)), this, SLOT(slotChangeClipSpeed()));*/
965
966     KAction *stickTransition = collection->addAction("auto_transition");
967     stickTransition->setData(QString("auto"));
968     stickTransition->setCheckable(true);
969     stickTransition->setEnabled(false);
970     stickTransition->setText(i18n("Automatic Transition"));
971     connect(stickTransition, SIGNAL(triggered(bool)), this, SLOT(slotAutoTransition()));
972
973     KAction* groupClip = new KAction(KIcon("object-group"), i18n("Group Clips"), this);
974     groupClip->setShortcut(Qt::CTRL + Qt::Key_G);
975     collection->addAction("group_clip", groupClip);
976     connect(groupClip, SIGNAL(triggered(bool)), this, SLOT(slotGroupClips()));
977
978     KAction* ungroupClip = new KAction(KIcon("object-ungroup"), i18n("Ungroup Clips"), this);
979     collection->addAction("ungroup_clip", ungroupClip);
980     ungroupClip->setShortcut(Qt::CTRL + Qt::SHIFT + Qt::Key_G);
981     ungroupClip->setData("ungroup_clip");
982     connect(ungroupClip, SIGNAL(triggered(bool)), this, SLOT(slotUnGroupClips()));
983
984     KAction* cutTimelineClip = new KAction(KIcon("edit-cut"), i18n("Cut Clip"), this);
985     cutTimelineClip->setShortcut(Qt::SHIFT + Qt::Key_R);
986     collection->addAction("cut_timeline_clip", cutTimelineClip);
987     connect(cutTimelineClip, SIGNAL(triggered(bool)), this, SLOT(slotCutTimelineClip()));
988
989     KAction* addClipMarker = new KAction(KIcon("bookmark-new"), i18n("Add Marker"), this);
990     collection->addAction("add_clip_marker", addClipMarker);
991     connect(addClipMarker, SIGNAL(triggered(bool)), this, SLOT(slotAddClipMarker()));
992
993     KAction* deleteClipMarker = new KAction(KIcon("edit-delete"), i18n("Delete Marker"), this);
994     collection->addAction("delete_clip_marker", deleteClipMarker);
995     connect(deleteClipMarker, SIGNAL(triggered(bool)), this, SLOT(slotDeleteClipMarker()));
996
997     KAction* deleteAllClipMarkers = new KAction(KIcon("edit-delete"), i18n("Delete All Markers"), this);
998     collection->addAction("delete_all_clip_markers", deleteAllClipMarkers);
999     connect(deleteAllClipMarkers, SIGNAL(triggered(bool)), this, SLOT(slotDeleteAllClipMarkers()));
1000
1001     KAction* editClipMarker = new KAction(KIcon("document-properties"), i18n("Edit Marker"), this);
1002     collection->addAction("edit_clip_marker", editClipMarker);
1003     connect(editClipMarker, SIGNAL(triggered(bool)), this, SLOT(slotEditClipMarker()));
1004
1005     KAction* splitAudio = new KAction(KIcon("document-new"), i18n("Split Audio"), this);
1006     collection->addAction("split_audio", splitAudio);
1007     connect(splitAudio, SIGNAL(triggered(bool)), this, SLOT(slotSplitAudio()));
1008
1009     KAction* audioOnly = new KAction(KIcon("document-new"), i18n("Audio Only"), this);
1010     collection->addAction("clip_audio_only", audioOnly);
1011     audioOnly->setData("clip_audio_only");
1012     audioOnly->setCheckable(true);
1013
1014     KAction* videoOnly = new KAction(KIcon("document-new"), i18n("Video Only"), this);
1015     collection->addAction("clip_video_only", videoOnly);
1016     videoOnly->setData("clip_video_only");
1017     videoOnly->setCheckable(true);
1018
1019     KAction* audioAndVideo = new KAction(KIcon("document-new"), i18n("Audio and Video"), this);
1020     collection->addAction("clip_audio_and_video", audioAndVideo);
1021     audioAndVideo->setData("clip_audio_and_video");
1022     audioAndVideo->setCheckable(true);
1023
1024     m_clipTypeGroup = new QActionGroup(this);
1025     m_clipTypeGroup->addAction(audioOnly);
1026     m_clipTypeGroup->addAction(videoOnly);
1027     m_clipTypeGroup->addAction(audioAndVideo);
1028     connect(m_clipTypeGroup, SIGNAL(triggered(QAction *)), this, SLOT(slotUpdateClipType(QAction *)));
1029     m_clipTypeGroup->setEnabled(false);
1030
1031     KAction *insertSpace = new KAction(KIcon(), i18n("Insert Space"), this);
1032     collection->addAction("insert_space", insertSpace);
1033     connect(insertSpace, SIGNAL(triggered()), this, SLOT(slotInsertSpace()));
1034
1035     KAction *removeSpace = new KAction(KIcon(), i18n("Remove Space"), this);
1036     collection->addAction("delete_space", removeSpace);
1037     connect(removeSpace, SIGNAL(triggered()), this, SLOT(slotRemoveSpace()));
1038
1039     KAction *insertTrack = new KAction(KIcon(), i18n("Insert Track"), this);
1040     collection->addAction("insert_track", insertTrack);
1041     connect(insertTrack, SIGNAL(triggered()), this, SLOT(slotInsertTrack()));
1042
1043     KAction *deleteTrack = new KAction(KIcon(), i18n("Delete Track"), this);
1044     collection->addAction("delete_track", deleteTrack);
1045     connect(deleteTrack, SIGNAL(triggered()), this, SLOT(slotDeleteTrack()));
1046
1047     KAction *changeTrack = new KAction(KIcon(), i18n("Change Track"), this);
1048     collection->addAction("change_track", changeTrack);
1049     connect(changeTrack, SIGNAL(triggered()), this, SLOT(slotChangeTrack()));
1050
1051     KAction *addGuide = new KAction(KIcon("document-new"), i18n("Add Guide"), this);
1052     collection->addAction("add_guide", addGuide);
1053     connect(addGuide, SIGNAL(triggered()), this, SLOT(slotAddGuide()));
1054
1055     QAction *delGuide = new KAction(KIcon("edit-delete"), i18n("Delete Guide"), this);
1056     collection->addAction("delete_guide", delGuide);
1057     connect(delGuide, SIGNAL(triggered()), this, SLOT(slotDeleteGuide()));
1058
1059     QAction *editGuide = new KAction(KIcon("document-properties"), i18n("Edit Guide"), this);
1060     collection->addAction("edit_guide", editGuide);
1061     connect(editGuide, SIGNAL(triggered()), this, SLOT(slotEditGuide()));
1062
1063     QAction *delAllGuides = new KAction(KIcon("edit-delete"), i18n("Delete All Guides"), this);
1064     collection->addAction("delete_all_guides", delAllGuides);
1065     connect(delAllGuides, SIGNAL(triggered()), this, SLOT(slotDeleteAllGuides()));
1066
1067     QAction *pasteEffects = new KAction(KIcon("edit-paste"), i18n("Paste Effects"), this);
1068     collection->addAction("paste_effects", pasteEffects);
1069     pasteEffects->setData("paste_effects");
1070     connect(pasteEffects , SIGNAL(triggered()), this, SLOT(slotPasteEffects()));
1071
1072     QAction *showTimeline = new KAction(i18n("Show Timeline"), this);
1073     collection->addAction("show_timeline", showTimeline);
1074     showTimeline->setCheckable(true);
1075     showTimeline->setChecked(true);
1076     connect(showTimeline, SIGNAL(triggered(bool)), this, SLOT(slotShowTimeline(bool)));
1077
1078     /*QAction *maxCurrent = new KAction(i18n("Maximize Current Widget"), this);
1079     collection->addAction("maximize_current", maxCurrent);
1080     maxCurrent->setCheckable(true);
1081     maxCurrent->setChecked(false);
1082     connect(maxCurrent, SIGNAL(triggered(bool)), this, SLOT(slotMaximizeCurrent(bool)));*/
1083
1084
1085     m_closeAction = KStandardAction::close(this, SLOT(closeCurrentDocument()), collection);
1086
1087     KStandardAction::quit(this, SLOT(queryQuit()), collection);
1088
1089     KStandardAction::open(this, SLOT(openFile()), collection);
1090
1091     m_saveAction = KStandardAction::save(this, SLOT(saveFile()), collection);
1092
1093     KStandardAction::saveAs(this, SLOT(saveFileAs()), collection);
1094
1095     KStandardAction::openNew(this, SLOT(newFile()), collection);
1096
1097     KStandardAction::preferences(this, SLOT(slotPreferences()), collection);
1098
1099     KStandardAction::configureNotifications(this , SLOT(configureNotifications()), collection);
1100
1101     KStandardAction::copy(this, SLOT(slotCopy()), collection);
1102
1103     KStandardAction::paste(this, SLOT(slotPaste()), collection);
1104
1105     KAction *undo = KStandardAction::undo(m_commandStack, SLOT(undo()), collection);
1106     undo->setEnabled(false);
1107     connect(m_commandStack, SIGNAL(canUndoChanged(bool)), undo, SLOT(setEnabled(bool)));
1108
1109     KAction *redo = KStandardAction::redo(m_commandStack, SLOT(redo()), collection);
1110     redo->setEnabled(false);
1111     connect(m_commandStack, SIGNAL(canRedoChanged(bool)), redo, SLOT(setEnabled(bool)));
1112
1113     KStandardAction::fullScreen(this, SLOT(slotFullScreen()), this, collection);
1114
1115     /*
1116     //TODO: Add status tooltip to actions ?
1117     connect(collection, SIGNAL(actionHovered(QAction*)),
1118             this, SLOT(slotDisplayActionMessage(QAction*)));*/
1119
1120
1121     QAction *addClip = new KAction(KIcon("kdenlive-add-clip"), i18n("Add Clip"), this);
1122     collection->addAction("add_clip", addClip);
1123     connect(addClip , SIGNAL(triggered()), m_projectList, SLOT(slotAddClip()));
1124
1125     QAction *addColorClip = new KAction(KIcon("kdenlive-add-color-clip"), i18n("Add Color Clip"), this);
1126     collection->addAction("add_color_clip", addColorClip);
1127     connect(addColorClip , SIGNAL(triggered()), m_projectList, SLOT(slotAddColorClip()));
1128
1129     QAction *addSlideClip = new KAction(KIcon("kdenlive-add-slide-clip"), i18n("Add Slideshow Clip"), this);
1130     collection->addAction("add_slide_clip", addSlideClip);
1131     connect(addSlideClip , SIGNAL(triggered()), m_projectList, SLOT(slotAddSlideshowClip()));
1132
1133     QAction *addTitleClip = new KAction(KIcon("kdenlive-add-text-clip"), i18n("Add Title Clip"), this);
1134     collection->addAction("add_text_clip", addTitleClip);
1135     connect(addTitleClip , SIGNAL(triggered()), m_projectList, SLOT(slotAddTitleClip()));
1136
1137     QAction *addTitleTemplateClip = new KAction(KIcon("kdenlive-add-text-clip"), i18n("Add Template Title"), this);
1138     collection->addAction("add_text_template_clip", addTitleTemplateClip);
1139     connect(addTitleTemplateClip , SIGNAL(triggered()), m_projectList, SLOT(slotAddTitleTemplateClip()));
1140
1141     QAction *addFolderButton = new KAction(KIcon("folder-new"), i18n("Create Folder"), this);
1142     collection->addAction("add_folder", addFolderButton);
1143     connect(addFolderButton , SIGNAL(triggered()), m_projectList, SLOT(slotAddFolder()));
1144
1145     QAction *clipProperties = new KAction(KIcon("document-edit"), i18n("Clip Properties"), this);
1146     collection->addAction("clip_properties", clipProperties);
1147     clipProperties->setData("clip_properties");
1148     connect(clipProperties , SIGNAL(triggered()), m_projectList, SLOT(slotEditClip()));
1149     clipProperties->setEnabled(false);
1150
1151     QAction *openClip = new KAction(KIcon("document-open"), i18n("Edit Clip"), this);
1152     collection->addAction("edit_clip", openClip);
1153     openClip->setData("edit_clip");
1154     connect(openClip , SIGNAL(triggered()), m_projectList, SLOT(slotOpenClip()));
1155     openClip->setEnabled(false);
1156
1157     QAction *deleteClip = new KAction(KIcon("edit-delete"), i18n("Delete Clip"), this);
1158     collection->addAction("delete_clip", deleteClip);
1159     deleteClip->setData("delete_clip");
1160     connect(deleteClip , SIGNAL(triggered()), m_projectList, SLOT(slotRemoveClip()));
1161     deleteClip->setEnabled(false);
1162
1163     QAction *reloadClip = new KAction(KIcon("view-refresh"), i18n("Reload Clip"), this);
1164     collection->addAction("reload_clip", reloadClip);
1165     reloadClip->setData("reload_clip");
1166     connect(reloadClip , SIGNAL(triggered()), m_projectList, SLOT(slotReloadClip()));
1167     reloadClip->setEnabled(false);
1168
1169     QMenu *addClips = new QMenu();
1170     addClips->addAction(addClip);
1171     addClips->addAction(addColorClip);
1172     addClips->addAction(addSlideClip);
1173     addClips->addAction(addTitleClip);
1174     addClips->addAction(addTitleTemplateClip);
1175     addClips->addAction(addFolderButton);
1176
1177     addClips->addAction(reloadClip);
1178     addClips->addAction(clipProperties);
1179     addClips->addAction(openClip);
1180     addClips->addAction(deleteClip);
1181     m_projectList->setupMenu(addClips, addClip);
1182
1183     //connect(collection, SIGNAL( clearStatusText() ),
1184     //statusBar(), SLOT( clear() ) );
1185 }
1186
1187 void MainWindow::slotDisplayActionMessage(QAction *a)
1188 {
1189     statusBar()->showMessage(a->data().toString(), 3000);
1190 }
1191
1192 void MainWindow::saveOptions()
1193 {
1194     KdenliveSettings::self()->writeConfig();
1195     KSharedConfigPtr config = KGlobal::config();
1196     m_fileOpenRecent->saveEntries(KConfigGroup(config, "Recent Files"));
1197     KConfigGroup treecolumns(config, "Project Tree");
1198     treecolumns.writeEntry("columns", m_projectList->headerInfo());
1199     config->sync();
1200 }
1201
1202 void MainWindow::readOptions()
1203 {
1204     KSharedConfigPtr config = KGlobal::config();
1205     m_fileOpenRecent->loadEntries(KConfigGroup(config, "Recent Files"));
1206     KConfigGroup initialGroup(config, "version");
1207     bool upgrade = false;
1208     if (initialGroup.exists()) {
1209         if (initialGroup.readEntry("version", QString()).section(' ', 0, 0) != QString(version).section(' ', 0, 0)) {
1210             upgrade = true;
1211         }
1212
1213         if (initialGroup.readEntry("version") == "0.7") {
1214             //Add new settings from 0.7.1
1215             if (KdenliveSettings::defaultprojectfolder().isEmpty()) {
1216                 QString path = QDir::homePath() + "/kdenlive";
1217                 if (KStandardDirs::makeDir(path)  == false) {
1218                     kDebug() << "/// ERROR CREATING PROJECT FOLDER: " << path;
1219                 } else KdenliveSettings::setDefaultprojectfolder(path);
1220             }
1221         }
1222
1223     }
1224
1225     if (!initialGroup.exists() || upgrade) {
1226         // this is our first run, show Wizard
1227         Wizard *w = new Wizard(upgrade, this);
1228         if (w->exec() == QDialog::Accepted && w->isOk()) {
1229             w->adjustSettings();
1230             initialGroup.writeEntry("version", version);
1231             delete w;
1232         } else {
1233             ::exit(1);
1234         }
1235     }
1236     KConfigGroup treecolumns(config, "Project Tree");
1237     const QByteArray state = treecolumns.readEntry("columns", QByteArray());
1238     if (!state.isEmpty())
1239         m_projectList->setHeaderInfo(state);
1240 }
1241
1242 void MainWindow::slotRunWizard()
1243 {
1244     Wizard *w = new Wizard(false, this);
1245     if (w->exec() == QDialog::Accepted && w->isOk()) {
1246         w->adjustSettings();
1247     }
1248     delete w;
1249 }
1250
1251 void MainWindow::newFile(bool showProjectSettings)
1252 {
1253     if (!m_timelineArea->isEnabled()) return;
1254     m_fileRevert->setEnabled(false);
1255     QString profileName;
1256     KUrl projectFolder;
1257     QPoint projectTracks(KdenliveSettings::videotracks(), KdenliveSettings::audiotracks());
1258     if (!showProjectSettings && m_timelineArea->count() == 0) {
1259         if (!KdenliveSettings::activatetabs()) closeCurrentDocument();
1260         profileName = KdenliveSettings::default_profile();
1261         projectFolder = KdenliveSettings::defaultprojectfolder();
1262     } else {
1263         ProjectSettings *w = new ProjectSettings(NULL, projectTracks.x(), projectTracks.y(), KdenliveSettings::defaultprojectfolder(), false, true, this);
1264         if (w->exec() != QDialog::Accepted) return;
1265         if (!KdenliveSettings::activatetabs()) closeCurrentDocument();
1266         KdenliveSettings::setVideothumbnails(w->enableVideoThumbs());
1267         m_buttonVideoThumbs->setChecked(KdenliveSettings::videothumbnails());
1268         KdenliveSettings::setAudiothumbnails(w->enableAudioThumbs());
1269         m_buttonAudioThumbs->setChecked(KdenliveSettings::audiothumbnails());
1270         profileName = w->selectedProfile();
1271         projectFolder = w->selectedFolder();
1272         projectTracks = w->tracks();
1273         delete w;
1274     }
1275     KdenliveDoc *doc = new KdenliveDoc(KUrl(), projectFolder, m_commandStack, profileName, projectTracks, m_projectMonitor->render, this);
1276     doc->m_autosave = new KAutoSaveFile(KUrl(), doc);
1277     bool ok;
1278     TrackView *trackView = new TrackView(doc, &ok, this);
1279     m_timelineArea->addTab(trackView, KIcon("kdenlive"), doc->description());
1280     if (!ok) {
1281         // MLT is broken
1282         m_timelineArea->setEnabled(false);
1283         m_projectList->setEnabled(false);
1284         m_monitorManager->slotBlockMonitors();
1285         slotPreferences(6);
1286         return;
1287     }
1288     if (m_timelineArea->count() == 1) {
1289         connectDocumentInfo(doc);
1290         connectDocument(trackView, doc);
1291     } else m_timelineArea->setTabBarHidden(false);
1292     m_closeAction->setEnabled(m_timelineArea->count() > 1);
1293 }
1294
1295 void MainWindow::activateDocument()
1296 {
1297     if (m_timelineArea->currentWidget() == NULL || !m_timelineArea->isEnabled()) return;
1298     TrackView *currentTab = (TrackView *) m_timelineArea->currentWidget();
1299     KdenliveDoc *currentDoc = currentTab->document();
1300     connectDocumentInfo(currentDoc);
1301     connectDocument(currentTab, currentDoc);
1302 }
1303
1304 void MainWindow::closeCurrentDocument(bool saveChanges)
1305 {
1306     QWidget *w = m_timelineArea->currentWidget();
1307     if (!w) return;
1308     // closing current document
1309     int ix = m_timelineArea->currentIndex() + 1;
1310     if (ix == m_timelineArea->count()) ix = 0;
1311     m_timelineArea->setCurrentIndex(ix);
1312     TrackView *tabToClose = (TrackView *) w;
1313     KdenliveDoc *docToClose = tabToClose->document();
1314     if (docToClose && docToClose->isModified() && saveChanges) {
1315         switch (KMessageBox::warningYesNoCancel(this, i18n("Save changes to document?"))) {
1316         case KMessageBox::Yes :
1317             // save document here. If saving fails, return false;
1318             if (saveFile() == false) return;
1319             break;
1320         case KMessageBox::Cancel :
1321             return;
1322             break;
1323         default:
1324             break;
1325         }
1326     }
1327     m_timelineArea->removeTab(m_timelineArea->indexOf(w));
1328     if (m_timelineArea->count() == 1) {
1329         m_timelineArea->setTabBarHidden(true);
1330         m_closeAction->setEnabled(false);
1331     }
1332     if (docToClose == m_activeDocument) {
1333         delete m_activeDocument;
1334         m_activeDocument = NULL;
1335         m_effectStack->clear();
1336         m_transitionConfig->slotTransitionItemSelected(NULL, 0, QPoint(), false);
1337     } else delete docToClose;
1338     if (w == m_activeTimeline) {
1339         delete m_activeTimeline;
1340         m_activeTimeline = NULL;
1341     } else delete w;
1342 }
1343
1344 bool MainWindow::saveFileAs(const QString &outputFileName)
1345 {
1346     QString currentSceneList;
1347     if (KdenliveSettings::dropbframes()) {
1348         KdenliveSettings::setDropbframes(false);
1349         m_activeDocument->clipManager()->updatePreviewSettings();
1350         currentSceneList = m_projectMonitor->sceneList();
1351         KdenliveSettings::setDropbframes(true);
1352         m_activeDocument->clipManager()->updatePreviewSettings();
1353     } else currentSceneList = m_projectMonitor->sceneList();
1354
1355     if (m_activeDocument->saveSceneList(outputFileName, currentSceneList) == false)
1356         return false;
1357
1358     // Save timeline thumbnails
1359     m_activeTimeline->projectView()->saveThumbnails();
1360     m_activeDocument->setUrl(KUrl(outputFileName));
1361     if (m_activeDocument->m_autosave == NULL) {
1362         m_activeDocument->m_autosave = new KAutoSaveFile(KUrl(outputFileName), this);
1363     } else m_activeDocument->m_autosave->setManagedFile(KUrl(outputFileName));
1364     setCaption(m_activeDocument->description());
1365     m_timelineArea->setTabText(m_timelineArea->currentIndex(), m_activeDocument->description());
1366     m_timelineArea->setTabToolTip(m_timelineArea->currentIndex(), m_activeDocument->url().path());
1367     m_activeDocument->setModified(false);
1368     m_fileOpenRecent->addUrl(KUrl(outputFileName));
1369     m_fileRevert->setEnabled(true);
1370     return true;
1371 }
1372
1373 bool MainWindow::saveFileAs()
1374 {
1375     // Check that the Kdenlive mime type is correctly installed
1376     QString mimetype = "application/x-kdenlive";
1377     KMimeType::Ptr mime = KMimeType::mimeType(mimetype);
1378     if (!mime) mimetype = "*.kdenlive";
1379
1380     QString outputFile = KFileDialog::getSaveFileName(KUrl(), mimetype);
1381     if (outputFile.isEmpty()) return false;
1382     if (QFile::exists(outputFile)) {
1383         if (KMessageBox::questionYesNo(this, i18n("File already exists.\nDo you want to overwrite it?")) == KMessageBox::No) return false;
1384     }
1385     return saveFileAs(outputFile);
1386 }
1387
1388 bool MainWindow::saveFile()
1389 {
1390     if (!m_activeDocument) return true;
1391     if (m_activeDocument->url().isEmpty()) {
1392         return saveFileAs();
1393     } else {
1394         bool result = saveFileAs(m_activeDocument->url().path());
1395         m_activeDocument->m_autosave->resize(0);
1396         return result;
1397     }
1398 }
1399
1400 void MainWindow::openFile()
1401 {
1402     if (!m_startUrl.isEmpty()) {
1403         openFile(m_startUrl);
1404         m_startUrl = KUrl();
1405         return;
1406     }
1407     // Check that the Kdenlive mime type is correctly installed
1408     QString mimetype = "application/x-kdenlive";
1409     KMimeType::Ptr mime = KMimeType::mimeType(mimetype);
1410     if (!mime) mimetype = "*.kdenlive";
1411
1412     KUrl url = KFileDialog::getOpenUrl(KUrl("kfiledialog:///projectfolder"), mimetype);
1413     if (url.isEmpty()) return;
1414     m_fileOpenRecent->addUrl(url);
1415     openFile(url);
1416 }
1417
1418 void MainWindow::openLastFile()
1419 {
1420     KSharedConfigPtr config = KGlobal::config();
1421     KUrl::List urls = m_fileOpenRecent->urls();
1422     //WARNING: this is buggy, we get a random url, not the last one. Bug in KRecentFileAction?
1423     if (urls.isEmpty()) newFile(false);
1424     else openFile(urls.last());
1425 }
1426
1427 void MainWindow::openFile(const KUrl &url)
1428 {
1429     // Check if the document is already opened
1430     const int ct = m_timelineArea->count();
1431     bool isOpened = false;
1432     int i;
1433     for (i = 0; i < ct; i++) {
1434         TrackView *tab = (TrackView *) m_timelineArea->widget(i);
1435         KdenliveDoc *doc = tab->document();
1436         if (doc->url() == url) {
1437             isOpened = true;
1438             break;
1439         }
1440     }
1441     if (isOpened) {
1442         m_timelineArea->setCurrentIndex(i);
1443         return;
1444     }
1445
1446     // Check for backup file
1447     QList<KAutoSaveFile *> staleFiles = KAutoSaveFile::staleFiles(url);
1448     if (!staleFiles.isEmpty()) {
1449         if (KMessageBox::questionYesNo(this,
1450                                        i18n("Auto-saved files exist. Do you want to recover them now?"),
1451                                        i18n("File Recovery"),
1452                                        KGuiItem(i18n("Recover")), KGuiItem(i18n("Don't recover"))) == KMessageBox::Yes) {
1453             recoverFiles(staleFiles);
1454             return;
1455         } else {
1456             // remove the stale files
1457             foreach(KAutoSaveFile *stale, staleFiles) {
1458                 stale->open(QIODevice::ReadWrite);
1459                 delete stale;
1460             }
1461         }
1462     }
1463     if (!KdenliveSettings::activatetabs()) closeCurrentDocument();
1464     m_messageLabel->setMessage(i18n("Opening file %1", url.path()), InformationMessage);
1465     qApp->processEvents();
1466     doOpenFile(url, NULL);
1467 }
1468
1469 void MainWindow::doOpenFile(const KUrl &url, KAutoSaveFile *stale)
1470 {
1471     if (!m_timelineArea->isEnabled()) return;
1472     m_fileRevert->setEnabled(true);
1473     KdenliveDoc *doc = new KdenliveDoc(url, KdenliveSettings::defaultprojectfolder(), m_commandStack, KdenliveSettings::default_profile(), QPoint(KdenliveSettings::videotracks(), KdenliveSettings::audiotracks()), m_projectMonitor->render, this);
1474     if (stale == NULL) {
1475         stale = new KAutoSaveFile(url, doc);
1476         doc->m_autosave = stale;
1477     } else {
1478         doc->m_autosave = stale;
1479         doc->setUrl(stale->managedFile());
1480         doc->setModified(true);
1481         stale->setParent(doc);
1482     }
1483     connectDocumentInfo(doc);
1484     bool ok;
1485     TrackView *trackView = new TrackView(doc, &ok, this);
1486     m_timelineArea->setCurrentIndex(m_timelineArea->addTab(trackView, KIcon("kdenlive"), doc->description()));
1487     if (!ok) {
1488         m_timelineArea->setEnabled(false);
1489         m_projectList->setEnabled(false);
1490         m_monitorManager->slotBlockMonitors();
1491         slotPreferences(6);
1492         return;
1493     }
1494     m_timelineArea->setTabToolTip(m_timelineArea->currentIndex(), doc->url().path());
1495     trackView->setDuration(trackView->duration());
1496     trackView->projectView()->initCursorPos(m_projectMonitor->render->seekPosition().frames(doc->fps()));
1497
1498     if (m_timelineArea->count() > 1) m_timelineArea->setTabBarHidden(false);
1499     slotGotProgressInfo(QString(), -1);
1500     m_clipMonitor->refreshMonitor(true);
1501     m_projectMonitor->adjustRulerSize(trackView->duration());
1502     m_projectMonitor->slotZoneMoved(trackView->inPoint(), trackView->outPoint());
1503 }
1504
1505 void MainWindow::recoverFiles(QList<KAutoSaveFile *> staleFiles)
1506 {
1507     if (!KdenliveSettings::activatetabs()) closeCurrentDocument();
1508     foreach(KAutoSaveFile *stale, staleFiles) {
1509         /*if (!stale->open(QIODevice::QIODevice::ReadOnly)) {
1510                   // show an error message; we could not steal the lockfile
1511                   // maybe another application got to the file before us?
1512                   delete stale;
1513                   continue;
1514         }*/
1515         kDebug() << "// OPENING RECOVERY: " << stale->fileName() << "\nMANAGED: " << stale->managedFile().path();
1516         // the stalefiles also contain ".lock" files so we must ignore them... bug in KAutoSaveFile?
1517         if (!stale->fileName().endsWith(".lock")) doOpenFile(KUrl(stale->fileName()), stale);
1518         else KIO::NetAccess::del(KUrl(stale->fileName()), this);
1519     }
1520 }
1521
1522
1523 void MainWindow::parseProfiles(const QString &mltPath)
1524 {
1525     // kDebug()<<" + + YOUR MLT INSTALL WAS FOUND IN: "<< MLT_PREFIX <<endl;
1526
1527     //KdenliveSettings::setDefaulttmpfolder();
1528     if (!mltPath.isEmpty()) {
1529         KdenliveSettings::setMltpath(mltPath + "/share/mlt/profiles/");
1530         KdenliveSettings::setRendererpath(mltPath + "/bin/melt");
1531     }
1532
1533     if (KdenliveSettings::mltpath().isEmpty()) {
1534         KdenliveSettings::setMltpath(QString(MLT_PREFIX) + QString("/share/mlt/profiles/"));
1535     }
1536     if (KdenliveSettings::rendererpath().isEmpty() || KdenliveSettings::rendererpath().endsWith("inigo")) {
1537         QString meltPath = QString(MLT_PREFIX) + QString("/bin/melt");
1538         if (!QFile::exists(meltPath))
1539             meltPath = KStandardDirs::findExe("melt");
1540         KdenliveSettings::setRendererpath(meltPath);
1541     }
1542     QStringList profilesFilter;
1543     profilesFilter << "*";
1544     QStringList profilesList = QDir(KdenliveSettings::mltpath()).entryList(profilesFilter, QDir::Files);
1545
1546     if (profilesList.isEmpty()) {
1547         // Cannot find MLT path, try finding melt
1548         QString profilePath = KdenliveSettings::rendererpath();
1549         if (!profilePath.isEmpty()) {
1550             profilePath = profilePath.section('/', 0, -3);
1551             KdenliveSettings::setMltpath(profilePath + "/share/mlt/profiles/");
1552             QStringList profilesList = QDir(KdenliveSettings::mltpath()).entryList(profilesFilter, QDir::Files);
1553         }
1554
1555         if (profilesList.isEmpty()) {
1556             // Cannot find the MLT profiles, ask for location
1557             KUrlRequesterDialog *getUrl = new KUrlRequesterDialog(KdenliveSettings::mltpath(), i18n("Cannot find your Mlt profiles, please give the path"), this);
1558             getUrl->fileDialog()->setMode(KFile::Directory);
1559             if (getUrl->exec() == QDialog::Rejected) {
1560                 ::exit(0);
1561             }
1562             KUrl mltPath = getUrl->selectedUrl();
1563             delete getUrl;
1564             if (mltPath.isEmpty()) ::exit(0);
1565             KdenliveSettings::setMltpath(mltPath.path(KUrl::AddTrailingSlash));
1566             QStringList profilesList = QDir(KdenliveSettings::mltpath()).entryList(profilesFilter, QDir::Files);
1567         }
1568     }
1569
1570     if (KdenliveSettings::rendererpath().isEmpty()) {
1571         // Cannot find the MLT melt renderer, ask for location
1572         KUrlRequesterDialog *getUrl = new KUrlRequesterDialog(QString(), i18n("Cannot find the melt program required for rendering (part of Mlt)"), this);
1573         if (getUrl->exec() == QDialog::Rejected) {
1574             ::exit(0);
1575         }
1576         KUrl rendererPath = getUrl->selectedUrl();
1577         delete getUrl;
1578         if (rendererPath.isEmpty()) ::exit(0);
1579         KdenliveSettings::setRendererpath(rendererPath.path());
1580     }
1581
1582     kDebug() << "RESULTING MLT PATH: " << KdenliveSettings::mltpath();
1583
1584     // Parse MLT profiles to build a list of available video formats
1585     if (profilesList.isEmpty()) parseProfiles();
1586 }
1587
1588
1589 void MainWindow::slotEditProfiles()
1590 {
1591     ProfilesDialog *w = new ProfilesDialog;
1592     if (w->exec() == QDialog::Accepted) {
1593         KdenliveSettingsDialog* d = static_cast <KdenliveSettingsDialog*>(KConfigDialog::exists("settings"));
1594         if (d) d->checkProfile();
1595     }
1596     delete w;
1597 }
1598
1599 void MainWindow::slotDetectAudioDriver()
1600 {
1601     /* WARNING: do not use this method because sometimes detects wrong driver (pulse instead of alsa),
1602     leading to no audio output, see bug #934 */
1603
1604     //decide which audio driver is really best, in some cases SDL is wrong
1605     if (KdenliveSettings::audiodrivername().isEmpty()) {
1606         QString driver;
1607         KProcess readProcess;
1608         //PulseAudio needs to be selected if it exists, the ALSA pulse pcm device is not fast enough.
1609         if (!KStandardDirs::findExe("pactl").isEmpty()) {
1610             readProcess.setOutputChannelMode(KProcess::OnlyStdoutChannel);
1611             readProcess.setProgram("pactl", QStringList() << "stat");
1612             readProcess.execute(2000); // Kill it after 2 seconds
1613
1614             QString result = QString(readProcess.readAllStandardOutput());
1615             kDebug() << "// / / / / / READING PACTL: ";
1616             kDebug() << result;
1617             if (!result.isEmpty()) {
1618                 driver = "pulse";
1619                 kDebug() << "// / / / / PULSEAUDIO DETECTED";
1620             }
1621         }
1622         //put others here
1623         KdenliveSettings::setAutoaudiodrivername(driver);
1624     }
1625 }
1626
1627 void MainWindow::slotEditProjectSettings()
1628 {
1629     QPoint p = m_activeDocument->getTracksCount();
1630     ProjectSettings *w = new ProjectSettings(m_activeDocument->clipManager(), p.x(), p.y(), m_activeDocument->projectFolder().path(), true, !m_activeDocument->isModified(), this);
1631
1632     if (w->exec() == QDialog::Accepted) {
1633         if (w->deleteUnused()) {
1634             // we are going to trash the unused clips
1635             m_projectList->trashUnusedClips();
1636         }
1637         QString profile = w->selectedProfile();
1638         m_activeDocument->setProjectFolder(w->selectedFolder());
1639         if (m_renderWidget) m_renderWidget->setDocumentPath(w->selectedFolder().path(KUrl::AddTrailingSlash));
1640         if (m_activeDocument->profilePath() != profile) {
1641             // Profile was changed
1642             double dar = m_activeDocument->dar();
1643
1644             // Deselect current effect / transition
1645             m_effectStack->slotClipItemSelected(NULL, 0);
1646             m_transitionConfig->slotTransitionItemSelected(NULL, 0, QPoint(), false);
1647             m_clipMonitor->slotSetXml(NULL, 0);
1648             bool updateFps = m_activeDocument->setProfilePath(profile);
1649             KdenliveSettings::setCurrent_profile(profile);
1650             KdenliveSettings::setProject_fps(m_activeDocument->fps());
1651             setCaption(m_activeDocument->description(), m_activeDocument->isModified());
1652
1653             m_activeDocument->clipManager()->clearUnusedProducers();
1654             m_monitorManager->resetProfiles(m_activeDocument->timecode());
1655
1656             m_transitionConfig->updateProjectFormat(m_activeDocument->mltProfile(), m_activeDocument->timecode(), m_activeTimeline->tracksNumber());
1657             m_effectStack->updateProjectFormat(m_activeDocument->mltProfile(), m_activeDocument->timecode());
1658             if (m_renderWidget) m_renderWidget->setProfile(m_activeDocument->mltProfile());
1659             m_timelineArea->setTabText(m_timelineArea->currentIndex(), m_activeDocument->description());
1660             //m_activeDocument->clipManager()->resetProducersList(m_projectMonitor->render->producersList());
1661             if (dar != m_activeDocument->dar()) m_projectList->reloadClipThumbnails();
1662             if (updateFps) m_activeTimeline->updateProjectFps();
1663             m_activeDocument->setModified(true);
1664             m_commandStack->activeStack()->clear();
1665             // We need to desactivate & reactivate monitors to get a refresh
1666             //m_monitorManager->switchMonitors();
1667         }
1668     }
1669     delete w;
1670 }
1671
1672
1673 void MainWindow::slotRenderProject()
1674 {
1675     if (!m_renderWidget) {
1676         QString projectfolder = m_activeDocument ? m_activeDocument->projectFolder().path(KUrl::AddTrailingSlash) : KdenliveSettings::defaultprojectfolder();
1677         m_renderWidget = new RenderWidget(projectfolder, this);
1678         connect(m_renderWidget, SIGNAL(shutdown()), this, SLOT(slotShutdown()));
1679         connect(m_renderWidget, SIGNAL(selectedRenderProfile(const QString &, const QString &, const QString&)), this, SLOT(slotSetDocumentRenderProfile(const QString &, const QString &, const QString&)));
1680         connect(m_renderWidget, SIGNAL(prepareRenderingData(bool, bool, const QString&)), this, SLOT(slotPrepareRendering(bool, bool, const QString&)));
1681         connect(m_renderWidget, SIGNAL(abortProcess(const QString &)), this, SIGNAL(abortRenderJob(const QString &)));
1682         connect(m_renderWidget, SIGNAL(openDvdWizard(const QString &, const QString &)), this, SLOT(slotDvdWizard(const QString &, const QString &)));
1683         if (m_activeDocument) {
1684             m_renderWidget->setProfile(m_activeDocument->mltProfile());
1685             m_renderWidget->setGuides(m_activeDocument->guidesXml(), m_activeDocument->projectDuration());
1686             m_renderWidget->setDocumentPath(m_activeDocument->projectFolder().path(KUrl::AddTrailingSlash));
1687             m_renderWidget->setRenderProfile(m_activeDocument->getDocumentProperty("renderdestination"), m_activeDocument->getDocumentProperty("renderprofile"), m_activeDocument->getDocumentProperty("renderurl"));
1688         }
1689     }
1690     /*TrackView *currentTab = (TrackView *) m_timelineArea->currentWidget();
1691     if (currentTab) m_renderWidget->setTimeline(currentTab);
1692     m_renderWidget->setDocument(m_activeDocument);*/
1693     m_renderWidget->show();
1694     m_renderWidget->showNormal();
1695 }
1696
1697 void MainWindow::setRenderingProgress(const QString &url, int progress)
1698 {
1699     if (m_renderWidget) m_renderWidget->setRenderJob(url, progress);
1700 }
1701
1702 void MainWindow::setRenderingFinished(const QString &url, int status, const QString &error)
1703 {
1704     if (m_renderWidget) m_renderWidget->setRenderStatus(url, status, error);
1705 }
1706
1707 void MainWindow::slotCleanProject()
1708 {
1709     if (KMessageBox::warningContinueCancel(this, i18n("This will remove all unused clips from your project."), i18n("Clean up project")) == KMessageBox::Cancel) return;
1710     m_projectList->cleanup();
1711 }
1712
1713 void MainWindow::slotUpdateMousePosition(int pos)
1714 {
1715     if (m_activeDocument)
1716         switch (m_timecodeFormat->currentIndex()) {
1717         case 0:
1718             statusBar()->changeItem(m_activeDocument->timecode().getTimecodeFromFrames(pos), ID_TIMELINE_POS);
1719             break;
1720         default:
1721             statusBar()->changeItem(QString::number(pos), ID_TIMELINE_POS);
1722         }
1723 }
1724
1725 void MainWindow::slotUpdateDocumentState(bool modified)
1726 {
1727     if (!m_activeDocument) return;
1728     setCaption(m_activeDocument->description(), modified);
1729     m_saveAction->setEnabled(modified);
1730     if (modified) {
1731         m_timelineArea->setTabTextColor(m_timelineArea->currentIndex(), palette().color(QPalette::Link));
1732         m_timelineArea->setTabIcon(m_timelineArea->currentIndex(), KIcon("document-save"));
1733     } else {
1734         m_timelineArea->setTabTextColor(m_timelineArea->currentIndex(), palette().color(QPalette::Text));
1735         m_timelineArea->setTabIcon(m_timelineArea->currentIndex(), KIcon("kdenlive"));
1736     }
1737 }
1738
1739 void MainWindow::connectDocumentInfo(KdenliveDoc *doc)
1740 {
1741     if (m_activeDocument) {
1742         if (m_activeDocument == doc) return;
1743         disconnect(m_activeDocument, SIGNAL(progressInfo(const QString &, int)), this, SLOT(slotGotProgressInfo(const QString &, int)));
1744     }
1745     connect(doc, SIGNAL(progressInfo(const QString &, int)), this, SLOT(slotGotProgressInfo(const QString &, int)));
1746 }
1747
1748 void MainWindow::connectDocument(TrackView *trackView, KdenliveDoc *doc)   //changed
1749 {
1750     //m_projectMonitor->stop();
1751     m_closeAction->setEnabled(m_timelineArea->count() > 1);
1752     kDebug() << "///////////////////   CONNECTING DOC TO PROJECT VIEW ////////////////";
1753     if (m_activeDocument) {
1754         if (m_activeDocument == doc) return;
1755         if (m_activeTimeline) {
1756             disconnect(m_projectMonitor, SIGNAL(renderPosition(int)), m_activeTimeline, SLOT(moveCursorPos(int)));
1757             disconnect(m_projectMonitor, SIGNAL(zoneUpdated(QPoint)), m_activeTimeline, SLOT(slotSetZone(QPoint)));
1758             disconnect(m_projectMonitor, SIGNAL(durationChanged(int)), m_activeTimeline, SLOT(setDuration(int)));
1759             disconnect(m_projectList, SIGNAL(projectModified()), m_activeDocument, SLOT(setModified()));
1760             disconnect(m_projectMonitor->render, SIGNAL(refreshDocumentProducers()), m_activeDocument, SLOT(checkProjectClips()));
1761
1762             disconnect(m_activeDocument, SIGNAL(guidesUpdated()), this, SLOT(slotGuidesUpdated()));
1763             disconnect(m_activeDocument, SIGNAL(addProjectClip(DocClipBase *, bool)), m_projectList, SLOT(slotAddClip(DocClipBase *, bool)));
1764             disconnect(m_activeDocument, SIGNAL(resetProjectList()), m_projectList, SLOT(slotResetProjectList()));
1765             disconnect(m_activeDocument, SIGNAL(signalDeleteProjectClip(const QString &)), m_projectList, SLOT(slotDeleteClip(const QString &)));
1766             disconnect(m_activeDocument, SIGNAL(updateClipDisplay(const QString &)), m_projectList, SLOT(slotUpdateClip(const QString &)));
1767             disconnect(m_activeDocument, SIGNAL(selectLastAddedClip(const QString &)), m_projectList, SLOT(slotSelectClip(const QString &)));
1768             disconnect(m_activeDocument, SIGNAL(deleteTimelineClip(const QString &)), m_activeTimeline, SLOT(slotDeleteClip(const QString &)));
1769             disconnect(m_activeTimeline->projectView(), SIGNAL(clipItemSelected(ClipItem*, int)), m_effectStack, SLOT(slotClipItemSelected(ClipItem*, int)));
1770             disconnect(m_activeTimeline->projectView(), SIGNAL(clipItemSelected(ClipItem*, int)), this, SLOT(slotActivateEffectStackView()));
1771             disconnect(m_activeTimeline->projectView(), SIGNAL(transitionItemSelected(Transition*, int, QPoint, bool)), m_transitionConfig, SLOT(slotTransitionItemSelected(Transition*, int, QPoint, bool)));
1772             disconnect(m_activeTimeline->projectView(), SIGNAL(transitionItemSelected(Transition*, int, QPoint, bool)), this, SLOT(slotActivateTransitionView(Transition *)));
1773             disconnect(m_zoomSlider, SIGNAL(valueChanged(int)), m_activeTimeline, SLOT(slotChangeZoom(int)));
1774             disconnect(m_activeTimeline->projectView(), SIGNAL(displayMessage(const QString&, MessageType)), m_messageLabel, SLOT(setMessage(const QString&, MessageType)));
1775             disconnect(m_activeTimeline->projectView(), SIGNAL(showClipFrame(DocClipBase *, const int)), m_clipMonitor, SLOT(slotSetXml(DocClipBase *, const int)));
1776             disconnect(m_activeTimeline, SIGNAL(cursorMoved()), m_projectMonitor, SLOT(activateMonitor()));
1777             disconnect(m_activeTimeline, SIGNAL(insertTrack(int)), this, SLOT(slotInsertTrack(int)));
1778             disconnect(m_activeTimeline, SIGNAL(deleteTrack(int)), this, SLOT(slotDeleteTrack(int)));
1779             disconnect(m_activeTimeline, SIGNAL(changeTrack(int)), this, SLOT(slotChangeTrack(int)));
1780             disconnect(m_activeDocument, SIGNAL(docModified(bool)), this, SLOT(slotUpdateDocumentState(bool)));
1781             disconnect(m_effectStack, SIGNAL(updateClipEffect(ClipItem*, QDomElement, QDomElement, int)), m_activeTimeline->projectView(), SLOT(slotUpdateClipEffect(ClipItem*, QDomElement, QDomElement, int)));
1782             disconnect(m_effectStack, SIGNAL(removeEffect(ClipItem*, QDomElement)), m_activeTimeline->projectView(), SLOT(slotDeleteEffect(ClipItem*, QDomElement)));
1783             disconnect(m_effectStack, SIGNAL(changeEffectState(ClipItem*, int, bool)), m_activeTimeline->projectView(), SLOT(slotChangeEffectState(ClipItem*, int, bool)));
1784             disconnect(m_effectStack, SIGNAL(changeEffectPosition(ClipItem*, int, int)), m_activeTimeline->projectView(), SLOT(slotChangeEffectPosition(ClipItem*, int, int)));
1785             disconnect(m_effectStack, SIGNAL(refreshEffectStack(ClipItem*)), m_activeTimeline->projectView(), SLOT(slotRefreshEffects(ClipItem*)));
1786             disconnect(m_effectStack, SIGNAL(reloadEffects()), this, SLOT(slotReloadEffects()));
1787             disconnect(m_transitionConfig, SIGNAL(transitionUpdated(Transition *, QDomElement)), m_activeTimeline->projectView() , SLOT(slotTransitionUpdated(Transition *, QDomElement)));
1788             disconnect(m_transitionConfig, SIGNAL(seekTimeline(int)), m_activeTimeline->projectView() , SLOT(setCursorPos(int)));
1789             disconnect(m_activeTimeline->projectView(), SIGNAL(activateDocumentMonitor()), m_projectMonitor, SLOT(activateMonitor()));
1790             disconnect(m_activeTimeline, SIGNAL(zoneMoved(int, int)), this, SLOT(slotZoneMoved(int, int)));
1791             disconnect(m_projectList, SIGNAL(loadingIsOver()), m_activeTimeline->projectView(), SLOT(slotUpdateAllThumbs()));
1792             disconnect(m_projectList, SIGNAL(displayMessage(const QString&, int)), this, SLOT(slotGotProgressInfo(const QString&, int)));
1793             m_effectStack->clear();
1794         }
1795         //m_activeDocument->setRenderer(NULL);
1796         disconnect(m_projectList, SIGNAL(clipSelected(DocClipBase *)), m_clipMonitor, SLOT(slotSetXml(DocClipBase *)));
1797         disconnect(m_projectList, SIGNAL(refreshClip()), m_clipMonitor, SLOT(refreshMonitor()));
1798         m_clipMonitor->stop();
1799     }
1800     KdenliveSettings::setCurrent_profile(doc->profilePath());
1801     KdenliveSettings::setProject_fps(doc->fps());
1802     m_monitorManager->resetProfiles(doc->timecode());
1803     m_projectList->setDocument(doc);
1804     m_transitionConfig->updateProjectFormat(doc->mltProfile(), doc->timecode(), trackView->tracksNumber());
1805     m_effectStack->updateProjectFormat(doc->mltProfile(), doc->timecode());
1806     connect(m_projectList, SIGNAL(clipSelected(DocClipBase *)), m_clipMonitor, SLOT(slotSetXml(DocClipBase *)));
1807     connect(m_projectList, SIGNAL(refreshClip()), m_clipMonitor, SLOT(refreshMonitor()));
1808     connect(m_projectList, SIGNAL(projectModified()), doc, SLOT(setModified()));
1809     connect(m_projectList, SIGNAL(clipNameChanged(const QString, const QString)), trackView->projectView(), SLOT(clipNameChanged(const QString, const QString)));
1810
1811
1812     connect(trackView, SIGNAL(cursorMoved()), m_projectMonitor, SLOT(activateMonitor()));
1813     connect(trackView, SIGNAL(insertTrack(int)), this, SLOT(slotInsertTrack(int)));
1814     connect(trackView, SIGNAL(deleteTrack(int)), this, SLOT(slotDeleteTrack(int)));
1815     connect(trackView, SIGNAL(changeTrack(int)), this, SLOT(slotChangeTrack(int)));
1816     connect(trackView, SIGNAL(mousePosition(int)), this, SLOT(slotUpdateMousePosition(int)));
1817     connect(m_projectMonitor, SIGNAL(renderPosition(int)), trackView, SLOT(moveCursorPos(int)));
1818     connect(m_projectMonitor, SIGNAL(zoneUpdated(QPoint)), trackView, SLOT(slotSetZone(QPoint)));
1819     connect(m_projectMonitor, SIGNAL(durationChanged(int)), trackView, SLOT(setDuration(int)));
1820     connect(m_projectMonitor->render, SIGNAL(refreshDocumentProducers()), doc, SLOT(checkProjectClips()));
1821
1822     connect(doc, SIGNAL(addProjectClip(DocClipBase *, bool)), m_projectList, SLOT(slotAddClip(DocClipBase *, bool)));
1823     connect(doc, SIGNAL(resetProjectList()), m_projectList, SLOT(slotResetProjectList()));
1824     connect(doc, SIGNAL(signalDeleteProjectClip(const QString &)), m_projectList, SLOT(slotDeleteClip(const QString &)));
1825     connect(doc, SIGNAL(updateClipDisplay(const QString &)), m_projectList, SLOT(slotUpdateClip(const QString &)));
1826     connect(doc, SIGNAL(selectLastAddedClip(const QString &)), m_projectList, SLOT(slotSelectClip(const QString &)));
1827
1828     connect(doc, SIGNAL(deleteTimelineClip(const QString &)), trackView, SLOT(slotDeleteClip(const QString &)));
1829     connect(doc, SIGNAL(docModified(bool)), this, SLOT(slotUpdateDocumentState(bool)));
1830     connect(doc, SIGNAL(guidesUpdated()), this, SLOT(slotGuidesUpdated()));
1831
1832
1833     connect(trackView->projectView(), SIGNAL(clipItemSelected(ClipItem*, int)), m_effectStack, SLOT(slotClipItemSelected(ClipItem*, int)));
1834     connect(trackView->projectView(), SIGNAL(updateClipMarkers(DocClipBase *)), this, SLOT(slotUpdateClipMarkers(DocClipBase*)));
1835
1836     connect(trackView->projectView(), SIGNAL(clipItemSelected(ClipItem*, int)), this, SLOT(slotActivateEffectStackView()));
1837     connect(trackView->projectView(), SIGNAL(transitionItemSelected(Transition*, int, QPoint, bool)), m_transitionConfig, SLOT(slotTransitionItemSelected(Transition*, int, QPoint, bool)));
1838     connect(trackView->projectView(), SIGNAL(transitionItemSelected(Transition*, int, QPoint, bool)), this, SLOT(slotActivateTransitionView(Transition *)));
1839     m_zoomSlider->setValue(doc->zoom().x());
1840     connect(m_zoomSlider, SIGNAL(valueChanged(int)), trackView, SLOT(slotChangeZoom(int)));
1841     connect(trackView->projectView(), SIGNAL(zoomIn()), this, SLOT(slotZoomIn()));
1842     connect(trackView->projectView(), SIGNAL(zoomOut()), this, SLOT(slotZoomOut()));
1843     connect(trackView, SIGNAL(setZoom(int)), this, SLOT(slotSetZoom(int)));
1844     connect(trackView->projectView(), SIGNAL(displayMessage(const QString&, MessageType)), m_messageLabel, SLOT(setMessage(const QString&, MessageType)));
1845
1846     connect(trackView->projectView(), SIGNAL(showClipFrame(DocClipBase *, const int)), m_clipMonitor, SLOT(slotSetXml(DocClipBase *, const int)));
1847
1848
1849     connect(m_effectStack, SIGNAL(updateClipEffect(ClipItem*, QDomElement, QDomElement, int)), trackView->projectView(), SLOT(slotUpdateClipEffect(ClipItem*, QDomElement, QDomElement, int)));
1850     connect(m_effectStack, SIGNAL(removeEffect(ClipItem*, QDomElement)), trackView->projectView(), SLOT(slotDeleteEffect(ClipItem*, QDomElement)));
1851     connect(m_effectStack, SIGNAL(changeEffectState(ClipItem*, int, bool)), trackView->projectView(), SLOT(slotChangeEffectState(ClipItem*, int, bool)));
1852     connect(m_effectStack, SIGNAL(changeEffectPosition(ClipItem*, int, int)), trackView->projectView(), SLOT(slotChangeEffectPosition(ClipItem*, int, int)));
1853     connect(m_effectStack, SIGNAL(refreshEffectStack(ClipItem*)), trackView->projectView(), SLOT(slotRefreshEffects(ClipItem*)));
1854     connect(m_transitionConfig, SIGNAL(transitionUpdated(Transition *, QDomElement)), trackView->projectView() , SLOT(slotTransitionUpdated(Transition *, QDomElement)));
1855     connect(m_transitionConfig, SIGNAL(seekTimeline(int)), trackView->projectView() , SLOT(setCursorPos(int)));
1856     connect(m_effectStack, SIGNAL(reloadEffects()), this, SLOT(slotReloadEffects()));
1857
1858     connect(trackView->projectView(), SIGNAL(activateDocumentMonitor()), m_projectMonitor, SLOT(activateMonitor()));
1859     connect(trackView, SIGNAL(zoneMoved(int, int)), this, SLOT(slotZoneMoved(int, int)));
1860     connect(m_projectList, SIGNAL(loadingIsOver()), trackView->projectView(), SLOT(slotUpdateAllThumbs()));
1861     connect(m_projectList, SIGNAL(displayMessage(const QString&, int)), this, SLOT(slotGotProgressInfo(const QString&, int)));
1862
1863
1864     trackView->projectView()->setContextMenu(m_timelineContextMenu, m_timelineContextClipMenu, m_timelineContextTransitionMenu, m_clipTypeGroup);
1865     m_activeTimeline = trackView;
1866     if (m_renderWidget) {
1867         m_renderWidget->setProfile(doc->mltProfile());
1868         m_renderWidget->setGuides(doc->guidesXml(), doc->projectDuration());
1869         m_renderWidget->setDocumentPath(doc->projectFolder().path(KUrl::AddTrailingSlash));
1870         m_renderWidget->setRenderProfile(doc->getDocumentProperty("renderdestination"), doc->getDocumentProperty("renderprofile"), doc->getDocumentProperty("renderurl"));
1871     }
1872     //doc->setRenderer(m_projectMonitor->render);
1873     m_commandStack->setActiveStack(doc->commandStack());
1874     KdenliveSettings::setProject_display_ratio(doc->dar());
1875     //doc->clipManager()->checkAudioThumbs();
1876
1877     //m_overView->setScene(trackView->projectScene());
1878     //m_overView->scale(m_overView->width() / trackView->duration(), m_overView->height() / (50 * trackView->tracksNumber()));
1879     //m_overView->fitInView(m_overView->itemAt(0, 50), Qt::KeepAspectRatio);
1880
1881     setCaption(doc->description(), doc->isModified());
1882     m_saveAction->setEnabled(doc->isModified());
1883     m_activeDocument = doc;
1884     m_activeTimeline->updateProjectFps();
1885     m_activeDocument->checkProjectClips();
1886     if (KdenliveSettings::dropbframes()) slotUpdatePreviewSettings();
1887
1888     // set tool to select tool
1889     m_buttonSelectTool->setChecked(true);
1890 }
1891
1892 void MainWindow::slotZoneMoved(int start, int end)
1893 {
1894     m_activeDocument->setZone(start, end);
1895     m_projectMonitor->slotZoneMoved(start, end);
1896 }
1897
1898 void MainWindow::slotGuidesUpdated()
1899 {
1900     if (m_renderWidget) m_renderWidget->setGuides(m_activeDocument->guidesXml(), m_activeDocument->projectDuration());
1901 }
1902
1903 void MainWindow::slotPreferences(int page, int option)
1904 {
1905     //An instance of your dialog could be already created and could be
1906     // cached, in which case you want to display the cached dialog
1907     // instead of creating another one
1908     if (KConfigDialog::showDialog("settings")) {
1909         KdenliveSettingsDialog* d = static_cast <KdenliveSettingsDialog*>(KConfigDialog::exists("settings"));
1910         if (page != -1) d->showPage(page, option);
1911         return;
1912     }
1913
1914     // KConfigDialog didn't find an instance of this dialog, so lets
1915     // create it :
1916     KdenliveSettingsDialog* dialog = new KdenliveSettingsDialog(this);
1917     connect(dialog, SIGNAL(settingsChanged(const QString&)), this, SLOT(updateConfiguration()));
1918     //connect(dialog, SIGNAL(doResetProfile()), this, SLOT(slotDetectAudioDriver()));
1919     connect(dialog, SIGNAL(doResetProfile()), m_monitorManager, SLOT(slotResetProfiles()));
1920     connect(dialog, SIGNAL(updatePreviewSettings()), this, SLOT(slotUpdatePreviewSettings()));
1921 #ifndef Q_WS_MAC
1922     connect(dialog, SIGNAL(updateCaptureFolder()), m_recMonitor, SLOT(slotUpdateCaptureFolder()));
1923 #endif
1924     //connect(dialog, SIGNAL(updatePreviewSettings()), this, SLOT(slotUpdatePreviewSettings()));
1925     dialog->show();
1926     if (page != -1) dialog->showPage(page, option);
1927 }
1928
1929 void MainWindow::slotUpdatePreviewSettings()
1930 {
1931     if (m_activeDocument) {
1932         m_clipMonitor->slotSetXml(NULL, 0);
1933         m_activeDocument->updatePreviewSettings();
1934     }
1935 }
1936
1937 void MainWindow::updateConfiguration()
1938 {
1939     //TODO: we should apply settings to all projects, not only the current one
1940     if (m_activeTimeline) {
1941         m_activeTimeline->refresh();
1942         m_activeTimeline->projectView()->checkAutoScroll();
1943         m_activeTimeline->projectView()->checkTrackHeight();
1944         if (m_activeDocument) m_activeDocument->clipManager()->checkAudioThumbs();
1945     }
1946     m_buttonAudioThumbs->setChecked(KdenliveSettings::audiothumbnails());
1947     m_buttonVideoThumbs->setChecked(KdenliveSettings::videothumbnails());
1948
1949     // Update list of transcoding profiles
1950     loadTranscoders();
1951 #ifndef NO_JOGSHUTTLE
1952     activateShuttleDevice();
1953 #endif /* NO_JOGSHUTTLE */
1954
1955 }
1956
1957
1958 void MainWindow::slotSwitchVideoThumbs()
1959 {
1960     KdenliveSettings::setVideothumbnails(!KdenliveSettings::videothumbnails());
1961     if (m_activeTimeline) {
1962         m_activeTimeline->projectView()->slotUpdateAllThumbs();
1963     }
1964     m_buttonVideoThumbs->setChecked(KdenliveSettings::videothumbnails());
1965 }
1966
1967 void MainWindow::slotSwitchAudioThumbs()
1968 {
1969     KdenliveSettings::setAudiothumbnails(!KdenliveSettings::audiothumbnails());
1970     if (m_activeTimeline) {
1971         m_activeTimeline->refresh();
1972         m_activeTimeline->projectView()->checkAutoScroll();
1973         if (m_activeDocument) m_activeDocument->clipManager()->checkAudioThumbs();
1974     }
1975     m_buttonAudioThumbs->setChecked(KdenliveSettings::audiothumbnails());
1976 }
1977
1978 void MainWindow::slotSwitchMarkersComments()
1979 {
1980     KdenliveSettings::setShowmarkers(!KdenliveSettings::showmarkers());
1981     if (m_activeTimeline) {
1982         m_activeTimeline->refresh();
1983     }
1984     m_buttonShowMarkers->setChecked(KdenliveSettings::showmarkers());
1985 }
1986
1987 void MainWindow::slotSwitchSnap()
1988 {
1989     KdenliveSettings::setSnaptopoints(!KdenliveSettings::snaptopoints());
1990     m_buttonSnap->setChecked(KdenliveSettings::snaptopoints());
1991 }
1992
1993
1994 void MainWindow::slotDeleteTimelineClip()
1995 {
1996     if (QApplication::focusWidget()->parentWidget()->parentWidget() == m_projectListDock) m_projectList->slotRemoveClip();
1997     else if (m_activeTimeline) {
1998         m_activeTimeline->projectView()->deleteSelectedClips();
1999     }
2000 }
2001
2002 void MainWindow::slotUpdateClipMarkers(DocClipBase *clip)
2003 {
2004     if (m_clipMonitor->isActive()) m_clipMonitor->checkOverlay();
2005     m_clipMonitor->updateMarkers(clip);
2006 }
2007
2008 void MainWindow::slotAddClipMarker()
2009 {
2010     DocClipBase *clip = NULL;
2011     GenTime pos;
2012     if (m_projectMonitor->isActive()) {
2013         if (m_activeTimeline) {
2014             ClipItem *item = m_activeTimeline->projectView()->getActiveClipUnderCursor();
2015             if (item) {
2016                 pos = GenTime((int)((m_projectMonitor->position() - item->startPos() + item->cropStart()).frames(m_activeDocument->fps()) * item->speed() + 0.5), m_activeDocument->fps());
2017                 clip = item->baseClip();
2018             }
2019         }
2020     } else {
2021         clip = m_clipMonitor->activeClip();
2022         pos = m_clipMonitor->position();
2023     }
2024     if (!clip) {
2025         m_messageLabel->setMessage(i18n("Cannot find clip to add marker"), ErrorMessage);
2026         return;
2027     }
2028     QString id = clip->getId();
2029     CommentedTime marker(pos, i18n("Marker"));
2030     MarkerDialog d(clip, marker, m_activeDocument->timecode(), i18n("Add Marker"), this);
2031     if (d.exec() == QDialog::Accepted) {
2032         m_activeTimeline->projectView()->slotAddClipMarker(id, d.newMarker().time(), d.newMarker().comment());
2033     }
2034 }
2035
2036 void MainWindow::slotDeleteClipMarker()
2037 {
2038     DocClipBase *clip = NULL;
2039     GenTime pos;
2040     if (m_projectMonitor->isActive()) {
2041         if (m_activeTimeline) {
2042             ClipItem *item = m_activeTimeline->projectView()->getActiveClipUnderCursor();
2043             if (item) {
2044                 pos = (m_projectMonitor->position() - item->startPos() + item->cropStart()) / item->speed();
2045                 clip = item->baseClip();
2046             }
2047         }
2048     } else {
2049         clip = m_clipMonitor->activeClip();
2050         pos = m_clipMonitor->position();
2051     }
2052     if (!clip) {
2053         m_messageLabel->setMessage(i18n("Cannot find clip to remove marker"), ErrorMessage);
2054         return;
2055     }
2056
2057     QString id = clip->getId();
2058     QString comment = clip->markerComment(pos);
2059     if (comment.isEmpty()) {
2060         m_messageLabel->setMessage(i18n("No marker found at cursor time"), ErrorMessage);
2061         return;
2062     }
2063     m_activeTimeline->projectView()->slotDeleteClipMarker(comment, id, pos);
2064 }
2065
2066 void MainWindow::slotDeleteAllClipMarkers()
2067 {
2068     DocClipBase *clip = NULL;
2069     if (m_projectMonitor->isActive()) {
2070         if (m_activeTimeline) {
2071             ClipItem *item = m_activeTimeline->projectView()->getActiveClipUnderCursor();
2072             if (item) {
2073                 clip = item->baseClip();
2074             }
2075         }
2076     } else {
2077         clip = m_clipMonitor->activeClip();
2078     }
2079     if (!clip) {
2080         m_messageLabel->setMessage(i18n("Cannot find clip to remove marker"), ErrorMessage);
2081         return;
2082     }
2083     m_activeTimeline->projectView()->slotDeleteAllClipMarkers(clip->getId());
2084 }
2085
2086 void MainWindow::slotEditClipMarker()
2087 {
2088     DocClipBase *clip = NULL;
2089     GenTime pos;
2090     if (m_projectMonitor->isActive()) {
2091         if (m_activeTimeline) {
2092             ClipItem *item = m_activeTimeline->projectView()->getActiveClipUnderCursor();
2093             if (item) {
2094                 pos = (m_projectMonitor->position() - item->startPos() + item->cropStart()) / item->speed();
2095                 clip = item->baseClip();
2096             }
2097         }
2098     } else {
2099         clip = m_clipMonitor->activeClip();
2100         pos = m_clipMonitor->position();
2101     }
2102     if (!clip) {
2103         m_messageLabel->setMessage(i18n("Cannot find clip to remove marker"), ErrorMessage);
2104         return;
2105     }
2106
2107     QString id = clip->getId();
2108     QString oldcomment = clip->markerComment(pos);
2109     if (oldcomment.isEmpty()) {
2110         m_messageLabel->setMessage(i18n("No marker found at cursor time"), ErrorMessage);
2111         return;
2112     }
2113
2114     CommentedTime marker(pos, oldcomment);
2115     MarkerDialog d(clip, marker, m_activeDocument->timecode(), i18n("Edit Marker"), this);
2116     if (d.exec() == QDialog::Accepted) {
2117         m_activeTimeline->projectView()->slotAddClipMarker(id, d.newMarker().time(), d.newMarker().comment());
2118         if (d.newMarker().time() != pos) {
2119             // remove old marker
2120             m_activeTimeline->projectView()->slotAddClipMarker(id, pos, QString());
2121         }
2122     }
2123 }
2124
2125 void MainWindow::slotAddGuide()
2126 {
2127     if (m_activeTimeline)
2128         m_activeTimeline->projectView()->slotAddGuide();
2129 }
2130
2131 void MainWindow::slotInsertSpace()
2132 {
2133     if (m_activeTimeline)
2134         m_activeTimeline->projectView()->slotInsertSpace();
2135 }
2136
2137 void MainWindow::slotRemoveSpace()
2138 {
2139     if (m_activeTimeline)
2140         m_activeTimeline->projectView()->slotRemoveSpace();
2141 }
2142
2143 void MainWindow::slotInsertTrack(int ix)
2144 {
2145     m_projectMonitor->activateMonitor();
2146     if (m_activeTimeline)
2147         m_activeTimeline->projectView()->slotInsertTrack(ix);
2148 }
2149
2150 void MainWindow::slotDeleteTrack(int ix)
2151 {
2152     m_projectMonitor->activateMonitor();
2153     if (m_activeTimeline)
2154         m_activeTimeline->projectView()->slotDeleteTrack(ix);
2155 }
2156
2157 void MainWindow::slotChangeTrack(int ix)
2158 {
2159     m_projectMonitor->activateMonitor();
2160     if (m_activeTimeline)
2161         m_activeTimeline->projectView()->slotChangeTrack(ix);
2162 }
2163
2164 void MainWindow::slotEditGuide()
2165 {
2166     if (m_activeTimeline)
2167         m_activeTimeline->projectView()->slotEditGuide();
2168 }
2169
2170 void MainWindow::slotDeleteGuide()
2171 {
2172     if (m_activeTimeline)
2173         m_activeTimeline->projectView()->slotDeleteGuide();
2174 }
2175
2176 void MainWindow::slotDeleteAllGuides()
2177 {
2178     if (m_activeTimeline)
2179         m_activeTimeline->projectView()->slotDeleteAllGuides();
2180 }
2181
2182 void MainWindow::slotCutTimelineClip()
2183 {
2184     if (m_activeTimeline) {
2185         m_activeTimeline->projectView()->cutSelectedClips();
2186     }
2187 }
2188
2189 void MainWindow::slotGroupClips()
2190 {
2191     if (m_activeTimeline) {
2192         m_activeTimeline->projectView()->groupClips();
2193     }
2194 }
2195
2196 void MainWindow::slotUnGroupClips()
2197 {
2198     if (m_activeTimeline) {
2199         m_activeTimeline->projectView()->groupClips(false);
2200     }
2201 }
2202
2203 void MainWindow::slotAddProjectClip(KUrl url)
2204 {
2205     if (m_activeDocument)
2206         m_activeDocument->slotAddClipFile(url, QString());
2207 }
2208
2209 void MainWindow::slotAddTransition(QAction *result)
2210 {
2211     if (!result) return;
2212     QStringList info = result->data().toStringList();
2213     if (info.isEmpty()) return;
2214     QDomElement transition = transitions.getEffectByTag(info.at(1), info.at(2));
2215     if (m_activeTimeline && !transition.isNull()) {
2216         m_activeTimeline->projectView()->slotAddTransitionToSelectedClips(transition.cloneNode().toElement());
2217     }
2218 }
2219
2220 void MainWindow::slotAddVideoEffect(QAction *result)
2221 {
2222     if (!result) return;
2223     QStringList info = result->data().toStringList();
2224     if (info.isEmpty()) return;
2225     QDomElement effect = videoEffects.getEffectByTag(info.at(1), info.at(2));
2226     slotAddEffect(effect);
2227 }
2228
2229 void MainWindow::slotAddAudioEffect(QAction *result)
2230 {
2231     if (!result) return;
2232     QStringList info = result->data().toStringList();
2233     if (info.isEmpty()) return;
2234     QDomElement effect = audioEffects.getEffectByTag(info.at(1), info.at(2));
2235     slotAddEffect(effect);
2236 }
2237
2238 void MainWindow::slotAddCustomEffect(QAction *result)
2239 {
2240     if (!result) return;
2241     QStringList info = result->data().toStringList();
2242     if (info.isEmpty()) return;
2243     QDomElement effect = customEffects.getEffectByTag(info.at(1), info.at(2));
2244     slotAddEffect(effect);
2245 }
2246
2247 void MainWindow::slotZoomIn()
2248 {
2249     m_zoomSlider->setValue(m_zoomSlider->value() - 1);
2250 }
2251
2252 void MainWindow::slotZoomOut()
2253 {
2254     m_zoomSlider->setValue(m_zoomSlider->value() + 1);
2255 }
2256
2257 void MainWindow::slotFitZoom()
2258 {
2259     if (m_activeTimeline) {
2260         m_zoomSlider->setValue(m_activeTimeline->fitZoom());
2261     }
2262 }
2263
2264 void MainWindow::slotSetZoom(int value)
2265 {
2266     m_zoomSlider->setValue(value);
2267 }
2268
2269 void MainWindow::slotGotProgressInfo(const QString &message, int progress)
2270 {
2271     m_statusProgressBar->setValue(progress);
2272     if (progress >= 0) {
2273         if (!message.isEmpty()) m_messageLabel->setMessage(message, InformationMessage);//statusLabel->setText(message);
2274         m_statusProgressBar->setVisible(true);
2275     } else {
2276         m_messageLabel->setMessage(QString(), DefaultMessage);
2277         m_statusProgressBar->setVisible(false);
2278     }
2279 }
2280
2281 void MainWindow::slotShowClipProperties(DocClipBase *clip)
2282 {
2283     if (clip->clipType() == TEXT) {
2284         QString titlepath = m_activeDocument->projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
2285         if (!clip->getProperty("resource").isEmpty() && clip->getProperty("xmldata").isEmpty()) {
2286             // template text clip
2287
2288             // Get the list of existing templates
2289             QStringList filter;
2290             filter << "*.kdenlivetitle";
2291             QStringList templateFiles = QDir(titlepath).entryList(filter, QDir::Files);
2292
2293             QDialog *dia = new QDialog(this);
2294             Ui::TemplateClip_UI dia_ui;
2295             dia_ui.setupUi(dia);
2296             int ix = -1;
2297             const QString templatePath = clip->getProperty("resource");
2298             for (int i = 0; i < templateFiles.size(); ++i) {
2299                 dia_ui.template_list->comboBox()->addItem(templateFiles.at(i), titlepath + templateFiles.at(i));
2300                 if (templatePath == KUrl(titlepath + templateFiles.at(i)).path()) ix = i;
2301             }
2302             if (ix != -1) dia_ui.template_list->comboBox()->setCurrentIndex(ix);
2303             else dia_ui.template_list->comboBox()->insertItem(0, templatePath);
2304             dia_ui.template_list->fileDialog()->setFilter("*.kdenlivetitle");
2305             //warning: setting base directory doesn't work??
2306             KUrl startDir(titlepath);
2307             dia_ui.template_list->fileDialog()->setUrl(startDir);
2308             dia_ui.description->setText(clip->getProperty("description"));
2309             if (dia->exec() == QDialog::Accepted) {
2310                 QString textTemplate = dia_ui.template_list->comboBox()->itemData(dia_ui.template_list->comboBox()->currentIndex()).toString();
2311                 if (textTemplate.isEmpty()) textTemplate = dia_ui.template_list->comboBox()->currentText();
2312
2313                 QMap <QString, QString> newprops;
2314
2315                 if (KUrl(textTemplate).path() != templatePath) {
2316                     // The template was changed
2317                     newprops.insert("resource", textTemplate);
2318                 }
2319
2320                 if (dia_ui.description->toPlainText() != clip->getProperty("description")) {
2321                     newprops.insert("description", dia_ui.description->toPlainText());
2322                 }
2323
2324                 QString newtemplate = newprops.value("xmltemplate");
2325                 if (newtemplate.isEmpty()) newtemplate = templatePath;
2326
2327                 // template modified we need to update xmldata
2328                 QString description = newprops.value("description");
2329                 if (description.isEmpty()) description = clip->getProperty("description");
2330                 else newprops.insert("templatetext", description);
2331                 //newprops.insert("xmldata", m_projectList->generateTemplateXml(newtemplate, description).toString());
2332
2333                 EditClipCommand *command = new EditClipCommand(m_projectList, clip->getId(), clip->properties(), newprops, true);
2334                 m_activeDocument->commandStack()->push(command);
2335             }
2336             return;
2337         }
2338         QString path = clip->getProperty("resource");
2339         TitleWidget *dia_ui = new TitleWidget(KUrl(), m_activeDocument->timecode(), titlepath, m_projectMonitor->render, this);
2340         QDomDocument doc;
2341         doc.setContent(clip->getProperty("xmldata"));
2342         dia_ui->setXml(doc);
2343         if (dia_ui->exec() == QDialog::Accepted) {
2344             QMap <QString, QString> newprops;
2345             newprops.insert("xmldata", dia_ui->xml().toString());
2346             if (dia_ui->duration() != clip->duration().frames(m_activeDocument->fps()) - 1) {
2347                 // duration changed, we need to update duration
2348                 newprops.insert("out", QString::number(dia_ui->duration()));
2349             }
2350             EditClipCommand *command = new EditClipCommand(m_projectList, clip->getId(), clip->properties(), newprops, true);
2351             m_activeDocument->commandStack()->push(command);
2352             m_activeTimeline->projectView()->slotUpdateClip(clip->getId());
2353             m_activeDocument->setModified(true);
2354         }
2355         delete dia_ui;
2356
2357         //m_activeDocument->editTextClip(clip->getProperty("xml"), clip->getId());
2358         return;
2359     }
2360     ClipProperties dia(clip, m_activeDocument->timecode(), m_activeDocument->fps(), this);
2361     connect(&dia, SIGNAL(addMarker(const QString &, GenTime, QString)), m_activeTimeline->projectView(), SLOT(slotAddClipMarker(const QString &, GenTime, QString)));
2362     if (dia.exec() == QDialog::Accepted) {
2363         EditClipCommand *command = new EditClipCommand(m_projectList, clip->getId(), clip->properties(), dia.properties(), true);
2364         m_activeDocument->commandStack()->push(command);
2365
2366         if (dia.needsTimelineRefresh()) {
2367             // update clip occurences in timeline
2368             m_activeTimeline->projectView()->slotUpdateClip(clip->getId(), dia.needsTimelineReload());
2369         }
2370     }
2371 }
2372
2373 void MainWindow::customEvent(QEvent* e)
2374 {
2375     if (e->type() == QEvent::User) {
2376         m_messageLabel->setMessage(static_cast <MltErrorEvent *>(e)->message(), MltError);
2377     }
2378 }
2379 void MainWindow::slotActivateEffectStackView()
2380 {
2381     m_effectStack->raiseWindow(m_effectStackDock);
2382 }
2383
2384 void MainWindow::slotActivateTransitionView(Transition *t)
2385 {
2386     if (t) m_transitionConfig->raiseWindow(m_transitionConfigDock);
2387 }
2388
2389 void MainWindow::slotSnapRewind()
2390 {
2391     if (m_projectMonitor->isActive()) {
2392         if (m_activeTimeline)
2393             m_activeTimeline->projectView()->slotSeekToPreviousSnap();
2394     } else m_clipMonitor->slotSeekToPreviousSnap();
2395 }
2396
2397 void MainWindow::slotSnapForward()
2398 {
2399     if (m_projectMonitor->isActive()) {
2400         if (m_activeTimeline)
2401             m_activeTimeline->projectView()->slotSeekToNextSnap();
2402     } else m_clipMonitor->slotSeekToNextSnap();
2403 }
2404
2405 void MainWindow::slotClipStart()
2406 {
2407     if (m_projectMonitor->isActive()) {
2408         if (m_activeTimeline)
2409             m_activeTimeline->projectView()->clipStart();
2410     }
2411 }
2412
2413 void MainWindow::slotClipEnd()
2414 {
2415     if (m_projectMonitor->isActive()) {
2416         if (m_activeTimeline)
2417             m_activeTimeline->projectView()->clipEnd();
2418     }
2419 }
2420
2421 void MainWindow::slotChangeTool(QAction * action)
2422 {
2423     if (action == m_buttonSelectTool) slotSetTool(SELECTTOOL);
2424     else if (action == m_buttonRazorTool) slotSetTool(RAZORTOOL);
2425     else if (action == m_buttonSpacerTool) slotSetTool(SPACERTOOL);
2426 }
2427
2428 void MainWindow::slotSetTool(PROJECTTOOL tool)
2429 {
2430     if (m_activeDocument && m_activeTimeline) {
2431         //m_activeDocument->setTool(tool);
2432         QString message;
2433         switch (tool)  {
2434         case SPACERTOOL:
2435             message = i18n("Ctrl + click to use spacer on current track only");
2436             break;
2437         case RAZORTOOL:
2438             message = i18n("Click on a clip to cut it");
2439             break;
2440         default:
2441             message = i18n("Shift + click to create a selection rectangle, Ctrl + click to add an item to selection");
2442             break;
2443         }
2444         m_messageLabel->setMessage(message, InformationMessage);
2445         m_activeTimeline->projectView()->setTool(tool);
2446     }
2447 }
2448
2449 void MainWindow::slotCopy()
2450 {
2451     if (!m_activeDocument || !m_activeTimeline) return;
2452     m_activeTimeline->projectView()->copyClip();
2453 }
2454
2455 void MainWindow::slotPaste()
2456 {
2457     if (!m_activeDocument || !m_activeTimeline) return;
2458     m_activeTimeline->projectView()->pasteClip();
2459 }
2460
2461 void MainWindow::slotPasteEffects()
2462 {
2463     if (!m_activeDocument || !m_activeTimeline) return;
2464     m_activeTimeline->projectView()->pasteClipEffects();
2465 }
2466
2467 void MainWindow::slotFind()
2468 {
2469     if (!m_activeDocument || !m_activeTimeline) return;
2470     m_projectSearch->setEnabled(false);
2471     m_findActivated = true;
2472     m_findString.clear();
2473     m_activeTimeline->projectView()->initSearchStrings();
2474     statusBar()->showMessage(i18n("Starting -- find text as you type"));
2475     m_findTimer.start(5000);
2476     qApp->installEventFilter(this);
2477 }
2478
2479 void MainWindow::slotFindNext()
2480 {
2481     if (m_activeTimeline && m_activeTimeline->projectView()->findNextString(m_findString)) {
2482         statusBar()->showMessage(i18n("Found: %1", m_findString));
2483     } else {
2484         statusBar()->showMessage(i18n("Reached end of project"));
2485     }
2486     m_findTimer.start(4000);
2487 }
2488
2489 void MainWindow::findAhead()
2490 {
2491     if (m_activeTimeline && m_activeTimeline->projectView()->findString(m_findString)) {
2492         m_projectSearchNext->setEnabled(true);
2493         statusBar()->showMessage(i18n("Found: %1", m_findString));
2494     } else {
2495         m_projectSearchNext->setEnabled(false);
2496         statusBar()->showMessage(i18n("Not found: %1", m_findString));
2497     }
2498 }
2499
2500 void MainWindow::findTimeout()
2501 {
2502     m_projectSearchNext->setEnabled(false);
2503     m_findActivated = false;
2504     m_findString.clear();
2505     statusBar()->showMessage(i18n("Find stopped"), 3000);
2506     if (m_activeTimeline) m_activeTimeline->projectView()->clearSearchStrings();
2507     m_projectSearch->setEnabled(true);
2508     removeEventFilter(this);
2509 }
2510
2511 void MainWindow::keyPressEvent(QKeyEvent *ke)
2512 {
2513     if (m_findActivated) {
2514         if (ke->key() == Qt::Key_Backspace) {
2515             m_findString = m_findString.left(m_findString.length() - 1);
2516
2517             if (!m_findString.isEmpty()) {
2518                 findAhead();
2519             } else {
2520                 findTimeout();
2521             }
2522
2523             m_findTimer.start(4000);
2524             ke->accept();
2525             return;
2526         } else if (ke->key() == Qt::Key_Escape) {
2527             findTimeout();
2528             ke->accept();
2529             return;
2530         } else if (ke->key() == Qt::Key_Space || !ke->text().trimmed().isEmpty()) {
2531             m_findString += ke->text();
2532
2533             findAhead();
2534
2535             m_findTimer.start(4000);
2536             ke->accept();
2537             return;
2538         }
2539     } else KXmlGuiWindow::keyPressEvent(ke);
2540 }
2541
2542
2543 /** Gets called when the window gets hidden */
2544 void MainWindow::hideEvent(QHideEvent */*event*/)
2545 {
2546     // kDebug() << "I was hidden";
2547     // issue http://www.kdenlive.org/mantis/view.php?id=231
2548     if (isMinimized()) {
2549         // kDebug() << "I am minimized";
2550         if (m_monitorManager) m_monitorManager->stopActiveMonitor();
2551     }
2552 }
2553
2554 bool MainWindow::eventFilter(QObject *obj, QEvent *event)
2555 {
2556     if (m_findActivated) {
2557         if (event->type() == QEvent::ShortcutOverride) {
2558             QKeyEvent* ke = (QKeyEvent*) event;
2559             if (ke->text().trimmed().isEmpty()) return false;
2560             ke->accept();
2561             return true;
2562         } else return false;
2563     } else {
2564         // pass the event on to the parent class
2565         return QMainWindow::eventFilter(obj, event);
2566     }
2567 }
2568
2569
2570 void MainWindow::slotSaveZone(Render *render, QPoint zone)
2571 {
2572     KDialog *dialog = new KDialog(this);
2573     dialog->setCaption("Save clip zone");
2574     dialog->setButtons(KDialog::Ok | KDialog::Cancel);
2575
2576     QWidget *widget = new QWidget(dialog);
2577     dialog->setMainWidget(widget);
2578
2579     QVBoxLayout *vbox = new QVBoxLayout(widget);
2580     QLabel *label1 = new QLabel(i18n("Save clip zone as:"), this);
2581     QString path = m_activeDocument->projectFolder().path();
2582     path.append("/");
2583     path.append("untitled.mlt");
2584     KUrlRequester *url = new KUrlRequester(KUrl(path), this);
2585     url->setFilter("video/mlt-playlist");
2586     QLabel *label2 = new QLabel(i18n("Description:"), this);
2587     KLineEdit *edit = new KLineEdit(this);
2588     vbox->addWidget(label1);
2589     vbox->addWidget(url);
2590     vbox->addWidget(label2);
2591     vbox->addWidget(edit);
2592     if (dialog->exec() == QDialog::Accepted) render->saveZone(url->url(), edit->text(), zone);
2593
2594 }
2595
2596 void MainWindow::slotSetInPoint()
2597 {
2598     if (m_clipMonitor->isActive()) {
2599         m_clipMonitor->slotSetZoneStart();
2600     } else m_activeTimeline->projectView()->setInPoint();
2601 }
2602
2603 void MainWindow::slotSetOutPoint()
2604 {
2605     if (m_clipMonitor->isActive()) {
2606         m_clipMonitor->slotSetZoneEnd();
2607     } else m_activeTimeline->projectView()->setOutPoint();
2608 }
2609
2610 void MainWindow::slotGetNewLumaStuff()
2611 {
2612     //KNS::Entry::List download();
2613     KNS::Entry::List entries = KNS::Engine::download();
2614     // list of changed entries
2615     kDebug() << "// PARSING KNS";
2616     foreach(KNS::Entry* entry, entries) {
2617         // care only about installed ones
2618         if (entry->status() == KNS::Entry::Installed) {
2619             foreach(const QString &file, entry->installedFiles()) {
2620                 kDebug() << "// CURRENTLY INSTALLED: " << file;
2621             }
2622         }
2623     }
2624     qDeleteAll(entries);
2625     initEffects::refreshLumas();
2626     m_activeTimeline->projectView()->reloadTransitionLumas();
2627 }
2628
2629 void MainWindow::slotGetNewRenderStuff()
2630 {
2631     //KNS::Entry::List download();
2632
2633     KNS::Engine engine(0);
2634     if (engine.init("kdenlive_render.knsrc")) {
2635         KNS::Entry::List entries = engine.downloadDialogModal(this);
2636
2637         if (entries.size() > 0) {
2638             foreach(KNS::Entry* entry, entries) {
2639                 // care only about installed ones
2640                 if (entry->status() == KNS::Entry::Installed) {
2641                     foreach(const QString &file, entry->installedFiles()) {
2642                         kDebug() << "// CURRENTLY INSTALLED: " << file;
2643                     }
2644                 }
2645             }
2646         }
2647         if (m_renderWidget) m_renderWidget->reloadProfiles();
2648     }
2649 }
2650
2651 void MainWindow::slotGetNewMltProfileStuff()
2652 {
2653     //KNS::Entry::List download();
2654
2655     KNS::Engine engine(0);
2656     if (engine.init("kdenlive_mltprofiles.knsrc")) {
2657         KNS::Entry::List entries = engine.downloadDialogModal(this);
2658
2659         if (entries.size() > 0) {
2660             foreach(KNS::Entry* entry, entries) {
2661                 // care only about installed ones
2662                 if (entry->status() == KNS::Entry::Installed) {
2663                     foreach(const QString &file, entry->installedFiles()) {
2664                         kDebug() << "// CURRENTLY INSTALLED: " << file;
2665                     }
2666                 }
2667             }
2668
2669             // update the list of profiles in settings dialog
2670             KdenliveSettingsDialog* d = static_cast <KdenliveSettingsDialog*>(KConfigDialog::exists("settings"));
2671             if (d) d->checkProfile();
2672         }
2673     }
2674 }
2675
2676 void MainWindow::slotAutoTransition()
2677 {
2678     if (m_activeTimeline) m_activeTimeline->projectView()->autoTransition();
2679 }
2680
2681 void MainWindow::slotSplitAudio()
2682 {
2683     if (m_activeTimeline) m_activeTimeline->projectView()->splitAudio();
2684 }
2685
2686 void MainWindow::slotUpdateClipType(QAction *action)
2687 {
2688     if (m_activeTimeline) {
2689         if (action->data().toString() == "clip_audio_only") m_activeTimeline->projectView()->setAudioOnly();
2690         else if (action->data().toString() == "clip_video_only") m_activeTimeline->projectView()->setVideoOnly();
2691         else m_activeTimeline->projectView()->setAudioAndVideo();
2692     }
2693 }
2694
2695 void MainWindow::slotDvdWizard(const QString &url, const QString &profile)
2696 {
2697     // We must stop the monitors since we create a new on in the dvd wizard
2698     m_clipMonitor->stop();
2699     m_projectMonitor->stop();
2700     DvdWizard w(url, profile, this);
2701     w.exec();
2702     m_projectMonitor->start();
2703 }
2704
2705 void MainWindow::slotShowTimeline(bool show)
2706 {
2707     if (show == false) {
2708         m_timelineState = saveState();
2709         centralWidget()->setHidden(true);
2710     } else {
2711         centralWidget()->setHidden(false);
2712         restoreState(m_timelineState);
2713     }
2714 }
2715
2716 void MainWindow::slotMaximizeCurrent(bool /*show*/)
2717 {
2718     //TODO: is there a way to maximize current widget?
2719     //if (show == true)
2720     {
2721         m_timelineState = saveState();
2722         QWidget *par = focusWidget()->parentWidget();
2723         while (par->parentWidget() && par->parentWidget() != this) {
2724             par = par->parentWidget();
2725         }
2726         kDebug() << "CURRENT WIDGET: " << par->objectName();
2727     }
2728     /*else {
2729     //centralWidget()->setHidden(false);
2730     //restoreState(m_timelineState);
2731     }*/
2732 }
2733
2734 void MainWindow::loadTranscoders()
2735 {
2736     QMenu *transMenu = static_cast<QMenu*>(factory()->container("transcoders", this));
2737     transMenu->clear();
2738
2739     KSharedConfigPtr config = KSharedConfig::openConfig("kdenlivetranscodingrc");
2740     KConfigGroup transConfig(config, "Transcoding");
2741     // read the entries
2742     QMap< QString, QString > profiles = transConfig.entryMap();
2743     QMapIterator<QString, QString> i(profiles);
2744     while (i.hasNext()) {
2745         i.next();
2746         QAction *a = transMenu->addAction(i.key());
2747         a->setData(i.value());
2748         connect(a, SIGNAL(triggered()), this, SLOT(slotTranscode()));
2749     }
2750 }
2751
2752 void MainWindow::slotTranscode(KUrl::List urls)
2753 {
2754     QString params;
2755     if (urls.isEmpty()) {
2756         urls.append(m_projectList->currentClipUrl());
2757         QAction *action = qobject_cast<QAction *>(sender());
2758         params = action->data().toString();
2759     }
2760     if (urls.isEmpty()) return;
2761     ClipTranscode *d = new ClipTranscode(urls, params);
2762     connect(d, SIGNAL(addClip(KUrl)), this, SLOT(slotAddProjectClip(KUrl)));
2763     d->show();
2764     //QProcess::startDetached("ffmpeg", parameters);
2765 }
2766
2767 void MainWindow::slotTranscodeClip()
2768 {
2769     KUrl::List urls = KFileDialog::getOpenUrls(KUrl("kfiledialog:///projectfolder"));
2770     if (urls.isEmpty()) return;
2771     slotTranscode(urls);
2772 }
2773
2774 void MainWindow::slotSetDocumentRenderProfile(const QString &dest, const QString &name, const QString &file)
2775 {
2776     if (m_activeDocument == NULL) return;
2777     m_activeDocument->setDocumentProperty("renderdestination", dest);
2778     m_activeDocument->setDocumentProperty("renderprofile", name);
2779     m_activeDocument->setDocumentProperty("renderurl", file);
2780     m_activeDocument->setModified(true);
2781 }
2782
2783
2784 void MainWindow::slotPrepareRendering(bool scriptExport, bool zoneOnly, const QString &chapterFile)
2785 {
2786     if (m_activeDocument == NULL || m_renderWidget == NULL) return;
2787     QString scriptPath;
2788     QString playlistPath;
2789     if (scriptExport) {
2790         bool ok;
2791         QString scriptsFolder = m_activeDocument->projectFolder().path() + "/scripts/";
2792         QString path = m_renderWidget->getFreeScriptName();
2793         scriptPath = QInputDialog::getText(this, i18n("Create Render Script"), i18n("Script name (will be saved in: %1)", scriptsFolder), QLineEdit::Normal, KUrl(path).fileName(), &ok);
2794         if (!ok || scriptPath.isEmpty()) return;
2795         scriptPath.prepend(scriptsFolder);
2796         QFile f(scriptPath);
2797         if (f.exists()) {
2798             if (KMessageBox::warningYesNo(this, i18n("Script file already exists. Do you want to overwrite it?")) != KMessageBox::Yes)
2799                 return;
2800         }
2801         playlistPath = scriptPath + ".mlt";
2802         m_projectMonitor->saveSceneList(playlistPath);
2803     } else {
2804         KTemporaryFile temp;
2805         temp.setAutoRemove(false);
2806         temp.setSuffix(".mlt");
2807         temp.open();
2808         playlistPath = temp.fileName();
2809         m_projectMonitor->saveSceneList(playlistPath);
2810     }
2811
2812     if (!chapterFile.isEmpty()) {
2813         int in = 0;
2814         int out;
2815         if (!zoneOnly) out = (int) GenTime(m_activeDocument->projectDuration()).frames(m_activeDocument->fps());
2816         else {
2817             in = m_activeTimeline->inPoint();
2818             out = m_activeTimeline->outPoint();
2819         }
2820         QDomDocument doc;
2821         QDomElement chapters = doc.createElement("chapters");
2822         chapters.setAttribute("fps", m_activeDocument->fps());
2823         doc.appendChild(chapters);
2824
2825         QDomElement guidesxml = m_activeDocument->guidesXml();
2826         QDomNodeList nodes = guidesxml.elementsByTagName("guide");
2827         for (int i = 0; i < nodes.count(); i++) {
2828             QDomElement e = nodes.item(i).toElement();
2829             if (!e.isNull()) {
2830                 QString comment = e.attribute("comment");
2831                 int time = (int) GenTime(e.attribute("time").toDouble()).frames(m_activeDocument->fps());
2832                 if (time >= in && time < out) {
2833                     if (zoneOnly) time = time - in;
2834                     QDomElement chapter = doc.createElement("chapter");
2835                     chapters.appendChild(chapter);
2836                     chapter.setAttribute("title", comment);
2837                     chapter.setAttribute("time", time);
2838                 }
2839             }
2840         }
2841         if (chapters.childNodes().count() > 0) {
2842             if (m_activeTimeline->projectView()->hasGuide(out, 0) == -1) {
2843                 // Always insert a guide in pos 0
2844                 QDomElement chapter = doc.createElement("chapter");
2845                 chapters.insertBefore(chapter, QDomNode());
2846                 chapter.setAttribute("title", i18n("Start"));
2847                 chapter.setAttribute("time", "0");
2848             }
2849             // save chapters file
2850             QFile file(chapterFile);
2851             if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
2852                 kWarning() << "//////  ERROR writing DVD CHAPTER file: " << chapterFile;
2853             } else {
2854                 file.write(doc.toString().toUtf8());
2855                 if (file.error() != QFile::NoError) {
2856                     kWarning() << "//////  ERROR writing DVD CHAPTER file: " << chapterFile;
2857                 }
2858                 file.close();
2859             }
2860         }
2861     }
2862
2863     m_renderWidget->slotExport(scriptExport, m_activeTimeline->inPoint(), m_activeTimeline->outPoint(), playlistPath, scriptPath);
2864 }
2865
2866 void MainWindow::slotUpdateTimecodeFormat(int ix)
2867 {
2868     KdenliveSettings::setFrametimecode(ix == 1);
2869     m_clipMonitor->updateTimecodeFormat();
2870     m_projectMonitor->updateTimecodeFormat();
2871 }
2872
2873 void MainWindow::slotRemoveFocus()
2874 {
2875     statusBar()->setFocus();
2876     statusBar()->clearFocus();
2877 }
2878
2879 void MainWindow::slotRevert()
2880 {
2881     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;
2882     KUrl url = m_activeDocument->url();
2883     closeCurrentDocument(false);
2884     doOpenFile(url, NULL);
2885 }
2886
2887
2888 void MainWindow::slotShutdown()
2889 {
2890     if (m_activeDocument) m_activeDocument->setModified(false);
2891     // Call shutdown
2892     QDBusConnectionInterface* interface = QDBusConnection::sessionBus().interface();
2893     if (interface && interface->isServiceRegistered("org.kde.ksmserver")) {
2894         QDBusInterface smserver("org.kde.ksmserver", "/KSMServer", "org.kde.KSMServerInterface");
2895         smserver.call("logout", 1, 2, 2);
2896     }
2897 }
2898
2899 #include "mainwindow.moc"