]> git.sesse.net Git - kdenlive/blob - src/titlewidget.cpp
const'ref.
[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 void TitleWidget::templateIndexChanged(int index)
643 {
644     QString item = templateBox->itemData(index).toString();
645     if (!item.isEmpty()) {
646         if (lastDocumentHash != QCryptographicHash::hash(xml().toString().toAscii(), QCryptographicHash::Md5).toHex()) {
647             if (KMessageBox::questionYesNo(this, i18n("Do you really want to load a new template? Changes in this title will be lost!")) == KMessageBox::No) return;
648         }
649         loadTitle(item);
650
651         // mbt 1607: Add property to distinguish between unchanged template titles and user titles.
652         // Text of unchanged template titles should be selected when clicked.
653         QList<QGraphicsItem *> list = graphicsView->scene()->items();
654         foreach(QGraphicsItem * qgItem, list) {
655             if (qgItem->type() == TEXTITEM) {
656                 QGraphicsTextItem *i;
657                 i = static_cast<QGraphicsTextItem *>(qgItem);
658                 i->setProperty("isTemplate", "true");
659                 i->setProperty("templateText", i->toHtml());
660             }
661
662         }
663         lastDocumentHash = QCryptographicHash::hash(xml().toString().toAscii(), QCryptographicHash::Md5).toHex();
664     }
665 }
666 //virtual
667 void TitleWidget::resizeEvent(QResizeEvent * /*event*/)
668 {
669     //slotAdjustZoom();
670 }
671 //virtual
672 void TitleWidget::keyPressEvent(QKeyEvent *e){
673     if(e->key()!=Qt::Key_Escape && e->key()!=Qt::Key_Return && e->key()!=Qt::Key_Enter) QDialog::keyPressEvent(e);
674 }
675 void TitleWidget::slotTextTool()
676 {
677     m_scene->setTool(TITLE_TEXT);
678     showToolbars(TITLE_TEXT);
679     checkButton(TITLE_TEXT);
680 }
681
682 void TitleWidget::slotRectTool()
683 {
684     m_scene->setTool(TITLE_RECTANGLE);
685     showToolbars(TITLE_RECTANGLE);
686     checkButton(TITLE_RECTANGLE);
687
688     // Disable dragging mode, would make dragging a rect impossible otherwise ;)
689     graphicsView->setDragMode(QGraphicsView::NoDrag);
690 }
691
692 void TitleWidget::slotSelectTool()
693 {
694     m_scene->setTool(TITLE_SELECT);
695
696     // Enable rubberband selecting mode.
697     graphicsView->setDragMode(QGraphicsView::RubberBandDrag);
698
699     // Find out which toolbars need to be shown, depending on selected item
700     TITLETOOL t = TITLE_SELECT;
701     QList<QGraphicsItem *> l = graphicsView->scene()->selectedItems();
702     if (l.size() > 0) {
703         switch (l.at(0)->type()) {
704         case TEXTITEM:
705             t = TITLE_TEXT;
706             break;
707         case RECTITEM:
708             t = TITLE_RECTANGLE;
709             break;
710         case IMAGEITEM:
711             t = TITLE_IMAGE;
712             break;
713         }
714     }
715
716     enableToolbars(t);
717     if (t == TITLE_RECTANGLE && (l.at(0) == m_endViewport || l.at(0) == m_startViewport)) {
718         //graphicsView->centerOn(l.at(0));
719         t = TITLE_SELECT;
720     }
721     showToolbars(t);
722
723     if (l.size() > 0) {
724         updateCoordinates(l.at(0));
725         updateDimension(l.at(0));
726         updateRotZoom(l.at(0));
727     }
728
729     checkButton(TITLE_SELECT);
730 }
731
732 void TitleWidget::slotImageTool()
733 {
734     // TODO: find a way to get a list of all supported image types...
735     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";
736     KUrl url = KFileDialog::getOpenUrl(KUrl(), allExtensions, this, i18n("Load Image")); //"*.svg *.png *.jpg *.jpeg *.gif *.raw"
737     if (!url.isEmpty()) {
738         if (url.path().endsWith(".svg")) {
739             QGraphicsSvgItem *svg = new QGraphicsSvgItem(url.toLocalFile());
740             svg->setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable);
741             svg->setZValue(m_count++);
742             svg->setData(Qt::UserRole, url.path());
743             graphicsView->scene()->addItem(svg);
744             prepareTools(svg);
745         } else {
746             QPixmap pix(url.path());
747             QGraphicsPixmapItem *image = new QGraphicsPixmapItem(pix);
748             image->setShapeMode(QGraphicsPixmapItem::BoundingRectShape);
749             image->setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable);
750             image->setData(Qt::UserRole, url.path());
751             image->setZValue(m_count++);
752             graphicsView->scene()->addItem(image);
753             prepareTools(image);
754         }
755     }
756     m_scene->setTool(TITLE_SELECT);
757     showToolbars(TITLE_SELECT);
758     checkButton(TITLE_SELECT);
759 }
760
761 void TitleWidget::showToolbars(TITLETOOL toolType)
762 {
763     switch (toolType) {
764     case TITLE_SELECT:
765         toolbar_stack->setCurrentIndex(0);
766         break;
767     case TITLE_IMAGE:
768         toolbar_stack->setCurrentIndex(3);
769         break;
770     case TITLE_RECTANGLE:
771         toolbar_stack->setCurrentIndex(1);
772         break;
773     case TITLE_TEXT:
774         toolbar_stack->setCurrentIndex(2);
775         break;
776     }
777 }
778
779 void TitleWidget::enableToolbars(TITLETOOL toolType)
780 {
781     // TITLETOOL is defined in graphicsscenerectmove.h
782     bool enable = false;
783     if (toolType == TITLE_RECTANGLE || toolType == TITLE_IMAGE) enable = true;
784     value_w->setEnabled(enable);
785     value_h->setEnabled(enable);
786 }
787
788 void TitleWidget::checkButton(TITLETOOL toolType)
789 {
790     bool bSelect = false;
791     bool bText = false;
792     bool bRect = false;
793     bool bImage = false;
794
795     switch (toolType) {
796     case TITLE_SELECT:
797         bSelect = true;
798         break;
799     case TITLE_TEXT:
800         bText = true;
801         break;
802     case TITLE_RECTANGLE:
803         bRect = true;
804         break;
805     case TITLE_IMAGE:
806         bImage = true;
807         break;
808     default:
809         break;
810     }
811
812     m_buttonCursor->setChecked(bSelect);
813     m_buttonText->setChecked(bText);
814     m_buttonRect->setChecked(bRect);
815     m_buttonImage->setChecked(bImage);
816 }
817
818 void TitleWidget::displayBackgroundFrame()
819 {
820     QRectF r = m_frameBorder->sceneBoundingRect();
821     if (!displayBg->isChecked()) {
822         QPixmap pattern(20, 20);
823         pattern.fill();
824         QColor bgcolor(210, 210, 210);
825         QPainter p(&pattern);
826         p.fillRect(QRect(0, 0, 10, 10), bgcolor);
827         p.fillRect(QRect(10, 10, 20, 20), bgcolor);
828         p.end();
829         QBrush br(pattern);
830         QPixmap bg((int) (r.width() / 2), (int) (r.height()/ 2));
831         QPainter p2(&bg);
832         p2.fillRect(bg.rect(), br);
833         p2.end();
834         m_frameImage->setPixmap(bg);
835     } else {
836         QImage img = m_render->extractFrame((int) m_render->seekPosition().frames(m_render->fps()), QString(), m_render->frameRenderWidth() / 2, m_render->renderHeight() / 2);
837         m_frameImage->setPixmap(QPixmap::fromImage(img.scaled(r.width() / 2, r.height() / 2)));
838     }
839 }
840
841 void TitleWidget::initAnimation()
842 {
843     align_box->setEnabled(false);
844     QPen startpen(Qt::DotLine);
845     QPen endpen(Qt::DashDotLine);
846     startpen.setColor(QColor(100, 200, 100, 140));
847     endpen.setColor(QColor(200, 100, 100, 140));
848
849     m_startViewport->setPen(startpen);
850     m_endViewport->setPen(endpen);
851
852     m_startViewport->setZValue(-1000);
853     m_endViewport->setZValue(-1000);
854
855     m_startViewport->setFlags(0);
856     m_endViewport->setFlags(0);
857
858     graphicsView->scene()->addItem(m_startViewport);
859     graphicsView->scene()->addItem(m_endViewport);
860
861     connect(keep_aspect, SIGNAL(toggled(bool)), this, SLOT(slotKeepAspect(bool)));
862     connect(resize50, SIGNAL(clicked()), this, SLOT(slotResize50()));
863     connect(resize100, SIGNAL(clicked()), this, SLOT(slotResize100()));
864     connect(resize200, SIGNAL(clicked()), this, SLOT(slotResize200()));
865 }
866
867 void TitleWidget::slotUpdateZoom(int pos)
868 {
869     zoom_spin->setValue(pos);
870     zoom_slider->setValue(pos);
871     m_scene->setZoom((double) pos / 100);
872 }
873
874 void TitleWidget::slotZoom(bool up)
875 {
876     int pos = zoom_slider->value();
877     if (up) pos++;
878     else pos--;
879     zoom_slider->setValue(pos);
880 }
881
882 void TitleWidget::slotAdjustZoom()
883 {
884     /*double scalex = graphicsView->width() / (double)(m_frameWidth * 1.2);
885     double scaley = graphicsView->height() / (double)(m_frameHeight * 1.2);
886     if (scalex > scaley) scalex = scaley;
887     int zoompos = (int)(scalex * 7 + 0.5);*/
888     graphicsView->fitInView(m_frameBorder, Qt::KeepAspectRatio);
889     int zoompos = graphicsView->matrix().m11() * 100;
890     zoom_slider->setValue(zoompos);
891     graphicsView->centerOn(m_frameBorder);
892 }
893
894 void TitleWidget::slotZoomOneToOne()
895 {
896     zoom_slider->setValue(100);
897     graphicsView->centerOn(m_frameBorder);
898 }
899
900 void TitleWidget::slotNewRect(QGraphicsRectItem * rect)
901 {
902     updateAxisButtons(rect); // back to default
903
904     QColor f = rectFColor->color();
905 #if not KDE_IS_VERSION(4,5,0)
906     f.setAlpha(rectFAlpha->value());
907 #endif
908     QPen penf(f);
909     penf.setWidth(rectLineWidth->value());
910     penf.setJoinStyle(Qt::RoundJoin);
911     rect->setPen(penf);
912     QColor b = rectBColor->color();
913 #if not KDE_IS_VERSION(4,5,0)
914     b.setAlpha(rectBAlpha->value());
915 #endif
916     rect->setBrush(QBrush(b));
917     rect->setZValue(m_count++);
918     rect->setData(ZOOMFACTOR, 100);
919     prepareTools(rect);
920     //setCurrentItem(rect);
921     //graphicsView->setFocus();
922 }
923
924 void TitleWidget::slotNewText(QGraphicsTextItem *tt)
925 {
926     updateAxisButtons(tt); // back to default
927
928     QFont font = font_family->currentFont();
929     font.setPixelSize(font_size->value());
930     // mbd: issue 551:
931     font.setWeight(font_weight_box->itemData(font_weight_box->currentIndex()).toInt());
932     font.setItalic(buttonItalic->isChecked());
933     font.setUnderline(buttonUnder->isChecked());
934
935     tt->setFont(font);
936     QColor color = fontColorButton->color();
937     QColor outlineColor = textOutlineColor->color();
938 #if not KDE_IS_VERSION(4,5,0)    
939     color.setAlpha(textAlpha->value());
940     outlineColor.setAlpha(textOutlineAlpha->value());
941 #endif
942     tt->setDefaultTextColor(color);
943
944     QTextCursor cur(tt->document());
945     cur.select(QTextCursor::Document);
946     QTextBlockFormat format = cur.blockFormat();
947     QTextCharFormat cformat = cur.charFormat();
948     double outlineWidth = textOutline->value() / 10.0;
949
950     tt->setData(101, outlineWidth);
951     tt->setData(102, outlineColor);
952     if (outlineWidth > 0.0) cformat.setTextOutline(QPen(outlineColor, outlineWidth));
953
954     cformat.setForeground(QBrush(color));
955     cur.setCharFormat(cformat);
956     cur.setBlockFormat(format);
957     tt->setTextCursor(cur);
958     tt->setZValue(m_count++);
959     setCurrentItem(tt);
960     prepareTools(tt);
961 }
962
963 void TitleWidget::setFontBoxWeight(int weight)
964 {
965     int index = font_weight_box->findData(weight);
966     if (index < 0) {
967         index = font_weight_box->findData(QFont::Normal);
968     }
969     font_weight_box->setCurrentIndex(index);
970 }
971
972 void TitleWidget::setCurrentItem(QGraphicsItem *item)
973 {
974     m_scene->setSelectedItem(item);
975 }
976
977 void TitleWidget::zIndexChanged(int v)
978 {
979     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
980     for (int i = 0; i < l.size(); i++) {
981         l[i]->setZValue(v);
982     }
983 }
984
985 void TitleWidget::selectionChanged()
986 {
987     if (m_scene->tool() != TITLE_SELECT) return;
988
989     std::cout << "Number of selected items: " << graphicsView->scene()->selectedItems().length() << "\n";
990
991     QList<QGraphicsItem *> l;
992
993     // mbt 1607: One text item might have grabbed the keyboard.
994     // Ungrab it for all items that are not selected, otherwise
995     // text input would only work for the text item that grabbed
996     // the keyboard last.
997     l = graphicsView->scene()->items();
998     foreach(QGraphicsItem * item, l) {
999         if (item->type() == TEXTITEM && !item->isSelected()) {
1000             QGraphicsTextItem *i = static_cast<QGraphicsTextItem *>(item);
1001             i->ungrabKeyboard();
1002         }
1003     }
1004
1005     l = graphicsView->scene()->selectedItems();
1006
1007     if (l.size() > 0) {
1008         buttonUnselectAll->setEnabled(true);
1009         // Enable all z index buttons if items selected.
1010         // We can selectively disable them later.
1011         zUp->setEnabled(true);
1012         zDown->setEnabled(true);
1013         zTop->setEnabled(true);
1014         zBottom->setEnabled(true);
1015     } else {
1016         buttonUnselectAll->setEnabled(false);
1017     }
1018     if (l.size() >= 2) {
1019         buttonSelectText->setEnabled(true);
1020         buttonSelectRects->setEnabled(true);
1021         buttonSelectImages->setEnabled(true);
1022     } else {
1023         buttonSelectText->setEnabled(false);
1024         buttonSelectRects->setEnabled(false);
1025         buttonSelectImages->setEnabled(false);
1026     }
1027
1028     if (l.size() == 0) {
1029         prepareTools(NULL);
1030     } else if (l.size() == 1) {
1031         prepareTools(l.at(0));
1032     } else {
1033         /*
1034         For multiple selected objects we need to decide which tools to show.
1035         */
1036         int firstType = l.at(0)->type();
1037         bool allEqual = true;
1038         for (int i = 0; i < l.size(); i++) {
1039             if (l.at(i)->type() != firstType) {
1040                 allEqual = false;
1041                 break;
1042             }
1043         }
1044         std::cout << "All equal? " << allEqual << ".\n";
1045         if (allEqual) {
1046             prepareTools(l.at(0));
1047         } else {
1048             // Get the default toolset, but enable the property frame (x,y,w,h)
1049             prepareTools(NULL);
1050             frame_properties->setEnabled(true);
1051
1052             // Enable x/y/w/h if it makes sense.
1053             value_x->setEnabled(true);
1054             value_y->setEnabled(true);
1055             bool containsTextitem = false;
1056             for (int i = 0; i < l.size(); i++) {
1057                 if (l.at(i)->type() == TEXTITEM) {
1058                     containsTextitem = true;
1059                     break;
1060                 }
1061             }
1062             if (!containsTextitem) {
1063                 value_w->setEnabled(true);
1064                 value_h->setEnabled(true);
1065             }
1066         }
1067
1068         // Disable z index buttons if they don't make sense for the current selection
1069         int firstZindex = l.at(0)->zValue();
1070         allEqual = true;
1071         for (int i = 0; i < l.size(); i++) {
1072             if (l[i]->zValue() != firstZindex) {
1073                 allEqual = false;
1074                 break;
1075             }
1076         }
1077         if (!allEqual) {
1078             zUp->setEnabled(false);
1079             zDown->setEnabled(false);
1080         }
1081
1082
1083     }
1084
1085 }
1086
1087 void TitleWidget::slotValueChanged(int type)
1088 {
1089     /*
1090     type tells us which QSpinBox value has changed.
1091     */
1092
1093     QList<QGraphicsItem *> l = graphicsView->scene()->selectedItems();
1094     std::cout << l.size() << " items to be resized\n";
1095
1096     // Get the updated value here already to do less coding afterwards
1097     int val = 0;
1098     switch (type) {
1099     case ValueWidth:
1100         val = value_w->value();
1101         break;
1102     case ValueHeight:
1103         val = value_h->value();
1104         break;
1105     case ValueX:
1106         val = value_x->value();
1107         break;
1108     case ValueY:
1109         val = value_y->value();
1110         break;
1111     }
1112
1113     for (int k = 0; k < l.size(); k++) {
1114         std::cout << "Type of item " << k << ": " << l.at(k)->type() << "\n";
1115
1116         if (l.at(k)->type() == TEXTITEM) {
1117             // Just update the position. We don't allow setting width/height for text items yet.
1118             switch (type) {
1119             case ValueX:
1120                 updatePosition(l.at(k), val, l.at(k)->pos().y());
1121                 break;
1122             case ValueY:
1123                 updatePosition(l.at(k), l.at(k)->pos().x(), val);
1124                 break;
1125             }
1126
1127         } else if (l.at(k)->type() == RECTITEM) {
1128             QGraphicsRectItem *rec = static_cast <QGraphicsRectItem *>(l.at(k));
1129             switch (type) {
1130             case ValueX:
1131                 updatePosition(l.at(k), val, l.at(k)->pos().y());
1132                 break;
1133             case ValueY:
1134                 updatePosition(l.at(k), l.at(k)->pos().x(), val);
1135                 break;
1136             case ValueWidth:
1137                 rec->setRect(QRect(0, 0, val, rec->rect().height()));
1138                 break;
1139             case ValueHeight:
1140                 rec->setRect(QRect(0, 0, rec->rect().width(), val));
1141                 break;
1142             }
1143
1144         } else if (l.at(k)->type() == IMAGEITEM) {
1145
1146
1147             if (type == ValueX) {
1148                 updatePosition(l.at(k), val, l.at(k)->pos().y());
1149
1150             } else if (type == ValueY) {
1151                 updatePosition(l.at(k), l.at(k)->pos().x(), val);
1152
1153             } else {
1154                 // Width/height has changed. This is more complex.
1155
1156                 QGraphicsItem *i = l.at(k);
1157                 Transform t = m_transformations.value(i);
1158
1159                 // Ratio width:height
1160                 double phi = (double) i->boundingRect().width() / i->boundingRect().height();
1161                 // TODO: proper calculation for rotation around 3 axes
1162                 double alpha = (double) t.rotatez / 180.0 * M_PI;
1163
1164                 // New length
1165                 double length = val;
1166
1167                 // Scaling factor
1168                 double scale = 1;
1169
1170                 // We want to keep the aspect ratio of the image as the user does not yet have the possibility
1171                 // to restore the original ratio. You rarely want to change it anyway.
1172                 switch (type) {
1173                 case ValueWidth:
1174                     // Add 0.5 because otherwise incrementing by 1 might have no effect
1175                     length = val / (cos(alpha) + 1 / phi * sin(alpha)) + 0.5;
1176                     scale = length / i->boundingRect().width();
1177                     break;
1178                 case ValueHeight:
1179                     length = val / (phi * sin(alpha) + cos(alpha)) + 0.5;
1180                     scale = length / i->boundingRect().height();
1181                     break;
1182                 }
1183
1184                 t.scalex = scale;
1185                 t.scaley = scale;
1186                 QTransform qtrans;
1187                 qtrans.scale(scale, scale);
1188                 qtrans.rotate(t.rotatex, Qt::XAxis);
1189                 qtrans.rotate(t.rotatey, Qt::YAxis);
1190                 qtrans.rotate(t.rotatez, Qt::ZAxis);
1191                 i->setTransform(qtrans);
1192                 std::cout << "scale is: " << scale << "\n";
1193                 std::cout << i->boundingRect().width() << ": new width\n";
1194                 m_transformations[i] = t;
1195
1196                 if (l.size() == 1) {
1197                     // Only update the w/h values if the selection contains just one item.
1198                     // Otherwise, what should we do? ;)
1199                     // (Use the values of the first item? Of the second? Of the x-th?)
1200                     updateDimension(i);
1201                     // Update rotation/zoom values.
1202                     // These values are not yet able to handle multiple items!
1203                     updateRotZoom(i);
1204                 }
1205             }
1206
1207         }
1208     }
1209
1210
1211 }
1212
1213 void TitleWidget::updateDimension(QGraphicsItem *i)
1214 {
1215     bool wBlocked = value_w->signalsBlocked();
1216     bool hBlocked = value_h->signalsBlocked();
1217     bool zBlocked = zValue->signalsBlocked();
1218     value_w->blockSignals(true);
1219     value_h->blockSignals(true);
1220     zValue->blockSignals(true);
1221
1222     zValue->setValue((int) i->zValue());
1223     if (i->type() == IMAGEITEM) {
1224         // Get multipliers for rotation/scaling
1225
1226         /*Transform t = m_transformations.value(i);
1227         QRectF r = i->boundingRect();
1228         int width = (int) ( abs(r.width()*t.scalex * cos(t.rotate/180.0*M_PI))
1229                     + abs(r.height()*t.scaley * sin(t.rotate/180.0*M_PI)) );
1230         int height = (int) ( abs(r.height()*t.scaley * cos(t.rotate/180*M_PI))
1231                     + abs(r.width()*t.scalex * sin(t.rotate/180*M_PI)) );*/
1232
1233         value_w->setValue(i->sceneBoundingRect().width());
1234         value_h->setValue(i->sceneBoundingRect().height());
1235     } else if (i->type() == RECTITEM) {
1236         QGraphicsRectItem *r = static_cast <QGraphicsRectItem *>(i);
1237         std::cout << "Rect width is: " << r->rect().width() << ", was: " << value_w->value() << "\n";
1238         value_w->setValue((int) r->rect().width());
1239         value_h->setValue((int) r->rect().height());
1240     } else if (i->type() == TEXTITEM) {
1241         QGraphicsTextItem *t = static_cast <QGraphicsTextItem *>(i);
1242         value_w->setValue((int) t->boundingRect().width());
1243         value_h->setValue((int) t->boundingRect().height());
1244     }
1245
1246     zValue->blockSignals(zBlocked);
1247     value_w->blockSignals(wBlocked);
1248     value_h->blockSignals(hBlocked);
1249 }
1250
1251 void TitleWidget::updateCoordinates(QGraphicsItem *i)
1252 {
1253     // Block signals emitted by this method
1254     value_x->blockSignals(true);
1255     value_y->blockSignals(true);
1256
1257     if (i->type() == TEXTITEM) {
1258
1259         QGraphicsTextItem *rec = static_cast <QGraphicsTextItem *>(i);
1260
1261         // Set the correct x coordinate value
1262         if (origin_x_left->isChecked()) {
1263             // Origin (0 point) is at m_frameWidth, coordinate axis is inverted
1264             value_x->setValue((int)(m_frameWidth - rec->pos().x() - rec->boundingRect().width()));
1265         } else {
1266             // Origin is at 0 (default)
1267             value_x->setValue((int) rec->pos().x());
1268         }
1269
1270         // Same for y
1271         if (origin_y_top->isChecked()) {
1272             value_y->setValue((int)(m_frameHeight - rec->pos().y() - rec->boundingRect().height()));
1273         } else {
1274             value_y->setValue((int) rec->pos().y());
1275         }
1276
1277     } else if (i->type() == RECTITEM) {
1278
1279         QGraphicsRectItem *rec = static_cast <QGraphicsRectItem *>(i);
1280
1281         if (origin_x_left->isChecked()) {
1282             // Origin (0 point) is at m_frameWidth
1283             value_x->setValue((int)(m_frameWidth - rec->pos().x() - rec->rect().width()));
1284         } else {
1285             // Origin is at 0 (default)
1286             value_x->setValue((int) rec->pos().x());
1287         }
1288
1289         if (origin_y_top->isChecked()) {
1290             value_y->setValue((int)(m_frameHeight - rec->pos().y() - rec->rect().height()));
1291         } else {
1292             value_y->setValue((int) rec->pos().y());
1293         }
1294
1295     } else if (i->type() == IMAGEITEM) {
1296
1297         if (origin_x_left->isChecked()) {
1298             value_x->setValue((int)(m_frameWidth - i->pos().x() - i->sceneBoundingRect().width()));
1299         } else {
1300             value_x->setValue((int) i->pos().x());
1301         }
1302
1303         if (origin_y_top->isChecked()) {
1304             value_y->setValue((int)(m_frameHeight - i->pos().y() - i->sceneBoundingRect().height()));
1305         } else {
1306             value_y->setValue((int) i->pos().y());
1307         }
1308
1309     }
1310
1311     // Stop blocking signals now
1312     value_x->blockSignals(false);
1313     value_y->blockSignals(false);
1314 }
1315
1316 void TitleWidget::updateRotZoom(QGraphicsItem *i)
1317 {
1318     itemzoom->blockSignals(true);
1319     itemrotatex->blockSignals(true);
1320     itemrotatey->blockSignals(true);
1321     itemrotatez->blockSignals(true);
1322
1323     Transform t = m_transformations.value(i);
1324
1325     if (!i->data(ZOOMFACTOR).isNull()) itemzoom->setValue(i->data(ZOOMFACTOR).toInt());
1326     else itemzoom->setValue((int)(t.scalex * 100.0 + 0.5));
1327
1328     itemrotatex->setValue((int)(t.rotatex));
1329     itemrotatey->setValue((int)(t.rotatey));
1330     itemrotatez->setValue((int)(t.rotatez));
1331
1332     itemzoom->blockSignals(false);
1333     itemrotatex->blockSignals(false);
1334     itemrotatey->blockSignals(false);
1335     itemrotatez->blockSignals(false);
1336 }
1337
1338 void TitleWidget::updatePosition(QGraphicsItem *i)
1339 {
1340     updatePosition(i, value_x->value(), value_y->value());
1341 }
1342
1343 void TitleWidget::updatePosition(QGraphicsItem *i, int x, int y)
1344 {
1345     if (i->type() == TEXTITEM) {
1346         QGraphicsTextItem *rec = static_cast <QGraphicsTextItem *>(i);
1347
1348         int posX;
1349         if (origin_x_left->isChecked()) {
1350             /*
1351              * Origin of the X axis is at m_frameWidth, and distance from right
1352              * border of the item to the right border of the frame is taken. See
1353              * comment to slotOriginXClicked().
1354              */
1355             posX = m_frameWidth - x - rec->boundingRect().width();
1356         } else {
1357             posX = x;
1358         }
1359
1360         int posY;
1361         if (origin_y_top->isChecked()) {
1362             /* Same for y axis */
1363             posY = m_frameHeight - y - rec->boundingRect().height();
1364         } else {
1365             posY = y;
1366         }
1367
1368         rec->setPos(posX, posY);
1369
1370     } else if (i->type() == RECTITEM) {
1371
1372         QGraphicsRectItem *rec = static_cast <QGraphicsRectItem *>(i);
1373
1374         int posX;
1375         if (origin_x_left->isChecked()) {
1376             posX = m_frameWidth - x - rec->rect().width();
1377         } else {
1378             posX = x;
1379         }
1380
1381         int posY;
1382         if (origin_y_top->isChecked()) {
1383             posY = m_frameHeight - y - rec->rect().height();
1384         } else {
1385             posY = y;
1386         }
1387
1388         rec->setPos(posX, posY);
1389
1390     } else if (i->type() == IMAGEITEM) {
1391         int posX;
1392         if (origin_x_left->isChecked()) {
1393             // Use the sceneBoundingRect because this also regards transformations like zoom
1394             posX = m_frameWidth - x - i->sceneBoundingRect().width();
1395         } else {
1396             posX = x;
1397         }
1398
1399         int posY;
1400         if (origin_y_top->isChecked()) {
1401             posY = m_frameHeight - y - i->sceneBoundingRect().height();
1402         } else {
1403             posY = y;
1404         }
1405
1406         i->setPos(posX, posY);
1407
1408     }
1409
1410 }
1411
1412 void TitleWidget::updateTextOriginX()
1413 {
1414     if (origin_x_left->isChecked()) {
1415         origin_x_left->setText(i18n("\u2212X"));
1416     } else {
1417         origin_x_left->setText(i18n("+X"));
1418     }
1419 }
1420
1421 void TitleWidget::slotOriginXClicked()
1422 {
1423     // Update the text displayed on the button.
1424     updateTextOriginX();
1425
1426     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1427     if (l.size() >= 1) {
1428         updateCoordinates(l.at(0));
1429
1430         // Remember x axis setting
1431         l.at(0)->setData(TitleDocument::OriginXLeft, origin_x_left->isChecked() ?
1432                          TitleDocument::AxisInverted : TitleDocument::AxisDefault);
1433     }
1434     graphicsView->setFocus();
1435 }
1436
1437 void TitleWidget::updateTextOriginY()
1438 {
1439     if (origin_y_top->isChecked()) {
1440         origin_y_top->setText(i18n("\u2212Y"));
1441     } else {
1442         origin_y_top->setText(i18n("+Y"));
1443     }
1444 }
1445
1446 void TitleWidget::slotOriginYClicked()
1447 {
1448     // Update the text displayed on the button.
1449     updateTextOriginY();
1450
1451     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1452     if (l.size() >= 1) {
1453         updateCoordinates(l.at(0));
1454
1455         l.at(0)->setData(TitleDocument::OriginYTop, origin_y_top->isChecked() ?
1456                          TitleDocument::AxisInverted : TitleDocument::AxisDefault);
1457
1458     }
1459     graphicsView->setFocus();
1460 }
1461
1462 void TitleWidget::updateAxisButtons(QGraphicsItem *i)
1463 {
1464     int xAxis = i->data(TitleDocument::OriginXLeft).toInt();
1465     int yAxis = i->data(TitleDocument::OriginYTop).toInt();
1466     origin_x_left->blockSignals(true);
1467     origin_y_top->blockSignals(true);
1468
1469     if (xAxis == TitleDocument::AxisInverted) {
1470         origin_x_left->setChecked(true);
1471     } else {
1472         origin_x_left->setChecked(false);
1473     }
1474     updateTextOriginX();
1475
1476     if (yAxis == TitleDocument::AxisInverted) {
1477         origin_y_top->setChecked(true);
1478     } else {
1479         origin_y_top->setChecked(false);
1480     }
1481     updateTextOriginY();
1482
1483     origin_x_left->blockSignals(false);
1484     origin_y_top->blockSignals(false);
1485 }
1486
1487 void TitleWidget::slotChangeBackground()
1488 {
1489     QColor color = backgroundColor->color();
1490     m_scene->setBackgroundBrush(QBrush(color));
1491     color.setAlpha(backgroundAlpha->value());
1492     m_frameBorder->setBrush(QBrush(color));
1493 }
1494
1495 void TitleWidget::slotChanged()
1496 {
1497     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1498     if (l.size() >= 1 && l.at(0)->type() == TEXTITEM) {
1499         textChanged(static_cast <QGraphicsTextItem *>(l.at(0)));
1500     }
1501 }
1502
1503 void TitleWidget::textChanged(QGraphicsTextItem *i)
1504 {
1505     /*
1506      * If the user has set origin_x_left (the same for y), we need to look
1507      * whether a text element has been selected. If yes, we need to ensure that
1508      * the right border of the text field remains fixed also when some text has
1509      * been entered.
1510      *
1511      * This is also known as right-justified, with the difference that it is not
1512      * valid for text but for its boundingRect. Text may still be
1513      * left-justified.
1514      */
1515     updateDimension(i);
1516
1517     if (origin_x_left->isChecked() || origin_y_top->isChecked()) {
1518         if (!i->toPlainText().isEmpty())
1519             updatePosition(i);
1520         else {
1521             /*
1522              * Don't do anything if the string is empty. If the position were
1523              * updated here, a newly created text field would be set to the
1524              * position of the last selected text field.
1525              */
1526         }
1527     }
1528
1529     // mbt 1607: Template text has changed; don't auto-select content anymore.
1530     if (i->property("isTemplate").isValid()) {
1531         if (i->property("templateText").isValid()) {
1532             if (i->property("templateText") == i->toHtml()) {
1533                 // Unchanged, do nothing.
1534             } else {
1535                 i->setProperty("isTemplate", QVariant::Invalid);
1536                 i->setProperty("templateText", QVariant::Invalid);
1537             }
1538         }
1539     }
1540 }
1541
1542 void TitleWidget::slotInsertUnicode()
1543 {
1544     m_unicodeDialog->exec();
1545 }
1546
1547 void TitleWidget::slotInsertUnicodeString(const QString &text)
1548 {
1549     QList<QGraphicsItem *> l = graphicsView->scene()->selectedItems();
1550     if (l.size() > 0) {
1551         if (l.at(0)->type() == TEXTITEM) {
1552             QGraphicsTextItem *t = static_cast <QGraphicsTextItem *>(l.at(0));
1553             t->textCursor().insertText(text);
1554         }
1555     }
1556 }
1557
1558 void TitleWidget::slotUpdateText()
1559 {
1560     QFont font = font_family->currentFont();
1561     font.setPixelSize(font_size->value());
1562     font.setItalic(buttonItalic->isChecked());
1563     font.setUnderline(buttonUnder->isChecked());
1564     font.setWeight(font_weight_box->itemData(font_weight_box->currentIndex()).toInt());
1565     QColor color = fontColorButton->color();
1566     QColor outlineColor = textOutlineColor->color();
1567 #if not KDE_IS_VERSION(4,5,0)
1568     color.setAlpha(textAlpha->value());
1569     outlineColor.setAlpha(textOutlineAlpha->value());
1570 #endif
1571
1572     double outlineWidth = textOutline->value() / 10.0;
1573
1574     int i;
1575     for (i = 0; i < graphicsView->scene()->selectedItems().length(); i++) {
1576         QGraphicsTextItem* item = NULL;
1577         QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1578         if (l.at(i)->type() == TEXTITEM) {
1579             item = static_cast <QGraphicsTextItem *>(l.at(i));
1580         }
1581         if (!item) {
1582             // No text item, try next one.
1583             continue;
1584         }
1585
1586         // Set alignment of all text in the text item
1587         QTextCursor cur(item->document());
1588         cur.select(QTextCursor::Document);
1589         QTextBlockFormat format = cur.blockFormat();
1590         if (buttonAlignLeft->isChecked() || buttonAlignCenter->isChecked() || buttonAlignRight->isChecked()) {
1591             item->setTextWidth(item->boundingRect().width());
1592             if (buttonAlignCenter->isChecked()) format.setAlignment(Qt::AlignHCenter);
1593             else if (buttonAlignRight->isChecked()) format.setAlignment(Qt::AlignRight);
1594             else if (buttonAlignLeft->isChecked()) format.setAlignment(Qt::AlignLeft);
1595         } else {
1596             format.setAlignment(Qt::AlignLeft);
1597             item->setTextWidth(-1);
1598         }
1599
1600         // Set font properties
1601         item->setFont(font);
1602         QTextCharFormat cformat = cur.charFormat();
1603
1604         item->setData(101, outlineWidth);
1605         item->setData(102, outlineColor);
1606         if (outlineWidth > 0.0) cformat.setTextOutline(QPen(outlineColor, outlineWidth, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
1607
1608         cformat.setForeground(QBrush(color));
1609         cur.setCharFormat(cformat);
1610         cur.setBlockFormat(format);
1611 //  item->setTextCursor(cur);
1612         cur.clearSelection();
1613         item->setTextCursor(cur);
1614         item->setDefaultTextColor(color);
1615     }
1616 }
1617
1618 void TitleWidget::rectChanged()
1619 {
1620     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1621     int i;
1622     for (i = 0; i < l.length(); i++) {
1623         if (l.at(i)->type() == RECTITEM && !settingUp) {
1624             QGraphicsRectItem *rec = static_cast<QGraphicsRectItem *>(l.at(i));
1625             QColor f = rectFColor->color();
1626 #if not KDE_IS_VERSION(4,5,0)
1627             f.setAlpha(rectFAlpha->value());
1628 #endif
1629             QPen penf(f);
1630             penf.setWidth(rectLineWidth->value());
1631             penf.setJoinStyle(Qt::RoundJoin);
1632             rec->setPen(penf);
1633             QColor b = rectBColor->color();
1634 #if not KDE_IS_VERSION(4,5,0)
1635             b.setAlpha(rectBAlpha->value());
1636 #endif
1637             rec->setBrush(QBrush(b));
1638         }
1639     }
1640 }
1641
1642 void TitleWidget::itemScaled(int val)
1643 {
1644     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1645     if (l.size() == 1) {
1646         Transform x = m_transformations.value(l.at(0));
1647         x.scalex = (double)val / 100.0;
1648         x.scaley = (double)val / 100.0;
1649         QTransform qtrans;
1650         qtrans.scale(x.scalex, x.scaley);
1651         qtrans.rotate(x.rotatex, Qt::XAxis);
1652         qtrans.rotate(x.rotatey, Qt::YAxis);
1653         qtrans.rotate(x.rotatez, Qt::ZAxis);
1654         l[0]->setTransform(qtrans);
1655         l[0]->setData(ZOOMFACTOR, val);
1656         m_transformations[l.at(0)] = x;
1657         updateDimension(l.at(0));
1658     }
1659 }
1660
1661 void TitleWidget::itemRotateX(qreal val)
1662 {
1663     itemRotate(val, 0);
1664 }
1665
1666 void TitleWidget::itemRotateY(qreal val)
1667 {
1668     itemRotate(val, 1);
1669 }
1670
1671 void TitleWidget::itemRotateZ(qreal val)
1672 {
1673     itemRotate(val, 2);
1674 }
1675
1676 void TitleWidget::itemRotate(qreal val, int axis)
1677 {
1678     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1679     if (l.size() == 1) {
1680         Transform x = m_transformations[l.at(0)];
1681         switch (axis) {
1682         case 0:
1683             x.rotatex = val;
1684             break;
1685         case 1:
1686             x.rotatey = val;
1687             break;
1688         case 2:
1689             x.rotatez = val;
1690             break;
1691         }
1692
1693         l[0]->setData(ROTATEFACTOR, QList<QVariant>() << QVariant(x.rotatex) << QVariant(x.rotatey) << QVariant(x.rotatez));
1694
1695         QTransform qtrans;
1696         qtrans.scale(x.scalex, x.scaley);
1697         qtrans.rotate(x.rotatex, Qt::XAxis);
1698         qtrans.rotate(x.rotatey, Qt::YAxis);
1699         qtrans.rotate(x.rotatez, Qt::ZAxis);
1700         l[0]->setTransform(qtrans);
1701         m_transformations[l.at(0)] = x;
1702         if (l[0]->data(ZOOMFACTOR).isNull()) l[0]->setData(ZOOMFACTOR, 100);
1703         updateDimension(l.at(0));
1704     }
1705 }
1706
1707 void TitleWidget::itemHCenter()
1708 {
1709     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1710     if (l.size() == 1) {
1711         QGraphicsItem *item = l.at(0);
1712         QRectF br = item->sceneBoundingRect();
1713         int width = (int)br.width();
1714         int newPos = (int)((m_frameWidth - width) / 2);
1715         newPos += item->pos().x() - br.left(); // Check item transformation
1716         item->setPos(newPos, item->pos().y());
1717         updateCoordinates(item);
1718     }
1719 }
1720
1721 void TitleWidget::itemVCenter()
1722 {
1723     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1724     if (l.size() == 1) {
1725         QGraphicsItem *item = l.at(0);
1726         QRectF br = item->sceneBoundingRect();
1727         int height = (int)br.height();
1728         int newPos = (int)((m_frameHeight - height) / 2);
1729         newPos += item->pos().y() - br.top(); // Check item transformation
1730         item->setPos(item->pos().x(), newPos);
1731         updateCoordinates(item);
1732     }
1733 }
1734
1735 void TitleWidget::itemTop()
1736 {
1737     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1738     if (l.size() == 1) {
1739         QGraphicsItem *item = l.at(0);
1740         QRectF br = item->sceneBoundingRect();
1741         double diff;
1742         if (br.top() > 0) diff = -br.top();
1743         else diff = -br.bottom();
1744         item->moveBy(0, diff);
1745         updateCoordinates(item);
1746     }
1747 }
1748
1749 void TitleWidget::itemBottom()
1750 {
1751     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1752     if (l.size() == 1) {
1753         QGraphicsItem *item = l.at(0);
1754         QRectF br = item->sceneBoundingRect();
1755         double diff;
1756         if (br.bottom() > m_frameHeight) diff = m_frameHeight - br.top();
1757         else diff = m_frameHeight - br.bottom();
1758         item->moveBy(0, diff);
1759         updateCoordinates(item);
1760     }
1761 }
1762
1763 void TitleWidget::itemLeft()
1764 {
1765     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1766     if (l.size() == 1) {
1767         QGraphicsItem *item = l.at(0);
1768         QRectF br = item->sceneBoundingRect();
1769         double diff;
1770         if (br.left() > 0) diff = -br.left();
1771         else diff = -br.right();
1772         item->moveBy(diff, 0);
1773         updateCoordinates(item);
1774     }
1775 }
1776
1777 void TitleWidget::itemRight()
1778 {
1779     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1780     if (l.size() == 1) {
1781         QGraphicsItem *item = l.at(0);
1782         QRectF br = item->sceneBoundingRect();
1783         double diff;
1784         if (br.right() < m_frameWidth) diff = m_frameWidth - br.right();
1785         else diff = m_frameWidth - br.left();
1786         item->moveBy(diff, 0);
1787         updateCoordinates(item);
1788     }
1789 }
1790
1791 void TitleWidget::setupViewports()
1792 {
1793     //double aspect_ratio = 4.0 / 3.0;//read from project
1794     //better zoom centered, but render uses only the created rect, so no problem to change the zoom function
1795     /*QRectF sp(0, 0, startViewportSize->value() * m_frameWidth / 100.0 , startViewportSize->value()* m_frameHeight / 100.0);
1796     QRectF ep(0, 0, endViewportSize->value() * m_frameWidth / 100.0, endViewportSize->value() * m_frameHeight / 100.0);
1797     // use a polygon thiat uses 16:9 and 4:3 rects forpreview the size in all aspect ratios ?
1798     QPolygonF spoly(sp);
1799     QPolygonF epoly(ep);
1800     spoly.translate(startViewportX->value(), startViewportY->value());
1801     epoly.translate(endViewportX->value(), endViewportY->value());
1802     m_startViewport->setPolygon(spoly);
1803     m_endViewport->setPolygon(epoly);
1804     if (! insertingValues) {
1805         m_startViewport->setData(0, startViewportX->value());
1806         m_startViewport->setData(1, startViewportY->value());
1807         m_startViewport->setData(2, startViewportSize->value());
1808
1809         m_endViewport->setData(0, endViewportX->value());
1810         m_endViewport->setData(1, endViewportY->value());
1811         m_endViewport->setData(2, endViewportSize->value());
1812     }*/
1813 }
1814
1815 void TitleWidget::loadTitle(KUrl url)
1816 {
1817     if (url.isEmpty()) url = KFileDialog::getOpenUrl(KUrl(m_projectTitlePath), "application/x-kdenlivetitle", this, i18n("Load Title"));
1818     if (!url.isEmpty()) {
1819         QList<QGraphicsItem *> items = m_scene->items();
1820         for (int i = 0; i < items.size(); i++) {
1821             if (items.at(i)->zValue() > -1000) delete items.at(i);
1822         }
1823         m_scene->clearTextSelection();
1824         QDomDocument doc;
1825         QString tmpfile;
1826
1827         if (KIO::NetAccess::download(url, tmpfile, 0)) {
1828             QFile file(tmpfile);
1829             if (file.open(QIODevice::ReadOnly)) {
1830                 doc.setContent(&file, false);
1831                 file.close();
1832             } else return;
1833             KIO::NetAccess::removeTempFile(tmpfile);
1834         }
1835         setXml(doc);
1836
1837         /*int out;
1838         m_count = m_titledocument.loadDocument(url, m_startViewport, m_endViewport, &out) + 1;
1839         adjustFrameSize();
1840         title_duration->setText(m_tc.getTimecode(GenTime(out, m_render->fps())));
1841         insertingValues = true;
1842         startViewportX->setValue(m_startViewport->data(0).toInt());
1843         startViewportY->setValue(m_startViewport->data(1).toInt());
1844         startViewportSize->setValue(m_startViewport->data(2).toInt());
1845         endViewportX->setValue(m_endViewport->data(0).toInt());
1846         endViewportY->setValue(m_endViewport->data(1).toInt());
1847         endViewportSize->setValue(m_endViewport->data(2).toInt());
1848
1849         insertingValues = false;
1850         slotSelectTool();
1851         slotAdjustZoom();*/
1852     }
1853 }
1854
1855 void TitleWidget::saveTitle(KUrl url)
1856 {
1857     if (anim_start->isChecked()) slotAnimStart(false);
1858     if (anim_end->isChecked()) slotAnimEnd(false);
1859     bool embed_image=false;
1860
1861     // If we have images in the title, ask for embed
1862     QList <QGraphicsItem *> list = graphicsView->scene()->items();
1863     QGraphicsPixmapItem pix;
1864     int pixmapType = pix.type();
1865     foreach(const QGraphicsItem *item, list) {
1866         if (item->type() == pixmapType && item != m_frameImage) {
1867             embed_image = true;
1868             break;
1869         }
1870     }
1871     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)
1872     {
1873         embed_image=false;
1874     }
1875     if (url.isEmpty()) {
1876         QPointer<KFileDialog> fs = new KFileDialog(KUrl(m_projectTitlePath), "application/x-kdenlivetitle", this);
1877         fs->setOperationMode(KFileDialog::Saving);
1878         fs->setMode(KFile::File);
1879         fs->setConfirmOverwrite(true);
1880         fs->setKeepLocation(true);
1881         fs->exec();
1882         if (fs) url = fs->selectedUrl();
1883         delete fs;
1884     }
1885     if (!url.isEmpty()) {
1886         if (m_titledocument.saveDocument(url, m_startViewport, m_endViewport, m_tc.getFrameCount(title_duration->text()), embed_image) == false)
1887             KMessageBox::error(this, i18n("Cannot write to file %1", url.path()));
1888     }
1889 }
1890
1891 QDomDocument TitleWidget::xml()
1892 {
1893     QDomDocument doc = m_titledocument.xml(m_startViewport, m_endViewport);
1894     doc.documentElement().setAttribute("duration", m_tc.getFrameCount(title_duration->text()));
1895     return doc;
1896 }
1897
1898 int TitleWidget::duration() const
1899 {
1900     return m_tc.getFrameCount(title_duration->text());
1901 }
1902
1903 void TitleWidget::setXml(const QDomDocument &doc)
1904 {
1905     int duration;
1906     m_count = m_titledocument.loadFromXml(doc, m_startViewport, m_endViewport, &duration, m_projectTitlePath);
1907     adjustFrameSize();
1908     title_duration->setText(m_tc.getTimecode(GenTime(duration, m_render->fps())));
1909     /*if (doc.documentElement().hasAttribute("out")) {
1910     GenTime duration = GenTime(doc.documentElement().attribute("out").toDouble() / 1000.0);
1911     title_duration->setText(m_tc.getTimecode(duration));
1912     }
1913     else title_duration->setText(m_tc.getTimecode(GenTime(5000)));*/
1914
1915     QDomElement e = doc.documentElement();
1916     m_transformations.clear();
1917     QList <QGraphicsItem *> items = graphicsView->scene()->items();
1918     const double PI = 4.0 * atan(1.0);
1919     for (int i = 0; i < items.count(); i++) {
1920         QTransform t = items.at(i)->transform();
1921         Transform x;
1922         x.scalex = t.m11();
1923         x.scaley = t.m22();
1924         if (!items.at(i)->data(ROTATEFACTOR).isNull()) {
1925             QList<QVariant> rotlist = items.at(i)->data(ROTATEFACTOR).toList();
1926             if (rotlist.count() >= 3) {
1927                 x.rotatex = rotlist[0].toDouble();
1928                 x.rotatey = rotlist[1].toDouble();
1929                 x.rotatez = rotlist[2].toDouble();
1930
1931                 // Try to adjust zoom
1932                 t.rotate(x.rotatex *(-1), Qt::XAxis);
1933                 t.rotate(x.rotatey *(-1), Qt::YAxis);
1934                 t.rotate(x.rotatez *(-1), Qt::ZAxis);
1935                 x.scalex = t.m11();
1936                 x.scaley = t.m22();
1937             } else {
1938                 x.rotatex = 0;
1939                 x.rotatey = 0;
1940                 x.rotatez = 0;
1941             }
1942         } else {
1943             x.rotatex = 0;
1944             x.rotatey = 0;
1945             x.rotatez = 180. / PI * atan2(-t.m21(), t.m11());
1946         }
1947         m_transformations[items.at(i)] = x;
1948     }
1949     // mbd: Update the GUI color selectors to match the stuff from the loaded document
1950     QColor background_color = m_titledocument.getBackgroundColor();
1951     backgroundAlpha->blockSignals(true);
1952     backgroundColor->blockSignals(true);
1953     backgroundAlpha->setValue(background_color.alpha());
1954     background_color.setAlpha(255);
1955     backgroundColor->setColor(background_color);
1956     backgroundAlpha->blockSignals(false);
1957     backgroundColor->blockSignals(false);
1958
1959     /*startViewportX->setValue(m_startViewport->data(0).toInt());
1960     startViewportY->setValue(m_startViewport->data(1).toInt());
1961     startViewportSize->setValue(m_startViewport->data(2).toInt());
1962     endViewportX->setValue(m_endViewport->data(0).toInt());
1963     endViewportY->setValue(m_endViewport->data(1).toInt());
1964     endViewportSize->setValue(m_endViewport->data(2).toInt());*/
1965
1966     QTimer::singleShot(200, this, SLOT(slotAdjustZoom()));
1967     slotSelectTool();
1968     selectionChanged();
1969 }
1970
1971 void TitleWidget::slotAccepted()
1972 {
1973     if (anim_start->isChecked()) slotAnimStart(false);
1974     if (anim_end->isChecked()) slotAnimEnd(false);
1975     writeChoices();
1976 }
1977
1978 void TitleWidget::writeChoices()
1979 {
1980     // Get a pointer to a shared configuration instance, then get the TitleWidget group.
1981     KSharedConfigPtr config = KGlobal::config();
1982     KConfigGroup titleConfig(config, "TitleWidget");
1983     // Write the entries
1984     titleConfig.writeEntry("font_family", font_family->currentFont());
1985     //titleConfig.writeEntry("font_size", font_size->value());
1986     titleConfig.writeEntry("font_pixel_size", font_size->value());
1987     titleConfig.writeEntry("font_color", fontColorButton->color());
1988     titleConfig.writeEntry("font_outline_color", textOutlineColor->color());
1989 #if KDE_IS_VERSION(4,5,0)
1990     titleConfig.writeEntry("font_alpha", fontColorButton->color().alpha());
1991     titleConfig.writeEntry("font_outline_alpha", textOutlineColor->color().alpha());
1992 #else
1993     titleConfig.writeEntry("font_alpha", textAlpha->value());
1994     titleConfig.writeEntry("font_outline_alpha", textOutlineAlpha->value());
1995 #endif
1996    
1997     titleConfig.writeEntry("font_outline", textOutline->value());
1998     titleConfig.writeEntry("font_weight", font_weight_box->itemData(font_weight_box->currentIndex()).toInt());
1999     titleConfig.writeEntry("font_italic", buttonItalic->isChecked());
2000     titleConfig.writeEntry("font_underlined", buttonUnder->isChecked());
2001
2002     titleConfig.writeEntry("rect_background_color", rectBColor->color());
2003     titleConfig.writeEntry("rect_foreground_color", rectFColor->color());
2004
2005 #if KDE_IS_VERSION(4,5,0)
2006     titleConfig.writeEntry("rect_background_alpha", rectBColor->color().alpha());
2007     titleConfig.writeEntry("rect_foreground_alpha", rectFColor->color().alpha());
2008 #else
2009     titleConfig.writeEntry("rect_background_alpha", rectBAlpha->value());
2010     titleConfig.writeEntry("rect_foreground_alpha", rectFAlpha->value());
2011 #endif
2012
2013     titleConfig.writeEntry("rect_line_width", rectLineWidth->value());
2014
2015     titleConfig.writeEntry("background_color", backgroundColor->color());
2016     titleConfig.writeEntry("background_alpha", backgroundAlpha->value());
2017
2018     //! \todo Not sure if I should sync - it is probably safe to do it
2019     config->sync();
2020
2021 }
2022
2023 void TitleWidget::readChoices()
2024 {
2025     // Get a pointer to a shared configuration instance, then get the TitleWidget group.
2026     KSharedConfigPtr config = KGlobal::config();
2027     KConfigGroup titleConfig(config, "TitleWidget");
2028     // read the entries
2029     font_family->setCurrentFont(titleConfig.readEntry("font_family", font_family->currentFont()));
2030     font_size->setValue(titleConfig.readEntry("font_pixel_size", font_size->value()));
2031     m_scene->slotUpdateFontSize(font_size->value());
2032     QColor fontColor = QColor(titleConfig.readEntry("font_color", fontColorButton->color()));
2033     QColor outlineColor = QColor(titleConfig.readEntry("font_outline_color", textOutlineColor->color()));
2034 #if KDE_IS_VERSION(4,5,0)
2035     fontColor.setAlpha(titleConfig.readEntry("font_alpha", fontColor.alpha()));
2036     outlineColor.setAlpha(titleConfig.readEntry("font_outline_alpha", outlineColor.alpha()));
2037 #else
2038     textAlpha->setValue(titleConfig.readEntry("font_alpha", textAlpha->value()));
2039     textOutlineAlpha->setValue(titleConfig.readEntry("font_outline_alpha", textOutlineAlpha->value()));
2040 #endif
2041     fontColorButton->setColor(fontColor);
2042     textOutlineColor->setColor(outlineColor);
2043     textOutline->setValue(titleConfig.readEntry("font_outline", textOutline->value()));
2044
2045     int weight;
2046     if (titleConfig.readEntry("font_bold", false)) weight = QFont::Bold;
2047     else weight = titleConfig.readEntry("font_weight", font_weight_box->itemData(font_weight_box->currentIndex()).toInt());
2048     setFontBoxWeight(weight);
2049     buttonItalic->setChecked(titleConfig.readEntry("font_italic", buttonItalic->isChecked()));
2050     buttonUnder->setChecked(titleConfig.readEntry("font_underlined", buttonUnder->isChecked()));
2051
2052     QColor fgColor = QColor(titleConfig.readEntry("rect_foreground_color", rectFColor->color()));
2053     QColor bgColor = QColor(titleConfig.readEntry("rect_background_color", rectBColor->color()));
2054
2055 #if KDE_IS_VERSION(4,5,0)
2056     fgColor.setAlpha(titleConfig.readEntry("rect_foreground_alpha", fgColor.alpha()));
2057     bgColor.setAlpha(titleConfig.readEntry("rect_background_alpha", bgColor.alpha()));
2058 #else
2059     rectFAlpha->setValue(titleConfig.readEntry("rect_foreground_alpha", rectFAlpha->value()));
2060     rectBAlpha->setValue(titleConfig.readEntry("rect_background_alpha", rectBAlpha->value()));
2061 #endif
2062     rectFColor->setColor(fgColor);
2063     rectBColor->setColor(bgColor);
2064
2065     rectLineWidth->setValue(titleConfig.readEntry("rect_line_width", rectLineWidth->value()));
2066
2067     backgroundColor->setColor(titleConfig.readEntry("background_color", backgroundColor->color()));
2068     backgroundAlpha->setValue(titleConfig.readEntry("background_alpha", backgroundAlpha->value()));
2069 }
2070
2071 void TitleWidget::adjustFrameSize()
2072 {
2073     m_frameWidth = m_titledocument.frameWidth();
2074     m_frameHeight = m_titledocument.frameHeight();
2075     m_frameBorder->setRect(0, 0, m_frameWidth, m_frameHeight);
2076     displayBackgroundFrame();
2077 }
2078
2079 void TitleWidget::slotAnimStart(bool anim)
2080 {
2081     if (anim && anim_end->isChecked()) {
2082         anim_end->setChecked(false);
2083         m_endViewport->setZValue(-1000);
2084         m_endViewport->setBrush(QBrush());
2085     }
2086     slotSelectTool();
2087     QList<QGraphicsItem *> list = m_scene->items();
2088     for (int i = 0; i < list.count(); i++) {
2089         if (list.at(i)->zValue() > -1000) {
2090             list.at(i)->setFlag(QGraphicsItem::ItemIsMovable, !anim);
2091             list.at(i)->setFlag(QGraphicsItem::ItemIsSelectable, !anim);
2092         }
2093     }
2094     align_box->setEnabled(anim);
2095     itemzoom->setEnabled(!anim);
2096     itemrotatex->setEnabled(!anim);
2097     itemrotatey->setEnabled(!anim);
2098     itemrotatez->setEnabled(!anim);
2099     frame_toolbar->setEnabled(!anim);
2100     toolbar_stack->setEnabled(!anim);
2101     if (anim) {
2102         keep_aspect->setChecked(!m_startViewport->data(0).isNull());
2103         m_startViewport->setZValue(1100);
2104         QColor col = m_startViewport->pen().color();
2105         col.setAlpha(100);
2106         m_startViewport->setBrush(col);
2107         m_startViewport->setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable);
2108         m_startViewport->setSelected(true);
2109         selectionChanged();
2110         slotSelectTool();
2111         if (m_startViewport->childItems().isEmpty()) addAnimInfoText();
2112     } else {
2113         m_startViewport->setZValue(-1000);
2114         m_startViewport->setBrush(QBrush());
2115         m_startViewport->setFlags(0);
2116         if (!anim_end->isChecked()) deleteAnimInfoText();
2117     }
2118
2119 }
2120
2121 void TitleWidget::slotAnimEnd(bool anim)
2122 {
2123     if (anim && anim_start->isChecked()) {
2124         anim_start->setChecked(false);
2125         m_startViewport->setZValue(-1000);
2126         m_startViewport->setBrush(QBrush());
2127     }
2128     slotSelectTool();
2129     QList<QGraphicsItem *> list = m_scene->items();
2130     for (int i = 0; i < list.count(); i++) {
2131         if (list.at(i)->zValue() > -1000) {
2132             list.at(i)->setFlag(QGraphicsItem::ItemIsMovable, !anim);
2133             list.at(i)->setFlag(QGraphicsItem::ItemIsSelectable, !anim);
2134         }
2135     }
2136     align_box->setEnabled(anim);
2137     itemzoom->setEnabled(!anim);
2138     itemrotatex->setEnabled(!anim);
2139     itemrotatey->setEnabled(!anim);
2140     itemrotatez->setEnabled(!anim);
2141     frame_toolbar->setEnabled(!anim);
2142     toolbar_stack->setEnabled(!anim);
2143     if (anim) {
2144         keep_aspect->setChecked(!m_endViewport->data(0).isNull());
2145         m_endViewport->setZValue(1100);
2146         QColor col = m_endViewport->pen().color();
2147         col.setAlpha(100);
2148         m_endViewport->setBrush(col);
2149         m_endViewport->setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable);
2150         m_endViewport->setSelected(true);
2151         selectionChanged();
2152         slotSelectTool();
2153         if (m_endViewport->childItems().isEmpty()) addAnimInfoText();
2154     } else {
2155         m_endViewport->setZValue(-1000);
2156         m_endViewport->setBrush(QBrush());
2157         m_endViewport->setFlags(0);
2158         if (!anim_start->isChecked()) deleteAnimInfoText();
2159     }
2160 }
2161
2162 void TitleWidget::addAnimInfoText()
2163 {
2164     // add text to anim viewport
2165     QGraphicsTextItem *t = new QGraphicsTextItem(i18nc("Indicates the start of an animation", "Start"), m_startViewport);
2166     QGraphicsTextItem *t2 = new QGraphicsTextItem(i18nc("Indicates the end of an animation", "End"), m_endViewport);
2167     QFont font = t->font();
2168     font.setPixelSize(m_startViewport->rect().width() / 10);
2169     QColor col = m_startViewport->pen().color();
2170     col.setAlpha(255);
2171     t->setDefaultTextColor(col);
2172     t->setFont(font);
2173     font.setPixelSize(m_endViewport->rect().width() / 10);
2174     col = m_endViewport->pen().color();
2175     col.setAlpha(255);
2176     t2->setDefaultTextColor(col);
2177     t2->setFont(font);
2178 }
2179
2180 void TitleWidget::updateInfoText()
2181 {
2182     // update info text font
2183     if (!m_startViewport->childItems().isEmpty()) {
2184         QGraphicsTextItem *item = static_cast <QGraphicsTextItem *>(m_startViewport->childItems().at(0));
2185         if (item) {
2186             QFont font = item->font();
2187             font.setPixelSize(m_startViewport->rect().width() / 10);
2188             item->setFont(font);
2189         }
2190     }
2191     if (!m_endViewport->childItems().isEmpty()) {
2192         QGraphicsTextItem *item = static_cast <QGraphicsTextItem *>(m_endViewport->childItems().at(0));
2193         if (item) {
2194             QFont font = item->font();
2195             font.setPixelSize(m_endViewport->rect().width() / 10);
2196             item->setFont(font);
2197         }
2198     }
2199 }
2200
2201 void TitleWidget::deleteAnimInfoText()
2202 {
2203     // end animation editing, remove info text
2204     while (!m_startViewport->childItems().isEmpty()) {
2205         QGraphicsItem *item = m_startViewport->childItems().at(0);
2206         m_scene->removeItem(item);
2207         delete item;
2208     }
2209     while (!m_endViewport->childItems().isEmpty()) {
2210         QGraphicsItem *item = m_endViewport->childItems().at(0);
2211         m_scene->removeItem(item);
2212         delete item;
2213     }
2214 }
2215
2216 void TitleWidget::slotKeepAspect(bool keep)
2217 {
2218     if (m_endViewport->zValue() == 1100) {
2219         m_endViewport->setData(0, keep == true ? m_frameWidth : QVariant());
2220         m_endViewport->setData(1, keep == true ? m_frameHeight : QVariant());
2221     } else {
2222         m_startViewport->setData(0, keep == true ? m_frameWidth : QVariant());
2223         m_startViewport->setData(1, keep == true ? m_frameHeight : QVariant());
2224     }
2225 }
2226
2227 void TitleWidget::slotResize50()
2228 {
2229     if (m_endViewport->zValue() == 1100) {
2230         m_endViewport->setRect(0, 0, m_frameWidth / 2, m_frameHeight / 2);
2231     } else m_startViewport->setRect(0, 0, m_frameWidth / 2, m_frameHeight / 2);
2232 }
2233
2234 void TitleWidget::slotResize100()
2235 {
2236     if (m_endViewport->zValue() == 1100) {
2237         m_endViewport->setRect(0, 0, m_frameWidth, m_frameHeight);
2238     } else m_startViewport->setRect(0, 0, m_frameWidth, m_frameHeight);
2239 }
2240
2241 void TitleWidget::slotResize200()
2242 {
2243     if (m_endViewport->zValue() == 1100) {
2244         m_endViewport->setRect(0, 0, m_frameWidth * 2, m_frameHeight * 2);
2245     } else m_startViewport->setRect(0, 0, m_frameWidth * 2, m_frameHeight * 2);
2246 }
2247
2248 void TitleWidget::slotAddEffect(int ix)
2249 {
2250     QList<QGraphicsItem *> list = graphicsView->scene()->selectedItems();
2251     int effect = effect_list->itemData(ix).toInt();
2252
2253     if (list.size() == 1) {
2254         if (effect == NOEFFECT)
2255             effect_stack->setHidden(true);
2256         else {
2257             effect_stack->setCurrentIndex(effect - 1);
2258             effect_stack->setHidden(false);
2259         }
2260     } else // Hide the effects stack when more than one element is selected.
2261         effect_stack->setHidden(true);
2262
2263     foreach(QGraphicsItem * item, list) {
2264         switch (effect) {
2265         case NOEFFECT:
2266             item->setData(100, QVariant());
2267 #if QT_VERSION >= 0x040600
2268             item->setGraphicsEffect(0);
2269 #endif
2270             break;
2271         case TYPEWRITEREFFECT:
2272             /*
2273              * Allow the user to set the typewriter effect to more than one
2274              * element, but do not add it to non-text elements.
2275              */
2276             if (item->type() == TEXTITEM) {
2277                 QStringList effdata = QStringList() << "typewriter" << QString::number(typewriter_delay->value()) + ';' + QString::number(typewriter_start->value());
2278                 item->setData(100, effdata);
2279             }
2280             break;
2281 #if QT_VERSION >= 0x040600
2282             // Do not remove the non-QGraphicsEffects.
2283         case BLUREFFECT:
2284             item->setGraphicsEffect(new QGraphicsBlurEffect());
2285             break;
2286         case SHADOWEFFECT:
2287             item->setGraphicsEffect(new QGraphicsDropShadowEffect());
2288             break;
2289 #endif
2290         }
2291     }
2292 }
2293
2294 void TitleWidget::slotFontText(const QString& s)
2295 {
2296     const QFont f(s);
2297     if (f.exactMatch()) {
2298         // Font really exists (could also just be a Â«d» if the user
2299         // starts typing Â«dejavu» for example).
2300         font_family->setCurrentFont(f);
2301     }
2302     // Note: Typing dejavu serif does not recognize the font (takes sans)
2303     // in older Qt versions. Case must match there (except for first letter)
2304 }
2305
2306 void TitleWidget::slotEditTypewriter(int /*ix*/)
2307 {
2308     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
2309     if (l.size() == 1) {
2310         QStringList effdata = QStringList() << "typewriter" << QString::number(typewriter_delay->value()) + ';' + QString::number(typewriter_start->value());
2311         l[0]->setData(100, effdata);
2312     }
2313 }
2314
2315 void TitleWidget::slotEditBlur(int ix)
2316 {
2317 #if QT_VERSION < 0x040600
2318     return;
2319 #else
2320     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
2321     if (l.size() == 1) {
2322         QGraphicsEffect *eff = l[0]->graphicsEffect();
2323         QGraphicsBlurEffect *blur = static_cast <QGraphicsBlurEffect *>(eff);
2324         if (blur) blur->setBlurRadius(ix);
2325     }
2326 #endif
2327 }
2328
2329 void TitleWidget::slotEditShadow()
2330 {
2331 #if QT_VERSION < 0x040600
2332     return;
2333 #else
2334     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
2335     if (l.size() == 1) {
2336         QGraphicsEffect *eff = l[0]->graphicsEffect();
2337         QGraphicsDropShadowEffect *shadow = static_cast <QGraphicsDropShadowEffect *>(eff);
2338         if (shadow) {
2339             shadow->setBlurRadius(shadow_radius->value());
2340             shadow->setOffset(shadow_x->value(), shadow_y->value());
2341         }
2342     }
2343 #endif
2344 }
2345
2346 qreal TitleWidget::zIndexBounds(bool maxBound, bool intersectingOnly)
2347 {
2348     qreal bound = maxBound ? -99 : 99;
2349     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
2350     if (l.size() > 0) {
2351         QList<QGraphicsItem*> lItems;
2352         // Get items (all or intersecting only)
2353         if (intersectingOnly) {
2354             lItems = graphicsView->scene()->items(l[0]->sceneBoundingRect(), Qt::IntersectsItemShape);
2355         } else {
2356             lItems = graphicsView->scene()->items();
2357         }
2358         if (lItems.size() > 0) {
2359             int n = lItems.size();
2360             qreal z;
2361             if (maxBound) {
2362                 for (int i = 0; i < n; i++) {
2363                     z = lItems[i]->zValue();
2364                     if (z > bound && !lItems[i]->isSelected()) {
2365                         bound = z;
2366                     } else if (z - 1 > bound) {
2367                         // To get the maximum index even if it is of an item of the current selection.
2368                         // Used when updating multiple items, to get all to the same level.
2369                         // Otherwise, the maximum would stay at -99 if the highest item is in the selection.
2370                         bound = z - 1;
2371                     }
2372                 }
2373             } else {
2374                 // Get minimum z index.
2375                 for (int i = 0; i < n; i++) {
2376                     z = lItems[i]->zValue();
2377                     if (z < bound && !lItems[i]->isSelected() && z > -999) {
2378                         // There are items at the very bottom (background e.g.) with z-index < -1000.
2379                         bound = z;
2380                     } else if (z + 1 < bound && z > -999) {
2381                         bound = z + 1;
2382                     }
2383                 }
2384             }
2385         }
2386     }
2387     return bound;
2388 }
2389
2390 void TitleWidget::slotZIndexUp()
2391 {
2392     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
2393     if (l.size() >= 1) {
2394         qreal currentZ = l[0]->zValue();
2395         qreal max = zIndexBounds(true, true);
2396         if (currentZ <= max) {
2397             l[0]->setZValue(currentZ + 1);
2398             updateDimension(l[0]);
2399         }
2400     }
2401 }
2402
2403 void TitleWidget::slotZIndexTop()
2404 {
2405     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
2406     qreal max = zIndexBounds(true, false);
2407     std::cout << "Max z-index is " << max << ".\n";
2408     for (int i = 0; i < l.size(); i++) {
2409         qreal currentZ = l[i]->zValue();
2410         if (currentZ <= max) {
2411             std::cout << "Updating item " << i << ", is " << currentZ << ".\n";
2412             l[i]->setZValue(max + 1);
2413         } else {
2414             std::cout << "Not updating " << i << ", is " << currentZ << ".\n";
2415         }
2416     }
2417     // Update the z index value in the GUI
2418     if (l.size() > 0) {
2419         updateDimension(l[0]);
2420     }
2421 }
2422
2423 void TitleWidget::slotZIndexDown()
2424 {
2425     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
2426     if (l.size() >= 1) {
2427         qreal currentZ = l[0]->zValue();
2428         qreal min = zIndexBounds(false, true);
2429         if (currentZ >= min) {
2430             l[0]->setZValue(currentZ - 1);
2431             updateDimension(l[0]);
2432         }
2433     }
2434 }
2435
2436 void TitleWidget::slotZIndexBottom()
2437 {
2438     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
2439     qreal min = zIndexBounds(false, false);
2440     for (int i = 0; i < l.size(); i++) {
2441         qreal currentZ = l[i]->zValue();
2442         if (currentZ >= min) {
2443             l[i]->setZValue(min - 1);
2444         }
2445     }
2446     // Update the z index value in the GUI
2447     if (l.size() > 0) {
2448         updateDimension(l[0]);
2449     }
2450 }
2451
2452 void TitleWidget::slotSelectAll()
2453 {
2454     QList<QGraphicsItem*> l = graphicsView->scene()->items();
2455     for (int i = 0; i < l.size(); i++) {
2456         l.at(i)->setSelected(true);
2457     }
2458 }
2459
2460 void TitleWidget::selectItems(int itemType)
2461 {
2462     QList<QGraphicsItem*> l;
2463     if (graphicsView->scene()->selectedItems().size() > 0) {
2464         l = graphicsView->scene()->selectedItems();
2465         for (int i = 0; i < l.size(); i++) {
2466             if (l.at(i)->type() != itemType) {
2467                 l.at(i)->setSelected(false);
2468             }
2469         }
2470     } else {
2471         l = graphicsView->scene()->items();
2472         for (int i = 0; i < l.size(); i++) {
2473             if (l.at(i)->type() == itemType) {
2474                 l.at(i)->setSelected(true);
2475             }
2476         }
2477     }
2478 }
2479
2480 void TitleWidget::slotSelectText()
2481 {
2482     selectItems(TEXTITEM);
2483 }
2484
2485 void TitleWidget::slotSelectRects()
2486 {
2487     selectItems(RECTITEM);
2488 }
2489
2490 void TitleWidget::slotSelectImages()
2491 {
2492     selectItems(IMAGEITEM);
2493 }
2494
2495 void TitleWidget::slotSelectNone()
2496 {
2497     graphicsView->blockSignals(true);
2498     QList<QGraphicsItem*> l = graphicsView->scene()->items();
2499     for (int i = 0; i < l.size(); i++) {
2500         l.at(i)->setSelected(false);
2501     }
2502     graphicsView->blockSignals(false);
2503     selectionChanged();
2504 }
2505
2506 QString TitleWidget::getTooltipWithShortcut(const QString &text, QAction *button)
2507 {
2508     return text + "  <b>" + button->shortcut().toString() + "</b>";
2509 }
2510
2511 void TitleWidget::prepareTools(QGraphicsItem *referenceItem)
2512 {
2513     // Let some GUI elements block signals. We may want to change their values without any sideeffects.
2514     // Additionally, store the previous blocking state to avoid side effects when this function is called from within another one.
2515     // Note: Disabling an element also blocks signals. So disabled elements don't need to be set to blocking too.
2516     bool blockOX = origin_x_left->signalsBlocked();
2517     bool blockOY = origin_y_top->signalsBlocked();
2518     bool blockEff = effect_list->signalsBlocked();
2519     bool blockRX = itemrotatex->signalsBlocked();
2520     bool blockRY = itemrotatey->signalsBlocked();
2521     bool blockRZ = itemrotatez->signalsBlocked();
2522     bool blockZoom = itemzoom->signalsBlocked();
2523     bool blockX = value_x->signalsBlocked();
2524     bool blockY = value_y->signalsBlocked();
2525     bool blockW = value_w->signalsBlocked();
2526     bool blockH = value_h->signalsBlocked();
2527     origin_x_left->blockSignals(true);
2528     origin_y_top->blockSignals(true);
2529     effect_list->blockSignals(true);
2530     itemrotatex->blockSignals(true);
2531     itemrotatey->blockSignals(true);
2532     itemrotatez->blockSignals(true);
2533     itemzoom->blockSignals(true);
2534     value_x->blockSignals(true);
2535     value_y->blockSignals(true);
2536     value_w->blockSignals(true);
2537     value_h->blockSignals(true);
2538
2539     if (referenceItem == NULL) {
2540         std::cout << "NULL item.\n";
2541         effect_stack->setHidden(true);
2542         effect_frame->setEnabled(false);
2543         effect_list->setCurrentIndex(0);
2544         origin_x_left->setChecked(false);
2545         origin_y_top->setChecked(false);
2546         updateTextOriginX();
2547         updateTextOriginY();
2548         enableToolbars(TITLE_SELECT);
2549         showToolbars(TITLE_SELECT);
2550
2551         itemzoom->setEnabled(false);
2552         itemrotatex->setEnabled(false);
2553         itemrotatey->setEnabled(false);
2554         itemrotatez->setEnabled(false);
2555         frame_properties->setEnabled(false);
2556     } else {
2557         effect_frame->setEnabled(true);
2558         frame_properties->setEnabled(true);
2559         if (referenceItem != m_startViewport && referenceItem != m_endViewport) {
2560             itemzoom->setEnabled(true);
2561             itemrotatex->setEnabled(true);
2562             itemrotatey->setEnabled(true);
2563             itemrotatez->setEnabled(true);
2564         } else {
2565             itemzoom->setEnabled(false);
2566             itemrotatex->setEnabled(false);
2567             itemrotatey->setEnabled(false);
2568             itemrotatez->setEnabled(false);
2569             updateInfoText();
2570         }
2571         if (referenceItem->type() == TEXTITEM) {
2572             showToolbars(TITLE_TEXT);
2573             QGraphicsTextItem* i = static_cast <QGraphicsTextItem *>(referenceItem);
2574             if (!i->toPlainText().isEmpty()) {
2575                 // We have an existing text item selected
2576                 if (!i->data(100).isNull()) {
2577                     // Item has an effect
2578                     QStringList effdata = i->data(100).toStringList();
2579                     QString effectName = effdata.takeFirst();
2580                     if (effectName == "typewriter") {
2581                         QStringList params = effdata.at(0).split(';');
2582                         typewriter_delay->setValue(params.at(0).toInt());
2583                         typewriter_start->setValue(params.at(1).toInt());
2584                         effect_list->setCurrentIndex(effect_list->findData((int) TYPEWRITEREFFECT));
2585                         effect_stack->setHidden(false);
2586                     }
2587                 } else {
2588 #if QT_VERSION >= 0x040600
2589                     if (i->graphicsEffect()) {
2590                         QGraphicsBlurEffect *blur = static_cast <QGraphicsBlurEffect *>(i->graphicsEffect());
2591                         if (blur) {
2592                             effect_list->setCurrentIndex(effect_list->findData((int) BLUREFFECT));
2593                             int rad = (int) blur->blurRadius();
2594                             blur_radius->setValue(rad);
2595                             effect_stack->setHidden(false);
2596                         } else {
2597                             QGraphicsDropShadowEffect *shad = static_cast <QGraphicsDropShadowEffect *>(i->graphicsEffect());
2598                             if (shad) {
2599                                 effect_list->setCurrentIndex(effect_list->findData((int) SHADOWEFFECT));
2600                                 shadow_radius->setValue(shad->blurRadius());
2601                                 shadow_x->setValue(shad->xOffset());
2602                                 shadow_y->setValue(shad->yOffset());
2603                                 effect_stack->setHidden(false);
2604                             }
2605                         }
2606                     } else {
2607                         effect_list->setCurrentIndex(effect_list->findData((int) NOEFFECT));
2608                         effect_stack->setHidden(true);
2609                     }
2610 #else
2611                     effect_list->setCurrentIndex(effect_list->findData((int) NOEFFECT));
2612                     effect_stack->setHidden(true);
2613 #endif
2614                 }
2615                 font_size->blockSignals(true);
2616                 font_family->blockSignals(true);
2617                 font_weight_box->blockSignals(true);
2618                 buttonItalic->blockSignals(true);
2619                 buttonUnder->blockSignals(true);
2620                 fontColorButton->blockSignals(true);
2621 #if not KDE_IS_VERSION(4,5,0)
2622                 textAlpha->blockSignals(true);
2623 #endif
2624                 buttonAlignLeft->blockSignals(true);
2625                 buttonAlignRight->blockSignals(true);
2626                 buttonAlignNone->blockSignals(true);
2627                 buttonAlignCenter->blockSignals(true);
2628
2629                 QFont font = i->font();
2630                 font_family->setCurrentFont(font);
2631                 font_size->setValue(font.pixelSize());
2632                 m_scene->slotUpdateFontSize(font.pixelSize());
2633                 buttonItalic->setChecked(font.italic());
2634                 buttonUnder->setChecked(font.underline());
2635                 setFontBoxWeight(font.weight());
2636
2637                 QTextCursor cursor(i->document());
2638                 cursor.select(QTextCursor::Document);
2639                 QColor color = cursor.charFormat().foreground().color();
2640 #if not KDE_IS_VERSION(4,5,0)
2641                 textAlpha->setValue(color.alpha());
2642                 color.setAlpha(255);
2643 #endif
2644                 fontColorButton->setColor(color);
2645
2646                 if (!i->data(101).isNull()) {
2647                     textOutline->blockSignals(true);
2648                     textOutline->setValue(i->data(101).toDouble() * 10);
2649                     textOutline->blockSignals(false);
2650                 }
2651                 if (!i->data(102).isNull()) {
2652                     textOutlineColor->blockSignals(true);
2653                     QVariant variant = i->data(102);
2654                     color = variant.value<QColor>();
2655 #if not KDE_IS_VERSION(4,5,0)
2656                     textOutlineAlpha->blockSignals(true);
2657                     textOutlineAlpha->setValue(color.alpha());
2658                     color.setAlpha(255);
2659                     textOutlineAlpha->blockSignals(false);
2660 #endif
2661                     textOutlineColor->setColor(color);
2662                     textOutlineColor->blockSignals(false);
2663                 }
2664                 QTextCursor cur = i->textCursor();
2665                 QTextBlockFormat format = cur.blockFormat();
2666                 if (i->textWidth() == -1) buttonAlignNone->setChecked(true);
2667                 else if (format.alignment() == Qt::AlignHCenter) buttonAlignCenter->setChecked(true);
2668                 else if (format.alignment() == Qt::AlignRight) buttonAlignRight->setChecked(true);
2669                 else if (format.alignment() == Qt::AlignLeft) buttonAlignLeft->setChecked(true);
2670
2671                 font_size->blockSignals(false);
2672                 font_family->blockSignals(false);
2673                 font_weight_box->blockSignals(false);
2674                 buttonItalic->blockSignals(false);
2675                 buttonUnder->blockSignals(false);
2676                 fontColorButton->blockSignals(false);
2677 #if not KDE_IS_VERSION(4,5,0)
2678                 textAlpha->blockSignals(false);
2679 #endif
2680                 buttonAlignLeft->blockSignals(false);
2681                 buttonAlignRight->blockSignals(false);
2682                 buttonAlignNone->blockSignals(false);
2683                 buttonAlignCenter->blockSignals(false);
2684
2685                 // mbt 1607: Select text if the text item is an unchanged template item.
2686                 if (i->property("isTemplate").isValid()) {
2687                     cur.setPosition(0, QTextCursor::MoveAnchor);
2688                     cur.select(QTextCursor::Document);
2689                     i->setTextCursor(cur);
2690                     // Make text editable now.
2691                     i->grabKeyboard();
2692                     i->setTextInteractionFlags(Qt::TextEditorInteraction);
2693                 }
2694             }
2695
2696             updateAxisButtons(i);
2697             updateCoordinates(i);
2698             updateDimension(i);
2699             enableToolbars(TITLE_TEXT);
2700
2701         } else if ((referenceItem)->type() == RECTITEM) {
2702             showToolbars(TITLE_RECTANGLE);
2703             settingUp = true;
2704             QGraphicsRectItem *rec = static_cast <QGraphicsRectItem *>(referenceItem);
2705             if (rec == m_startViewport || rec == m_endViewport) {
2706                 /*toolBox->setCurrentIndex(3);
2707                 toolBox->widget(0)->setEnabled(false);
2708                 toolBox->widget(1)->setEnabled(false);*/
2709                 enableToolbars(TITLE_SELECT);
2710             } else {
2711                 /*toolBox->widget(0)->setEnabled(true);
2712                 toolBox->widget(1)->setEnabled(true);
2713                 toolBox->setCurrentIndex(0);*/
2714                 //toolBox->setItemEnabled(3, true);
2715 #if not KDE_IS_VERSION(4,5,0)                
2716                 rectFAlpha->setValue(rec->pen().color().alpha());
2717                 rectBAlpha->setValue(rec->brush().color().alpha());
2718 #endif
2719                 //kDebug() << rec->brush().color().alpha();
2720                 QColor fcol = rec->pen().color();
2721                 QColor bcol = rec->brush().color();
2722                 //fcol.setAlpha(255);
2723                 //bcol.setAlpha(255);
2724                 rectFColor->setColor(fcol);
2725                 rectBColor->setColor(bcol);
2726                 settingUp = false;
2727                 rectLineWidth->setValue(rec->pen().width());
2728                 enableToolbars(TITLE_RECTANGLE);
2729             }
2730
2731             updateAxisButtons(referenceItem);
2732             updateCoordinates(rec);
2733             updateDimension(rec);
2734
2735         } else if (referenceItem->type() == IMAGEITEM) {
2736             showToolbars(TITLE_IMAGE);
2737
2738             updateCoordinates(referenceItem);
2739             updateDimension(referenceItem);
2740
2741             enableToolbars(TITLE_IMAGE);
2742
2743         } else {
2744             //toolBox->setCurrentIndex(0);
2745             showToolbars(TITLE_SELECT);
2746             enableToolbars(TITLE_SELECT);
2747             frame_properties->setEnabled(false);
2748         }
2749         zValue->setValue((int)referenceItem->zValue());
2750         if (!referenceItem->data(ZOOMFACTOR).isNull()) itemzoom->setValue(referenceItem->data(ZOOMFACTOR).toInt());
2751         else itemzoom->setValue((int)(m_transformations.value(referenceItem).scalex * 100.0 + 0.5));
2752         itemrotatex->setValue((int)(m_transformations.value(referenceItem).rotatex));
2753         itemrotatey->setValue((int)(m_transformations.value(referenceItem).rotatey));
2754         itemrotatez->setValue((int)(m_transformations.value(referenceItem).rotatez));
2755     }
2756
2757
2758     effect_list->blockSignals(blockEff);
2759     itemrotatex->blockSignals(blockRX);
2760     itemrotatey->blockSignals(blockRY);
2761     itemrotatez->blockSignals(blockRZ);
2762     itemzoom->blockSignals(blockZoom);
2763     origin_x_left->blockSignals(blockOX);
2764     origin_y_top->blockSignals(blockOY);
2765     value_x->blockSignals(blockX);
2766     value_y->blockSignals(blockY);
2767     value_w->blockSignals(blockW);
2768     value_h->blockSignals(blockH);
2769 }