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