]> git.sesse.net Git - kdenlive/blob - src/titlewidget.cpp
Reindent sources
[kdenlive] / src / titlewidget.cpp
1 /***************************************************************************
2                           titlewidget.cpp  -  description
3                              -------------------
4     begin                : Feb 28 2008
5     copyright            : (C) 2008 by Marco Gittler
6     email                : g.marco@freenet.de
7  ***************************************************************************/
8
9 /***************************************************************************
10  *                                                                         *
11  *   This program is free software; you can redistribute it and/or modify  *
12  *   it under the terms of the GNU General Public License as published by  *
13  *   the Free Software Foundation; either version 2 of the License, or     *
14  *   (at your option) any later version.                                   *
15  *                                                                         *
16  ***************************************************************************/
17
18 #include "titlewidget.h"
19 #include "kdenlivesettings.h"
20
21 #include <cmath>
22
23 #include <KDebug>
24 #include <KGlobalSettings>
25 #include <KFileDialog>
26 #include <KStandardDirs>
27 #include <KMessageBox>
28 #include <kio/netaccess.h>
29 #include <kdeversion.h>
30
31 #include <QDomDocument>
32 #include <QGraphicsItem>
33 #include <QGraphicsSvgItem>
34 #include <QTimer>
35 #include <QToolBar>
36 #include <QMenu>
37 #include <QSignalMapper>
38 #include <QTextBlockFormat>
39 #include <QTextCursor>
40
41 int settingUp = false;
42
43 const int IMAGEITEM = 7;
44 const int RECTITEM = 3;
45 const int TEXTITEM = 8;
46 static bool insertingValues = false;
47
48 TitleWidget::TitleWidget(KUrl url, Timecode tc, QString projectTitlePath, Render *render, QWidget *parent) :
49         QDialog(parent),
50         Ui::TitleWidget_UI(),
51         m_startViewport(NULL),
52         m_endViewport(NULL),
53         m_render(render),
54         m_count(0),
55         m_unicodeDialog(new UnicodeDialog(UnicodeDialog::InputHex)),
56         m_projectTitlePath(projectTitlePath),
57         m_tc(tc)
58 {
59     setupUi(this);
60     setFont(KGlobalSettings::toolBarFont());
61     //toolBox->setFont(KGlobalSettings::toolBarFont());
62     frame_properties->setEnabled(false);
63     rect_properties->setFixedHeight(frame_properties->height() + 4);
64     no_properties->setFixedHeight(frame_properties->height() + 4);
65     image_properties->setFixedHeight(frame_properties->height() + 4);
66     text_properties->setFixedHeight(frame_properties->height() + 4);
67     frame_properties->setFixedHeight(frame_toolbar->height());
68
69     itemzoom->setSuffix(i18n("%"));
70     m_frameWidth = render->renderWidth();
71     m_frameHeight = render->renderHeight();
72     showToolbars(TITLE_NONE);
73
74     //TODO: get default title duration instead of hardcoded one
75     title_duration->setText(m_tc.getTimecode(GenTime(5000 / 1000.0)));
76
77     connect(kcolorbutton, SIGNAL(clicked()), this, SLOT(slotChangeBackground())) ;
78     connect(horizontalSlider, SIGNAL(valueChanged(int)), this, SLOT(slotChangeBackground())) ;
79
80     connect(fontColorButton, SIGNAL(clicked()), this, SLOT(slotUpdateText())) ;
81     connect(font_family, SIGNAL(currentFontChanged(const QFont &)), this, SLOT(slotUpdateText())) ;
82     connect(font_size, SIGNAL(valueChanged(int)), this, SLOT(slotUpdateText())) ;
83     connect(textAlpha, SIGNAL(valueChanged(int)), this, SLOT(slotUpdateText()));
84     connect(font_weight_box, SIGNAL(currentIndexChanged(int)), this, SLOT(slotUpdateText()));
85
86     connect(rectFAlpha, SIGNAL(valueChanged(int)), this, SLOT(rectChanged()));
87     connect(rectBAlpha, SIGNAL(valueChanged(int)), this, SLOT(rectChanged()));
88     connect(rectFColor, SIGNAL(clicked()), this, SLOT(rectChanged()));
89     connect(rectBColor, SIGNAL(clicked()), this, SLOT(rectChanged()));
90     connect(rectLineWidth, SIGNAL(valueChanged(int)), this, SLOT(rectChanged()));
91
92     /*connect(startViewportX, SIGNAL(valueChanged(int)), this, SLOT(setupViewports()));
93     connect(startViewportY, SIGNAL(valueChanged(int)), this, SLOT(setupViewports()));
94     connect(startViewportSize, SIGNAL(valueChanged(int)), this, SLOT(setupViewports()));
95     connect(endViewportX, SIGNAL(valueChanged(int)), this, SLOT(setupViewports()));
96     connect(endViewportY, SIGNAL(valueChanged(int)), this, SLOT(setupViewports()));
97     connect(endViewportSize, SIGNAL(valueChanged(int)), this, SLOT(setupViewports()));*/
98
99     connect(zValue, SIGNAL(valueChanged(int)), this, SLOT(zIndexChanged(int)));
100     connect(itemzoom, SIGNAL(valueChanged(int)), this, SLOT(itemScaled(int)));
101     connect(itemrotate, SIGNAL(valueChanged(int)), this, SLOT(itemRotate(int)));
102     connect(itemhcenter, SIGNAL(clicked()), this, SLOT(itemHCenter()));
103     connect(itemvcenter, SIGNAL(clicked()), this, SLOT(itemVCenter()));
104     connect(itemtop, SIGNAL(clicked()), this, SLOT(itemTop()));
105     connect(itembottom, SIGNAL(clicked()), this, SLOT(itemBottom()));
106     connect(itemleft, SIGNAL(clicked()), this, SLOT(itemLeft()));
107     connect(itemright, SIGNAL(clicked()), this, SLOT(itemRight()));
108
109     connect(origin_x_left, SIGNAL(clicked()), this, SLOT(slotOriginXClicked()));
110     connect(origin_y_top, SIGNAL(clicked()), this, SLOT(slotOriginYClicked()));
111
112     m_signalMapper = new QSignalMapper(this);
113     m_signalMapper->setMapping(value_w, ValueWidth);
114     m_signalMapper->setMapping(value_h, ValueHeight);
115     connect(value_w, SIGNAL(valueChanged(int)), m_signalMapper, SLOT(map()));
116     connect(value_h, SIGNAL(valueChanged(int)), m_signalMapper, SLOT(map()));
117     connect(m_signalMapper, SIGNAL(mapped(int)), this, SLOT(slotValueChanged(int)));
118
119     connect(value_x, SIGNAL(valueChanged(int)), this, SLOT(slotAdjustSelectedItem()));
120     connect(value_y, SIGNAL(valueChanged(int)), this, SLOT(slotAdjustSelectedItem()));
121     connect(value_w, SIGNAL(valueChanged(int)), this, SLOT(slotAdjustSelectedItem()));
122     connect(value_h, SIGNAL(valueChanged(int)), this, SLOT(slotAdjustSelectedItem()));
123     connect(buttonFitZoom, SIGNAL(clicked()), this, SLOT(slotAdjustZoom()));
124     connect(buttonRealSize, SIGNAL(clicked()), this, SLOT(slotZoomOneToOne()));
125     connect(buttonItalic, SIGNAL(clicked()), this, SLOT(slotUpdateText()));
126     connect(buttonUnder, SIGNAL(clicked()), this, SLOT(slotUpdateText()));
127     connect(buttonAlignLeft, SIGNAL(clicked()), this, SLOT(slotUpdateText()));
128     connect(buttonAlignRight, SIGNAL(clicked()), this, SLOT(slotUpdateText()));
129     connect(buttonAlignCenter, SIGNAL(clicked()), this, SLOT(slotUpdateText()));
130     connect(buttonAlignNone, SIGNAL(clicked()), this, SLOT(slotUpdateText()));
131     //connect(buttonInsertUnicode, SIGNAL(clicked()), this, SLOT(slotInsertUnicode()));
132     connect(displayBg, SIGNAL(stateChanged(int)), this, SLOT(displayBackgroundFrame()));
133
134     connect(m_unicodeDialog, SIGNAL(charSelected(QString)), this, SLOT(slotInsertUnicodeString(QString)));
135
136     // mbd
137     connect(this, SIGNAL(accepted()), this, SLOT(slotAccepted()));
138
139     font_weight_box->blockSignals(true);
140     font_weight_box->addItem(i18nc("Font style", "Light"), QFont::Light);
141     font_weight_box->addItem(i18nc("Font style", "Normal"), QFont::Normal);
142     font_weight_box->addItem(i18nc("Font style", "Demi-Bold"), QFont::DemiBold);
143     font_weight_box->addItem(i18nc("Font style", "Bold"), QFont::Bold);
144     font_weight_box->addItem(i18nc("Font style", "Black"), QFont::Black);
145     font_weight_box->setToolTip(i18n("Font weight"));
146     font_weight_box->setCurrentIndex(1);
147     font_weight_box->blockSignals(false);
148
149     buttonFitZoom->setIcon(KIcon("zoom-fit-best"));
150     buttonRealSize->setIcon(KIcon("zoom-original"));
151     buttonItalic->setIcon(KIcon("format-text-italic"));
152     buttonUnder->setIcon(KIcon("format-text-underline"));
153     buttonAlignCenter->setIcon(KIcon("format-justify-center"));
154     buttonAlignLeft->setIcon(KIcon("format-justify-left"));
155     buttonAlignRight->setIcon(KIcon("format-justify-right"));
156     buttonAlignNone->setIcon(KIcon("kdenlive-align-none"));
157
158     buttonAlignNone->setToolTip(i18n("No alignment"));
159     buttonAlignRight->setToolTip(i18n("Align right"));
160     buttonAlignLeft->setToolTip(i18n("Align left"));
161     buttonAlignCenter->setToolTip(i18n("Align center"));
162
163     m_unicodeAction = new QAction(KIcon("kdenlive-insert-unicode"), QString(), this);
164     m_unicodeAction->setShortcut(Qt::SHIFT + Qt::CTRL + Qt::Key_U);
165     m_unicodeAction->setToolTip(i18n("Insert Unicode character") + ' ' + m_unicodeAction->shortcut().toString());
166     connect(m_unicodeAction, SIGNAL(triggered()), this, SLOT(slotInsertUnicode()));
167     buttonInsertUnicode->setDefaultAction(m_unicodeAction);
168
169     origin_x_left->setToolTip(i18n("Invert x axis and change 0 point"));
170     origin_y_top->setToolTip(i18n("Invert y axis and change 0 point"));
171     rectBColor->setToolTip(i18n("Select fill color"));
172     rectFColor->setToolTip(i18n("Select border color"));
173     rectBAlpha->setToolTip(i18n("Fill transparency"));
174     rectFAlpha->setToolTip(i18n("Border transparency"));
175     zoom_slider->setToolTip(i18n("Zoom"));
176     buttonRealSize->setToolTip(i18n("Original size (1:1)"));
177     buttonFitZoom->setToolTip(i18n("Fit zoom"));
178     kcolorbutton->setToolTip(i18n("Select background color"));
179     horizontalSlider->setToolTip(i18n("Background Transparency"));
180
181     itemhcenter->setIcon(KIcon("kdenlive-align-hor"));
182     itemhcenter->setToolTip(i18n("Align item horizontally"));
183     itemvcenter->setIcon(KIcon("kdenlive-align-vert"));
184     itemvcenter->setToolTip(i18n("Align item vertically"));
185     itemtop->setIcon(KIcon("kdenlive-align-top"));
186     itemtop->setToolTip(i18n("Align item to top"));
187     itembottom->setIcon(KIcon("kdenlive-align-bottom"));
188     itembottom->setToolTip(i18n("Align item to bottom"));
189     itemright->setIcon(KIcon("kdenlive-align-right"));
190     itemright->setToolTip(i18n("Align item to right"));
191     itemleft->setIcon(KIcon("kdenlive-align-left"));
192     itemleft->setToolTip(i18n("Align item to left"));
193
194
195     QHBoxLayout *layout = new QHBoxLayout;
196     frame_toolbar->setLayout(layout);
197     layout->setContentsMargins(2, 2, 2, 2);
198     QToolBar *m_toolbar = new QToolBar("titleToolBar", this);
199
200     m_buttonCursor = m_toolbar->addAction(KIcon("transform-move"), QString());
201     m_buttonCursor->setCheckable(true);
202     m_buttonCursor->setShortcut(Qt::ALT + Qt::Key_S);
203     m_buttonCursor->setToolTip(i18n("Selection Tool") + ' ' + m_buttonCursor->shortcut().toString());
204     connect(m_buttonCursor, SIGNAL(triggered()), this, SLOT(slotSelectTool()));
205
206     m_buttonText = m_toolbar->addAction(KIcon("insert-text"), QString());
207     m_buttonText->setCheckable(true);
208     m_buttonText->setShortcut(Qt::ALT + Qt::Key_T);
209     m_buttonText->setToolTip(i18n("Add Text") + ' ' + m_buttonText->shortcut().toString());
210     connect(m_buttonText, SIGNAL(triggered()), this, SLOT(slotTextTool()));
211
212     m_buttonRect = m_toolbar->addAction(KIcon("kdenlive-insert-rect"), QString());
213     m_buttonRect->setCheckable(true);
214     m_buttonRect->setShortcut(Qt::ALT + Qt::Key_R);
215     m_buttonRect->setToolTip(i18n("Add Rectangle") + ' ' + m_buttonRect->shortcut().toString());
216     connect(m_buttonRect, SIGNAL(triggered()), this, SLOT(slotRectTool()));
217
218     m_buttonImage = m_toolbar->addAction(KIcon("insert-image"), QString());
219     m_buttonImage->setCheckable(false);
220     m_buttonImage->setShortcut(Qt::ALT + Qt::Key_I);
221     m_buttonImage->setToolTip(i18n("Add Image") + ' ' + m_buttonImage->shortcut().toString());
222     connect(m_buttonImage, SIGNAL(triggered()), this, SLOT(slotImageTool()));
223
224     m_toolbar->addSeparator();
225
226     m_buttonLoad = m_toolbar->addAction(KIcon("document-open"), i18n("Open Document"));
227     m_buttonLoad->setCheckable(false);
228     m_buttonLoad->setShortcut(Qt::CTRL + Qt::Key_O);
229     connect(m_buttonLoad, SIGNAL(triggered()), this, SLOT(loadTitle()));
230
231     m_buttonSave = m_toolbar->addAction(KIcon("document-save-as"), i18n("Save As"));
232     m_buttonSave->setCheckable(false);
233     m_buttonSave->setShortcut(Qt::CTRL + Qt::Key_S);
234     connect(m_buttonSave, SIGNAL(triggered()), this, SLOT(saveTitle()));
235
236     layout->addWidget(m_toolbar);
237
238     // initialize graphic scene
239     m_scene = new GraphicsSceneRectMove(this);
240     graphicsView->setScene(m_scene);
241     m_titledocument.setScene(m_scene, m_frameWidth, m_frameHeight);
242     connect(m_scene, SIGNAL(changed(QList<QRectF>)), this, SLOT(slotChanged()));
243
244     // a gradient background
245     /*QRadialGradient *gradient = new QRadialGradient(0, 0, 10);
246     gradient->setSpread(QGradient::ReflectSpread);
247     scene->setBackgroundBrush(*gradient);*/
248
249     m_frameImage = new QGraphicsPixmapItem();
250     QTransform qtrans;
251     qtrans.scale(2.0, 2.0);
252     m_frameImage->setTransform(qtrans);
253     m_frameImage->setZValue(-1200);
254     m_frameImage->setFlags(0);
255     displayBackgroundFrame();
256     graphicsView->scene()->addItem(m_frameImage);
257
258     connect(m_scene, SIGNAL(selectionChanged()), this , SLOT(selectionChanged()));
259     connect(m_scene, SIGNAL(itemMoved()), this , SLOT(selectionChanged()));
260     connect(m_scene, SIGNAL(sceneZoom(bool)), this , SLOT(slotZoom(bool)));
261     connect(m_scene, SIGNAL(actionFinished()), this , SLOT(slotSelectTool()));
262     //connect(m_scene, SIGNAL(actionFinished()), this , SLOT(selectionChanged()));
263     connect(m_scene, SIGNAL(newRect(QGraphicsRectItem *)), this , SLOT(slotNewRect(QGraphicsRectItem *)));
264     connect(m_scene, SIGNAL(newText(QGraphicsTextItem *)), this , SLOT(slotNewText(QGraphicsTextItem *)));
265     connect(zoom_slider, SIGNAL(valueChanged(int)), this , SLOT(slotUpdateZoom(int)));
266
267     QPen framepen(Qt::DotLine);
268     framepen.setColor(Qt::red);
269
270     m_frameBorder = new QGraphicsRectItem(QRectF(0, 0, m_frameWidth, m_frameHeight));
271     m_frameBorder->setPen(framepen);
272     m_frameBorder->setZValue(-1100);
273     m_frameBorder->setBrush(Qt::transparent);
274     m_frameBorder->setFlags(0);
275     graphicsView->scene()->addItem(m_frameBorder);
276
277     // mbd: load saved settings
278     readChoices();
279
280     graphicsView->show();
281     //graphicsView->setRenderHint(QPainter::Antialiasing);
282     graphicsView->setInteractive(true);
283     //graphicsView->resize(400, 300);
284     kDebug() << "// TITLE WIDGWT: " << graphicsView->viewport()->width() << "x" << graphicsView->viewport()->height();
285     //toolBox->setItemEnabled(2, false);
286     m_startViewport = new QGraphicsRectItem(QRectF(0, 0, m_frameWidth, m_frameHeight));
287     m_endViewport = new QGraphicsRectItem(QRectF(0, 0, m_frameWidth, m_frameHeight));
288     m_startViewport->setData(0, m_frameWidth);
289     m_startViewport->setData(1, m_frameHeight);
290     m_endViewport->setData(0, m_frameWidth);
291     m_endViewport->setData(1, m_frameHeight);
292
293     if (!url.isEmpty()) loadTitle(url);
294     else {
295         slotTextTool();
296         QTimer::singleShot(200, this, SLOT(slotAdjustZoom()));
297     }
298     initAnimation();
299     connect(anim_start, SIGNAL(toggled(bool)), this, SLOT(slotAnimStart(bool)));
300     connect(anim_end, SIGNAL(toggled(bool)), this, SLOT(slotAnimEnd(bool)));
301 }
302
303 TitleWidget::~TitleWidget()
304 {
305     delete m_buttonRect;
306     delete m_buttonText;
307     delete m_buttonImage;
308     delete m_buttonCursor;
309     delete m_buttonSave;
310     delete m_buttonLoad;
311     delete m_unicodeAction;
312
313     delete m_unicodeDialog;
314     delete m_frameBorder;
315     delete m_frameImage;
316     delete m_startViewport;
317     delete m_endViewport;
318     delete m_scene;
319     delete m_signalMapper;
320 }
321
322 //static
323 QStringList TitleWidget::getFreeTitleInfo(const KUrl &projectUrl, bool isClone)
324 {
325     QStringList result;
326     QString titlePath = projectUrl.path(KUrl::AddTrailingSlash) + "titles/";
327     KStandardDirs::makeDir(titlePath);
328     titlePath.append((isClone == false) ? "title" : "clone");
329     int counter = 0;
330     QString path;
331     while (path.isEmpty() || QFile::exists(path)) {
332         counter++;
333         path = titlePath + QString::number(counter).rightJustified(3, '0', false) + ".png";
334     }
335     result.append(((isClone == false) ? i18n("Title") : i18n("Clone")) + ' ' + QString::number(counter).rightJustified(3, '0', false));
336     result.append(path);
337     return result;
338 }
339
340 QString TitleWidget::getTitleResourceFromName(const KUrl &projectUrl, const QString &titleName)
341 {
342     QStringList result;
343     QString titlePath = projectUrl.path(KUrl::AddTrailingSlash) + "titles/";
344     KStandardDirs::makeDir(titlePath);
345     return titlePath + titleName + ".png";
346 }
347
348 //virtual
349 void TitleWidget::resizeEvent(QResizeEvent * /*event*/)
350 {
351     //slotAdjustZoom();
352 }
353
354 void TitleWidget::slotTextTool()
355 {
356     m_scene->setTool(TITLE_TEXT);
357     showToolbars(TITLE_TEXT);
358     checkButton(TITLE_TEXT);
359 }
360
361 void TitleWidget::slotRectTool()
362 {
363     m_scene->setTool(TITLE_RECTANGLE);
364     showToolbars(TITLE_RECTANGLE);
365     checkButton(TITLE_RECTANGLE);
366 }
367
368 void TitleWidget::slotSelectTool()
369 {
370     m_scene->setTool(TITLE_SELECT);
371
372     // Find out which toolbars need to be shown, depending on selected item
373     TITLETOOL t = TITLE_SELECT;
374     QList<QGraphicsItem *> l = graphicsView->scene()->selectedItems();
375     if (l.size() > 0) {
376         switch (l.at(0)->type()) {
377         case TEXTITEM:
378             t = TITLE_TEXT;
379             break;
380         case RECTITEM:
381             t = TITLE_RECTANGLE;
382             break;
383         case IMAGEITEM:
384             t = TITLE_IMAGE;
385             break;
386         }
387     }
388
389     enableToolbars(t);
390     if (t == TITLE_RECTANGLE && (l.at(0) == m_endViewport || l.at(0) == m_startViewport)) {
391         //graphicsView->centerOn(l.at(0));
392         t = TITLE_NONE;
393     }
394     showToolbars(t);
395
396     if (l.size() > 0) {
397         updateCoordinates(l.at(0));
398         updateDimension(l.at(0));
399         updateRotZoom(l.at(0));
400     }
401
402     checkButton(TITLE_SELECT);
403 }
404
405 void TitleWidget::slotImageTool()
406 {
407     KUrl url = KFileDialog::getOpenUrl(KUrl(), "*.svg *.png *.jpg *.jpeg *.gif *.raw", this, i18n("Load Image"));
408     if (!url.isEmpty()) {
409         if (url.path().endsWith(".svg")) {
410             QGraphicsSvgItem *svg = new QGraphicsSvgItem(url.toLocalFile());
411             svg->setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable);
412             svg->setZValue(m_count++);
413             svg->setData(Qt::UserRole, url.path());
414             graphicsView->scene()->addItem(svg);
415         } else {
416             QPixmap pix(url.path());
417             QGraphicsPixmapItem *image = new QGraphicsPixmapItem(pix);
418             image->setShapeMode(QGraphicsPixmapItem::BoundingRectShape);
419             image->setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable);
420             image->setData(Qt::UserRole, url.path());
421             image->setZValue(m_count++);
422             graphicsView->scene()->addItem(image);
423         }
424     }
425     m_scene->setTool(TITLE_SELECT);
426     showToolbars(TITLE_SELECT);
427     checkButton(TITLE_NONE);
428 }
429
430 void TitleWidget::showToolbars(TITLETOOL toolType)
431 {
432     switch (toolType) {
433     case TITLE_TEXT:
434         rect_properties->setHidden(true);
435         image_properties->setHidden(true);
436         no_properties->setHidden(true);
437         text_properties->setHidden(false);
438         break;
439     case TITLE_RECTANGLE:
440         image_properties->setHidden(true);
441         no_properties->setHidden(true);
442         text_properties->setHidden(true);
443         rect_properties->setHidden(false);
444         break;
445     case TITLE_IMAGE:
446         no_properties->setHidden(true);
447         text_properties->setHidden(true);
448         rect_properties->setHidden(true);
449         image_properties->setHidden(false);
450         break;
451     default:
452         text_properties->setHidden(true);
453         rect_properties->setHidden(true);
454         image_properties->setHidden(true);
455         no_properties->setHidden(false);
456         break;
457     }
458 }
459
460 void TitleWidget::enableToolbars(TITLETOOL toolType)
461 {
462     // TITLETOOL is defined in graphicsscenerectmove.h
463     bool bFrame = false;
464     bool bText = false;
465     bool bRect = false;
466     bool bImage = false;
467     bool bValue_w = false;
468     bool bValue_h = false;
469
470     switch (toolType) {
471     case TITLE_SELECT:
472         break;
473     case TITLE_TEXT:
474         bFrame = true;
475         bText = true;
476         break;
477     case TITLE_RECTANGLE:
478         bFrame = true;
479         bRect = true;
480         bValue_w = true;
481         bValue_h = true;
482         break;
483     case TITLE_IMAGE:
484         bFrame = true;
485         bValue_w = true;
486         bValue_h = true;
487         bImage = true;
488         break;
489     default:
490         break;
491     }
492     frame_properties->setEnabled(bFrame);
493     text_properties->setEnabled(bText);
494     rect_properties->setEnabled(bRect);
495     image_properties->setEnabled(bImage);
496     value_w->setEnabled(bValue_w);
497     value_h->setEnabled(bValue_h);
498 }
499
500 void TitleWidget::checkButton(TITLETOOL toolType)
501 {
502     bool bSelect = false;
503     bool bText = false;
504     bool bRect = false;
505     bool bImage = false;
506
507     switch (toolType) {
508     case TITLE_SELECT:
509         bSelect = true;
510         break;
511     case TITLE_TEXT:
512         bText = true;
513         break;
514     case TITLE_RECTANGLE:
515         bRect = true;
516         break;
517     case TITLE_IMAGE:
518         bImage = true;
519         break;
520     case TITLE_NONE:
521         break;
522     }
523
524     m_buttonCursor->setChecked(bSelect);
525     m_buttonText->setChecked(bText);
526     m_buttonRect->setChecked(bRect);
527     m_buttonImage->setChecked(bImage);
528 }
529
530 void TitleWidget::displayBackgroundFrame()
531 {
532     if (!displayBg->isChecked()) {
533         QPixmap bg(m_frameWidth / 2, m_frameHeight / 2);
534         QPixmap pattern(20, 20);
535         pattern.fill();
536         QColor bgcolor(210, 210, 210);
537         QPainter p;
538         p.begin(&pattern);
539         p.fillRect(QRect(0, 0, 10, 10), bgcolor);
540         p.fillRect(QRect(10, 10, 20, 20), bgcolor);
541         p.end();
542         QBrush br(pattern);
543
544         p.begin(&bg);
545         p.fillRect(bg.rect(), br);
546         p.end();
547         m_frameImage->setPixmap(bg);
548     } else {
549         m_frameImage->setPixmap(QPixmap::fromImage(m_render->extractFrame((int) m_render->seekPosition().frames(m_render->fps()), m_frameWidth / 2, m_frameHeight / 2)));
550     }
551 }
552
553 void TitleWidget::initAnimation()
554 {
555     align_box->setEnabled(false);
556     QPen startpen(Qt::DotLine);
557     QPen endpen(Qt::DashDotLine);
558     startpen.setColor(QColor(100, 200, 100, 140));
559     endpen.setColor(QColor(200, 100, 100, 140));
560
561     m_startViewport->setPen(startpen);
562     m_endViewport->setPen(endpen);
563
564     m_startViewport->setZValue(-1000);
565     m_endViewport->setZValue(-1000);
566
567     m_startViewport->setFlags(0);
568     m_endViewport->setFlags(0);
569
570     graphicsView->scene()->addItem(m_startViewport);
571     graphicsView->scene()->addItem(m_endViewport);
572
573     connect(keep_aspect, SIGNAL(toggled(bool)), this, SLOT(slotKeepAspect(bool)));
574     connect(resize50, SIGNAL(clicked()), this, SLOT(slotResize50()));
575     connect(resize100, SIGNAL(clicked()), this, SLOT(slotResize100()));
576     connect(resize200, SIGNAL(clicked()), this, SLOT(slotResize200()));
577 }
578
579 void TitleWidget::slotUpdateZoom(int pos)
580 {
581     m_scene->setZoom((double) pos / 100);
582     zoom_label->setText(QString::number(pos) + '%');
583 }
584
585 void TitleWidget::slotZoom(bool up)
586 {
587     int pos = zoom_slider->value();
588     if (up) pos++;
589     else pos--;
590     zoom_slider->setValue(pos);
591 }
592
593 void TitleWidget::slotAdjustZoom()
594 {
595     /*double scalex = graphicsView->width() / (double)(m_frameWidth * 1.2);
596     double scaley = graphicsView->height() / (double)(m_frameHeight * 1.2);
597     if (scalex > scaley) scalex = scaley;
598     int zoompos = (int)(scalex * 7 + 0.5);*/
599     graphicsView->fitInView(m_frameBorder, Qt::KeepAspectRatio);
600     int zoompos = graphicsView->matrix().m11() * 100;
601     zoom_slider->setValue(zoompos);
602     graphicsView->centerOn(m_frameBorder);
603 }
604
605 void TitleWidget::slotZoomOneToOne()
606 {
607     zoom_slider->setValue(100);
608     graphicsView->centerOn(m_frameBorder);
609 }
610
611 void TitleWidget::slotNewRect(QGraphicsRectItem * rect)
612 {
613     updateAxisButtons(rect); // back to default
614
615     QColor f = rectFColor->color();
616     f.setAlpha(rectFAlpha->value());
617     QPen penf(f);
618     penf.setWidth(rectLineWidth->value());
619     rect->setPen(penf);
620     QColor b = rectBColor->color();
621     b.setAlpha(rectBAlpha->value());
622     rect->setBrush(QBrush(b));
623     rect->setZValue(m_count++);
624     //setCurrentItem(rect);
625     //graphicsView->setFocus();
626 }
627
628 void TitleWidget::slotNewText(QGraphicsTextItem *tt)
629 {
630     updateAxisButtons(tt); // back to default
631
632     QFont font = font_family->currentFont();
633     font.setPixelSize(font_size->value());
634     // mbd: issue 551:
635     font.setWeight(font_weight_box->itemData(font_weight_box->currentIndex()).toInt());
636     font.setItalic(buttonItalic->isChecked());
637     font.setUnderline(buttonUnder->isChecked());
638
639     tt->setFont(font);
640     QColor color = fontColorButton->color();
641     color.setAlpha(textAlpha->value());
642     tt->setDefaultTextColor(color);
643     tt->setZValue(m_count++);
644     setCurrentItem(tt);
645 }
646
647 void TitleWidget::setFontBoxWeight(int weight)
648 {
649     int index = font_weight_box->findData(weight);
650     if (index < 0) {
651         index = font_weight_box->findData(QFont::Normal);
652     }
653     font_weight_box->setCurrentIndex(index);
654 }
655
656 void TitleWidget::setCurrentItem(QGraphicsItem *item)
657 {
658     m_scene->setSelectedItem(item);
659 }
660
661 void TitleWidget::zIndexChanged(int v)
662 {
663     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
664     if (l.size() >= 1) {
665         l[0]->setZValue(v);
666     }
667 }
668
669 void TitleWidget::selectionChanged()
670 {
671     if (m_scene->tool() != TITLE_SELECT) return;
672     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
673     //toolBox->setItemEnabled(2, false);
674     //toolBox->setItemEnabled(3, false);
675     value_x->blockSignals(true);
676     value_y->blockSignals(true);
677     value_w->blockSignals(true);
678     value_h->blockSignals(true);
679     itemzoom->blockSignals(true);
680     itemrotate->blockSignals(true);
681     if (l.size() == 0) {
682         bool blockX = !origin_x_left->signalsBlocked();
683         bool blockY = !origin_y_top->signalsBlocked();
684         if (blockX) origin_x_left->blockSignals(true);
685         if (blockY) origin_y_top->blockSignals(true);
686         origin_x_left->setChecked(false);
687         origin_y_top->setChecked(false);
688         updateTextOriginX();
689         updateTextOriginY();
690         enableToolbars(TITLE_NONE);
691         if (blockX) origin_x_left->blockSignals(false);
692         if (blockY) origin_y_top->blockSignals(false);
693         itemzoom->setEnabled(false);
694         itemrotate->setEnabled(false);
695     } else if (l.size() == 1) {
696         if (l.at(0) != m_startViewport && l.at(0) != m_endViewport) {
697             itemzoom->setEnabled(true);
698             itemrotate->setEnabled(true);
699         } else {
700             itemzoom->setEnabled(false);
701             itemrotate->setEnabled(false);
702         }
703         if (l.at(0)->type() == TEXTITEM) {
704             showToolbars(TITLE_TEXT);
705             QGraphicsTextItem* i = static_cast <QGraphicsTextItem *>(l.at(0));
706             //if (l[0]->hasFocus())
707             //toolBox->setCurrentIndex(0);
708             //toolBox->setItemEnabled(2, true);
709             font_size->blockSignals(true);
710             font_family->blockSignals(true);
711             font_weight_box->blockSignals(true);
712             buttonItalic->blockSignals(true);
713             buttonUnder->blockSignals(true);
714             fontColorButton->blockSignals(true);
715             textAlpha->blockSignals(true);
716             buttonAlignLeft->blockSignals(true);
717             buttonAlignRight->blockSignals(true);
718             buttonAlignNone->blockSignals(true);
719             buttonAlignCenter->blockSignals(true);
720
721             QFont font = i->font();
722             font_family->setCurrentFont(font);
723             font_size->setValue(font.pixelSize());
724             buttonItalic->setChecked(font.italic());
725             buttonUnder->setChecked(font.underline());
726             setFontBoxWeight(font.weight());
727
728             QColor color = i->defaultTextColor();
729             fontColorButton->setColor(color);
730             textAlpha->setValue(color.alpha());
731
732             QTextCursor cur = i->textCursor();
733             QTextBlockFormat format = cur.blockFormat();
734             if (i->textWidth() == -1) buttonAlignNone->setChecked(true);
735             else if (format.alignment() == Qt::AlignHCenter) buttonAlignCenter->setChecked(true);
736             else if (format.alignment() == Qt::AlignRight) buttonAlignRight->setChecked(true);
737             else if (format.alignment() == Qt::AlignLeft) buttonAlignLeft->setChecked(true);
738
739             font_size->blockSignals(false);
740             font_family->blockSignals(false);
741             font_weight_box->blockSignals(false);
742             buttonItalic->blockSignals(false);
743             buttonUnder->blockSignals(false);
744             fontColorButton->blockSignals(false);
745             textAlpha->blockSignals(false);
746             buttonAlignLeft->blockSignals(false);
747             buttonAlignRight->blockSignals(false);
748             buttonAlignNone->blockSignals(false);
749             buttonAlignCenter->blockSignals(false);
750
751             updateAxisButtons(i);
752             updateCoordinates(i);
753             updateDimension(i);
754             enableToolbars(TITLE_TEXT);
755
756         } else if ((l.at(0))->type() == RECTITEM) {
757             showToolbars(TITLE_RECTANGLE);
758             settingUp = true;
759             QGraphicsRectItem *rec = static_cast <QGraphicsRectItem *>(l.at(0));
760             if (rec == m_startViewport || rec == m_endViewport) {
761                 /*toolBox->setCurrentIndex(3);
762                 toolBox->widget(0)->setEnabled(false);
763                 toolBox->widget(1)->setEnabled(false);*/
764                 enableToolbars(TITLE_NONE);
765             } else {
766                 /*toolBox->widget(0)->setEnabled(true);
767                 toolBox->widget(1)->setEnabled(true);
768                 toolBox->setCurrentIndex(0);*/
769                 //toolBox->setItemEnabled(3, true);
770                 rectFAlpha->setValue(rec->pen().color().alpha());
771                 rectBAlpha->setValue(rec->brush().color().alpha());
772                 //kDebug() << rec->brush().color().alpha();
773                 QColor fcol = rec->pen().color();
774                 QColor bcol = rec->brush().color();
775                 //fcol.setAlpha(255);
776                 //bcol.setAlpha(255);
777                 rectFColor->setColor(fcol);
778                 rectBColor->setColor(bcol);
779                 settingUp = false;
780                 rectLineWidth->setValue(rec->pen().width());
781                 enableToolbars(TITLE_RECTANGLE);
782             }
783
784             updateAxisButtons(l.at(0));
785             updateCoordinates(rec);
786             updateDimension(rec);
787
788         } else if (l.at(0)->type() == IMAGEITEM) {
789             showToolbars(TITLE_IMAGE);
790
791             updateCoordinates(l.at(0));
792             updateDimension(l.at(0));
793
794             enableToolbars(TITLE_IMAGE);
795
796         } else {
797             //toolBox->setCurrentIndex(0);
798             showToolbars(TITLE_NONE);
799             enableToolbars(TITLE_NONE);
800             /*frame_properties->setEnabled(false);
801             text_properties->setEnabled(false);
802             rect_properties->setEnabled(false);*/
803         }
804         zValue->setValue((int)l.at(0)->zValue());
805         itemzoom->setValue((int)(m_transformations.value(l.at(0)).scalex * 100.0 + 0.5));
806         itemrotate->setValue((int)(m_transformations.value(l.at(0)).rotate));
807         value_x->blockSignals(false);
808         value_y->blockSignals(false);
809         value_w->blockSignals(false);
810         value_h->blockSignals(false);
811         itemzoom->blockSignals(false);
812         itemrotate->blockSignals(false);
813     }
814 }
815
816 void TitleWidget::slotValueChanged(int type)
817 {
818     QList<QGraphicsItem *> l = graphicsView->scene()->selectedItems();
819     if (l.size() > 0 && l.at(0)->type() == IMAGEITEM) {
820
821         int val = 0;
822         switch (type) {
823         case ValueWidth:
824             val = value_w->value();
825             break;
826         case ValueHeight:
827             val = value_h->value();
828             break;
829         }
830
831         QGraphicsItem *i = l.at(0);
832         Transform t = m_transformations.value(i);
833
834         // Ratio width:height
835         double phi = (double) i->boundingRect().width() / i->boundingRect().height();
836         double alpha = (double) t.rotate / 180.0 * M_PI;
837
838         // New length
839         double length = val;
840
841         // Scaling factor
842         double scale = 1;
843
844         switch (type) {
845         case ValueWidth:
846             // Add 0.5 because otherwise incrementing by 1 might have no effect
847             length = val / (cos(alpha) + 1 / phi * sin(alpha)) + 0.5;
848             scale = length / i->boundingRect().width();
849             break;
850         case ValueHeight:
851             length = val / (phi * sin(alpha) + cos(alpha)) + 0.5;
852             scale = length / i->boundingRect().height();
853             break;
854         }
855
856         t.scalex = scale;
857         t.scaley = scale;
858         QTransform qtrans;
859         qtrans.scale(scale, scale);
860         qtrans.rotate(t.rotate);
861         i->setTransform(qtrans);
862         m_transformations[i] = t;
863
864         updateDimension(i);
865         updateRotZoom(i);
866     }
867 }
868
869 /** \brief Updates position/size of the selected item when a value
870  * of an item (coordinates, size) has changed */
871 void TitleWidget::slotAdjustSelectedItem()
872 {
873     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
874     if (l.size() >= 1) {
875         if (l.at(0)->type() == RECTITEM) {
876             //rect item
877             QGraphicsRectItem *rec = static_cast <QGraphicsRectItem *>(l.at(0));
878             updatePosition(rec);
879             rec->setRect(QRect(0, 0, value_w->value(), value_h->value()));
880         } else if (l.at(0)->type() == TEXTITEM) {
881             //text item
882             updatePosition(l.at(0));
883         } else if (l.at(0)->type() == IMAGEITEM) {
884             //image item
885             updatePosition(l.at(0));
886         }
887     }
888 }
889
890 /** \brief Updates width/height int the text fields, regarding transformation matrix */
891 void TitleWidget::updateDimension(QGraphicsItem *i)
892 {
893     value_w->blockSignals(true);
894     value_h->blockSignals(true);
895
896
897     if (i->type() == IMAGEITEM) {
898         // Get multipliers for rotation/scaling
899
900         /*Transform t = m_transformations.value(i);
901         QRectF r = i->boundingRect();
902         int width = (int) ( abs(r.width()*t.scalex * cos(t.rotate/180.0*M_PI))
903                     + abs(r.height()*t.scaley * sin(t.rotate/180.0*M_PI)) );
904         int height = (int) ( abs(r.height()*t.scaley * cos(t.rotate/180*M_PI))
905                     + abs(r.width()*t.scalex * sin(t.rotate/180*M_PI)) );*/
906
907         value_w->setValue(i->sceneBoundingRect().width());
908         value_h->setValue(i->sceneBoundingRect().height());
909     } else if (i->type() == RECTITEM) {
910         QGraphicsRectItem *r = static_cast <QGraphicsRectItem *>(i);
911         value_w->setValue((int) r->rect().width());
912         value_h->setValue((int) r->rect().height());
913     } else if (i->type() == TEXTITEM) {
914         QGraphicsTextItem *t = static_cast <QGraphicsTextItem *>(i);
915         value_w->setValue((int) t->boundingRect().width());
916         value_h->setValue((int) t->boundingRect().height());
917     }
918
919     value_w->blockSignals(false);
920     value_h->blockSignals(false);
921 }
922
923 /** \brief Updates the coordinates in the text fields from the item */
924 void TitleWidget::updateCoordinates(QGraphicsItem *i)
925 {
926     // Block signals emitted by this method
927     value_x->blockSignals(true);
928     value_y->blockSignals(true);
929
930     if (i->type() == TEXTITEM) {
931
932         QGraphicsTextItem *rec = static_cast <QGraphicsTextItem *>(i);
933
934         // Set the correct x coordinate value
935         if (origin_x_left->isChecked()) {
936             // Origin (0 point) is at m_frameWidth, coordinate axis is inverted
937             value_x->setValue((int)(m_frameWidth - rec->pos().x() - rec->boundingRect().width()));
938         } else {
939             // Origin is at 0 (default)
940             value_x->setValue((int) rec->pos().x());
941         }
942
943         // Same for y
944         if (origin_y_top->isChecked()) {
945             value_y->setValue((int)(m_frameHeight - rec->pos().y() - rec->boundingRect().height()));
946         } else {
947             value_y->setValue((int) rec->pos().y());
948         }
949
950     } else if (i->type() == RECTITEM) {
951
952         QGraphicsRectItem *rec = static_cast <QGraphicsRectItem *>(i);
953
954         if (origin_x_left->isChecked()) {
955             // Origin (0 point) is at m_frameWidth
956             value_x->setValue((int)(m_frameWidth - rec->pos().x() - rec->rect().width()));
957         } else {
958             // Origin is at 0 (default)
959             value_x->setValue((int) rec->pos().x());
960         }
961
962         if (origin_y_top->isChecked()) {
963             value_y->setValue((int)(m_frameHeight - rec->pos().y() - rec->rect().height()));
964         } else {
965             value_y->setValue((int) rec->pos().y());
966         }
967
968     } else if (i->type() == IMAGEITEM) {
969
970         if (origin_x_left->isChecked()) {
971             value_x->setValue((int)(m_frameWidth - i->pos().x() - i->sceneBoundingRect().width()));
972         } else {
973             value_x->setValue((int) i->pos().x());
974         }
975
976         if (origin_y_top->isChecked()) {
977             value_y->setValue((int)(m_frameHeight - i->pos().y() - i->sceneBoundingRect().height()));
978         } else {
979             value_y->setValue((int) i->pos().y());
980         }
981
982     }
983
984     // Stop blocking signals now
985     value_x->blockSignals(false);
986     value_y->blockSignals(false);
987 }
988
989 void TitleWidget::updateRotZoom(QGraphicsItem *i)
990 {
991     itemzoom->blockSignals(true);
992     itemrotate->blockSignals(false);
993
994     Transform t = m_transformations.value(i);
995     itemzoom->setValue((int)(t.scalex * 100.0 + 0.5));
996     itemrotate->setValue((int)(t.rotate));
997
998     itemzoom->blockSignals(false);
999     itemrotate->blockSignals(false);
1000 }
1001
1002 /** \brief Updates the position of an item by reading coordinates from the text fields */
1003 void TitleWidget::updatePosition(QGraphicsItem *i)
1004 {
1005     if (i->type() == TEXTITEM) {
1006         QGraphicsTextItem *rec = static_cast <QGraphicsTextItem *>(i);
1007
1008         int posX;
1009         if (origin_x_left->isChecked()) {
1010             /* Origin of the x axis is at m_frameWidth,
1011              * and distance from right border of the item to the right
1012              * border of the frame is taken.
1013              * See comment to slotOriginXClicked().
1014              */
1015             posX = m_frameWidth - value_x->value() - rec->boundingRect().width();
1016         } else {
1017             posX = value_x->value();
1018         }
1019
1020         int posY;
1021         if (origin_y_top->isChecked()) {
1022             /* Same for y axis */
1023             posY = m_frameHeight - value_y->value() - rec->boundingRect().height();
1024         } else {
1025             posY = value_y->value();
1026         }
1027
1028         rec->setPos(posX, posY);
1029
1030     } else if (i->type() == RECTITEM) {
1031
1032         QGraphicsRectItem *rec = static_cast <QGraphicsRectItem *>(i);
1033
1034         int posX;
1035         if (origin_x_left->isChecked()) {
1036             posX = m_frameWidth - value_x->value() - rec->rect().width();
1037         } else {
1038             posX = value_x->value();
1039         }
1040
1041         int posY;
1042         if (origin_y_top->isChecked()) {
1043             posY = m_frameHeight - value_y->value() - rec->rect().height();
1044         } else {
1045             posY = value_y->value();
1046         }
1047
1048         rec->setPos(posX, posY);
1049
1050     } else if (i->type() == IMAGEITEM) {
1051         int posX;
1052         if (origin_x_left->isChecked()) {
1053             // Use the sceneBoundingRect because this also regards transformations like zoom
1054             posX = m_frameWidth - value_x->value() - i->sceneBoundingRect().width();
1055         } else {
1056             posX = value_x->value();
1057         }
1058
1059         int posY;
1060         if (origin_y_top->isChecked()) {
1061             posY = m_frameHeight - value_y->value() - i->sceneBoundingRect().height();
1062         } else {
1063             posY = value_y->value();
1064         }
1065
1066         i->setPos(posX, posY);
1067
1068     }
1069
1070 }
1071
1072 void TitleWidget::updateTextOriginX()
1073 {
1074     if (origin_x_left->isChecked()) {
1075         origin_x_left->setText(i18n("\u2212X"));
1076     } else {
1077         origin_x_left->setText(i18n("+X"));
1078     }
1079 }
1080
1081 void TitleWidget::slotOriginXClicked()
1082 {
1083     // Update the text displayed on the button.
1084     updateTextOriginX();
1085
1086     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1087     if (l.size() >= 1) {
1088         updateCoordinates(l.at(0));
1089
1090         // Remember x axis setting
1091         l.at(0)->setData(TitleDocument::OriginXLeft, origin_x_left->isChecked() ?
1092                          TitleDocument::AxisInverted : TitleDocument::AxisDefault);
1093     }
1094     graphicsView->setFocus();
1095 }
1096
1097 void TitleWidget::updateTextOriginY()
1098 {
1099     if (origin_y_top->isChecked()) {
1100         origin_y_top->setText(i18n("\u2212Y"));
1101     } else {
1102         origin_y_top->setText(i18n("+Y"));
1103     }
1104 }
1105
1106 void TitleWidget::slotOriginYClicked()
1107 {
1108     // Update the text displayed on the button.
1109     updateTextOriginY();
1110
1111     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1112     if (l.size() >= 1) {
1113         updateCoordinates(l.at(0));
1114
1115         l.at(0)->setData(TitleDocument::OriginYTop, origin_y_top->isChecked() ?
1116                          TitleDocument::AxisInverted : TitleDocument::AxisDefault);
1117
1118     }
1119     graphicsView->setFocus();
1120 }
1121
1122 void TitleWidget::updateAxisButtons(QGraphicsItem *i)
1123 {
1124     int xAxis = i->data(TitleDocument::OriginXLeft).toInt();
1125     int yAxis = i->data(TitleDocument::OriginYTop).toInt();
1126     origin_x_left->blockSignals(true);
1127     origin_y_top->blockSignals(true);
1128
1129     if (xAxis == TitleDocument::AxisInverted) {
1130         origin_x_left->setChecked(true);
1131     } else {
1132         origin_x_left->setChecked(false);
1133     }
1134     updateTextOriginX();
1135
1136     if (yAxis == TitleDocument::AxisInverted) {
1137         origin_y_top->setChecked(true);
1138     } else {
1139         origin_y_top->setChecked(false);
1140     }
1141     updateTextOriginY();
1142
1143     origin_x_left->blockSignals(false);
1144     origin_y_top->blockSignals(false);
1145 }
1146
1147 void TitleWidget::slotChangeBackground()
1148 {
1149     QColor color = kcolorbutton->color();
1150     color.setAlpha(horizontalSlider->value());
1151     m_frameBorder->setBrush(QBrush(color));
1152 }
1153
1154 /**
1155  * Something (yeah) has changed in our QGraphicsScene.
1156  */
1157 void TitleWidget::slotChanged()
1158 {
1159     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1160     if (l.size() >= 1 && l.at(0)->type() == TEXTITEM) {
1161         textChanged(static_cast <QGraphicsTextItem *>(l.at(0)));
1162     }
1163 }
1164
1165 /**
1166  * If the user has set origin_x_left (everything also for y),
1167  * we need to look whether a text element has been selected. If yes,
1168  * we need to ensure that the right border of the text field
1169  * remains fixed also when some text has been entered.
1170  *
1171  * This is also known as right-justified, with the difference that
1172  * it is not valid for text but for its boundingRect. Text may still
1173  * be left-justified.
1174  */
1175 void TitleWidget::textChanged(QGraphicsTextItem *i)
1176 {
1177
1178     updateDimension(i);
1179
1180     if (origin_x_left->isChecked() || origin_y_top->isChecked()) {
1181
1182         if (!i->toPlainText().isEmpty()) {
1183             updatePosition(i);
1184         } else {
1185             /*
1186              * Don't do anything if the string is empty. If the position
1187              * would be updated here, a newly created text field would
1188              * be set to the position of the last selected text field.
1189              */
1190         }
1191     }
1192 }
1193
1194 void TitleWidget::slotInsertUnicode()
1195 {
1196     m_unicodeDialog->exec();
1197 }
1198
1199 void TitleWidget::slotInsertUnicodeString(QString text)
1200 {
1201     QList<QGraphicsItem *> l = graphicsView->scene()->selectedItems();
1202     if (l.size() > 0) {
1203         if (l.at(0)->type() == TEXTITEM) {
1204             QGraphicsTextItem *t = static_cast <QGraphicsTextItem *>(l.at(0));
1205             t->textCursor().insertText(text);
1206         }
1207     }
1208 }
1209
1210 void TitleWidget::slotUpdateText()
1211 {
1212     QFont font = font_family->currentFont();
1213     font.setPixelSize(font_size->value());
1214     font.setItalic(buttonItalic->isChecked());
1215     font.setUnderline(buttonUnder->isChecked());
1216     font.setWeight(font_weight_box->itemData(font_weight_box->currentIndex()).toInt());
1217     QColor color = fontColorButton->color();
1218     color.setAlpha(textAlpha->value());
1219
1220     QGraphicsTextItem* item = NULL;
1221     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1222     if (l.size() == 1 && l.at(0)->type() == TEXTITEM) {
1223         item = static_cast <QGraphicsTextItem *>(l.at(0));
1224     }
1225     if (!item) return;
1226     //if (item->textCursor().selection ().isEmpty())
1227     QTextCursor cur = item->textCursor();
1228     QTextBlockFormat format = cur.blockFormat();
1229     if (buttonAlignLeft->isChecked() || buttonAlignCenter->isChecked() || buttonAlignRight->isChecked()) {
1230         item->setTextWidth(item->boundingRect().width());
1231         if (buttonAlignCenter->isChecked()) format.setAlignment(Qt::AlignHCenter);
1232         else if (buttonAlignRight->isChecked()) format.setAlignment(Qt::AlignRight);
1233         else if (buttonAlignLeft->isChecked()) format.setAlignment(Qt::AlignLeft);
1234     } else {
1235         format.setAlignment(Qt::AlignLeft);
1236         item->setTextWidth(-1);
1237     }
1238
1239     {
1240         item->setFont(font);
1241         item->setDefaultTextColor(color);
1242         cur.select(QTextCursor::Document);
1243         cur.setBlockFormat(format);
1244         item->setTextCursor(cur);
1245         cur.clearSelection();
1246         item->setTextCursor(cur);
1247
1248     }
1249 }
1250
1251 void TitleWidget::rectChanged()
1252 {
1253     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1254     if (l.size() == 1 && l.at(0)->type() == RECTITEM && !settingUp) {
1255         QGraphicsRectItem *rec = static_cast<QGraphicsRectItem *>(l.at(0));
1256         QColor f = rectFColor->color();
1257         f.setAlpha(rectFAlpha->value());
1258         QPen penf(f);
1259         penf.setWidth(rectLineWidth->value());
1260         rec->setPen(penf);
1261         QColor b = rectBColor->color();
1262         b.setAlpha(rectBAlpha->value());
1263         rec->setBrush(QBrush(b));
1264     }
1265 }
1266
1267 void TitleWidget::itemScaled(int val)
1268 {
1269     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1270     if (l.size() == 1) {
1271         Transform x = m_transformations.value(l.at(0));
1272         x.scalex = (double)val / 100.0;
1273         x.scaley = (double)val / 100.0;
1274         QTransform qtrans;
1275         qtrans.scale(x.scalex, x.scaley);
1276         qtrans.rotate(x.rotate);
1277         l[0]->setTransform(qtrans);
1278         m_transformations[l.at(0)] = x;
1279         updateDimension(l.at(0));
1280     }
1281 }
1282
1283 void TitleWidget::itemRotate(int val)
1284 {
1285     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1286     if (l.size() == 1) {
1287         Transform x = m_transformations[l.at(0)];
1288         x.rotate = (double)val;
1289         QTransform qtrans;
1290         qtrans.scale(x.scalex, x.scaley);
1291         qtrans.rotate(x.rotate);
1292         l[0]->setTransform(qtrans);
1293         m_transformations[l.at(0)] = x;
1294         updateDimension(l.at(0));
1295     }
1296 }
1297
1298 void TitleWidget::itemHCenter()
1299 {
1300     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1301     if (l.size() == 1) {
1302         QGraphicsItem *item = l.at(0);
1303         QRectF br = item->sceneBoundingRect();
1304         int width = (int)br.width();
1305         int newPos = (int)((m_frameWidth - width) / 2);
1306         newPos += item->pos().x() - br.left(); // Check item transformation
1307         item->setPos(newPos, item->pos().y());
1308         updateCoordinates(item);
1309     }
1310 }
1311
1312 void TitleWidget::itemVCenter()
1313 {
1314     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1315     if (l.size() == 1) {
1316         QGraphicsItem *item = l.at(0);
1317         QRectF br = item->sceneBoundingRect();
1318         int height = (int)br.height();
1319         int newPos = (int)((m_frameHeight - height) / 2);
1320         newPos += item->pos().y() - br.top(); // Check item transformation
1321         item->setPos(item->pos().x(), newPos);
1322         updateCoordinates(item);
1323     }
1324 }
1325
1326 void TitleWidget::itemTop()
1327 {
1328     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1329     if (l.size() == 1) {
1330         QGraphicsItem *item = l.at(0);
1331         QRectF br = item->sceneBoundingRect();
1332         double diff;
1333         if (br.top() > 0) diff = -br.top();
1334         else diff = -br.bottom();
1335         item->moveBy(0, diff);
1336         updateCoordinates(item);
1337     }
1338 }
1339
1340 void TitleWidget::itemBottom()
1341 {
1342     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1343     if (l.size() == 1) {
1344         QGraphicsItem *item = l.at(0);
1345         QRectF br = item->sceneBoundingRect();
1346         double diff;
1347         if (br.bottom() > m_frameHeight) diff = m_frameHeight - br.top();
1348         else diff = m_frameHeight - br.bottom();
1349         item->moveBy(0, diff);
1350         updateCoordinates(item);
1351     }
1352 }
1353
1354 void TitleWidget::itemLeft()
1355 {
1356     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1357     if (l.size() == 1) {
1358         QGraphicsItem *item = l.at(0);
1359         QRectF br = item->sceneBoundingRect();
1360         double diff;
1361         if (br.left() > 0) diff = -br.left();
1362         else diff = -br.right();
1363         item->moveBy(diff, 0);
1364         updateCoordinates(item);
1365     }
1366 }
1367
1368 void TitleWidget::itemRight()
1369 {
1370     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1371     if (l.size() == 1) {
1372         QGraphicsItem *item = l.at(0);
1373         QRectF br = item->sceneBoundingRect();
1374         double diff;
1375         if (br.right() < m_frameWidth) diff = m_frameWidth - br.right();
1376         else diff = m_frameWidth - br.left();
1377         item->moveBy(diff, 0);
1378         updateCoordinates(item);
1379     }
1380 }
1381
1382 void TitleWidget::setupViewports()
1383 {
1384     //double aspect_ratio = 4.0 / 3.0;//read from project
1385     //better zoom centered, but render uses only the created rect, so no problem to change the zoom function
1386     /*QRectF sp(0, 0, startViewportSize->value() * m_frameWidth / 100.0 , startViewportSize->value()* m_frameHeight / 100.0);
1387     QRectF ep(0, 0, endViewportSize->value() * m_frameWidth / 100.0, endViewportSize->value() * m_frameHeight / 100.0);
1388     // use a polygon thiat uses 16:9 and 4:3 rects forpreview the size in all aspect ratios ?
1389     QPolygonF spoly(sp);
1390     QPolygonF epoly(ep);
1391     spoly.translate(startViewportX->value(), startViewportY->value());
1392     epoly.translate(endViewportX->value(), endViewportY->value());
1393     m_startViewport->setPolygon(spoly);
1394     m_endViewport->setPolygon(epoly);
1395     if (! insertingValues) {
1396         m_startViewport->setData(0, startViewportX->value());
1397         m_startViewport->setData(1, startViewportY->value());
1398         m_startViewport->setData(2, startViewportSize->value());
1399
1400         m_endViewport->setData(0, endViewportX->value());
1401         m_endViewport->setData(1, endViewportY->value());
1402         m_endViewport->setData(2, endViewportSize->value());
1403     }*/
1404 }
1405
1406 void TitleWidget::loadTitle(KUrl url)
1407 {
1408     if (url.isEmpty()) url = KFileDialog::getOpenUrl(KUrl(m_projectTitlePath), "application/x-kdenlivetitle", this, i18n("Load Title"));
1409     if (!url.isEmpty()) {
1410         QList<QGraphicsItem *> items = m_scene->items();
1411         for (int i = 0; i < items.size(); i++) {
1412             if (items.at(i)->zValue() > -1000) delete items.at(i);
1413         }
1414         m_scene->clearTextSelection();
1415         QDomDocument doc;
1416         QString tmpfile;
1417
1418         if (KIO::NetAccess::download(url, tmpfile, 0)) {
1419             QFile file(tmpfile);
1420             if (file.open(QIODevice::ReadOnly)) {
1421                 doc.setContent(&file, false);
1422                 file.close();
1423             } else return;
1424             KIO::NetAccess::removeTempFile(tmpfile);
1425         }
1426         setXml(doc);
1427
1428         /*int out;
1429         m_count = m_titledocument.loadDocument(url, m_startViewport, m_endViewport, &out) + 1;
1430         adjustFrameSize();
1431         title_duration->setText(m_tc.getTimecode(GenTime(out, m_render->fps())));
1432         insertingValues = true;
1433         startViewportX->setValue(m_startViewport->data(0).toInt());
1434         startViewportY->setValue(m_startViewport->data(1).toInt());
1435         startViewportSize->setValue(m_startViewport->data(2).toInt());
1436         endViewportX->setValue(m_endViewport->data(0).toInt());
1437         endViewportY->setValue(m_endViewport->data(1).toInt());
1438         endViewportSize->setValue(m_endViewport->data(2).toInt());
1439
1440         insertingValues = false;
1441         slotSelectTool();
1442         slotAdjustZoom();*/
1443     }
1444 }
1445
1446 void TitleWidget::saveTitle(KUrl url)
1447 {
1448     if (anim_start->isChecked()) slotAnimStart(false);
1449     if (anim_end->isChecked()) slotAnimEnd(false);
1450     if (url.isEmpty()) {
1451         KFileDialog *fs = new KFileDialog(KUrl(m_projectTitlePath), "application/x-kdenlivetitle", this);
1452         fs->setOperationMode(KFileDialog::Saving);
1453         fs->setMode(KFile::File);
1454 #if KDE_IS_VERSION(4,2,0)
1455         fs->setConfirmOverwrite(true);
1456 #endif
1457         fs->setKeepLocation(true);
1458         fs->exec();
1459         url = fs->selectedUrl();
1460         delete fs;
1461     }
1462     if (!url.isEmpty()) {
1463         if (m_titledocument.saveDocument(url, m_startViewport, m_endViewport, m_tc.getFrameCount(title_duration->text())) == false)
1464             KMessageBox::error(this, i18n("Cannot write to file %1", url.path()));
1465     }
1466 }
1467
1468 QDomDocument TitleWidget::xml()
1469 {
1470     QDomDocument doc = m_titledocument.xml(m_startViewport, m_endViewport);
1471     doc.documentElement().setAttribute("out", m_tc.getFrameCount(title_duration->text()));
1472     return doc;
1473 }
1474
1475 int TitleWidget::duration() const
1476 {
1477     return m_tc.getFrameCount(title_duration->text());
1478 }
1479
1480 void TitleWidget::setXml(QDomDocument doc)
1481 {
1482     int out;
1483     m_count = m_titledocument.loadFromXml(doc, m_startViewport, m_endViewport, &out);
1484     adjustFrameSize();
1485     title_duration->setText(m_tc.getTimecode(GenTime(out, m_render->fps())));
1486     /*if (doc.documentElement().hasAttribute("out")) {
1487     GenTime duration = GenTime(doc.documentElement().attribute("out").toDouble() / 1000.0);
1488     title_duration->setText(m_tc.getTimecode(duration));
1489     }
1490     else title_duration->setText(m_tc.getTimecode(GenTime(5000)));*/
1491
1492     QDomElement e = doc.documentElement();
1493     m_transformations.clear();
1494     QList <QGraphicsItem *> items = graphicsView->scene()->items();
1495     const double PI = 4.0 * atan(1.0);
1496     for (int i = 0; i < items.count(); i++) {
1497         QTransform t = items.at(i)->transform();
1498         Transform x;
1499         x.scalex = t.m11();
1500         x.scaley = t.m22();
1501         x.rotate = 180. / PI * atan2(-t.m21(), t.m11());
1502         m_transformations[items.at(i)] = x;
1503     }
1504     // mbd: Update the GUI color selectors to match the stuff from the loaded document
1505     QColor background_color = m_titledocument.getBackgroundColor();
1506     horizontalSlider->blockSignals(true);
1507     kcolorbutton->blockSignals(true);
1508     horizontalSlider->setValue(background_color.alpha());
1509     background_color.setAlpha(255);
1510     kcolorbutton->setColor(background_color);
1511     horizontalSlider->blockSignals(false);
1512     kcolorbutton->blockSignals(false);
1513
1514     /*startViewportX->setValue(m_startViewport->data(0).toInt());
1515     startViewportY->setValue(m_startViewport->data(1).toInt());
1516     startViewportSize->setValue(m_startViewport->data(2).toInt());
1517     endViewportX->setValue(m_endViewport->data(0).toInt());
1518     endViewportY->setValue(m_endViewport->data(1).toInt());
1519     endViewportSize->setValue(m_endViewport->data(2).toInt());*/
1520
1521     QTimer::singleShot(200, this, SLOT(slotAdjustZoom()));
1522     slotSelectTool();
1523 }
1524
1525 /** \brief Connected to the accepted signal - calls writeChoices */
1526 void TitleWidget::slotAccepted()
1527 {
1528     if (anim_start->isChecked()) slotAnimStart(false);
1529     if (anim_end->isChecked()) slotAnimEnd(false);
1530     writeChoices();
1531 }
1532
1533 /** \brief Store the current choices of font, background and rect values */
1534 void TitleWidget::writeChoices()
1535 {
1536     // Get a pointer to a shared configuration instance, then get the TitleWidget group.
1537     KSharedConfigPtr config = KGlobal::config();
1538     KConfigGroup titleConfig(config, "TitleWidget");
1539     // Write the entries
1540     titleConfig.writeEntry("font_family", font_family->currentFont());
1541     //titleConfig.writeEntry("font_size", font_size->value());
1542     titleConfig.writeEntry("font_pixel_size", font_size->value());
1543     titleConfig.writeEntry("font_color", fontColorButton->color());
1544     titleConfig.writeEntry("font_alpha", textAlpha->value());
1545     titleConfig.writeEntry("font_weight", font_weight_box->itemData(font_weight_box->currentIndex()).toInt());
1546     titleConfig.writeEntry("font_italic", buttonItalic->isChecked());
1547     titleConfig.writeEntry("font_underlined", buttonUnder->isChecked());
1548
1549     titleConfig.writeEntry("rect_foreground_color", rectFColor->color());
1550     titleConfig.writeEntry("rect_foreground_alpha", rectFAlpha->value());
1551     titleConfig.writeEntry("rect_background_color", rectBColor->color());
1552     titleConfig.writeEntry("rect_background_alpha", rectBAlpha->value());
1553     titleConfig.writeEntry("rect_line_width", rectLineWidth->value());
1554
1555     titleConfig.writeEntry("background_color", kcolorbutton->color());
1556     titleConfig.writeEntry("background_alpha", horizontalSlider->value());
1557
1558     //! \todo Not sure if I should sync - it is probably safe to do it
1559     config->sync();
1560
1561 }
1562
1563 /** \brief Read the last stored choices into the dialog */
1564 void TitleWidget::readChoices()
1565 {
1566     // Get a pointer to a shared configuration instance, then get the TitleWidget group.
1567     KSharedConfigPtr config = KGlobal::config();
1568     KConfigGroup titleConfig(config, "TitleWidget");
1569     // read the entries
1570     font_family->setCurrentFont(titleConfig.readEntry("font_family", font_family->currentFont()));
1571     font_size->setValue(titleConfig.readEntry("font_pixel_size", font_size->value()));
1572     fontColorButton->setColor(titleConfig.readEntry("font_color", fontColorButton->color()));
1573     textAlpha->setValue(titleConfig.readEntry("font_alpha", textAlpha->value()));
1574     int weight;
1575     if (titleConfig.readEntry("font_bold", false)) weight = QFont::Bold;
1576     else weight = titleConfig.readEntry("font_weight", font_weight_box->itemData(font_weight_box->currentIndex()).toInt());
1577     setFontBoxWeight(weight);
1578     buttonItalic->setChecked(titleConfig.readEntry("font_italic", buttonItalic->isChecked()));
1579     buttonUnder->setChecked(titleConfig.readEntry("font_underlined", buttonUnder->isChecked()));
1580
1581     rectFColor->setColor(titleConfig.readEntry("rect_foreground_color", rectFColor->color()));
1582     rectFAlpha->setValue(titleConfig.readEntry("rect_foreground_alpha", rectFAlpha->value()));
1583     rectBColor->setColor(titleConfig.readEntry("rect_background_color", rectBColor->color()));
1584     rectBAlpha->setValue(titleConfig.readEntry("rect_background_alpha", rectBAlpha->value()));
1585     rectLineWidth->setValue(titleConfig.readEntry("rect_line_width", rectLineWidth->value()));
1586
1587     kcolorbutton->setColor(titleConfig.readEntry("background_color", kcolorbutton->color()));
1588     horizontalSlider->setValue(titleConfig.readEntry("background_alpha", horizontalSlider->value()));
1589 }
1590
1591 void TitleWidget::adjustFrameSize()
1592 {
1593     m_frameWidth = m_titledocument.frameWidth();
1594     m_frameHeight = m_titledocument.frameHeight();
1595     m_frameBorder->setRect(0, 0, m_frameWidth, m_frameHeight);
1596     displayBackgroundFrame();
1597 }
1598
1599 void TitleWidget::slotAnimStart(bool anim)
1600 {
1601     if (anim && anim_end->isChecked()) {
1602         anim_end->setChecked(false);
1603         m_endViewport->setZValue(-1000);
1604         m_endViewport->setBrush(QBrush());
1605     }
1606     slotSelectTool();
1607     QList<QGraphicsItem *> list = m_scene->items();
1608     for (int i = 0; i < list.count(); i++) {
1609         if (list.at(i)->zValue() > -1000) {
1610             list.at(i)->setFlag(QGraphicsItem::ItemIsMovable, !anim);
1611             list.at(i)->setFlag(QGraphicsItem::ItemIsSelectable, !anim);
1612         }
1613     }
1614     align_box->setEnabled(anim);
1615     itemzoom->setEnabled(!anim);
1616     itemrotate->setEnabled(!anim);
1617     frame_toolbar->setEnabled(!anim);
1618     rect_properties->setEnabled(!anim);
1619     if (anim) {
1620         keep_aspect->setChecked(!m_startViewport->data(0).isNull());
1621         m_startViewport->setZValue(1100);
1622         QColor col = m_startViewport->pen().color();
1623         col.setAlpha(100);
1624         m_startViewport->setBrush(col);
1625         m_startViewport->setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable);
1626         m_startViewport->setSelected(true);
1627         selectionChanged();
1628         slotSelectTool();
1629     } else {
1630         m_startViewport->setZValue(-1000);
1631         m_startViewport->setBrush(QBrush());
1632         m_startViewport->setFlags(0);
1633     }
1634
1635 }
1636
1637 void TitleWidget::slotAnimEnd(bool anim)
1638 {
1639     if (anim && anim_start->isChecked()) {
1640         anim_start->setChecked(false);
1641         m_startViewport->setZValue(-1000);
1642         m_startViewport->setBrush(QBrush());
1643     }
1644     slotSelectTool();
1645     QList<QGraphicsItem *> list = m_scene->items();
1646     for (int i = 0; i < list.count(); i++) {
1647         if (list.at(i)->zValue() > -1000) {
1648             list.at(i)->setFlag(QGraphicsItem::ItemIsMovable, !anim);
1649             list.at(i)->setFlag(QGraphicsItem::ItemIsSelectable, !anim);
1650         }
1651     }
1652     align_box->setEnabled(anim);
1653     itemzoom->setEnabled(!anim);
1654     itemrotate->setEnabled(!anim);
1655     frame_toolbar->setEnabled(!anim);
1656     rect_properties->setEnabled(!anim);
1657     if (anim) {
1658         keep_aspect->setChecked(!m_endViewport->data(0).isNull());
1659         m_endViewport->setZValue(1100);
1660         QColor col = m_endViewport->pen().color();
1661         col.setAlpha(100);
1662         m_endViewport->setBrush(col);
1663         m_endViewport->setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable);
1664         m_endViewport->setSelected(true);
1665         selectionChanged();
1666         slotSelectTool();
1667     } else {
1668         m_endViewport->setZValue(-1000);
1669         m_endViewport->setBrush(QBrush());
1670         m_endViewport->setFlags(0);
1671     }
1672 }
1673
1674 void TitleWidget::slotKeepAspect(bool keep)
1675 {
1676     if (m_endViewport->zValue() == 1100) {
1677         m_endViewport->setData(0, keep == true ? m_frameWidth : QVariant());
1678         m_endViewport->setData(1, keep == true ? m_frameHeight : QVariant());
1679     } else {
1680         m_startViewport->setData(0, keep == true ? m_frameWidth : QVariant());
1681         m_startViewport->setData(1, keep == true ? m_frameHeight : QVariant());
1682     }
1683 }
1684
1685 void TitleWidget::slotResize50()
1686 {
1687     if (m_endViewport->zValue() == 1100) {
1688         m_endViewport->setRect(0, 0, m_frameWidth / 2, m_frameHeight / 2);
1689     } else m_startViewport->setRect(0, 0, m_frameWidth / 2, m_frameHeight / 2);
1690 }
1691
1692 void TitleWidget::slotResize100()
1693 {
1694     if (m_endViewport->zValue() == 1100) {
1695         m_endViewport->setRect(0, 0, m_frameWidth, m_frameHeight);
1696     } else m_startViewport->setRect(0, 0, m_frameWidth, m_frameHeight);
1697 }
1698
1699 void TitleWidget::slotResize200()
1700 {
1701     if (m_endViewport->zValue() == 1100) {
1702         m_endViewport->setRect(0, 0, m_frameWidth * 2, m_frameHeight * 2);
1703     } else m_startViewport->setRect(0, 0, m_frameWidth * 2, m_frameHeight * 2);
1704 }
1705
1706
1707