]> git.sesse.net Git - kdenlive/blob - src/titlewidget.cpp
r6488@lapL: simon | 2010-06-03 23:37:50 +0200
[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 #include "KoSliderCombo.h"
21 #include "kthumb.h"
22 #include <cmath>
23
24 #include <KDebug>
25 #include <KGlobalSettings>
26 #include <KFileDialog>
27 #include <KStandardDirs>
28 #include <KMessageBox>
29 #include <kio/netaccess.h>
30 #include <kdeversion.h>
31
32 #include <QDomDocument>
33 #include <QGraphicsItem>
34 #include <QGraphicsSvgItem>
35 #include <QTimer>
36 #include <QToolBar>
37 #include <QMenu>
38 #include <QSignalMapper>
39 #include <QTextBlockFormat>
40 #include <QTextCursor>
41 #include <QComboBox>
42 #include <QCryptographicHash>
43
44 #if QT_VERSION >= 0x040600
45 #include <QGraphicsEffect>
46 #include <QGraphicsBlurEffect>
47 #include <QGraphicsDropShadowEffect>
48 #endif
49
50 #include <iostream>
51
52 static QList<TitleTemplate> titletemplates;
53
54 // What exactly is this variable good for?
55 int settingUp = false;
56
57 const int IMAGEITEM = 7;
58 const int RECTITEM = 3;
59 const int TEXTITEM = 8;
60
61 const int NOEFFECT = 0;
62 const int BLUREFFECT = 1;
63 const int SHADOWEFFECT = 2;
64 const int TYPEWRITEREFFECT = 3;
65
66 TitleWidget::TitleWidget(KUrl url, Timecode tc, QString projectTitlePath, Render *render, QWidget *parent) :
67     QDialog(parent),
68     Ui::TitleWidget_UI(),
69     m_startViewport(NULL),
70     m_endViewport(NULL),
71     m_render(render),
72     m_count(0),
73     m_unicodeDialog(new UnicodeDialog(UnicodeDialog::InputHex)),
74     m_projectTitlePath(projectTitlePath),
75     m_tc(tc)
76 {
77     setupUi(this);
78     setFont(KGlobalSettings::toolBarFont());
79     frame_properties->setEnabled(false);
80     frame_properties->setFixedHeight(frame_toolbar->height());
81
82     // Set combo sliders values
83     textAlpha->setMinimum(0);
84     textAlpha->setMaximum(255);
85     textAlpha->setDecimals(0);
86     textAlpha->setValue(255);
87     textAlpha->setToolTip(i18n("Font color opacity"));
88
89     textOutlineAlpha->setMinimum(0);
90     textOutlineAlpha->setMaximum(255);
91     textOutlineAlpha->setDecimals(0);
92     textOutlineAlpha->setValue(255);
93     textOutlineAlpha->setToolTip(i18n("Outline color opacity"));
94
95     textOutline->setMinimum(0);
96     textOutline->setMaximum(200);
97     textOutline->setDecimals(0);
98     textOutline->setValue(0);
99     textOutline->setToolTip(i18n("Outline width"));
100
101     backgroundAlpha->setMinimum(0);
102     backgroundAlpha->setMaximum(255);
103     backgroundAlpha->setDecimals(0);
104     backgroundAlpha->setValue(0);
105     backgroundAlpha->setToolTip(i18n("Background color opacity"));
106
107     itemrotatex->setMinimum(-360);
108     itemrotatex->setMaximum(360);
109     itemrotatex->setDecimals(0);
110     itemrotatex->setValue(0);
111     itemrotatex->setToolTip(i18n("Rotation around the X axis"));
112
113     itemrotatey->setMinimum(-360);
114     itemrotatey->setMaximum(360);
115     itemrotatey->setDecimals(0);
116     itemrotatey->setValue(0);
117     itemrotatey->setToolTip(i18n("Rotation around the Y axis"));
118
119     itemrotatez->setMinimum(-360);
120     itemrotatez->setMaximum(360);
121     itemrotatez->setDecimals(0);
122     itemrotatez->setValue(0);
123     itemrotatez->setToolTip(i18n("Rotation around the Z axis"));
124
125     rectBAlpha->setMinimum(0);
126     rectBAlpha->setMaximum(255);
127     rectBAlpha->setDecimals(0);
128     rectBAlpha->setValue(255);
129     rectBAlpha->setToolTip(i18n("Color opacity"));
130
131     rectFAlpha->setMinimum(0);
132     rectFAlpha->setMaximum(255);
133     rectFAlpha->setDecimals(0);
134     rectFAlpha->setValue(255);
135     rectFAlpha->setToolTip(i18n("Border opacity"));
136
137     rectLineWidth->setMinimum(0);
138     rectLineWidth->setMaximum(100);
139     rectLineWidth->setDecimals(0);
140     rectLineWidth->setValue(0);
141     rectLineWidth->setToolTip(i18n("Border width"));
142
143     itemzoom->setSuffix(i18n("%"));
144     m_frameWidth = render->renderWidth();
145     m_frameHeight = render->renderHeight();
146     showToolbars(TITLE_SELECT);
147
148     //If project is drop frame, set the input mask as such.
149     title_duration->setInputMask("");
150     title_duration->setValidator(m_tc.validator());
151     title_duration->setText(m_tc.reformatSeparators(KdenliveSettings::title_duration()));
152
153     connect(backgroundColor, SIGNAL(clicked()), this, SLOT(slotChangeBackground())) ;
154     connect(backgroundAlpha, SIGNAL(valueChanged(qreal, bool)), this, SLOT(slotChangeBackground())) ;
155
156     connect(fontColorButton, SIGNAL(clicked()), this, SLOT(slotUpdateText())) ;
157     connect(textOutlineColor, SIGNAL(clicked()), this, SLOT(slotUpdateText())) ;
158     connect(font_family, SIGNAL(currentFontChanged(const QFont &)), this, SLOT(slotUpdateText())) ;
159     connect(font_size, SIGNAL(valueChanged(int)), this, SLOT(slotUpdateText())) ;
160     connect(textAlpha, SIGNAL(valueChanged(qreal, bool)), this, SLOT(slotUpdateText()));
161     connect(textOutline, SIGNAL(valueChanged(qreal, bool)), this, SLOT(slotUpdateText()));
162     connect(textOutlineAlpha, SIGNAL(valueChanged(qreal, bool)), this, SLOT(slotUpdateText()));
163     connect(font_weight_box, SIGNAL(currentIndexChanged(int)), this, SLOT(slotUpdateText()));
164
165     connect(font_family, SIGNAL(editTextChanged(const QString &)), this, SLOT(slotFontText(const QString&)));
166
167     connect(rectFAlpha, SIGNAL(valueChanged(qreal, bool)), this, SLOT(rectChanged()));
168     connect(rectBAlpha, SIGNAL(valueChanged(qreal, bool)), this, SLOT(rectChanged()));
169     connect(rectFColor, SIGNAL(clicked()), this, SLOT(rectChanged()));
170     connect(rectBColor, SIGNAL(clicked()), this, SLOT(rectChanged()));
171     connect(rectLineWidth, SIGNAL(valueChanged(qreal, bool)), this, SLOT(rectChanged()));
172
173     /*connect(startViewportX, SIGNAL(valueChanged(int)), this, SLOT(setupViewports()));
174     connect(startViewportY, SIGNAL(valueChanged(int)), this, SLOT(setupViewports()));
175     connect(startViewportSize, SIGNAL(valueChanged(int)), this, SLOT(setupViewports()));
176     connect(endViewportX, SIGNAL(valueChanged(int)), this, SLOT(setupViewports()));
177     connect(endViewportY, SIGNAL(valueChanged(int)), this, SLOT(setupViewports()));
178     connect(endViewportSize, SIGNAL(valueChanged(int)), this, SLOT(setupViewports()));*/
179
180     // Fill effects
181     effect_list->addItem(i18n("None"), NOEFFECT);
182     effect_list->addItem(i18n("Typewriter"), TYPEWRITEREFFECT);
183     effect_list->addItem(i18n("Blur"), BLUREFFECT);
184
185
186     connect(zValue, SIGNAL(valueChanged(int)), this, SLOT(zIndexChanged(int)));
187     connect(itemzoom, SIGNAL(valueChanged(int)), this, SLOT(itemScaled(int)));
188     connect(itemrotatex, SIGNAL(valueChanged(qreal, bool)), this, SLOT(itemRotateX(qreal)));
189     connect(itemrotatey, SIGNAL(valueChanged(qreal, bool)), this, SLOT(itemRotateY(qreal)));
190     connect(itemrotatez, SIGNAL(valueChanged(qreal, bool)), this, SLOT(itemRotateZ(qreal)));
191     connect(itemhcenter, SIGNAL(clicked()), this, SLOT(itemHCenter()));
192     connect(itemvcenter, SIGNAL(clicked()), this, SLOT(itemVCenter()));
193     connect(itemtop, SIGNAL(clicked()), this, SLOT(itemTop()));
194     connect(itembottom, SIGNAL(clicked()), this, SLOT(itemBottom()));
195     connect(itemleft, SIGNAL(clicked()), this, SLOT(itemLeft()));
196     connect(itemright, SIGNAL(clicked()), this, SLOT(itemRight()));
197     connect(effect_list, SIGNAL(currentIndexChanged(int)), this, SLOT(slotAddEffect(int)));
198     connect(typewriter_delay, SIGNAL(valueChanged(int)), this, SLOT(slotEditTypewriter(int)));
199     connect(typewriter_start, SIGNAL(valueChanged(int)), this, SLOT(slotEditTypewriter(int)));
200     connect(blur_radius, SIGNAL(valueChanged(int)), this, SLOT(slotEditBlur(int)));
201     connect(shadow_radius, SIGNAL(valueChanged(int)), this, SLOT(slotEditShadow()));
202     connect(shadow_x, SIGNAL(valueChanged(int)), this, SLOT(slotEditShadow()));
203     connect(shadow_y, SIGNAL(valueChanged(int)), this, SLOT(slotEditShadow()));
204     effect_stack->setHidden(true);
205     effect_frame->setEnabled(false);
206
207     connect(origin_x_left, SIGNAL(clicked()), this, SLOT(slotOriginXClicked()));
208     connect(origin_y_top, SIGNAL(clicked()), this, SLOT(slotOriginYClicked()));
209
210     // Position and size
211     m_signalMapper = new QSignalMapper(this);
212     m_signalMapper->setMapping(value_w, ValueWidth);
213     m_signalMapper->setMapping(value_h, ValueHeight);
214     m_signalMapper->setMapping(value_x, ValueX);
215     m_signalMapper->setMapping(value_y, ValueY);
216     connect(value_w, SIGNAL(valueChanged(int)), m_signalMapper, SLOT(map()));
217     connect(value_h, SIGNAL(valueChanged(int)), m_signalMapper, SLOT(map()));
218     connect(value_x, SIGNAL(valueChanged(int)), m_signalMapper, SLOT(map()));
219     connect(value_y, SIGNAL(valueChanged(int)), m_signalMapper, SLOT(map()));
220     connect(m_signalMapper, SIGNAL(mapped(int)), this, SLOT(slotValueChanged(int)));
221
222     connect(buttonFitZoom, SIGNAL(clicked()), this, SLOT(slotAdjustZoom()));
223     connect(buttonRealSize, SIGNAL(clicked()), this, SLOT(slotZoomOneToOne()));
224     connect(buttonItalic, SIGNAL(clicked()), this, SLOT(slotUpdateText()));
225     connect(buttonUnder, SIGNAL(clicked()), this, SLOT(slotUpdateText()));
226     connect(buttonAlignLeft, SIGNAL(clicked()), this, SLOT(slotUpdateText()));
227     connect(buttonAlignRight, SIGNAL(clicked()), this, SLOT(slotUpdateText()));
228     connect(buttonAlignCenter, SIGNAL(clicked()), this, SLOT(slotUpdateText()));
229     connect(buttonAlignNone, SIGNAL(clicked()), this, SLOT(slotUpdateText()));
230     connect(displayBg, SIGNAL(stateChanged(int)), this, SLOT(displayBackgroundFrame()));
231
232     connect(m_unicodeDialog, SIGNAL(charSelected(QString)), this, SLOT(slotInsertUnicodeString(QString)));
233
234     // mbd
235     connect(this, SIGNAL(accepted()), this, SLOT(slotAccepted()));
236
237     font_weight_box->blockSignals(true);
238     font_weight_box->addItem(i18nc("Font style", "Light"), QFont::Light);
239     font_weight_box->addItem(i18nc("Font style", "Normal"), QFont::Normal);
240     font_weight_box->addItem(i18nc("Font style", "Demi-Bold"), QFont::DemiBold);
241     font_weight_box->addItem(i18nc("Font style", "Bold"), QFont::Bold);
242     font_weight_box->addItem(i18nc("Font style", "Black"), QFont::Black);
243     font_weight_box->setToolTip(i18n("Font weight"));
244     font_weight_box->setCurrentIndex(1);
245     font_weight_box->blockSignals(false);
246
247     buttonFitZoom->setIcon(KIcon("zoom-fit-best"));
248     buttonRealSize->setIcon(KIcon("zoom-original"));
249     buttonItalic->setIcon(KIcon("format-text-italic"));
250     buttonUnder->setIcon(KIcon("format-text-underline"));
251     buttonAlignCenter->setIcon(KIcon("format-justify-center"));
252     buttonAlignLeft->setIcon(KIcon("format-justify-left"));
253     buttonAlignRight->setIcon(KIcon("format-justify-right"));
254     buttonAlignNone->setIcon(KIcon("kdenlive-align-none"));
255
256     buttonAlignNone->setToolTip(i18n("No alignment"));
257     buttonAlignRight->setToolTip(i18n("Align right"));
258     buttonAlignLeft->setToolTip(i18n("Align left"));
259     buttonAlignCenter->setToolTip(i18n("Align center"));
260
261     m_unicodeAction = new QAction(KIcon("kdenlive-insert-unicode"), QString(), this);
262     m_unicodeAction->setShortcut(Qt::SHIFT + Qt::CTRL + Qt::Key_U);
263     m_unicodeAction->setToolTip(getTooltipWithShortcut(i18n("Insert Unicode character"), m_unicodeAction));
264     connect(m_unicodeAction, SIGNAL(triggered()), this, SLOT(slotInsertUnicode()));
265     buttonInsertUnicode->setDefaultAction(m_unicodeAction);
266
267     m_zUp = new QAction(KIcon("kdenlive-zindex-up"), QString(), this);
268     m_zUp->setShortcut(Qt::Key_PageUp);
269     m_zUp->setToolTip(i18n("Raise object"));
270     connect(m_zUp, SIGNAL(triggered()), this, SLOT(slotZIndexUp()));
271     zUp->setDefaultAction(m_zUp);
272
273     m_zDown = new QAction(KIcon("kdenlive-zindex-down"), QString(), this);
274     m_zDown->setShortcut(Qt::Key_PageDown);
275     m_zDown->setToolTip(i18n("Lower object"));
276     connect(m_zDown, SIGNAL(triggered()), this, SLOT(slotZIndexDown()));
277     zDown->setDefaultAction(m_zDown);
278
279     m_zTop = new QAction(KIcon("kdenlive-zindex-top"), QString(), this);
280     // TODO mbt 1414: Shortcut should change z index only if
281     // cursor is NOT in a text field ...
282     //m_zTop->setShortcut(Qt::Key_Home);
283     m_zTop->setToolTip(i18n("Raise object to top"));
284     connect(m_zTop, SIGNAL(triggered()), this, SLOT(slotZIndexTop()));
285     zTop->setDefaultAction(m_zTop);
286
287     m_zBottom = new QAction(KIcon("kdenlive-zindex-bottom"), QString(), this);
288     // TODO mbt 1414
289     //m_zBottom->setShortcut(Qt::Key_End);
290     m_zBottom->setToolTip(i18n("Lower object to bottom"));
291     connect(m_zBottom, SIGNAL(triggered()), this, SLOT(slotZIndexBottom()));
292     zBottom->setDefaultAction(m_zBottom);
293
294     m_selectAll = new QAction(KIcon("kdenlive-select-all"), QString(), this);
295     m_selectAll->setShortcut(Qt::CTRL + Qt::Key_A);
296     connect(m_selectAll, SIGNAL(triggered()), this, SLOT(slotSelectAll()));
297     buttonSelectAll->setDefaultAction(m_selectAll);
298
299     m_selectText = new QAction(KIcon("kdenlive-select-texts"), QString(), this);
300     m_selectText->setShortcut(Qt::CTRL + Qt::Key_T);
301     connect(m_selectText, SIGNAL(triggered()), this, SLOT(slotSelectText()));
302     buttonSelectText->setDefaultAction(m_selectText);
303     buttonSelectText->setEnabled(false);
304
305     m_selectRects = new QAction(KIcon("kdenlive-select-rects"), QString(), this);
306     m_selectRects->setShortcut(Qt::CTRL + Qt::Key_R);
307     connect(m_selectRects, SIGNAL(triggered()), this, SLOT(slotSelectRects()));
308     buttonSelectRects->setDefaultAction(m_selectRects);
309     buttonSelectRects->setEnabled(false);
310
311     m_selectImages = new QAction(KIcon("kdenlive-select-images"), QString(), this);
312     m_selectImages->setShortcut(Qt::CTRL + Qt::Key_I);
313     connect(m_selectImages, SIGNAL(triggered()), this, SLOT(slotSelectImages()));
314     buttonSelectImages->setDefaultAction(m_selectImages);
315     buttonSelectImages->setEnabled(false);
316
317     m_unselectAll = new QAction(KIcon("kdenlive-unselect-all"), QString(), this);
318     m_unselectAll->setShortcut(Qt::SHIFT + Qt::CTRL + Qt::Key_A);
319     connect(m_unselectAll, SIGNAL(triggered()), this, SLOT(slotSelectNone()));
320     buttonUnselectAll->setDefaultAction(m_unselectAll);
321     buttonUnselectAll->setEnabled(false);
322
323     zDown->setIcon(KIcon("kdenlive-zindex-down"));
324     zTop->setIcon(KIcon("kdenlive-zindex-top"));
325     zBottom->setIcon(KIcon("kdenlive-zindex-bottom"));
326     connect(zDown, SIGNAL(clicked()), this, SLOT(slotZIndexDown()));
327     connect(zTop, SIGNAL(clicked()), this, SLOT(slotZIndexTop()));
328     connect(zBottom, SIGNAL(clicked()), this, SLOT(slotZIndexBottom()));
329
330     origin_x_left->setToolTip(i18n("Invert x axis and change 0 point"));
331     origin_y_top->setToolTip(i18n("Invert y axis and change 0 point"));
332     rectBColor->setToolTip(i18n("Select fill color"));
333     rectFColor->setToolTip(i18n("Select border color"));
334     rectBAlpha->setToolTip(i18n("Fill opacity"));
335     rectFAlpha->setToolTip(i18n("Border opacity"));
336     zoom_slider->setToolTip(i18n("Zoom"));
337     buttonRealSize->setToolTip(i18n("Original size (1:1)"));
338     buttonFitZoom->setToolTip(i18n("Fit zoom"));
339     backgroundColor->setToolTip(i18n("Select background color"));
340     backgroundAlpha->setToolTip(i18n("Background opacity"));
341     buttonSelectAll->setToolTip(getTooltipWithShortcut(i18n("Select all"), m_selectAll));
342     buttonSelectText->setToolTip(getTooltipWithShortcut(i18n("Select text items in current selection"), m_selectText));
343     buttonSelectRects->setToolTip(getTooltipWithShortcut(i18n("Select rect items in current selection"), m_selectRects));
344     buttonSelectImages->setToolTip(getTooltipWithShortcut(i18n("Select image items in current selection"), m_selectImages));
345     buttonUnselectAll->setToolTip(getTooltipWithShortcut(i18n("Unselect all"), m_unselectAll));
346
347     itemhcenter->setIcon(KIcon("kdenlive-align-hor"));
348     itemhcenter->setToolTip(i18n("Align item horizontally"));
349     itemvcenter->setIcon(KIcon("kdenlive-align-vert"));
350     itemvcenter->setToolTip(i18n("Align item vertically"));
351     itemtop->setIcon(KIcon("kdenlive-align-top"));
352     itemtop->setToolTip(i18n("Align item to top"));
353     itembottom->setIcon(KIcon("kdenlive-align-bottom"));
354     itembottom->setToolTip(i18n("Align item to bottom"));
355     itemright->setIcon(KIcon("kdenlive-align-right"));
356     itemright->setToolTip(i18n("Align item to right"));
357     itemleft->setIcon(KIcon("kdenlive-align-left"));
358     itemleft->setToolTip(i18n("Align item to left"));
359
360
361     QHBoxLayout *layout = new QHBoxLayout;
362     frame_toolbar->setLayout(layout);
363     layout->setContentsMargins(0, 0, 0, 0);
364     QToolBar *m_toolbar = new QToolBar("titleToolBar", this);
365     int s = style()->pixelMetric(QStyle::PM_SmallIconSize);
366     m_toolbar->setIconSize(QSize(s, s));
367
368     m_buttonCursor = m_toolbar->addAction(KIcon("transform-move"), QString());
369     m_buttonCursor->setCheckable(true);
370     m_buttonCursor->setShortcut(Qt::ALT + Qt::Key_S);
371     m_buttonCursor->setToolTip(i18n("Selection Tool") + ' ' + m_buttonCursor->shortcut().toString());
372     connect(m_buttonCursor, SIGNAL(triggered()), this, SLOT(slotSelectTool()));
373
374     m_buttonText = m_toolbar->addAction(KIcon("insert-text"), QString());
375     m_buttonText->setCheckable(true);
376     m_buttonText->setShortcut(Qt::ALT + Qt::Key_T);
377     m_buttonText->setToolTip(i18n("Add Text") + ' ' + m_buttonText->shortcut().toString());
378     connect(m_buttonText, SIGNAL(triggered()), this, SLOT(slotTextTool()));
379
380     m_buttonRect = m_toolbar->addAction(KIcon("kdenlive-insert-rect"), QString());
381     m_buttonRect->setCheckable(true);
382     m_buttonRect->setShortcut(Qt::ALT + Qt::Key_R);
383     m_buttonRect->setToolTip(i18n("Add Rectangle") + ' ' + m_buttonRect->shortcut().toString());
384     connect(m_buttonRect, SIGNAL(triggered()), this, SLOT(slotRectTool()));
385
386     m_buttonImage = m_toolbar->addAction(KIcon("insert-image"), QString());
387     m_buttonImage->setCheckable(false);
388     m_buttonImage->setShortcut(Qt::ALT + Qt::Key_I);
389     m_buttonImage->setToolTip(i18n("Add Image") + ' ' + m_buttonImage->shortcut().toString());
390     connect(m_buttonImage, SIGNAL(triggered()), this, SLOT(slotImageTool()));
391
392     m_toolbar->addSeparator();
393
394     m_buttonLoad = m_toolbar->addAction(KIcon("document-open"), i18n("Open Document"));
395     m_buttonLoad->setCheckable(false);
396     m_buttonLoad->setShortcut(Qt::CTRL + Qt::Key_O);
397     connect(m_buttonLoad, SIGNAL(triggered()), this, SLOT(loadTitle()));
398
399     m_buttonSave = m_toolbar->addAction(KIcon("document-save-as"), i18n("Save As"));
400     m_buttonSave->setCheckable(false);
401     m_buttonSave->setShortcut(Qt::CTRL + Qt::Key_S);
402     connect(m_buttonSave, SIGNAL(triggered()), this, SLOT(saveTitle()));
403
404     layout->addWidget(m_toolbar);
405
406     // initialize graphic scene
407     m_scene = new GraphicsSceneRectMove(this);
408     graphicsView->setScene(m_scene);
409     graphicsView->setMouseTracking(true);
410     m_titledocument.setScene(m_scene, m_frameWidth, m_frameHeight);
411     connect(m_scene, SIGNAL(changed(QList<QRectF>)), this, SLOT(slotChanged()));
412     connect(font_size, SIGNAL(valueChanged(int)), m_scene, SLOT(slotUpdateFontSize(int)));
413
414     // a gradient background
415     /*QRadialGradient *gradient = new QRadialGradient(0, 0, 10);
416     gradient->setSpread(QGradient::ReflectSpread);
417     scene->setBackgroundBrush(*gradient);*/
418
419     m_frameImage = new QGraphicsPixmapItem();
420     QTransform qtrans;
421     qtrans.scale(2.0, 2.0);
422     m_frameImage->setTransform(qtrans);
423     m_frameImage->setZValue(-1200);
424     m_frameImage->setFlags(0);
425     displayBackgroundFrame();
426     graphicsView->scene()->addItem(m_frameImage);
427
428     connect(m_scene, SIGNAL(selectionChanged()), this , SLOT(selectionChanged()));
429     connect(m_scene, SIGNAL(itemMoved()), this , SLOT(selectionChanged()));
430     connect(m_scene, SIGNAL(sceneZoom(bool)), this , SLOT(slotZoom(bool)));
431     connect(m_scene, SIGNAL(actionFinished()), this , SLOT(slotSelectTool()));
432     //connect(m_scene, SIGNAL(actionFinished()), this , SLOT(selectionChanged()));
433     connect(m_scene, SIGNAL(newRect(QGraphicsRectItem *)), this , SLOT(slotNewRect(QGraphicsRectItem *)));
434     connect(m_scene, SIGNAL(newText(QGraphicsTextItem *)), this , SLOT(slotNewText(QGraphicsTextItem *)));
435     connect(zoom_slider, SIGNAL(valueChanged(int)), this , SLOT(slotUpdateZoom(int)));
436
437     QPen framepen(Qt::DotLine);
438     framepen.setColor(Qt::red);
439
440     m_frameBorder = new QGraphicsRectItem(QRectF(0, 0, m_frameWidth, m_frameHeight));
441     m_frameBorder->setPen(framepen);
442     m_frameBorder->setZValue(-1100);
443     m_frameBorder->setBrush(Qt::transparent);
444     m_frameBorder->setFlags(0);
445     graphicsView->scene()->addItem(m_frameBorder);
446
447     // mbd: load saved settings
448     readChoices();
449
450     graphicsView->show();
451     //graphicsView->setRenderHint(QPainter::Antialiasing);
452     graphicsView->setInteractive(true);
453     //graphicsView->resize(400, 300);
454     kDebug() << "// TITLE WIDGWT: " << graphicsView->viewport()->width() << "x" << graphicsView->viewport()->height();
455     //toolBox->setItemEnabled(2, false);
456     m_startViewport = new QGraphicsRectItem(QRectF(0, 0, m_frameWidth, m_frameHeight));
457     m_endViewport = new QGraphicsRectItem(QRectF(0, 0, m_frameWidth, m_frameHeight));
458     m_startViewport->setData(0, m_frameWidth);
459     m_startViewport->setData(1, m_frameHeight);
460     m_endViewport->setData(0, m_frameWidth);
461     m_endViewport->setData(1, m_frameHeight);
462
463     if(!url.isEmpty()) loadTitle(url);
464     else {
465         slotTextTool();
466         QTimer::singleShot(200, this, SLOT(slotAdjustZoom()));
467     }
468     initAnimation();
469     connect(anim_start, SIGNAL(toggled(bool)), this, SLOT(slotAnimStart(bool)));
470     connect(anim_end, SIGNAL(toggled(bool)), this, SLOT(slotAnimEnd(bool)));
471     connect(templateBox, SIGNAL(currentIndexChanged(int)), this, SLOT(templateIndexChanged(int)));
472
473     buttonBox->button(QDialogButtonBox::Ok)->setEnabled(KdenliveSettings::hastitleproducer());
474     refreshTitleTemplates();
475     //templateBox->setIconSize(QSize(60,60));
476     templateBox->clear();
477     templateBox->addItem("");
478     foreach(TitleTemplate t, titletemplates) {
479         templateBox->addItem(t.icon, t.name, t.file);
480     }
481     lastDocumentHash = QCryptographicHash::hash(xml().toString().toAscii(), QCryptographicHash::Md5).toHex();
482 }
483
484 TitleWidget::~TitleWidget()
485 {
486     delete m_buttonRect;
487     delete m_buttonText;
488     delete m_buttonImage;
489     delete m_buttonCursor;
490     delete m_buttonSave;
491     delete m_buttonLoad;
492     delete m_unicodeAction;
493     delete m_zUp;
494     delete m_zDown;
495     delete m_zTop;
496     delete m_zBottom;
497     delete m_selectAll;
498     delete m_selectText;
499     delete m_selectRects;
500     delete m_selectImages;
501     delete m_unselectAll;
502
503     delete m_unicodeDialog;
504     delete m_frameBorder;
505     delete m_frameImage;
506     delete m_startViewport;
507     delete m_endViewport;
508     delete m_scene;
509     delete m_signalMapper;
510 }
511
512 //static
513 QStringList TitleWidget::getFreeTitleInfo(const KUrl &projectUrl, bool isClone)
514 {
515     QStringList result;
516     QString titlePath = projectUrl.path(KUrl::AddTrailingSlash) + "titles/";
517     KStandardDirs::makeDir(titlePath);
518     titlePath.append((isClone == false) ? "title" : "clone");
519     int counter = 0;
520     QString path;
521     while(path.isEmpty() || QFile::exists(path)) {
522         counter++;
523         path = titlePath + QString::number(counter).rightJustified(3, '0', false) + ".png";
524     }
525     result.append(((isClone == false) ? i18n("Title") : i18n("Clone")) + ' ' + QString::number(counter).rightJustified(3, '0', false));
526     result.append(path);
527     return result;
528 }
529
530 // static
531 QString TitleWidget::getTitleResourceFromName(const KUrl &projectUrl, const QString &titleName)
532 {
533     QStringList result;
534     QString titlePath = projectUrl.path(KUrl::AddTrailingSlash) + "titles/";
535     KStandardDirs::makeDir(titlePath);
536     return titlePath + titleName + ".png";
537 }
538
539 // static
540 QStringList TitleWidget::extractImageList(QString xml)
541 {
542     QStringList result;
543     if(xml.isEmpty()) return result;
544     QDomDocument doc;
545     doc.setContent(xml);
546     QDomNodeList images = doc.elementsByTagName("content");
547     for(int i = 0; i < images.count(); i++) {
548         if(images.at(i).toElement().hasAttribute("url"))
549             result.append(images.at(i).toElement().attribute("url"));
550     }
551     return result;
552 }
553
554 // static
555 QStringList TitleWidget::extractFontList(QString xml)
556 {
557     QStringList result;
558     if(xml.isEmpty()) return result;
559     QDomDocument doc;
560     doc.setContent(xml);
561     QDomNodeList images = doc.elementsByTagName("content");
562     for(int i = 0; i < images.count(); i++) {
563         if(images.at(i).toElement().hasAttribute("font"))
564             result.append(images.at(i).toElement().attribute("font"));
565     }
566     return result;
567 }
568 //static
569 void TitleWidget::refreshTitleTemplates()
570 {
571     QStringList titlenamelist = QStringList() << i18n("None");
572     QStringList titlefiles = QStringList() << QString();
573     QStringList filters;
574     filters << "*.kdenlivetitle" ;
575     titletemplates.clear();
576     QStringList titleTemplates = KGlobal::dirs()->findDirs("appdata", "titles");
577     foreach(const QString & folder, titleTemplates) {
578         QStringList filesnames = QDir(folder).entryList(filters, QDir::Files);
579         foreach(const QString & fname, filesnames) {
580             //titlenamelist.append(fname);
581             //titlefiles.append(KUrl(folder).path(KUrl::AddTrailingSlash) + fname);
582             TitleTemplate t;
583             t.name = fname;
584             t.file = KUrl(folder).path(KUrl::AddTrailingSlash) + fname;
585             t.icon = QIcon(KThumb::getImage(t.file, 0, 60, 60));
586             titletemplates.append(t);
587         }
588     }
589     kDebug()  << titlenamelist << titlefiles;
590 }
591 void TitleWidget::templateIndexChanged(int index)
592 {
593     QString item = templateBox->itemData(index).toString();
594     if(item != "") {
595         if(lastDocumentHash != QCryptographicHash::hash(xml().toString().toAscii(), QCryptographicHash::Md5).toHex()) {
596             if(KMessageBox::questionYesNo(this, i18n("Do you really want to load a new template? Changes in this title will be lost!")) == KMessageBox::No) return;
597         }
598         loadTitle(item);
599
600         // mbt 1607: Add property to distinguish between unchanged template titles and user titles.
601         // Text of unchanged template titles should be selected when clicked.
602         QList<QGraphicsItem *> list = graphicsView->scene()->items();
603         foreach(QGraphicsItem * qgItem, list) {
604             if(qgItem->type() == TEXTITEM) {
605                 QGraphicsTextItem *i;
606                 i = static_cast<QGraphicsTextItem *>(qgItem);
607                 i->setProperty("isTemplate", "true");
608                 i->setProperty("templateText", i->toHtml());
609             }
610
611         }
612         lastDocumentHash = QCryptographicHash::hash(xml().toString().toAscii(), QCryptographicHash::Md5).toHex();
613     }
614 }
615 //virtual
616 void TitleWidget::resizeEvent(QResizeEvent * /*event*/)
617 {
618     //slotAdjustZoom();
619 }
620
621 void TitleWidget::slotTextTool()
622 {
623     m_scene->setTool(TITLE_TEXT);
624     showToolbars(TITLE_TEXT);
625     checkButton(TITLE_TEXT);
626 }
627
628 void TitleWidget::slotRectTool()
629 {
630     m_scene->setTool(TITLE_RECTANGLE);
631     showToolbars(TITLE_RECTANGLE);
632     checkButton(TITLE_RECTANGLE);
633 }
634
635 void TitleWidget::slotSelectTool()
636 {
637     m_scene->setTool(TITLE_SELECT);
638
639     // Find out which toolbars need to be shown, depending on selected item
640     TITLETOOL t = TITLE_SELECT;
641     QList<QGraphicsItem *> l = graphicsView->scene()->selectedItems();
642     if(l.size() > 0) {
643         switch(l.at(0)->type()) {
644         case TEXTITEM:
645             t = TITLE_TEXT;
646             break;
647         case RECTITEM:
648             t = TITLE_RECTANGLE;
649             break;
650         case IMAGEITEM:
651             t = TITLE_IMAGE;
652             break;
653         }
654     }
655
656     enableToolbars(t);
657     if(t == TITLE_RECTANGLE && (l.at(0) == m_endViewport || l.at(0) == m_startViewport)) {
658         //graphicsView->centerOn(l.at(0));
659         t = TITLE_SELECT;
660     }
661     showToolbars(t);
662
663     if(l.size() > 0) {
664         updateCoordinates(l.at(0));
665         updateDimension(l.at(0));
666         updateRotZoom(l.at(0));
667     }
668
669     checkButton(TITLE_SELECT);
670 }
671
672 void TitleWidget::slotImageTool()
673 {
674     // TODO: find a way to get a list of all supported image types...
675     QString allExtensions = "image/gif image/jpeg image/png image/x-tga image/x-bmp image/svg+xml image/tiff image/x-xcf-gimp image/x-vnd.adobe.photoshop image/x-pcx image/x-exr";
676     KUrl url = KFileDialog::getOpenUrl(KUrl(), allExtensions, this, i18n("Load Image")); //"*.svg *.png *.jpg *.jpeg *.gif *.raw"
677     if(!url.isEmpty()) {
678         if(url.path().endsWith(".svg")) {
679             QGraphicsSvgItem *svg = new QGraphicsSvgItem(url.toLocalFile());
680             svg->setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable);
681             svg->setZValue(m_count++);
682             svg->setData(Qt::UserRole, url.path());
683             graphicsView->scene()->addItem(svg);
684         } else {
685             QPixmap pix(url.path());
686             QGraphicsPixmapItem *image = new QGraphicsPixmapItem(pix);
687             image->setShapeMode(QGraphicsPixmapItem::BoundingRectShape);
688             image->setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable);
689             image->setData(Qt::UserRole, url.path());
690             image->setZValue(m_count++);
691             graphicsView->scene()->addItem(image);
692         }
693     }
694     m_scene->setTool(TITLE_SELECT);
695     showToolbars(TITLE_SELECT);
696     checkButton(TITLE_SELECT);
697 }
698
699 void TitleWidget::showToolbars(TITLETOOL toolType)
700 {
701     switch (toolType) {
702         case TITLE_SELECT:
703             toolbar_stack->setCurrentIndex(0);
704             break;
705         case TITLE_IMAGE:
706             toolbar_stack->setCurrentIndex(3);
707             break;
708         case TITLE_RECTANGLE:
709             toolbar_stack->setCurrentIndex(1);
710             break;
711         case TITLE_TEXT:
712             toolbar_stack->setCurrentIndex(2);
713             break;
714     }
715 //     toolbar_stack->setCurrentIndex((int) toolType);
716 }
717
718 void TitleWidget::enableToolbars(TITLETOOL toolType)
719 {
720     // TITLETOOL is defined in graphicsscenerectmove.h
721     bool enable = false;
722     if(toolType == TITLE_RECTANGLE || toolType == TITLE_IMAGE) enable = true;
723     value_w->setEnabled(enable);
724     value_h->setEnabled(enable);
725 }
726
727 void TitleWidget::checkButton(TITLETOOL toolType)
728 {
729     bool bSelect = false;
730     bool bText = false;
731     bool bRect = false;
732     bool bImage = false;
733
734     switch(toolType) {
735     case TITLE_SELECT:
736         bSelect = true;
737         break;
738     case TITLE_TEXT:
739         bText = true;
740         break;
741     case TITLE_RECTANGLE:
742         bRect = true;
743         break;
744     case TITLE_IMAGE:
745         bImage = true;
746         break;
747     default:
748         break;
749     }
750
751     m_buttonCursor->setChecked(bSelect);
752     m_buttonText->setChecked(bText);
753     m_buttonRect->setChecked(bRect);
754     m_buttonImage->setChecked(bImage);
755 }
756
757 void TitleWidget::displayBackgroundFrame()
758 {
759     if(!displayBg->isChecked()) {
760         QPixmap bg(m_frameWidth / 2, m_frameHeight / 2);
761         QPixmap pattern(20, 20);
762         pattern.fill();
763         QColor bgcolor(210, 210, 210);
764         QPainter p;
765         p.begin(&pattern);
766         p.fillRect(QRect(0, 0, 10, 10), bgcolor);
767         p.fillRect(QRect(10, 10, 20, 20), bgcolor);
768         p.end();
769         QBrush br(pattern);
770
771         p.begin(&bg);
772         p.fillRect(bg.rect(), br);
773         p.end();
774         m_frameImage->setPixmap(bg);
775     } else {
776         m_frameImage->setPixmap(QPixmap::fromImage(m_render->extractFrame((int) m_render->seekPosition().frames(m_render->fps()), m_frameWidth / 2, m_frameHeight / 2)));
777     }
778 }
779
780 void TitleWidget::initAnimation()
781 {
782     align_box->setEnabled(false);
783     QPen startpen(Qt::DotLine);
784     QPen endpen(Qt::DashDotLine);
785     startpen.setColor(QColor(100, 200, 100, 140));
786     endpen.setColor(QColor(200, 100, 100, 140));
787
788     m_startViewport->setPen(startpen);
789     m_endViewport->setPen(endpen);
790
791     m_startViewport->setZValue(-1000);
792     m_endViewport->setZValue(-1000);
793
794     m_startViewport->setFlags(0);
795     m_endViewport->setFlags(0);
796
797     graphicsView->scene()->addItem(m_startViewport);
798     graphicsView->scene()->addItem(m_endViewport);
799
800     connect(keep_aspect, SIGNAL(toggled(bool)), this, SLOT(slotKeepAspect(bool)));
801     connect(resize50, SIGNAL(clicked()), this, SLOT(slotResize50()));
802     connect(resize100, SIGNAL(clicked()), this, SLOT(slotResize100()));
803     connect(resize200, SIGNAL(clicked()), this, SLOT(slotResize200()));
804 }
805
806 void TitleWidget::slotUpdateZoom(int pos)
807 {
808     m_scene->setZoom((double) pos / 100);
809     zoom_label->setText(QString::number(pos) + '%');
810 }
811
812 void TitleWidget::slotZoom(bool up)
813 {
814     int pos = zoom_slider->value();
815     if(up) pos++;
816     else pos--;
817     zoom_slider->setValue(pos);
818 }
819
820 void TitleWidget::slotAdjustZoom()
821 {
822     /*double scalex = graphicsView->width() / (double)(m_frameWidth * 1.2);
823     double scaley = graphicsView->height() / (double)(m_frameHeight * 1.2);
824     if (scalex > scaley) scalex = scaley;
825     int zoompos = (int)(scalex * 7 + 0.5);*/
826     graphicsView->fitInView(m_frameBorder, Qt::KeepAspectRatio);
827     int zoompos = graphicsView->matrix().m11() * 100;
828     zoom_slider->setValue(zoompos);
829     graphicsView->centerOn(m_frameBorder);
830 }
831
832 void TitleWidget::slotZoomOneToOne()
833 {
834     zoom_slider->setValue(100);
835     graphicsView->centerOn(m_frameBorder);
836 }
837
838 void TitleWidget::slotNewRect(QGraphicsRectItem * rect)
839 {
840     updateAxisButtons(rect); // back to default
841
842     QColor f = rectFColor->color();
843     f.setAlpha(rectFAlpha->value());
844     QPen penf(f);
845     penf.setWidth(rectLineWidth->value());
846     penf.setJoinStyle(Qt::RoundJoin);
847     rect->setPen(penf);
848     QColor b = rectBColor->color();
849     b.setAlpha(rectBAlpha->value());
850     rect->setBrush(QBrush(b));
851     rect->setZValue(m_count++);
852     rect->setData(ZOOMFACTOR, 100);
853     //setCurrentItem(rect);
854     //graphicsView->setFocus();
855 }
856
857 void TitleWidget::slotNewText(QGraphicsTextItem *tt)
858 {
859     updateAxisButtons(tt); // back to default
860
861     QFont font = font_family->currentFont();
862     font.setPixelSize(font_size->value());
863     // mbd: issue 551:
864     font.setWeight(font_weight_box->itemData(font_weight_box->currentIndex()).toInt());
865     font.setItalic(buttonItalic->isChecked());
866     font.setUnderline(buttonUnder->isChecked());
867
868     tt->setFont(font);
869     QColor color = fontColorButton->color();
870     color.setAlpha(textAlpha->value());
871     tt->setDefaultTextColor(color);
872
873     QTextCursor cur(tt->document());
874     cur.select(QTextCursor::Document);
875     QTextBlockFormat format = cur.blockFormat();
876     QTextCharFormat cformat = cur.charFormat();
877     QColor outlineColor = textOutlineColor->color();
878     outlineColor.setAlpha(textOutlineAlpha->value());
879     double outlineWidth = textOutline->value() / 10.0;
880
881     tt->setData(101, outlineWidth);
882     tt->setData(102, outlineColor);
883     if(outlineWidth > 0.0) cformat.setTextOutline(QPen(outlineColor, outlineWidth));
884
885     cformat.setForeground(QBrush(color));
886     cur.setCharFormat(cformat);
887     cur.setBlockFormat(format);
888     tt->setTextCursor(cur);
889     tt->setZValue(m_count++);
890     setCurrentItem(tt);
891 }
892
893 void TitleWidget::setFontBoxWeight(int weight)
894 {
895     int index = font_weight_box->findData(weight);
896     if(index < 0) {
897         index = font_weight_box->findData(QFont::Normal);
898     }
899     font_weight_box->setCurrentIndex(index);
900 }
901
902 void TitleWidget::setCurrentItem(QGraphicsItem *item)
903 {
904     m_scene->setSelectedItem(item);
905 }
906
907 void TitleWidget::zIndexChanged(int v)
908 {
909     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
910     if(l.size() >= 1) {
911         l[0]->setZValue(v);
912     }
913 }
914
915 void TitleWidget::selectionChanged()
916 {
917     if(m_scene->tool() != TITLE_SELECT) return;
918
919     std::cout << "Number of selected items: " << graphicsView->scene()->selectedItems().length() << "\n";
920
921     QList<QGraphicsItem *> l;
922
923     // mbt 1607: One text item might have grabbed the keyboard.
924     // Ungrab it for all items that are not selected, otherwise
925     // text input would only work for the text item that grabbed
926     // the keyboard last.
927     l = graphicsView->scene()->items();
928     foreach(QGraphicsItem * item, l) {
929         if(item->type() == TEXTITEM && !item->isSelected()) {
930             QGraphicsTextItem *i = static_cast<QGraphicsTextItem *>(item);
931             i->ungrabKeyboard();
932         }
933     }
934
935     l = graphicsView->scene()->selectedItems();
936
937     if(l.size() > 0) {
938         buttonUnselectAll->setEnabled(true);
939     } else {
940         buttonUnselectAll->setEnabled(false);
941     }
942     if(l.size() >= 2) {
943         buttonSelectText->setEnabled(true);
944         buttonSelectRects->setEnabled(true);
945         buttonSelectImages->setEnabled(true);
946     } else {
947         buttonSelectText->setEnabled(false);
948         buttonSelectRects->setEnabled(false);
949         buttonSelectImages->setEnabled(false);
950     }
951     
952     if (l.size() == 0) {
953         prepareTools(NULL);
954     } else if (l.size() == 1) {
955         prepareTools(l.at(0));
956     } else {
957         int firstType = l.at(0)->type();
958         bool allEqual = true;
959         for (int i = 0; i < l.size(); i++) {
960             if (l.at(i)->type() != firstType) {
961                 allEqual = false;
962                 break;
963             }
964         }
965         std::cout << "All equal? " << allEqual << ".\n";
966         if (allEqual) {
967             prepareTools(l.at(0));
968         } else {
969             prepareTools(NULL);
970         }
971     }
972     
973 }
974
975 void TitleWidget::slotValueChanged(int type)
976 {
977     /*
978     type tells us which QSpinBox value has changed.
979     */
980     
981     QList<QGraphicsItem *> l = graphicsView->scene()->selectedItems();
982     std::cout << l.size() << " items to be resized\n";
983     
984     // Get the updated value here already to do less coding afterwards
985     int val = 0;
986     switch(type) {
987         case ValueWidth:
988             val = value_w->value();
989             break;
990         case ValueHeight:
991             val = value_h->value();
992             break;
993         case ValueX:
994             val = value_x->value();
995             break;
996         case ValueY:
997             val = value_y->value();
998             break;
999     }
1000     
1001     for (int k = 0; k < l.size(); k++) {
1002         std::cout << "Type of item " << k << ": " << l.at(k)->type() << "\n";
1003         
1004         if(l.at(k)->type() == TEXTITEM) {
1005             // Just update the position. We don't allow setting width/height for text items yet.
1006             switch (type) {
1007                 case ValueX:
1008                     updatePosition(l.at(k), val, l.at(k)->pos().y());
1009                     break;
1010                 case ValueY:
1011                     updatePosition(l.at(k), l.at(k)->pos().x(), val);
1012                     break;
1013             }
1014
1015         } else if (l.at(k)->type() == RECTITEM) {
1016             QGraphicsRectItem *rec = static_cast <QGraphicsRectItem *>(l.at(k));
1017              switch (type) {
1018                 case ValueX:
1019                     updatePosition(l.at(k), val, l.at(k)->pos().y());
1020                     break;
1021                 case ValueY:
1022                     updatePosition(l.at(k), l.at(k)->pos().x(), val);
1023                     break;
1024                 case ValueWidth:
1025                     rec->setRect(QRect(0, 0, val, rec->rect().height()));
1026                     break;
1027                 case ValueHeight:
1028                     rec->setRect(QRect(0, 0, rec->rect().width(), val));
1029                     break;
1030             }
1031             
1032         } else if(l.at(k)->type() == IMAGEITEM) {
1033
1034             
1035             if (type == ValueX) {
1036                 updatePosition(l.at(k), val, l.at(k)->pos().y());
1037                 
1038             } else if (type == ValueY) {
1039                 updatePosition(l.at(k), l.at(k)->pos().x(), val);
1040                 
1041             } else {
1042                 // Width/height has changed. This is more complex.
1043                 
1044                 QGraphicsItem *i = l.at(k);
1045                 Transform t = m_transformations.value(i);
1046
1047                 // Ratio width:height
1048                 double phi = (double) i->boundingRect().width() / i->boundingRect().height();
1049                 // TODO: proper calculation for rotation around 3 axes
1050                 double alpha = (double) t.rotatez / 180.0 * M_PI;
1051
1052                 // New length
1053                 double length = val;
1054
1055                 // Scaling factor
1056                 double scale = 1;
1057
1058                 // We want to keep the aspect ratio of the image as the user does not yet have the possibility
1059                 // to restore the original ratio. You rarely want to change it anyway.
1060                 switch(type) {
1061                 case ValueWidth:
1062                     // Add 0.5 because otherwise incrementing by 1 might have no effect
1063                     length = val / (cos(alpha) + 1 / phi * sin(alpha)) + 0.5;
1064                     scale = length / i->boundingRect().width();
1065                     break;
1066                 case ValueHeight:
1067                     length = val / (phi * sin(alpha) + cos(alpha)) + 0.5;
1068                     scale = length / i->boundingRect().height();
1069                     break;
1070                 }
1071
1072                 t.scalex = scale;
1073                 t.scaley = scale;
1074                 QTransform qtrans;
1075                 qtrans.scale(scale, scale);
1076                 qtrans.rotate(t.rotatex, Qt::XAxis);
1077                 qtrans.rotate(t.rotatey, Qt::YAxis);
1078                 qtrans.rotate(t.rotatez, Qt::ZAxis);
1079                 i->setTransform(qtrans);
1080                 std::cout << "scale is: " << scale << "\n";
1081                 std::cout << i->boundingRect().width() << ": new width\n";
1082                 m_transformations[i] = t;
1083
1084                 if (l.size() == 1) {
1085                     // Only update the w/h values if the selection contains just one item.
1086                     // Otherwise, what should we do? ;)
1087                     // (Use the values of the first item? Of the second? Of the x-th?)
1088                     updateDimension(i);
1089                     // Update rotation/zoom values.
1090                     // These values are not yet able to handle multiple items!
1091                     updateRotZoom(i);
1092                 }
1093             }
1094             
1095         }
1096     }
1097     
1098     
1099 }
1100
1101 void TitleWidget::updateDimension(QGraphicsItem *i)
1102 {
1103     bool wBlocked = value_w->signalsBlocked();
1104     bool hBlocked = value_h->signalsBlocked();
1105     bool zBlocked = zValue->signalsBlocked();
1106     value_w->blockSignals(true);
1107     value_h->blockSignals(true);
1108     zValue->blockSignals(true);
1109
1110     zValue->setValue((int) i->zValue());
1111     if(i->type() == IMAGEITEM) {
1112         // Get multipliers for rotation/scaling
1113
1114         /*Transform t = m_transformations.value(i);
1115         QRectF r = i->boundingRect();
1116         int width = (int) ( abs(r.width()*t.scalex * cos(t.rotate/180.0*M_PI))
1117                     + abs(r.height()*t.scaley * sin(t.rotate/180.0*M_PI)) );
1118         int height = (int) ( abs(r.height()*t.scaley * cos(t.rotate/180*M_PI))
1119                     + abs(r.width()*t.scalex * sin(t.rotate/180*M_PI)) );*/
1120
1121         value_w->setValue(i->sceneBoundingRect().width());
1122         value_h->setValue(i->sceneBoundingRect().height());
1123     } else if(i->type() == RECTITEM) {
1124         QGraphicsRectItem *r = static_cast <QGraphicsRectItem *>(i);
1125         std::cout << "Rect width is: " << r->rect().width() << ", was: " << value_w->value() << "\n";
1126         value_w->setValue((int) r->rect().width());
1127         value_h->setValue((int) r->rect().height());
1128     } else if(i->type() == TEXTITEM) {
1129         QGraphicsTextItem *t = static_cast <QGraphicsTextItem *>(i);
1130         value_w->setValue((int) t->boundingRect().width());
1131         value_h->setValue((int) t->boundingRect().height());
1132     }
1133
1134     zValue->blockSignals(zBlocked);
1135     value_w->blockSignals(wBlocked);
1136     value_h->blockSignals(hBlocked);
1137 }
1138
1139 void TitleWidget::updateCoordinates(QGraphicsItem *i)
1140 {
1141     // Block signals emitted by this method
1142     value_x->blockSignals(true);
1143     value_y->blockSignals(true);
1144
1145     if(i->type() == TEXTITEM) {
1146
1147         QGraphicsTextItem *rec = static_cast <QGraphicsTextItem *>(i);
1148
1149         // Set the correct x coordinate value
1150         if(origin_x_left->isChecked()) {
1151             // Origin (0 point) is at m_frameWidth, coordinate axis is inverted
1152             value_x->setValue((int)(m_frameWidth - rec->pos().x() - rec->boundingRect().width()));
1153         } else {
1154             // Origin is at 0 (default)
1155             value_x->setValue((int) rec->pos().x());
1156         }
1157
1158         // Same for y
1159         if(origin_y_top->isChecked()) {
1160             value_y->setValue((int)(m_frameHeight - rec->pos().y() - rec->boundingRect().height()));
1161         } else {
1162             value_y->setValue((int) rec->pos().y());
1163         }
1164
1165     } else if(i->type() == RECTITEM) {
1166
1167         QGraphicsRectItem *rec = static_cast <QGraphicsRectItem *>(i);
1168
1169         if(origin_x_left->isChecked()) {
1170             // Origin (0 point) is at m_frameWidth
1171             value_x->setValue((int)(m_frameWidth - rec->pos().x() - rec->rect().width()));
1172         } else {
1173             // Origin is at 0 (default)
1174             value_x->setValue((int) rec->pos().x());
1175         }
1176
1177         if(origin_y_top->isChecked()) {
1178             value_y->setValue((int)(m_frameHeight - rec->pos().y() - rec->rect().height()));
1179         } else {
1180             value_y->setValue((int) rec->pos().y());
1181         }
1182
1183     } else if(i->type() == IMAGEITEM) {
1184
1185         if(origin_x_left->isChecked()) {
1186             value_x->setValue((int)(m_frameWidth - i->pos().x() - i->sceneBoundingRect().width()));
1187         } else {
1188             value_x->setValue((int) i->pos().x());
1189         }
1190
1191         if(origin_y_top->isChecked()) {
1192             value_y->setValue((int)(m_frameHeight - i->pos().y() - i->sceneBoundingRect().height()));
1193         } else {
1194             value_y->setValue((int) i->pos().y());
1195         }
1196
1197     }
1198
1199     // Stop blocking signals now
1200     value_x->blockSignals(false);
1201     value_y->blockSignals(false);
1202 }
1203
1204 void TitleWidget::updateRotZoom(QGraphicsItem *i)
1205 {
1206     itemzoom->blockSignals(true);
1207     itemrotatex->blockSignals(true);
1208     itemrotatey->blockSignals(true);
1209     itemrotatez->blockSignals(true);
1210
1211     Transform t = m_transformations.value(i);
1212
1213     if(!i->data(ZOOMFACTOR).isNull()) itemzoom->setValue(i->data(ZOOMFACTOR).toInt());
1214     else itemzoom->setValue((int)(t.scalex * 100.0 + 0.5));
1215
1216     itemrotatex->setValue((int)(t.rotatex));
1217     itemrotatey->setValue((int)(t.rotatey));
1218     itemrotatez->setValue((int)(t.rotatez));
1219
1220     itemzoom->blockSignals(false);
1221     itemrotatex->blockSignals(false);
1222     itemrotatey->blockSignals(false);
1223     itemrotatez->blockSignals(false);
1224 }
1225
1226 void TitleWidget::updatePosition(QGraphicsItem *i) {
1227     updatePosition(i, value_x->value(), value_y->value());
1228 }
1229
1230 void TitleWidget::updatePosition(QGraphicsItem *i, int x, int y)
1231 {
1232     if(i->type() == TEXTITEM) {
1233         QGraphicsTextItem *rec = static_cast <QGraphicsTextItem *>(i);
1234
1235         int posX;
1236         if(origin_x_left->isChecked()) {
1237             /*
1238              * Origin of the X axis is at m_frameWidth, and distance from right
1239              * border of the item to the right border of the frame is taken. See
1240              * comment to slotOriginXClicked().
1241              */
1242             posX = m_frameWidth - x - rec->boundingRect().width();
1243         } else {
1244             posX = x;
1245         }
1246
1247         int posY;
1248         if(origin_y_top->isChecked()) {
1249             /* Same for y axis */
1250             posY = m_frameHeight - y - rec->boundingRect().height();
1251         } else {
1252             posY = y;
1253         }
1254
1255         rec->setPos(posX, posY);
1256
1257     } else if(i->type() == RECTITEM) {
1258
1259         QGraphicsRectItem *rec = static_cast <QGraphicsRectItem *>(i);
1260
1261         int posX;
1262         if(origin_x_left->isChecked()) {
1263             posX = m_frameWidth - x - rec->rect().width();
1264         } else {
1265             posX = x;
1266         }
1267
1268         int posY;
1269         if(origin_y_top->isChecked()) {
1270             posY = m_frameHeight - y - rec->rect().height();
1271         } else {
1272             posY = y;
1273         }
1274
1275         rec->setPos(posX, posY);
1276
1277     } else if(i->type() == IMAGEITEM) {
1278         int posX;
1279         if(origin_x_left->isChecked()) {
1280             // Use the sceneBoundingRect because this also regards transformations like zoom
1281             posX = m_frameWidth - x - i->sceneBoundingRect().width();
1282         } else {
1283             posX = x;
1284         }
1285
1286         int posY;
1287         if(origin_y_top->isChecked()) {
1288             posY = m_frameHeight - y - i->sceneBoundingRect().height();
1289         } else {
1290             posY = y;
1291         }
1292
1293         i->setPos(posX, posY);
1294
1295     }
1296
1297 }
1298
1299 void TitleWidget::updateTextOriginX()
1300 {
1301     if(origin_x_left->isChecked()) {
1302         origin_x_left->setText(i18n("\u2212X"));
1303     } else {
1304         origin_x_left->setText(i18n("+X"));
1305     }
1306 }
1307
1308 void TitleWidget::slotOriginXClicked()
1309 {
1310     // Update the text displayed on the button.
1311     updateTextOriginX();
1312
1313     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1314     if(l.size() >= 1) {
1315         updateCoordinates(l.at(0));
1316
1317         // Remember x axis setting
1318         l.at(0)->setData(TitleDocument::OriginXLeft, origin_x_left->isChecked() ?
1319                          TitleDocument::AxisInverted : TitleDocument::AxisDefault);
1320     }
1321     graphicsView->setFocus();
1322 }
1323
1324 void TitleWidget::updateTextOriginY()
1325 {
1326     if(origin_y_top->isChecked()) {
1327         origin_y_top->setText(i18n("\u2212Y"));
1328     } else {
1329         origin_y_top->setText(i18n("+Y"));
1330     }
1331 }
1332
1333 void TitleWidget::slotOriginYClicked()
1334 {
1335     // Update the text displayed on the button.
1336     updateTextOriginY();
1337
1338     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1339     if(l.size() >= 1) {
1340         updateCoordinates(l.at(0));
1341
1342         l.at(0)->setData(TitleDocument::OriginYTop, origin_y_top->isChecked() ?
1343                          TitleDocument::AxisInverted : TitleDocument::AxisDefault);
1344
1345     }
1346     graphicsView->setFocus();
1347 }
1348
1349 void TitleWidget::updateAxisButtons(QGraphicsItem *i)
1350 {
1351     int xAxis = i->data(TitleDocument::OriginXLeft).toInt();
1352     int yAxis = i->data(TitleDocument::OriginYTop).toInt();
1353     origin_x_left->blockSignals(true);
1354     origin_y_top->blockSignals(true);
1355
1356     if(xAxis == TitleDocument::AxisInverted) {
1357         origin_x_left->setChecked(true);
1358     } else {
1359         origin_x_left->setChecked(false);
1360     }
1361     updateTextOriginX();
1362
1363     if(yAxis == TitleDocument::AxisInverted) {
1364         origin_y_top->setChecked(true);
1365     } else {
1366         origin_y_top->setChecked(false);
1367     }
1368     updateTextOriginY();
1369
1370     origin_x_left->blockSignals(false);
1371     origin_y_top->blockSignals(false);
1372 }
1373
1374 void TitleWidget::slotChangeBackground()
1375 {
1376     QColor color = backgroundColor->color();
1377     color.setAlpha(backgroundAlpha->value());
1378     m_frameBorder->setBrush(QBrush(color));
1379 }
1380
1381 void TitleWidget::slotChanged()
1382 {
1383     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1384     if(l.size() >= 1 && l.at(0)->type() == TEXTITEM) {
1385         textChanged(static_cast <QGraphicsTextItem *>(l.at(0)));
1386     }
1387 }
1388
1389 void TitleWidget::textChanged(QGraphicsTextItem *i)
1390 {
1391     /*
1392      * If the user has set origin_x_left (the same for y), we need to look
1393      * whether a text element has been selected. If yes, we need to ensure that
1394      * the right border of the text field remains fixed also when some text has
1395      * been entered.
1396      *
1397      * This is also known as right-justified, with the difference that it is not
1398      * valid for text but for its boundingRect. Text may still be
1399      * left-justified.
1400      */
1401     updateDimension(i);
1402
1403     if(origin_x_left->isChecked() || origin_y_top->isChecked()) {
1404         if(!i->toPlainText().isEmpty())
1405             updatePosition(i);
1406         else {
1407             /*
1408              * Don't do anything if the string is empty. If the position were
1409              * updated here, a newly created text field would be set to the
1410              * position of the last selected text field.
1411              */
1412         }
1413     }
1414
1415     // mbt 1607: Template text has changed; don't auto-select content anymore.
1416     if(i->property("isTemplate").isValid()) {
1417         if(i->property("templateText").isValid()) {
1418             if(i->property("templateText") == i->toHtml()) {
1419                 // Unchanged, do nothing.
1420             } else {
1421                 i->setProperty("isTemplate", QVariant::Invalid);
1422                 i->setProperty("templateText", QVariant::Invalid);
1423             }
1424         }
1425     }
1426 }
1427
1428 void TitleWidget::slotInsertUnicode()
1429 {
1430     m_unicodeDialog->exec();
1431 }
1432
1433 void TitleWidget::slotInsertUnicodeString(QString text)
1434 {
1435     QList<QGraphicsItem *> l = graphicsView->scene()->selectedItems();
1436     if(l.size() > 0) {
1437         if(l.at(0)->type() == TEXTITEM) {
1438             QGraphicsTextItem *t = static_cast <QGraphicsTextItem *>(l.at(0));
1439             t->textCursor().insertText(text);
1440         }
1441     }
1442 }
1443
1444 void TitleWidget::slotUpdateText()
1445 {
1446     QFont font = font_family->currentFont();
1447     font.setPixelSize(font_size->value());
1448     font.setItalic(buttonItalic->isChecked());
1449     font.setUnderline(buttonUnder->isChecked());
1450     font.setWeight(font_weight_box->itemData(font_weight_box->currentIndex()).toInt());
1451     QColor color = fontColorButton->color();
1452     color.setAlpha(textAlpha->value());
1453
1454     QColor outlineColor = textOutlineColor->color();
1455     outlineColor.setAlpha(textOutlineAlpha->value());
1456     double outlineWidth = textOutline->value() / 10.0;
1457
1458     int i;
1459     for(i = 0; i < graphicsView->scene()->selectedItems().length(); i++) {
1460         QGraphicsTextItem* item = NULL;
1461         QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1462         if(l.at(i)->type() == TEXTITEM) {
1463             item = static_cast <QGraphicsTextItem *>(l.at(i));
1464         }
1465         if(!item) {
1466             // No text item, try next one.
1467             continue;
1468         }
1469
1470         // Set alignment of all text in the text item
1471         QTextCursor cur(item->document());
1472         cur.select(QTextCursor::Document);
1473         QTextBlockFormat format = cur.blockFormat();
1474         if(buttonAlignLeft->isChecked() || buttonAlignCenter->isChecked() || buttonAlignRight->isChecked()) {
1475             item->setTextWidth(item->boundingRect().width());
1476             if(buttonAlignCenter->isChecked()) format.setAlignment(Qt::AlignHCenter);
1477             else if(buttonAlignRight->isChecked()) format.setAlignment(Qt::AlignRight);
1478             else if(buttonAlignLeft->isChecked()) format.setAlignment(Qt::AlignLeft);
1479         } else {
1480             format.setAlignment(Qt::AlignLeft);
1481             item->setTextWidth(-1);
1482         }
1483
1484         // Set font properties
1485         item->setFont(font);
1486         QTextCharFormat cformat = cur.charFormat();
1487
1488         item->setData(101, outlineWidth);
1489         item->setData(102, outlineColor);
1490         if(outlineWidth > 0.0) cformat.setTextOutline(QPen(outlineColor, outlineWidth, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
1491
1492         cformat.setForeground(QBrush(color));
1493         cur.setCharFormat(cformat);
1494         cur.setBlockFormat(format);
1495 //  item->setTextCursor(cur);
1496         cur.clearSelection();
1497         item->setTextCursor(cur);
1498     }
1499 }
1500
1501 void TitleWidget::rectChanged()
1502 {
1503     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1504     int i;
1505     for(i = 0; i < l.length(); i++) {
1506         if(l.at(i)->type() == RECTITEM && !settingUp) {
1507             QGraphicsRectItem *rec = static_cast<QGraphicsRectItem *>(l.at(i));
1508             QColor f = rectFColor->color();
1509             f.setAlpha(rectFAlpha->value());
1510             QPen penf(f);
1511             penf.setWidth(rectLineWidth->value());
1512             penf.setJoinStyle(Qt::RoundJoin);
1513             rec->setPen(penf);
1514             QColor b = rectBColor->color();
1515             b.setAlpha(rectBAlpha->value());
1516             rec->setBrush(QBrush(b));
1517         }
1518     }
1519 }
1520
1521 void TitleWidget::itemScaled(int val)
1522 {
1523     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1524     if(l.size() == 1) {
1525         Transform x = m_transformations.value(l.at(0));
1526         x.scalex = (double)val / 100.0;
1527         x.scaley = (double)val / 100.0;
1528         QTransform qtrans;
1529         qtrans.scale(x.scalex, x.scaley);
1530         qtrans.rotate(x.rotatex, Qt::XAxis);
1531         qtrans.rotate(x.rotatey, Qt::YAxis);
1532         qtrans.rotate(x.rotatez, Qt::ZAxis);
1533         l[0]->setTransform(qtrans);
1534         l[0]->setData(ZOOMFACTOR, val);
1535         m_transformations[l.at(0)] = x;
1536         updateDimension(l.at(0));
1537     }
1538 }
1539
1540 void TitleWidget::itemRotateX(qreal val)
1541 {
1542     itemRotate(val, 0);
1543 }
1544
1545 void TitleWidget::itemRotateY(qreal val)
1546 {
1547     itemRotate(val, 1);
1548 }
1549
1550 void TitleWidget::itemRotateZ(qreal val)
1551 {
1552     itemRotate(val, 2);
1553 }
1554
1555 void TitleWidget::itemRotate(qreal val, int axis)
1556 {
1557     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1558     if(l.size() == 1) {
1559         Transform x = m_transformations[l.at(0)];
1560         switch(axis) {
1561         case 0:
1562             x.rotatex = val;
1563             break;
1564         case 1:
1565             x.rotatey = val;
1566             break;
1567         case 2:
1568             x.rotatez = val;
1569             break;
1570         }
1571
1572         l[0]->setData(ROTATEFACTOR, QList<QVariant>() << QVariant(x.rotatex) << QVariant(x.rotatey) << QVariant(x.rotatez));
1573
1574         QTransform qtrans;
1575         qtrans.scale(x.scalex, x.scaley);
1576         qtrans.rotate(x.rotatex, Qt::XAxis);
1577         qtrans.rotate(x.rotatey, Qt::YAxis);
1578         qtrans.rotate(x.rotatez, Qt::ZAxis);
1579         l[0]->setTransform(qtrans);
1580         m_transformations[l.at(0)] = x;
1581         if(l[0]->data(ZOOMFACTOR).isNull()) l[0]->setData(ZOOMFACTOR, 100);
1582         updateDimension(l.at(0));
1583     }
1584 }
1585
1586 void TitleWidget::itemHCenter()
1587 {
1588     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1589     if(l.size() == 1) {
1590         QGraphicsItem *item = l.at(0);
1591         QRectF br = item->sceneBoundingRect();
1592         int width = (int)br.width();
1593         int newPos = (int)((m_frameWidth - width) / 2);
1594         newPos += item->pos().x() - br.left(); // Check item transformation
1595         item->setPos(newPos, item->pos().y());
1596         updateCoordinates(item);
1597     }
1598 }
1599
1600 void TitleWidget::itemVCenter()
1601 {
1602     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1603     if(l.size() == 1) {
1604         QGraphicsItem *item = l.at(0);
1605         QRectF br = item->sceneBoundingRect();
1606         int height = (int)br.height();
1607         int newPos = (int)((m_frameHeight - height) / 2);
1608         newPos += item->pos().y() - br.top(); // Check item transformation
1609         item->setPos(item->pos().x(), newPos);
1610         updateCoordinates(item);
1611     }
1612 }
1613
1614 void TitleWidget::itemTop()
1615 {
1616     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1617     if(l.size() == 1) {
1618         QGraphicsItem *item = l.at(0);
1619         QRectF br = item->sceneBoundingRect();
1620         double diff;
1621         if(br.top() > 0) diff = -br.top();
1622         else diff = -br.bottom();
1623         item->moveBy(0, diff);
1624         updateCoordinates(item);
1625     }
1626 }
1627
1628 void TitleWidget::itemBottom()
1629 {
1630     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1631     if(l.size() == 1) {
1632         QGraphicsItem *item = l.at(0);
1633         QRectF br = item->sceneBoundingRect();
1634         double diff;
1635         if(br.bottom() > m_frameHeight) diff = m_frameHeight - br.top();
1636         else diff = m_frameHeight - br.bottom();
1637         item->moveBy(0, diff);
1638         updateCoordinates(item);
1639     }
1640 }
1641
1642 void TitleWidget::itemLeft()
1643 {
1644     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1645     if(l.size() == 1) {
1646         QGraphicsItem *item = l.at(0);
1647         QRectF br = item->sceneBoundingRect();
1648         double diff;
1649         if(br.left() > 0) diff = -br.left();
1650         else diff = -br.right();
1651         item->moveBy(diff, 0);
1652         updateCoordinates(item);
1653     }
1654 }
1655
1656 void TitleWidget::itemRight()
1657 {
1658     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1659     if(l.size() == 1) {
1660         QGraphicsItem *item = l.at(0);
1661         QRectF br = item->sceneBoundingRect();
1662         double diff;
1663         if(br.right() < m_frameWidth) diff = m_frameWidth - br.right();
1664         else diff = m_frameWidth - br.left();
1665         item->moveBy(diff, 0);
1666         updateCoordinates(item);
1667     }
1668 }
1669
1670 void TitleWidget::setupViewports()
1671 {
1672     //double aspect_ratio = 4.0 / 3.0;//read from project
1673     //better zoom centered, but render uses only the created rect, so no problem to change the zoom function
1674     /*QRectF sp(0, 0, startViewportSize->value() * m_frameWidth / 100.0 , startViewportSize->value()* m_frameHeight / 100.0);
1675     QRectF ep(0, 0, endViewportSize->value() * m_frameWidth / 100.0, endViewportSize->value() * m_frameHeight / 100.0);
1676     // use a polygon thiat uses 16:9 and 4:3 rects forpreview the size in all aspect ratios ?
1677     QPolygonF spoly(sp);
1678     QPolygonF epoly(ep);
1679     spoly.translate(startViewportX->value(), startViewportY->value());
1680     epoly.translate(endViewportX->value(), endViewportY->value());
1681     m_startViewport->setPolygon(spoly);
1682     m_endViewport->setPolygon(epoly);
1683     if (! insertingValues) {
1684         m_startViewport->setData(0, startViewportX->value());
1685         m_startViewport->setData(1, startViewportY->value());
1686         m_startViewport->setData(2, startViewportSize->value());
1687
1688         m_endViewport->setData(0, endViewportX->value());
1689         m_endViewport->setData(1, endViewportY->value());
1690         m_endViewport->setData(2, endViewportSize->value());
1691     }*/
1692 }
1693
1694 void TitleWidget::loadTitle(KUrl url)
1695 {
1696     if(url.isEmpty()) url = KFileDialog::getOpenUrl(KUrl(m_projectTitlePath), "application/x-kdenlivetitle", this, i18n("Load Title"));
1697     if(!url.isEmpty()) {
1698         QList<QGraphicsItem *> items = m_scene->items();
1699         for(int i = 0; i < items.size(); i++) {
1700             if(items.at(i)->zValue() > -1000) delete items.at(i);
1701         }
1702         m_scene->clearTextSelection();
1703         QDomDocument doc;
1704         QString tmpfile;
1705
1706         if(KIO::NetAccess::download(url, tmpfile, 0)) {
1707             QFile file(tmpfile);
1708             if(file.open(QIODevice::ReadOnly)) {
1709                 doc.setContent(&file, false);
1710                 file.close();
1711             } else return;
1712             KIO::NetAccess::removeTempFile(tmpfile);
1713         }
1714         setXml(doc);
1715
1716         /*int out;
1717         m_count = m_titledocument.loadDocument(url, m_startViewport, m_endViewport, &out) + 1;
1718         adjustFrameSize();
1719         title_duration->setText(m_tc.getTimecode(GenTime(out, m_render->fps())));
1720         insertingValues = true;
1721         startViewportX->setValue(m_startViewport->data(0).toInt());
1722         startViewportY->setValue(m_startViewport->data(1).toInt());
1723         startViewportSize->setValue(m_startViewport->data(2).toInt());
1724         endViewportX->setValue(m_endViewport->data(0).toInt());
1725         endViewportY->setValue(m_endViewport->data(1).toInt());
1726         endViewportSize->setValue(m_endViewport->data(2).toInt());
1727
1728         insertingValues = false;
1729         slotSelectTool();
1730         slotAdjustZoom();*/
1731     }
1732 }
1733
1734 void TitleWidget::saveTitle(KUrl url)
1735 {
1736     if(anim_start->isChecked()) slotAnimStart(false);
1737     if(anim_end->isChecked()) slotAnimEnd(false);
1738     if(url.isEmpty()) {
1739         KFileDialog *fs = new KFileDialog(KUrl(m_projectTitlePath), "application/x-kdenlivetitle", this);
1740         fs->setOperationMode(KFileDialog::Saving);
1741         fs->setMode(KFile::File);
1742 #if KDE_IS_VERSION(4,2,0)
1743         fs->setConfirmOverwrite(true);
1744 #endif
1745         fs->setKeepLocation(true);
1746         fs->exec();
1747         url = fs->selectedUrl();
1748         delete fs;
1749     }
1750     if(!url.isEmpty()) {
1751         if(m_titledocument.saveDocument(url, m_startViewport, m_endViewport, m_tc.getFrameCount(title_duration->text()) - 1) == false)
1752             KMessageBox::error(this, i18n("Cannot write to file %1", url.path()));
1753     }
1754 }
1755
1756 QDomDocument TitleWidget::xml()
1757 {
1758     QDomDocument doc = m_titledocument.xml(m_startViewport, m_endViewport);
1759     doc.documentElement().setAttribute("out", m_tc.getFrameCount(title_duration->text()) - 1);
1760     return doc;
1761 }
1762
1763 int TitleWidget::outPoint() const
1764 {
1765     return m_tc.getFrameCount(title_duration->text()) - 1;
1766 }
1767
1768 void TitleWidget::setXml(QDomDocument doc)
1769 {
1770     int out;
1771     m_count = m_titledocument.loadFromXml(doc, m_startViewport, m_endViewport, &out);
1772     adjustFrameSize();
1773     title_duration->setText(m_tc.getTimecode(GenTime(out + 1, m_render->fps())));
1774     /*if (doc.documentElement().hasAttribute("out")) {
1775     GenTime duration = GenTime(doc.documentElement().attribute("out").toDouble() / 1000.0);
1776     title_duration->setText(m_tc.getTimecode(duration));
1777     }
1778     else title_duration->setText(m_tc.getTimecode(GenTime(5000)));*/
1779
1780     QDomElement e = doc.documentElement();
1781     m_transformations.clear();
1782     QList <QGraphicsItem *> items = graphicsView->scene()->items();
1783     const double PI = 4.0 * atan(1.0);
1784     for(int i = 0; i < items.count(); i++) {
1785         QTransform t = items.at(i)->transform();
1786         Transform x;
1787         x.scalex = t.m11();
1788         x.scaley = t.m22();
1789         if(!items.at(i)->data(ROTATEFACTOR).isNull()) {
1790             QList<QVariant> rotlist = items.at(i)->data(ROTATEFACTOR).toList();
1791             if(rotlist.count() >= 3) {
1792                 x.rotatex = rotlist[0].toDouble();
1793                 x.rotatey = rotlist[1].toDouble();
1794                 x.rotatez = rotlist[2].toDouble();
1795
1796                 // Try to adjust zoom
1797                 t.rotate(x.rotatex *(-1), Qt::XAxis);
1798                 t.rotate(x.rotatey *(-1), Qt::YAxis);
1799                 t.rotate(x.rotatez *(-1), Qt::ZAxis);
1800                 x.scalex = t.m11();
1801                 x.scaley = t.m22();
1802             } else {
1803                 x.rotatex = 0;
1804                 x.rotatey = 0;
1805                 x.rotatez = 0;
1806             }
1807         } else {
1808             x.rotatex = 0;
1809             x.rotatey = 0;
1810             x.rotatez = 180. / PI * atan2(-t.m21(), t.m11());
1811         }
1812         m_transformations[items.at(i)] = x;
1813     }
1814     // mbd: Update the GUI color selectors to match the stuff from the loaded document
1815     QColor background_color = m_titledocument.getBackgroundColor();
1816     backgroundAlpha->blockSignals(true);
1817     backgroundColor->blockSignals(true);
1818     backgroundAlpha->setValue(background_color.alpha());
1819     background_color.setAlpha(255);
1820     backgroundColor->setColor(background_color);
1821     backgroundAlpha->blockSignals(false);
1822     backgroundColor->blockSignals(false);
1823
1824     /*startViewportX->setValue(m_startViewport->data(0).toInt());
1825     startViewportY->setValue(m_startViewport->data(1).toInt());
1826     startViewportSize->setValue(m_startViewport->data(2).toInt());
1827     endViewportX->setValue(m_endViewport->data(0).toInt());
1828     endViewportY->setValue(m_endViewport->data(1).toInt());
1829     endViewportSize->setValue(m_endViewport->data(2).toInt());*/
1830
1831     QTimer::singleShot(200, this, SLOT(slotAdjustZoom()));
1832     slotSelectTool();
1833     selectionChanged();
1834 }
1835
1836 void TitleWidget::slotAccepted()
1837 {
1838     if(anim_start->isChecked()) slotAnimStart(false);
1839     if(anim_end->isChecked()) slotAnimEnd(false);
1840     writeChoices();
1841 }
1842
1843 void TitleWidget::writeChoices()
1844 {
1845     // Get a pointer to a shared configuration instance, then get the TitleWidget group.
1846     KSharedConfigPtr config = KGlobal::config();
1847     KConfigGroup titleConfig(config, "TitleWidget");
1848     // Write the entries
1849     titleConfig.writeEntry("font_family", font_family->currentFont());
1850     //titleConfig.writeEntry("font_size", font_size->value());
1851     titleConfig.writeEntry("font_pixel_size", font_size->value());
1852     titleConfig.writeEntry("font_color", fontColorButton->color());
1853     titleConfig.writeEntry("font_alpha", textAlpha->value());
1854     titleConfig.writeEntry("font_outline", textOutline->value());
1855     titleConfig.writeEntry("font_outline_color", textOutlineColor->color());
1856     titleConfig.writeEntry("font_outline_alpha", textOutlineAlpha->value());
1857     titleConfig.writeEntry("font_weight", font_weight_box->itemData(font_weight_box->currentIndex()).toInt());
1858     titleConfig.writeEntry("font_italic", buttonItalic->isChecked());
1859     titleConfig.writeEntry("font_underlined", buttonUnder->isChecked());
1860
1861     titleConfig.writeEntry("rect_foreground_color", rectFColor->color());
1862     titleConfig.writeEntry("rect_foreground_alpha", rectFAlpha->value());
1863     titleConfig.writeEntry("rect_background_color", rectBColor->color());
1864     titleConfig.writeEntry("rect_background_alpha", rectBAlpha->value());
1865     titleConfig.writeEntry("rect_line_width", rectLineWidth->value());
1866
1867     titleConfig.writeEntry("background_color", backgroundColor->color());
1868     titleConfig.writeEntry("background_alpha", backgroundAlpha->value());
1869
1870     //! \todo Not sure if I should sync - it is probably safe to do it
1871     config->sync();
1872
1873 }
1874
1875 void TitleWidget::readChoices()
1876 {
1877     // Get a pointer to a shared configuration instance, then get the TitleWidget group.
1878     KSharedConfigPtr config = KGlobal::config();
1879     KConfigGroup titleConfig(config, "TitleWidget");
1880     // read the entries
1881     font_family->setCurrentFont(titleConfig.readEntry("font_family", font_family->currentFont()));
1882     font_size->setValue(titleConfig.readEntry("font_pixel_size", font_size->value()));
1883     m_scene->slotUpdateFontSize(font_size->value());
1884     fontColorButton->setColor(titleConfig.readEntry("font_color", fontColorButton->color()));
1885     textAlpha->setValue(titleConfig.readEntry("font_alpha", textAlpha->value()));
1886
1887     textOutlineColor->setColor(titleConfig.readEntry("font_outline_color", textOutlineColor->color()));
1888     textOutlineAlpha->setValue(titleConfig.readEntry("font_outline_alpha", textOutlineAlpha->value()));
1889     textOutline->setValue(titleConfig.readEntry("font_outline", textOutline->value()));
1890
1891     int weight;
1892     if(titleConfig.readEntry("font_bold", false)) weight = QFont::Bold;
1893     else weight = titleConfig.readEntry("font_weight", font_weight_box->itemData(font_weight_box->currentIndex()).toInt());
1894     setFontBoxWeight(weight);
1895     buttonItalic->setChecked(titleConfig.readEntry("font_italic", buttonItalic->isChecked()));
1896     buttonUnder->setChecked(titleConfig.readEntry("font_underlined", buttonUnder->isChecked()));
1897
1898     rectFColor->setColor(titleConfig.readEntry("rect_foreground_color", rectFColor->color()));
1899     rectFAlpha->setValue(titleConfig.readEntry("rect_foreground_alpha", rectFAlpha->value()));
1900     rectBColor->setColor(titleConfig.readEntry("rect_background_color", rectBColor->color()));
1901     rectBAlpha->setValue(titleConfig.readEntry("rect_background_alpha", rectBAlpha->value()));
1902     rectLineWidth->setValue(titleConfig.readEntry("rect_line_width", rectLineWidth->value()));
1903
1904     backgroundColor->setColor(titleConfig.readEntry("background_color", backgroundColor->color()));
1905     backgroundAlpha->setValue(titleConfig.readEntry("background_alpha", backgroundAlpha->value()));
1906 }
1907
1908 void TitleWidget::adjustFrameSize()
1909 {
1910     m_frameWidth = m_titledocument.frameWidth();
1911     m_frameHeight = m_titledocument.frameHeight();
1912     m_frameBorder->setRect(0, 0, m_frameWidth, m_frameHeight);
1913     displayBackgroundFrame();
1914 }
1915
1916 void TitleWidget::slotAnimStart(bool anim)
1917 {
1918     if(anim && anim_end->isChecked()) {
1919         anim_end->setChecked(false);
1920         m_endViewport->setZValue(-1000);
1921         m_endViewport->setBrush(QBrush());
1922     }
1923     slotSelectTool();
1924     QList<QGraphicsItem *> list = m_scene->items();
1925     for(int i = 0; i < list.count(); i++) {
1926         if(list.at(i)->zValue() > -1000) {
1927             list.at(i)->setFlag(QGraphicsItem::ItemIsMovable, !anim);
1928             list.at(i)->setFlag(QGraphicsItem::ItemIsSelectable, !anim);
1929         }
1930     }
1931     align_box->setEnabled(anim);
1932     itemzoom->setEnabled(!anim);
1933     itemrotatex->setEnabled(!anim);
1934     itemrotatey->setEnabled(!anim);
1935     itemrotatez->setEnabled(!anim);
1936     frame_toolbar->setEnabled(!anim);
1937     toolbar_stack->setEnabled(!anim);
1938     if(anim) {
1939         keep_aspect->setChecked(!m_startViewport->data(0).isNull());
1940         m_startViewport->setZValue(1100);
1941         QColor col = m_startViewport->pen().color();
1942         col.setAlpha(100);
1943         m_startViewport->setBrush(col);
1944         m_startViewport->setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable);
1945         m_startViewport->setSelected(true);
1946         selectionChanged();
1947         slotSelectTool();
1948         if(m_startViewport->childItems().isEmpty()) addAnimInfoText();
1949     } else {
1950         m_startViewport->setZValue(-1000);
1951         m_startViewport->setBrush(QBrush());
1952         m_startViewport->setFlags(0);
1953         if(!anim_end->isChecked()) deleteAnimInfoText();
1954     }
1955
1956 }
1957
1958 void TitleWidget::slotAnimEnd(bool anim)
1959 {
1960     if(anim && anim_start->isChecked()) {
1961         anim_start->setChecked(false);
1962         m_startViewport->setZValue(-1000);
1963         m_startViewport->setBrush(QBrush());
1964     }
1965     slotSelectTool();
1966     QList<QGraphicsItem *> list = m_scene->items();
1967     for(int i = 0; i < list.count(); i++) {
1968         if(list.at(i)->zValue() > -1000) {
1969             list.at(i)->setFlag(QGraphicsItem::ItemIsMovable, !anim);
1970             list.at(i)->setFlag(QGraphicsItem::ItemIsSelectable, !anim);
1971         }
1972     }
1973     align_box->setEnabled(anim);
1974     itemzoom->setEnabled(!anim);
1975     itemrotatex->setEnabled(!anim);
1976     itemrotatey->setEnabled(!anim);
1977     itemrotatez->setEnabled(!anim);
1978     frame_toolbar->setEnabled(!anim);
1979     toolbar_stack->setEnabled(!anim);
1980     if(anim) {
1981         keep_aspect->setChecked(!m_endViewport->data(0).isNull());
1982         m_endViewport->setZValue(1100);
1983         QColor col = m_endViewport->pen().color();
1984         col.setAlpha(100);
1985         m_endViewport->setBrush(col);
1986         m_endViewport->setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable);
1987         m_endViewport->setSelected(true);
1988         selectionChanged();
1989         slotSelectTool();
1990         if(m_endViewport->childItems().isEmpty()) addAnimInfoText();
1991     } else {
1992         m_endViewport->setZValue(-1000);
1993         m_endViewport->setBrush(QBrush());
1994         m_endViewport->setFlags(0);
1995         if(!anim_start->isChecked()) deleteAnimInfoText();
1996     }
1997 }
1998
1999 void TitleWidget::addAnimInfoText()
2000 {
2001     // add text to anim viewport
2002     QGraphicsTextItem *t = new QGraphicsTextItem(i18n("Start"), m_startViewport);
2003     QGraphicsTextItem *t2 = new QGraphicsTextItem(i18n("End"), m_endViewport);
2004     QFont font = t->font();
2005     font.setPixelSize(m_startViewport->rect().width() / 10);
2006     QColor col = m_startViewport->pen().color();
2007     col.setAlpha(255);
2008     t->setDefaultTextColor(col);
2009     t->setFont(font);
2010     font.setPixelSize(m_endViewport->rect().width() / 10);
2011     col = m_endViewport->pen().color();
2012     col.setAlpha(255);
2013     t2->setDefaultTextColor(col);
2014     t2->setFont(font);
2015 }
2016
2017 void TitleWidget::updateInfoText()
2018 {
2019     // update info text font
2020     if(!m_startViewport->childItems().isEmpty()) {
2021         QGraphicsTextItem *item = static_cast <QGraphicsTextItem *>(m_startViewport->childItems().at(0));
2022         if(item) {
2023             QFont font = item->font();
2024             font.setPixelSize(m_startViewport->rect().width() / 10);
2025             item->setFont(font);
2026         }
2027     }
2028     if(!m_endViewport->childItems().isEmpty()) {
2029         QGraphicsTextItem *item = static_cast <QGraphicsTextItem *>(m_endViewport->childItems().at(0));
2030         if(item) {
2031             QFont font = item->font();
2032             font.setPixelSize(m_endViewport->rect().width() / 10);
2033             item->setFont(font);
2034         }
2035     }
2036 }
2037
2038 void TitleWidget::deleteAnimInfoText()
2039 {
2040     // end animation editing, remove info text
2041     while(!m_startViewport->childItems().isEmpty()) {
2042         QGraphicsItem *item = m_startViewport->childItems().at(0);
2043         m_scene->removeItem(item);
2044         delete item;
2045     }
2046     while(!m_endViewport->childItems().isEmpty()) {
2047         QGraphicsItem *item = m_endViewport->childItems().at(0);
2048         m_scene->removeItem(item);
2049         delete item;
2050     }
2051 }
2052
2053 void TitleWidget::slotKeepAspect(bool keep)
2054 {
2055     if(m_endViewport->zValue() == 1100) {
2056         m_endViewport->setData(0, keep == true ? m_frameWidth : QVariant());
2057         m_endViewport->setData(1, keep == true ? m_frameHeight : QVariant());
2058     } else {
2059         m_startViewport->setData(0, keep == true ? m_frameWidth : QVariant());
2060         m_startViewport->setData(1, keep == true ? m_frameHeight : QVariant());
2061     }
2062 }
2063
2064 void TitleWidget::slotResize50()
2065 {
2066     if(m_endViewport->zValue() == 1100) {
2067         m_endViewport->setRect(0, 0, m_frameWidth / 2, m_frameHeight / 2);
2068     } else m_startViewport->setRect(0, 0, m_frameWidth / 2, m_frameHeight / 2);
2069 }
2070
2071 void TitleWidget::slotResize100()
2072 {
2073     if(m_endViewport->zValue() == 1100) {
2074         m_endViewport->setRect(0, 0, m_frameWidth, m_frameHeight);
2075     } else m_startViewport->setRect(0, 0, m_frameWidth, m_frameHeight);
2076 }
2077
2078 void TitleWidget::slotResize200()
2079 {
2080     if(m_endViewport->zValue() == 1100) {
2081         m_endViewport->setRect(0, 0, m_frameWidth * 2, m_frameHeight * 2);
2082     } else m_startViewport->setRect(0, 0, m_frameWidth * 2, m_frameHeight * 2);
2083 }
2084
2085 void TitleWidget::slotAddEffect(int ix)
2086 {
2087     QList<QGraphicsItem *> list = graphicsView->scene()->selectedItems();
2088     int effect = effect_list->itemData(ix).toInt();
2089
2090     if(list.size() == 1) {
2091         if(effect == NOEFFECT)
2092             effect_stack->setHidden(true);
2093         else {
2094             effect_stack->setCurrentIndex(effect - 1);
2095             effect_stack->setHidden(false);
2096         }
2097     } else // Hide the effects stack when more than one element is selected.
2098         effect_stack->setHidden(true);
2099
2100     foreach(QGraphicsItem * item, list) {
2101         switch(effect) {
2102         case NOEFFECT:
2103             item->setData(100, QVariant());
2104 #if QT_VERSION >= 0x040600
2105             item->setGraphicsEffect(0);
2106 #endif
2107             break;
2108         case TYPEWRITEREFFECT:
2109             /*
2110              * Allow the user to set the typewriter effect to more than one
2111              * element, but do not add it to non-text elements.
2112              */
2113             if(item->type() == TEXTITEM) {
2114                 QStringList effdata = QStringList() << "typewriter" << QString::number(typewriter_delay->value()) + ";" + QString::number(typewriter_start->value());
2115                 item->setData(100, effdata);
2116             }
2117             break;
2118 #if QT_VERSION >= 0x040600
2119             // Do not remove the non-QGraphicsEffects.
2120         case BLUREFFECT:
2121             item->setGraphicsEffect(new QGraphicsBlurEffect());
2122             break;
2123         case SHADOWEFFECT:
2124             item->setGraphicsEffect(new QGraphicsDropShadowEffect());
2125             break;
2126 #endif
2127         }
2128     }
2129 }
2130
2131 void TitleWidget::slotFontText(const QString& s)
2132 {
2133     const QFont f(s);
2134     if(f.exactMatch()) {
2135         // Font really exists (could also just be a Â«d» if the user
2136         // starts typing Â«dejavu» for example).
2137         font_family->setCurrentFont(f);
2138     }
2139     // Note: Typing dejavu serif does not recognize the font (takes sans)
2140     // in older Qt versions. Case must match there (except for first letter)
2141 }
2142
2143 void TitleWidget::slotEditTypewriter(int /*ix*/)
2144 {
2145     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
2146     if(l.size() == 1) {
2147         QStringList effdata = QStringList() << "typewriter" << QString::number(typewriter_delay->value()) + ";" + QString::number(typewriter_start->value());
2148         l[0]->setData(100, effdata);
2149     }
2150 }
2151
2152 void TitleWidget::slotEditBlur(int ix)
2153 {
2154 #if QT_VERSION < 0x040600
2155     return;
2156 #else
2157     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
2158     if(l.size() == 1) {
2159         QGraphicsEffect *eff = l[0]->graphicsEffect();
2160         QGraphicsBlurEffect *blur = static_cast <QGraphicsBlurEffect *>(eff);
2161         if(blur) blur->setBlurRadius(ix);
2162     }
2163 #endif
2164 }
2165
2166 void TitleWidget::slotEditShadow()
2167 {
2168 #if QT_VERSION < 0x040600
2169     return;
2170 #else
2171     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
2172     if(l.size() == 1) {
2173         QGraphicsEffect *eff = l[0]->graphicsEffect();
2174         QGraphicsDropShadowEffect *shadow = static_cast <QGraphicsDropShadowEffect *>(eff);
2175         if(shadow) {
2176             shadow->setBlurRadius(shadow_radius->value());
2177             shadow->setOffset(shadow_x->value(), shadow_y->value());
2178         }
2179     }
2180 #endif
2181 }
2182
2183 qreal TitleWidget::zIndexBounds(bool maxBound, bool intersectingOnly)
2184 {
2185     qreal bound = maxBound ? -99 : 99;
2186     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
2187     if(l.size() > 0) {
2188         QList<QGraphicsItem*> lItems;
2189         // Get items (all or intersecting only)
2190         if(intersectingOnly) {
2191             lItems = graphicsView->scene()->items(l[0]->sceneBoundingRect(), Qt::IntersectsItemShape);
2192         } else {
2193             lItems = graphicsView->scene()->items();
2194         }
2195         if(lItems.size() > 0) {
2196             int n = lItems.size();
2197             qreal z;
2198             if(maxBound) {
2199                 for(int i = 0; i < n; i++) {
2200                     z = lItems[i]->zValue();
2201                     if(z > bound && !lItems[i]->isSelected()) {
2202                         bound = z;
2203                     }
2204                 }
2205             } else {
2206                 // Get minimum z index.
2207                 for(int i = 0; i < n; i++) {
2208                     z = lItems[i]->zValue();
2209                     if(z < bound && !lItems[i]->isSelected() && z > -999) {
2210                         // There are items at the very bottom (background e.g.) with z-index < -1000.
2211                         bound = z;
2212                     }
2213                 }
2214             }
2215         }
2216     }
2217     return bound;
2218 }
2219
2220 void TitleWidget::slotZIndexUp()
2221 {
2222     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
2223     if(l.size() >= 1) {
2224         qreal currentZ = l[0]->zValue();
2225         qreal max = zIndexBounds(true, true);
2226         if(currentZ <= max) {
2227             l[0]->setZValue(currentZ + 1);
2228             updateDimension(l[0]);
2229         }
2230     }
2231 }
2232
2233 void TitleWidget::slotZIndexTop()
2234 {
2235     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
2236     if(l.size() >= 1) {
2237         qreal currentZ = l[0]->zValue();
2238         qreal max = zIndexBounds(true, false);
2239         if(currentZ <= max) {
2240             l[0]->setZValue(max + 1);
2241             updateDimension(l[0]);
2242         }
2243     }
2244 }
2245
2246 void TitleWidget::slotZIndexDown()
2247 {
2248     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
2249     if(l.size() >= 1) {
2250         qreal currentZ = l[0]->zValue();
2251         qreal min = zIndexBounds(false, true);
2252         if(currentZ >= min) {
2253             l[0]->setZValue(currentZ - 1);
2254             updateDimension(l[0]);
2255         }
2256     }
2257 }
2258
2259 void TitleWidget::slotZIndexBottom()
2260 {
2261     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
2262     if(l.size() >= 1) {
2263         qreal currentZ = l[0]->zValue();
2264         qreal min = zIndexBounds(false, false);
2265         if(currentZ >= min) {
2266             l[0]->setZValue(min - 1);
2267             updateDimension(l[0]);
2268         }
2269     }
2270 }
2271
2272 void TitleWidget::slotSelectAll()
2273 {
2274     QList<QGraphicsItem*> l = graphicsView->scene()->items();
2275     for(int i = 0; i < l.size(); i++) {
2276         l.at(i)->setSelected(true);
2277     }
2278 }
2279
2280 void TitleWidget::selectItems(int itemType)
2281 {
2282     QList<QGraphicsItem*> l;
2283     if(graphicsView->scene()->selectedItems().size() > 0) {
2284         l = graphicsView->scene()->selectedItems();
2285         for(int i = 0; i < l.size(); i++) {
2286             if(l.at(i)->type() != itemType) {
2287                 l.at(i)->setSelected(false);
2288             }
2289         }
2290     } else {
2291         l = graphicsView->scene()->items();
2292         for(int i = 0; i < l.size(); i++) {
2293             if(l.at(i)->type() == itemType) {
2294                 l.at(i)->setSelected(true);
2295             }
2296         }
2297     }
2298 }
2299
2300 void TitleWidget::slotSelectText()
2301 {
2302     selectItems(TEXTITEM);
2303 }
2304
2305 void TitleWidget::slotSelectRects()
2306 {
2307     selectItems(RECTITEM);
2308 }
2309
2310 void TitleWidget::slotSelectImages()
2311 {
2312     selectItems(IMAGEITEM);
2313 }
2314
2315 void TitleWidget::slotSelectNone()
2316 {
2317     graphicsView->blockSignals(true);
2318     QList<QGraphicsItem*> l = graphicsView->scene()->items();
2319     for(int i = 0; i < l.size(); i++) {
2320         l.at(i)->setSelected(false);
2321     }
2322     graphicsView->blockSignals(false);
2323     selectionChanged();
2324 }
2325
2326 QString TitleWidget::getTooltipWithShortcut(const QString text, QAction *button)
2327 {
2328     return text + "  <b>" + button->shortcut().toString() + "</b>";
2329 }
2330
2331 void TitleWidget::prepareTools(QGraphicsItem *referenceItem) 
2332 {
2333     // Let some GUI elements block signals. We may want to change their values without any sideeffects.
2334     // Additionally, store the previous blocking state to avoid side effects when this function is called from within another one.
2335     // Note: Disabling an element also blocks signals. So disabled elements don't need to be set to blocking too.
2336     bool blockOX = origin_x_left->signalsBlocked();
2337     bool blockOY = origin_y_top->signalsBlocked();
2338     bool blockEff = effect_list->signalsBlocked();
2339     bool blockRX = itemrotatex->signalsBlocked();
2340     bool blockRY = itemrotatey->signalsBlocked();
2341     bool blockRZ = itemrotatez->signalsBlocked();
2342     bool blockZoom = itemzoom->signalsBlocked();
2343     bool blockX = value_x->signalsBlocked();
2344     bool blockY = value_y->signalsBlocked();
2345     bool blockW = value_w->signalsBlocked();
2346     bool blockH = value_h->signalsBlocked();
2347     origin_x_left->blockSignals(true);
2348     origin_y_top->blockSignals(true);
2349     effect_list->blockSignals(true);
2350     itemrotatex->blockSignals(true);
2351     itemrotatey->blockSignals(true);
2352     itemrotatez->blockSignals(true);
2353     itemzoom->blockSignals(true);
2354     value_x->blockSignals(true);
2355     value_y->blockSignals(true);
2356     value_w->blockSignals(true);
2357     value_h->blockSignals(true);
2358     
2359     if(referenceItem == NULL) {
2360         std::cout << "NULL item.\n";
2361         effect_stack->setHidden(true);
2362         effect_frame->setEnabled(false);
2363         effect_list->setCurrentIndex(0);
2364         origin_x_left->setChecked(false);
2365         origin_y_top->setChecked(false);
2366         updateTextOriginX();
2367         updateTextOriginY();
2368         enableToolbars(TITLE_SELECT);
2369         showToolbars(TITLE_SELECT);
2370         
2371         itemzoom->setEnabled(false);
2372         itemrotatex->setEnabled(false);
2373         itemrotatey->setEnabled(false);
2374         itemrotatez->setEnabled(false);
2375         frame_properties->setEnabled(false);
2376     } else {
2377         effect_frame->setEnabled(true);
2378         frame_properties->setEnabled(true);
2379         if(referenceItem != m_startViewport && referenceItem != m_endViewport) {
2380             itemzoom->setEnabled(true);
2381             itemrotatex->setEnabled(true);
2382             itemrotatey->setEnabled(true);
2383             itemrotatez->setEnabled(true);
2384         } else {
2385             itemzoom->setEnabled(false);
2386             itemrotatex->setEnabled(false);
2387             itemrotatey->setEnabled(false);
2388             itemrotatez->setEnabled(false);
2389             updateInfoText();
2390         }
2391         if(referenceItem->type() == TEXTITEM) {
2392             showToolbars(TITLE_TEXT);
2393             QGraphicsTextItem* i = static_cast <QGraphicsTextItem *>(referenceItem);
2394             if(!i->data(100).isNull()) {
2395                 // Item has an effect
2396                 QStringList effdata = i->data(100).toStringList();
2397                 QString effectName = effdata.takeFirst();
2398                 if(effectName == "typewriter") {
2399                     QStringList params = effdata.at(0).split(';');
2400                     typewriter_delay->setValue(params.at(0).toInt());
2401                     typewriter_start->setValue(params.at(1).toInt());
2402                     effect_list->setCurrentIndex(effect_list->findData((int) TYPEWRITEREFFECT));
2403                     effect_stack->setHidden(false);
2404                 }
2405             } else {
2406 #if QT_VERSION >= 0x040600
2407                 if(i->graphicsEffect()) {
2408                     QGraphicsBlurEffect *blur = static_cast <QGraphicsBlurEffect *>(i->graphicsEffect());
2409                     if(blur) {
2410                         effect_list->setCurrentIndex(effect_list->findData((int) BLUREFFECT));
2411                         int rad = (int) blur->blurRadius();
2412                         blur_radius->setValue(rad);
2413                         effect_stack->setHidden(false);
2414                     } else {
2415                         QGraphicsDropShadowEffect *shad = static_cast <QGraphicsDropShadowEffect *>(i->graphicsEffect());
2416                         if(shad) {
2417                             effect_list->setCurrentIndex(effect_list->findData((int) SHADOWEFFECT));
2418                             shadow_radius->setValue(shad->blurRadius());
2419                             shadow_x->setValue(shad->xOffset());
2420                             shadow_y->setValue(shad->yOffset());
2421                             effect_stack->setHidden(false);
2422                         }
2423                     }
2424                 } else {
2425                     effect_list->setCurrentIndex(effect_list->findData((int) NOEFFECT));
2426                     effect_stack->setHidden(true);
2427                 }
2428 #else
2429                 effect_list->setCurrentIndex(effect_list->findData((int) NOEFFECT));
2430                 effect_stack->setHidden(true);
2431 #endif
2432             }
2433             font_size->blockSignals(true);
2434             font_family->blockSignals(true);
2435             font_weight_box->blockSignals(true);
2436             buttonItalic->blockSignals(true);
2437             buttonUnder->blockSignals(true);
2438             fontColorButton->blockSignals(true);
2439             textAlpha->blockSignals(true);
2440             buttonAlignLeft->blockSignals(true);
2441             buttonAlignRight->blockSignals(true);
2442             buttonAlignNone->blockSignals(true);
2443             buttonAlignCenter->blockSignals(true);
2444
2445             QFont font = i->font();
2446             font_family->setCurrentFont(font);
2447             font_size->setValue(font.pixelSize());
2448             m_scene->slotUpdateFontSize(font.pixelSize());
2449             buttonItalic->setChecked(font.italic());
2450             buttonUnder->setChecked(font.underline());
2451             setFontBoxWeight(font.weight());
2452
2453             QTextCursor cursor(i->document());
2454             cursor.select(QTextCursor::Document);
2455             QColor color = cursor.charFormat().foreground().color();
2456             textAlpha->setValue(color.alpha());
2457             color.setAlpha(255);
2458             fontColorButton->setColor(color);
2459
2460             if(!i->data(101).isNull()) {
2461                 textOutline->blockSignals(true);
2462                 textOutline->setValue(i->data(101).toDouble() * 10);
2463                 textOutline->blockSignals(false);
2464             }
2465             if(!i->data(102).isNull()) {
2466                 textOutlineColor->blockSignals(true);
2467                 textOutlineAlpha->blockSignals(true);
2468                 color = QColor(i->data(102).toString());
2469                 textOutlineAlpha->setValue(color.alpha());
2470                 color.setAlpha(255);
2471                 textOutlineColor->setColor(color);
2472                 textOutlineColor->blockSignals(false);
2473                 textOutlineAlpha->blockSignals(false);
2474             }
2475             QTextCursor cur = i->textCursor();
2476             QTextBlockFormat format = cur.blockFormat();
2477             if(i->textWidth() == -1) buttonAlignNone->setChecked(true);
2478             else if(format.alignment() == Qt::AlignHCenter) buttonAlignCenter->setChecked(true);
2479             else if(format.alignment() == Qt::AlignRight) buttonAlignRight->setChecked(true);
2480             else if(format.alignment() == Qt::AlignLeft) buttonAlignLeft->setChecked(true);
2481
2482             font_size->blockSignals(false);
2483             font_family->blockSignals(false);
2484             font_weight_box->blockSignals(false);
2485             buttonItalic->blockSignals(false);
2486             buttonUnder->blockSignals(false);
2487             fontColorButton->blockSignals(false);
2488             textAlpha->blockSignals(false);
2489             buttonAlignLeft->blockSignals(false);
2490             buttonAlignRight->blockSignals(false);
2491             buttonAlignNone->blockSignals(false);
2492             buttonAlignCenter->blockSignals(false);
2493
2494             // mbt 1607: Select text if the text item is an unchanged template item.
2495             if(i->property("isTemplate").isValid()) {
2496                 cur.setPosition(0, QTextCursor::MoveAnchor);
2497                 cur.select(QTextCursor::Document);
2498                 i->setTextCursor(cur);
2499                 // Make text editable now.
2500                 i->grabKeyboard();
2501                 i->setTextInteractionFlags(Qt::TextEditorInteraction);
2502             }
2503
2504             updateAxisButtons(i);
2505             updateCoordinates(i);
2506             updateDimension(i);
2507             enableToolbars(TITLE_TEXT);
2508
2509         } else if((referenceItem)->type() == RECTITEM) {
2510             showToolbars(TITLE_RECTANGLE);
2511             settingUp = true;
2512             QGraphicsRectItem *rec = static_cast <QGraphicsRectItem *>(referenceItem);
2513             if(rec == m_startViewport || rec == m_endViewport) {
2514                 /*toolBox->setCurrentIndex(3);
2515                 toolBox->widget(0)->setEnabled(false);
2516                 toolBox->widget(1)->setEnabled(false);*/
2517                 enableToolbars(TITLE_SELECT);
2518             } else {
2519                 /*toolBox->widget(0)->setEnabled(true);
2520                 toolBox->widget(1)->setEnabled(true);
2521                 toolBox->setCurrentIndex(0);*/
2522                 //toolBox->setItemEnabled(3, true);
2523                 rectFAlpha->setValue(rec->pen().color().alpha());
2524                 rectBAlpha->setValue(rec->brush().color().alpha());
2525                 //kDebug() << rec->brush().color().alpha();
2526                 QColor fcol = rec->pen().color();
2527                 QColor bcol = rec->brush().color();
2528                 //fcol.setAlpha(255);
2529                 //bcol.setAlpha(255);
2530                 rectFColor->setColor(fcol);
2531                 rectBColor->setColor(bcol);
2532                 settingUp = false;
2533                 rectLineWidth->setValue(rec->pen().width());
2534                 enableToolbars(TITLE_RECTANGLE);
2535             }
2536
2537             updateAxisButtons(referenceItem);
2538             updateCoordinates(rec);
2539             updateDimension(rec);
2540
2541         } else if(referenceItem->type() == IMAGEITEM) {
2542             showToolbars(TITLE_IMAGE);
2543
2544             updateCoordinates(referenceItem);
2545             updateDimension(referenceItem);
2546
2547             enableToolbars(TITLE_IMAGE);
2548
2549         } else {
2550             //toolBox->setCurrentIndex(0);
2551             showToolbars(TITLE_SELECT);
2552             enableToolbars(TITLE_SELECT);
2553             frame_properties->setEnabled(false);
2554         }
2555         zValue->setValue((int)referenceItem->zValue());
2556         if(!referenceItem->data(ZOOMFACTOR).isNull()) itemzoom->setValue(referenceItem->data(ZOOMFACTOR).toInt());
2557         else itemzoom->setValue((int)(m_transformations.value(referenceItem).scalex * 100.0 + 0.5));
2558         itemrotatex->setValue((int)(m_transformations.value(referenceItem).rotatex));
2559         itemrotatey->setValue((int)(m_transformations.value(referenceItem).rotatey));
2560         itemrotatez->setValue((int)(m_transformations.value(referenceItem).rotatez));
2561     }
2562
2563     
2564     effect_list->blockSignals(blockEff);
2565     itemrotatex->blockSignals(blockRX);
2566     itemrotatey->blockSignals(blockRY);
2567     itemrotatez->blockSignals(blockRZ);
2568     itemzoom->blockSignals(blockZoom);
2569     origin_x_left->blockSignals(blockOX);
2570     origin_y_top->blockSignals(blockOY);
2571     value_x->blockSignals(blockX);
2572     value_y->blockSignals(blockY);
2573     value_w->blockSignals(blockW);
2574     value_h->blockSignals(blockH);
2575 }