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