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