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