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