]> git.sesse.net Git - kdenlive/blob - src/titlewidget.cpp
Fix flickering of toolbars in titlewidget (always hide the current toolbar before...
[kdenlive] / src / titlewidget.cpp
1 /***************************************************************************
2                           titlewidget.cpp  -  description
3                              -------------------
4     begin                : Feb 28 2008
5     copyright            : (C) 2008 by Marco Gittler
6     email                : g.marco@freenet.de
7  ***************************************************************************/
8
9 /***************************************************************************
10  *                                                                         *
11  *   This program is free software; you can redistribute it and/or modify  *
12  *   it under the terms of the GNU General Public License as published by  *
13  *   the Free Software Foundation; either version 2 of the License, or     *
14  *   (at your option) any later version.                                   *
15  *                                                                         *
16  ***************************************************************************/
17
18 #include "titlewidget.h"
19 #include "kdenlivesettings.h"
20
21 #include <cmath>
22
23 #include <KDebug>
24 #include <KGlobalSettings>
25 #include <KFileDialog>
26 #include <KStandardDirs>
27 #include <KMessageBox>
28
29 #include <QDomDocument>
30 #include <QGraphicsItem>
31 #include <QGraphicsSvgItem>
32 #include <QTimer>
33 #include <QToolBar>
34 #include <QMenu>
35 #include <QSignalMapper>
36 #include <QTextBlockFormat>
37 #include <QTextCursor>
38
39 int settingUp = false;
40
41 const int IMAGEITEM = 7;
42 const int RECTITEM = 3;
43 const int TEXTITEM = 8;
44 static bool insertingValues = false;
45
46 TitleWidget::TitleWidget(KUrl url, QString projectTitlePath, Render *render, QWidget *parent) :
47         QDialog(parent),
48         Ui::TitleWidget_UI(),
49         m_startViewport(NULL),
50         m_endViewport(NULL),
51         m_render(render),
52         m_count(0),
53         m_unicodeDialog(new UnicodeDialog(UnicodeDialog::InputHex)),
54         m_projectTitlePath(projectTitlePath)
55 {
56     setupUi(this);
57     setFont(KGlobalSettings::toolBarFont());
58     //toolBox->setFont(KGlobalSettings::toolBarFont());
59     frame_properties->setEnabled(false);
60     rect_properties->setFixedHeight(frame_properties->height() + 4);
61     text_properties->setFixedHeight(frame_properties->height() + 4);
62     m_frameWidth = render->renderWidth();
63     m_frameHeight = render->renderHeight();
64
65     connect(kcolorbutton, SIGNAL(clicked()), this, SLOT(slotChangeBackground())) ;
66     connect(horizontalSlider, SIGNAL(valueChanged(int)), this, SLOT(slotChangeBackground())) ;
67
68     connect(fontColorButton, SIGNAL(clicked()), this, SLOT(slotUpdateText())) ;
69     connect(font_family, SIGNAL(currentFontChanged(const QFont &)), this, SLOT(slotUpdateText())) ;
70     connect(font_size, SIGNAL(valueChanged(int)), this, SLOT(slotUpdateText())) ;
71     connect(textAlpha, SIGNAL(valueChanged(int)), this, SLOT(slotUpdateText()));
72     connect(font_weight_box, SIGNAL(currentIndexChanged(int)), this, SLOT(slotUpdateText()));
73
74     connect(rectFAlpha, SIGNAL(valueChanged(int)), this, SLOT(rectChanged()));
75     connect(rectBAlpha, SIGNAL(valueChanged(int)), this, SLOT(rectChanged()));
76     connect(rectFColor, SIGNAL(clicked()), this, SLOT(rectChanged()));
77     connect(rectBColor, SIGNAL(clicked()), this, SLOT(rectChanged()));
78     connect(rectLineWidth, SIGNAL(valueChanged(int)), this, SLOT(rectChanged()));
79
80     connect(startViewportX, SIGNAL(valueChanged(int)), this, SLOT(setupViewports()));
81     connect(startViewportY, SIGNAL(valueChanged(int)), this, SLOT(setupViewports()));
82     connect(startViewportSize, SIGNAL(valueChanged(int)), this, SLOT(setupViewports()));
83     connect(endViewportX, SIGNAL(valueChanged(int)), this, SLOT(setupViewports()));
84     connect(endViewportY, SIGNAL(valueChanged(int)), this, SLOT(setupViewports()));
85     connect(endViewportSize, SIGNAL(valueChanged(int)), this, SLOT(setupViewports()));
86
87     connect(zValue, SIGNAL(valueChanged(int)), this, SLOT(zIndexChanged(int)));
88     connect(itemzoom, SIGNAL(valueChanged(int)), this, SLOT(itemScaled(int)));
89     connect(itemrotate, SIGNAL(valueChanged(int)), this, SLOT(itemRotate(int)));
90     connect(itemhcenter, SIGNAL(clicked()), this, SLOT(itemHCenter()));
91     connect(itemvcenter, SIGNAL(clicked()), this, SLOT(itemVCenter()));
92
93     connect(origin_x_left, SIGNAL(clicked()), this, SLOT(slotOriginXClicked()));
94     connect(origin_y_top, SIGNAL(clicked()), this, SLOT(slotOriginYClicked()));
95
96     m_signalMapper = new QSignalMapper(this);
97     m_signalMapper->setMapping(value_w, ValueWidth);
98     m_signalMapper->setMapping(value_h, ValueHeight);
99     connect(value_w, SIGNAL(valueChanged(int)), m_signalMapper, SLOT(map()));
100     connect(value_h, SIGNAL(valueChanged(int)), m_signalMapper, SLOT(map()));
101     connect(m_signalMapper, SIGNAL(mapped(int)), this, SLOT(slotValueChanged(int)));
102
103     connect(value_x, SIGNAL(valueChanged(int)), this, SLOT(slotAdjustSelectedItem()));
104     connect(value_y, SIGNAL(valueChanged(int)), this, SLOT(slotAdjustSelectedItem()));
105     connect(value_w, SIGNAL(valueChanged(int)), this, SLOT(slotAdjustSelectedItem()));
106     connect(value_h, SIGNAL(valueChanged(int)), this, SLOT(slotAdjustSelectedItem()));
107     connect(buttonFitZoom, SIGNAL(clicked()), this, SLOT(slotAdjustZoom()));
108     connect(buttonRealSize, SIGNAL(clicked()), this, SLOT(slotZoomOneToOne()));
109     connect(buttonItalic, SIGNAL(clicked()), this, SLOT(slotUpdateText()));
110     connect(buttonUnder, SIGNAL(clicked()), this, SLOT(slotUpdateText()));
111     connect(buttonAlignLeft, SIGNAL(clicked()), this, SLOT(slotUpdateText()));
112     connect(buttonAlignRight, SIGNAL(clicked()), this, SLOT(slotUpdateText()));
113     connect(buttonAlignCenter, SIGNAL(clicked()), this, SLOT(slotUpdateText()));
114     connect(buttonAlignNone, SIGNAL(clicked()), this, SLOT(slotUpdateText()));
115     //connect(buttonInsertUnicode, SIGNAL(clicked()), this, SLOT(slotInsertUnicode()));
116     connect(displayBg, SIGNAL(stateChanged(int)), this, SLOT(displayBackgroundFrame()));
117
118     connect(m_unicodeDialog, SIGNAL(charSelected(QString)), this, SLOT(slotInsertUnicodeString(QString)));
119
120     // mbd
121     connect(this, SIGNAL(accepted()), this, SLOT(slotAccepted()));
122
123     font_weight_box->blockSignals(true);
124     font_weight_box->addItem(i18nc("Font style", "Light"), QFont::Light);
125     font_weight_box->addItem(i18nc("Font style", "Normal"), QFont::Normal);
126     font_weight_box->addItem(i18nc("Font style", "Demi-Bold"), QFont::DemiBold);
127     font_weight_box->addItem(i18nc("Font style", "Bold"), QFont::Bold);
128     font_weight_box->addItem(i18nc("Font style", "Black"), QFont::Black);
129     font_weight_box->setToolTip(i18n("Font weight"));
130     font_weight_box->setCurrentIndex(1);
131     font_weight_box->blockSignals(false);
132
133     buttonFitZoom->setIcon(KIcon("zoom-fit-best"));
134     buttonRealSize->setIcon(KIcon("zoom-original"));
135     buttonItalic->setIcon(KIcon("format-text-italic"));
136     buttonUnder->setIcon(KIcon("format-text-underline"));
137     buttonAlignCenter->setIcon(KIcon("format-justify-center"));
138     buttonAlignLeft->setIcon(KIcon("format-justify-left"));
139     buttonAlignRight->setIcon(KIcon("format-justify-right"));
140     buttonAlignNone->setIcon(KIcon("kdenlive-align-none"));
141
142     buttonAlignNone->setToolTip(i18n("No alignment"));
143     buttonAlignRight->setToolTip(i18n("Align right"));
144     buttonAlignLeft->setToolTip(i18n("Align left"));
145     buttonAlignCenter->setToolTip(i18n("Align center"));
146
147     m_unicodeAction = new QAction(KIcon("kdenlive-insert-unicode"), QString(), this);
148     m_unicodeAction->setShortcut(Qt::SHIFT + Qt::CTRL + Qt::Key_U);
149     m_unicodeAction->setToolTip(i18n("Insert Unicode character") + ' ' + m_unicodeAction->shortcut().toString());
150     connect(m_unicodeAction, SIGNAL(triggered()), this, SLOT(slotInsertUnicode()));
151     buttonInsertUnicode->setDefaultAction(m_unicodeAction);
152
153     origin_x_left->setToolTip(i18n("Invert x axis and change 0 point"));
154     origin_y_top->setToolTip(i18n("Invert y axis and change 0 point"));
155     rectBColor->setToolTip(i18n("Select fill color"));
156     rectFColor->setToolTip(i18n("Select border color"));
157     rectBAlpha->setToolTip(i18n("Fill transparency"));
158     rectFAlpha->setToolTip(i18n("Border transparency"));
159     zoom_slider->setToolTip(i18n("Zoom"));
160     buttonRealSize->setToolTip(i18n("Original size (1:1)"));
161     buttonFitZoom->setToolTip(i18n("Fit zoom"));
162     kcolorbutton->setToolTip(i18n("Select background color"));
163     horizontalSlider->setToolTip(i18n("Background Transparency"));
164
165     itemhcenter->setIcon(KIcon("kdenlive-align-hor"));
166     itemhcenter->setToolTip(i18n("Align item horizontally"));
167     itemvcenter->setIcon(KIcon("kdenlive-align-vert"));
168     itemvcenter->setToolTip(i18n("Align item vertically"));
169
170     QHBoxLayout *layout = new QHBoxLayout;
171     frame_toolbar->setLayout(layout);
172     layout->setContentsMargins(2, 2, 2, 2);
173     QToolBar *m_toolbar = new QToolBar("titleToolBar", this);
174
175     m_buttonCursor = m_toolbar->addAction(KIcon("transform-move"), QString());
176     m_buttonCursor->setCheckable(true);
177     m_buttonCursor->setShortcut(Qt::ALT + Qt::Key_S);
178     m_buttonCursor->setToolTip(i18n("Selection Tool") + ' ' + m_buttonCursor->shortcut().toString());
179     connect(m_buttonCursor, SIGNAL(triggered()), this, SLOT(slotSelectTool()));
180
181     m_buttonText = m_toolbar->addAction(KIcon("insert-text"), QString());
182     m_buttonText->setCheckable(true);
183     m_buttonText->setShortcut(Qt::ALT + Qt::Key_T);
184     m_buttonText->setToolTip(i18n("Add Text") + ' ' + m_buttonText->shortcut().toString());
185     connect(m_buttonText, SIGNAL(triggered()), this, SLOT(slotTextTool()));
186
187     m_buttonRect = m_toolbar->addAction(KIcon("kdenlive-insert-rect"), QString());
188     m_buttonRect->setCheckable(true);
189     m_buttonRect->setShortcut(Qt::ALT + Qt::Key_R);
190     m_buttonRect->setToolTip(i18n("Add Rectangle") + ' ' + m_buttonRect->shortcut().toString());
191     connect(m_buttonRect, SIGNAL(triggered()), this, SLOT(slotRectTool()));
192
193     m_buttonImage = m_toolbar->addAction(KIcon("insert-image"), QString());
194     m_buttonImage->setCheckable(false);
195     m_buttonImage->setShortcut(Qt::ALT + Qt::Key_I);
196     m_buttonImage->setToolTip(i18n("Add Image") + ' ' + m_buttonImage->shortcut().toString());
197     connect(m_buttonImage, SIGNAL(triggered()), this, SLOT(slotImageTool()));
198
199     m_toolbar->addSeparator();
200
201     m_buttonLoad = m_toolbar->addAction(KIcon("document-open"), i18n("Open Document"));
202     m_buttonLoad->setCheckable(false);
203     m_buttonLoad->setShortcut(Qt::CTRL + Qt::Key_O);
204     connect(m_buttonLoad, SIGNAL(triggered()), this, SLOT(loadTitle()));
205
206     m_buttonSave = m_toolbar->addAction(KIcon("document-save-as"), i18n("Save As"));
207     m_buttonSave->setCheckable(false);
208     m_buttonSave->setShortcut(Qt::CTRL + Qt::Key_S);
209     connect(m_buttonSave, SIGNAL(triggered()), this, SLOT(saveTitle()));
210
211     layout->addWidget(m_toolbar);
212
213     // initialize graphic scene
214     m_scene = new GraphicsSceneRectMove(this);
215     graphicsView->setScene(m_scene);
216     m_titledocument.setScene(m_scene);
217     connect(m_scene, SIGNAL(changed(QList<QRectF>)), this, SLOT(slotChanged()));
218
219     // a gradient background
220     /*QRadialGradient *gradient = new QRadialGradient(0, 0, 10);
221     gradient->setSpread(QGradient::ReflectSpread);
222     scene->setBackgroundBrush(*gradient);*/
223
224     m_frameImage = new QGraphicsPixmapItem();
225     QTransform qtrans;
226     qtrans.scale(2.0, 2.0);
227     m_frameImage->setTransform(qtrans);
228     m_frameImage->setZValue(-1200);
229     m_frameImage->setFlags(QGraphicsItem::ItemClipsToShape);
230     displayBackgroundFrame();
231     graphicsView->scene()->addItem(m_frameImage);
232
233     connect(m_scene, SIGNAL(selectionChanged()), this , SLOT(selectionChanged()));
234     connect(m_scene, SIGNAL(itemMoved()), this , SLOT(selectionChanged()));
235     connect(m_scene, SIGNAL(sceneZoom(bool)), this , SLOT(slotZoom(bool)));
236     connect(m_scene, SIGNAL(actionFinished()), this , SLOT(slotSelectTool()));
237     //connect(m_scene, SIGNAL(actionFinished()), this , SLOT(selectionChanged()));
238     connect(m_scene, SIGNAL(newRect(QGraphicsRectItem *)), this , SLOT(slotNewRect(QGraphicsRectItem *)));
239     connect(m_scene, SIGNAL(newText(QGraphicsTextItem *)), this , SLOT(slotNewText(QGraphicsTextItem *)));
240     connect(zoom_slider, SIGNAL(valueChanged(int)), this , SLOT(slotUpdateZoom(int)));
241
242     QPen framepen(Qt::DotLine);
243     framepen.setColor(Qt::red);
244
245     m_frameBorder = new QGraphicsRectItem(QRectF(0, 0, m_frameWidth, m_frameHeight));
246     m_frameBorder->setPen(framepen);
247     m_frameBorder->setZValue(-1100);
248     m_frameBorder->setBrush(Qt::transparent);
249     m_frameBorder->setFlags(QGraphicsItem::ItemClipsToShape);
250     graphicsView->scene()->addItem(m_frameBorder);
251
252     // mbd: load saved settings
253     readChoices();
254
255     initViewports();
256     QTimer::singleShot(500, this, SLOT(slotAdjustZoom()));
257     graphicsView->show();
258     //graphicsView->setRenderHint(QPainter::Antialiasing);
259     graphicsView->setInteractive(true);
260     //graphicsView->resize(400, 300);
261     kDebug() << "// TITLE WIDGWT: " << graphicsView->viewport()->width() << "x" << graphicsView->viewport()->height();
262     //toolBox->setItemEnabled(2, false);
263     if (!url.isEmpty()) {
264         m_count = m_titledocument.loadDocument(url, m_startViewport, m_endViewport) + 1;
265         slotSelectTool();
266     } else {
267         slotTextTool();
268     }
269
270     showToolbars(TITLE_NONE);
271 }
272
273 TitleWidget::~TitleWidget()
274 {
275     delete m_buttonRect;
276     delete m_buttonText;
277     delete m_buttonImage;
278     delete m_buttonCursor;
279     delete m_buttonSave;
280     delete m_buttonLoad;
281     delete m_unicodeAction;
282
283     delete m_unicodeDialog;
284     delete m_frameBorder;
285     delete m_frameImage;
286     delete m_startViewport;
287     delete m_endViewport;
288     delete m_scene;
289     delete m_signalMapper;
290 }
291
292 //static
293 QStringList TitleWidget::getFreeTitleInfo(const KUrl &projectUrl, bool isClone)
294 {
295     QStringList result;
296     QString titlePath = projectUrl.path(KUrl::AddTrailingSlash) + "titles/";
297     KStandardDirs::makeDir(titlePath);
298     titlePath.append((isClone == false) ? "title" : "clone");
299     int counter = 0;
300     QString path;
301     while (path.isEmpty() || QFile::exists(path)) {
302         counter++;
303         path = titlePath + QString::number(counter).rightJustified(3, '0', false) + ".png";
304     }
305     result.append(((isClone == false) ? i18n("Title") : i18n("Clone")) + ' ' + QString::number(counter).rightJustified(3, '0', false));
306     result.append(path);
307     return result;
308 }
309
310 QString TitleWidget::getTitleResourceFromName(const KUrl &projectUrl, const QString &titleName)
311 {
312     QStringList result;
313     QString titlePath = projectUrl.path(KUrl::AddTrailingSlash) + "titles/";
314     KStandardDirs::makeDir(titlePath);
315     return titlePath + titleName + ".png";
316 }
317
318 //virtual
319 void TitleWidget::resizeEvent(QResizeEvent * /*event*/)
320 {
321     //slotAdjustZoom();
322 }
323
324 void TitleWidget::slotTextTool()
325 {
326     m_scene->setTool(TITLE_TEXT);
327     showToolbars(TITLE_TEXT);
328     checkButton(TITLE_TEXT);
329 }
330
331 void TitleWidget::slotRectTool()
332 {
333     m_scene->setTool(TITLE_RECTANGLE);
334     showToolbars(TITLE_RECTANGLE);
335     checkButton(TITLE_RECTANGLE);
336 }
337
338 void TitleWidget::slotSelectTool()
339 {
340     m_scene->setTool(TITLE_SELECT);
341
342     // Find out which toolbars need to be shown, depending on selected item
343     TITLETOOL t = TITLE_SELECT;
344     QList<QGraphicsItem *> l = graphicsView->scene()->selectedItems();
345     if (l.size() > 0) {
346         switch (l.at(0)->type()) {
347         case TEXTITEM:
348             t = TITLE_TEXT;
349             break;
350         case RECTITEM:
351             t = TITLE_RECTANGLE;
352             break;
353         case IMAGEITEM:
354             t = TITLE_IMAGE;
355             break;
356         }
357     }
358     enableToolbars(t);
359     showToolbars(t);
360
361     if (l.size() > 0) {
362         updateCoordinates(l.at(0));
363         updateDimension(l.at(0));
364         updateRotZoom(l.at(0));
365     }
366
367     checkButton(TITLE_SELECT);
368 }
369
370 void TitleWidget::slotImageTool()
371 {
372     KUrl url = KFileDialog::getOpenUrl(KUrl(), "*.svg *.png *.jpg *.jpeg *.gif *.raw", this, i18n("Load Image"));
373     if (!url.isEmpty()) {
374         if (url.path().endsWith(".svg")) {
375             QGraphicsSvgItem *svg = new QGraphicsSvgItem(url.toLocalFile());
376             svg->setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable);
377             svg->setZValue(m_count++);
378             svg->setData(Qt::UserRole, url.path());
379             graphicsView->scene()->addItem(svg);
380         } else {
381             QPixmap pix(url.path());
382             QGraphicsPixmapItem *image = new QGraphicsPixmapItem(pix);
383             image->setShapeMode(QGraphicsPixmapItem::BoundingRectShape);
384             image->setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable);
385             image->setData(Qt::UserRole, url.path());
386             image->setZValue(m_count++);
387             graphicsView->scene()->addItem(image);
388         }
389     }
390     m_scene->setTool(TITLE_SELECT);
391     showToolbars(TITLE_SELECT);
392     checkButton(TITLE_NONE);
393 }
394
395 void TitleWidget::showToolbars(TITLETOOL toolType)
396 {
397     switch (toolType) {
398     case TITLE_TEXT:
399         rect_properties->setHidden(true);
400         image_properties->setHidden(true);
401         no_properties->setHidden(true);
402         text_properties->setHidden(false);
403         break;
404     case TITLE_RECTANGLE:
405         image_properties->setHidden(true);
406         no_properties->setHidden(true);
407         text_properties->setHidden(true);
408         rect_properties->setHidden(false);
409         break;
410     case TITLE_IMAGE:
411         no_properties->setHidden(true);
412         text_properties->setHidden(true);
413         rect_properties->setHidden(true);
414         image_properties->setHidden(false);
415         break;
416     default:
417         text_properties->setHidden(true);
418         rect_properties->setHidden(true);
419         image_properties->setHidden(true);
420         no_properties->setHidden(false);
421         break;
422     }
423 }
424
425 void TitleWidget::enableToolbars(TITLETOOL toolType)
426 {
427     // TITLETOOL is defined in graphicsscenerectmove.h
428     bool bFrame = false;
429     bool bText = false;
430     bool bRect = false;
431     bool bImage = false;
432     bool bValue_w = false;
433     bool bValue_h = false;
434
435     switch (toolType) {
436     case TITLE_SELECT:
437         break;
438     case TITLE_TEXT:
439         bFrame = true;
440         bText = true;
441         break;
442     case TITLE_RECTANGLE:
443         bFrame = true;
444         bRect = true;
445         bValue_w = true;
446         bValue_h = true;
447         break;
448     case TITLE_IMAGE:
449         bFrame = true;
450         bValue_w = true;
451         bValue_h = true;
452         bImage = true;
453         break;
454     default:
455         break;
456     }
457     frame_properties->setEnabled(bFrame);
458     text_properties->setEnabled(bText);
459     rect_properties->setEnabled(bRect);
460     image_properties->setEnabled(bImage);
461     value_w->setEnabled(bValue_w);
462     value_h->setEnabled(bValue_h);
463 }
464
465 void TitleWidget::checkButton(TITLETOOL toolType)
466 {
467     bool bSelect = false;
468     bool bText = false;
469     bool bRect = false;
470     bool bImage = false;
471
472     switch (toolType) {
473     case TITLE_SELECT:
474         bSelect = true;
475         break;
476     case TITLE_TEXT:
477         bText = true;
478         break;
479     case TITLE_RECTANGLE:
480         bRect = true;
481         break;
482     case TITLE_IMAGE:
483         bImage = true;
484         break;
485     case TITLE_NONE:
486         break;
487     }
488
489     m_buttonCursor->setChecked(bSelect);
490     m_buttonText->setChecked(bText);
491     m_buttonRect->setChecked(bRect);
492     m_buttonImage->setChecked(bImage);
493 }
494
495 void TitleWidget::displayBackgroundFrame()
496 {
497     if (!displayBg->isChecked()) {
498         QPixmap bg(m_frameWidth / 2, m_frameHeight / 2);
499         QPixmap pattern(20, 20);
500         pattern.fill();
501         QPainter p;
502         p.begin(&pattern);
503         p.fillRect(QRect(0, 0, 10, 10), QColor(210, 210, 210));
504         p.fillRect(QRect(10, 10, 20, 20), QColor(210, 210, 210));
505         p.end();
506         QBrush br(pattern);
507
508         p.begin(&bg);
509         p.fillRect(bg.rect(), br);
510         p.end();
511         m_frameImage->setPixmap(bg);
512     } else {
513         m_frameImage->setPixmap(m_render->extractFrame((int) m_render->seekPosition().frames(m_render->fps()), m_frameWidth / 2, m_frameHeight / 2));
514     }
515 }
516
517 void TitleWidget::initViewports()
518 {
519     m_startViewport = new QGraphicsPolygonItem(QPolygonF(QRectF(0, 0, 0, 0)));
520     m_endViewport = new QGraphicsPolygonItem(QPolygonF(QRectF(0, 0, 0, 0)));
521
522     QPen startpen(Qt::DotLine);
523     QPen endpen(Qt::DashDotLine);
524     startpen.setColor(QColor(100, 200, 100, 140));
525     endpen.setColor(QColor(200, 100, 100, 140));
526
527     m_startViewport->setPen(startpen);
528     m_endViewport->setPen(endpen);
529
530     startViewportSize->setValue(100);
531     endViewportSize->setValue(100);
532
533     m_startViewport->setZValue(-1000);
534     m_endViewport->setZValue(-1000);
535
536     m_startViewport->setFlags(/*QGraphicsItem::ItemIsMovable|*/QGraphicsItem::ItemIsSelectable);
537     m_endViewport->setFlags(/*QGraphicsItem::ItemIsMovable|*/QGraphicsItem::ItemIsSelectable);
538
539     graphicsView->scene()->addItem(m_startViewport);
540     graphicsView->scene()->addItem(m_endViewport);
541 }
542
543 void TitleWidget::slotUpdateZoom(int pos)
544 {
545     m_scene->setZoom((double) pos / 100);
546     zoom_label->setText(QString::number(pos) + '%');
547 }
548
549 void TitleWidget::slotZoom(bool up)
550 {
551     int pos = zoom_slider->value();
552     if (up) pos++;
553     else pos--;
554     zoom_slider->setValue(pos);
555 }
556
557 void TitleWidget::slotAdjustZoom()
558 {
559     /*double scalex = graphicsView->width() / (double)(m_frameWidth * 1.2);
560     double scaley = graphicsView->height() / (double)(m_frameHeight * 1.2);
561     if (scalex > scaley) scalex = scaley;
562     int zoompos = (int)(scalex * 7 + 0.5);*/
563     graphicsView->fitInView(m_frameBorder, Qt::KeepAspectRatio);
564     int zoompos = graphicsView->matrix().m11() * 100;
565     zoom_slider->setValue(zoompos);
566     graphicsView->centerOn(m_frameBorder);
567 }
568
569 void TitleWidget::slotZoomOneToOne()
570 {
571     zoom_slider->setValue(100);
572     graphicsView->centerOn(m_frameBorder);
573 }
574
575 void TitleWidget::slotNewRect(QGraphicsRectItem * rect)
576 {
577     updateAxisButtons(rect); // back to default
578
579     QColor f = rectFColor->color();
580     f.setAlpha(rectFAlpha->value());
581     QPen penf(f);
582     penf.setWidth(rectLineWidth->value());
583     rect->setPen(penf);
584     QColor b = rectBColor->color();
585     b.setAlpha(rectBAlpha->value());
586     rect->setBrush(QBrush(b));
587     rect->setZValue(m_count++);
588     //setCurrentItem(rect);
589     //graphicsView->setFocus();
590 }
591
592 void TitleWidget::slotNewText(QGraphicsTextItem *tt)
593 {
594     updateAxisButtons(tt); // back to default
595
596     QFont font = font_family->currentFont();
597     font.setPixelSize(font_size->value());
598     // mbd: issue 551:
599     font.setWeight(font_weight_box->itemData(font_weight_box->currentIndex()).toInt());
600     font.setItalic(buttonItalic->isChecked());
601     font.setUnderline(buttonUnder->isChecked());
602
603     tt->setFont(font);
604     QColor color = fontColorButton->color();
605     color.setAlpha(textAlpha->value());
606     tt->setDefaultTextColor(color);
607     tt->setZValue(m_count++);
608     setCurrentItem(tt);
609 }
610
611 void TitleWidget::setFontBoxWeight(int weight)
612 {
613     int index = font_weight_box->findData(weight);
614     if (index < 0) {
615         index = font_weight_box->findData(QFont::Normal);
616     }
617     font_weight_box->setCurrentIndex(index);
618 }
619
620 void TitleWidget::setCurrentItem(QGraphicsItem *item)
621 {
622     m_scene->setSelectedItem(item);
623 }
624
625 void TitleWidget::zIndexChanged(int v)
626 {
627     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
628     if (l.size() >= 1) {
629         l[0]->setZValue(v);
630     }
631 }
632
633 void TitleWidget::selectionChanged()
634 {
635     if (m_scene->tool() != TITLE_SELECT) return;
636     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
637     //toolBox->setItemEnabled(2, false);
638     //toolBox->setItemEnabled(3, false);
639     value_x->blockSignals(true);
640     value_y->blockSignals(true);
641     value_w->blockSignals(true);
642     value_h->blockSignals(true);
643     itemzoom->blockSignals(true);
644     itemrotate->blockSignals(true);
645     if (l.size() == 0) {
646         bool blockX = !origin_x_left->signalsBlocked();
647         bool blockY = !origin_y_top->signalsBlocked();
648         if (blockX) origin_x_left->blockSignals(true);
649         if (blockY) origin_y_top->blockSignals(true);
650         origin_x_left->setChecked(false);
651         origin_y_top->setChecked(false);
652         updateTextOriginX();
653         updateTextOriginY();
654         enableToolbars(TITLE_NONE);
655         if (blockX) origin_x_left->blockSignals(false);
656         if (blockY) origin_y_top->blockSignals(false);
657     } else if (l.size() == 1) {
658         if (l.at(0)->type() == TEXTITEM) {
659             showToolbars(TITLE_TEXT);
660             QGraphicsTextItem* i = static_cast <QGraphicsTextItem *>(l.at(0));
661             //if (l[0]->hasFocus())
662             toolBox->setCurrentIndex(0);
663             //toolBox->setItemEnabled(2, true);
664             font_size->blockSignals(true);
665             font_family->blockSignals(true);
666             font_weight_box->blockSignals(true);
667             buttonItalic->blockSignals(true);
668             buttonUnder->blockSignals(true);
669             fontColorButton->blockSignals(true);
670             textAlpha->blockSignals(true);
671             buttonAlignLeft->blockSignals(true);
672             buttonAlignRight->blockSignals(true);
673             buttonAlignNone->blockSignals(true);
674             buttonAlignCenter->blockSignals(true);
675
676             QFont font = i->font();
677             font_family->setCurrentFont(font);
678             font_size->setValue(font.pixelSize());
679             buttonItalic->setChecked(font.italic());
680             buttonUnder->setChecked(font.underline());
681             setFontBoxWeight(font.weight());
682
683             QColor color = i->defaultTextColor();
684             fontColorButton->setColor(color);
685             textAlpha->setValue(color.alpha());
686
687             QTextCursor cur = i->textCursor();
688             QTextBlockFormat format = cur.blockFormat();
689             if (i->textWidth() == -1) buttonAlignNone->setChecked(true);
690             else if (format.alignment() == Qt::AlignHCenter) buttonAlignCenter->setChecked(true);
691             else if (format.alignment() == Qt::AlignRight) buttonAlignRight->setChecked(true);
692             else if (format.alignment() == Qt::AlignLeft) buttonAlignLeft->setChecked(true);
693
694             font_size->blockSignals(false);
695             font_family->blockSignals(false);
696             font_weight_box->blockSignals(false);
697             buttonItalic->blockSignals(false);
698             buttonUnder->blockSignals(false);
699             fontColorButton->blockSignals(false);
700             textAlpha->blockSignals(false);
701             buttonAlignLeft->blockSignals(false);
702             buttonAlignRight->blockSignals(false);
703             buttonAlignNone->blockSignals(false);
704             buttonAlignCenter->blockSignals(false);
705
706             updateAxisButtons(i);
707             updateCoordinates(i);
708             updateDimension(i);
709             enableToolbars(TITLE_TEXT);
710
711         } else if ((l.at(0))->type() == RECTITEM) {
712             showToolbars(TITLE_RECTANGLE);
713             settingUp = true;
714             QGraphicsRectItem *rec = static_cast <QGraphicsRectItem *>(l.at(0));
715             toolBox->setCurrentIndex(0);
716             //toolBox->setItemEnabled(3, true);
717             rectFAlpha->setValue(rec->pen().color().alpha());
718             rectBAlpha->setValue(rec->brush().color().alpha());
719             //kDebug() << rec->brush().color().alpha();
720             QColor fcol = rec->pen().color();
721             QColor bcol = rec->brush().color();
722             //fcol.setAlpha(255);
723             //bcol.setAlpha(255);
724             rectFColor->setColor(fcol);
725             rectBColor->setColor(bcol);
726             settingUp = false;
727             rectLineWidth->setValue(rec->pen().width());
728
729             updateAxisButtons(l.at(0));
730             updateCoordinates(rec);
731             updateDimension(rec);
732             enableToolbars(TITLE_RECTANGLE);
733
734         } else if (l.at(0)->type() == IMAGEITEM) {
735             showToolbars(TITLE_IMAGE);
736
737             updateCoordinates(l.at(0));
738             updateDimension(l.at(0));
739
740             enableToolbars(TITLE_IMAGE);
741
742         } else {
743             //toolBox->setCurrentIndex(0);
744             showToolbars(TITLE_NONE);
745             enableToolbars(TITLE_NONE);
746             /*frame_properties->setEnabled(false);
747             text_properties->setEnabled(false);
748             rect_properties->setEnabled(false);*/
749         }
750         zValue->setValue((int)l.at(0)->zValue());
751         itemzoom->setValue((int)(m_transformations.value(l.at(0)).scalex * 100.0 + 0.5));
752         itemrotate->setValue((int)(m_transformations.value(l.at(0)).rotate));
753         value_x->blockSignals(false);
754         value_y->blockSignals(false);
755         value_w->blockSignals(false);
756         value_h->blockSignals(false);
757         itemzoom->blockSignals(false);
758         itemrotate->blockSignals(false);
759     }
760 }
761
762 void TitleWidget::slotValueChanged(int type)
763 {
764     QList<QGraphicsItem *> l = graphicsView->scene()->selectedItems();
765     if (l.size() > 0 && l.at(0)->type() == IMAGEITEM) {
766
767         int val = 0;
768         switch (type) {
769         case ValueWidth:
770             val = value_w->value();
771             break;
772         case ValueHeight:
773             val = value_h->value();
774             break;
775         }
776
777         QGraphicsItem *i = l.at(0);
778         Transform t = m_transformations.value(i);
779
780         // Ratio width:height
781         double phi = (double) i->boundingRect().width() / i->boundingRect().height();
782         double alpha = (double) t.rotate / 180.0 * M_PI;
783
784         // New length
785         double length = val;
786
787         // Scaling factor
788         double scale = 1;
789
790         switch (type) {
791         case ValueWidth:
792             // Add 0.5 because otherwise incrementing by 1 might have no effect
793             length = val / (cos(alpha) + 1 / phi * sin(alpha)) + 0.5;
794             scale = length / i->boundingRect().width();
795             break;
796         case ValueHeight:
797             length = val / (phi * sin(alpha) + cos(alpha)) + 0.5;
798             scale = length / i->boundingRect().height();
799             break;
800         }
801
802         t.scalex = scale;
803         t.scaley = scale;
804         QTransform qtrans;
805         qtrans.scale(scale, scale);
806         qtrans.rotate(t.rotate);
807         i->setTransform(qtrans);
808         m_transformations[i] = t;
809
810         updateDimension(i);
811         updateRotZoom(i);
812     }
813 }
814
815 /** \brief Updates position/size of the selected item when a value
816  * of an item (coordinates, size) has changed */
817 void TitleWidget::slotAdjustSelectedItem()
818 {
819     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
820     if (l.size() >= 1) {
821         if (l.at(0)->type() == RECTITEM) {
822             //rect item
823             QGraphicsRectItem *rec = static_cast <QGraphicsRectItem *>(l.at(0));
824             updatePosition(rec);
825             rec->setRect(QRect(0, 0, value_w->value(), value_h->value()));
826         } else if (l.at(0)->type() == TEXTITEM) {
827             //text item
828             updatePosition(l.at(0));
829         } else if (l.at(0)->type() == IMAGEITEM) {
830             //image item
831             updatePosition(l.at(0));
832         }
833     }
834 }
835
836 /** \brief Updates width/height int the text fields, regarding transformation matrix */
837 void TitleWidget::updateDimension(QGraphicsItem *i)
838 {
839     value_w->blockSignals(true);
840     value_h->blockSignals(true);
841
842
843     if (i->type() == IMAGEITEM) {
844         // Get multipliers for rotation/scaling
845
846         /*Transform t = m_transformations.value(i);
847         QRectF r = i->boundingRect();
848         int width = (int) ( abs(r.width()*t.scalex * cos(t.rotate/180.0*M_PI))
849                     + abs(r.height()*t.scaley * sin(t.rotate/180.0*M_PI)) );
850         int height = (int) ( abs(r.height()*t.scaley * cos(t.rotate/180*M_PI))
851                     + abs(r.width()*t.scalex * sin(t.rotate/180*M_PI)) );*/
852
853         value_w->setValue(i->sceneBoundingRect().width());
854         value_h->setValue(i->sceneBoundingRect().height());
855     } else if (i->type() == RECTITEM) {
856         QGraphicsRectItem *r = static_cast <QGraphicsRectItem *>(i);
857         value_w->setValue((int) r->rect().width());
858         value_h->setValue((int) r->rect().height());
859     } else if (i->type() == TEXTITEM) {
860         QGraphicsTextItem *t = static_cast <QGraphicsTextItem *>(i);
861         value_w->setValue((int) t->boundingRect().width());
862         value_h->setValue((int) t->boundingRect().height());
863     }
864
865     value_w->blockSignals(false);
866     value_h->blockSignals(false);
867 }
868
869 /** \brief Updates the coordinates in the text fields from the item */
870 void TitleWidget::updateCoordinates(QGraphicsItem *i)
871 {
872     // Block signals emitted by this method
873     value_x->blockSignals(true);
874     value_y->blockSignals(true);
875
876     if (i->type() == TEXTITEM) {
877
878         QGraphicsTextItem *rec = static_cast <QGraphicsTextItem *>(i);
879
880         // Set the correct x coordinate value
881         if (origin_x_left->isChecked()) {
882             // Origin (0 point) is at m_frameWidth, coordinate axis is inverted
883             value_x->setValue((int)(m_frameWidth - rec->pos().x() - rec->boundingRect().width()));
884         } else {
885             // Origin is at 0 (default)
886             value_x->setValue((int) rec->pos().x());
887         }
888
889         // Same for y
890         if (origin_y_top->isChecked()) {
891             value_y->setValue((int)(m_frameHeight - rec->pos().y() - rec->boundingRect().height()));
892         } else {
893             value_y->setValue((int) rec->pos().y());
894         }
895
896     } else if (i->type() == RECTITEM) {
897
898         QGraphicsRectItem *rec = static_cast <QGraphicsRectItem *>(i);
899
900         if (origin_x_left->isChecked()) {
901             // Origin (0 point) is at m_frameWidth
902             value_x->setValue((int)(m_frameWidth - rec->pos().x() - rec->rect().width()));
903         } else {
904             // Origin is at 0 (default)
905             value_x->setValue((int) rec->pos().x());
906         }
907
908         if (origin_y_top->isChecked()) {
909             value_y->setValue((int)(m_frameHeight - rec->pos().y() - rec->rect().height()));
910         } else {
911             value_y->setValue((int) rec->pos().y());
912         }
913
914     } else if (i->type() == IMAGEITEM) {
915
916         if (origin_x_left->isChecked()) {
917             value_x->setValue((int)(m_frameWidth - i->pos().x() - i->sceneBoundingRect().width()));
918         } else {
919             value_x->setValue((int) i->pos().x());
920         }
921
922         if (origin_y_top->isChecked()) {
923             value_y->setValue((int)(m_frameHeight - i->pos().y() - i->sceneBoundingRect().height()));
924         } else {
925             value_y->setValue((int) i->pos().y());
926         }
927
928     }
929
930     // Stop blocking signals now
931     value_x->blockSignals(false);
932     value_y->blockSignals(false);
933 }
934
935 void TitleWidget::updateRotZoom(QGraphicsItem *i)
936 {
937     itemzoom->blockSignals(true);
938     itemrotate->blockSignals(false);
939
940     Transform t = m_transformations.value(i);
941     itemzoom->setValue((int)(t.scalex * 100.0 + 0.5));
942     itemrotate->setValue((int)(t.rotate));
943
944     itemzoom->blockSignals(false);
945     itemrotate->blockSignals(false);
946 }
947
948 /** \brief Updates the position of an item by reading coordinates from the text fields */
949 void TitleWidget::updatePosition(QGraphicsItem *i)
950 {
951     if (i->type() == TEXTITEM) {
952         QGraphicsTextItem *rec = static_cast <QGraphicsTextItem *>(i);
953
954         int posX;
955         if (origin_x_left->isChecked()) {
956             /* Origin of the x axis is at m_frameWidth,
957              * and distance from right border of the item to the right
958              * border of the frame is taken.
959              * See comment to slotOriginXClicked().
960              */
961             posX = m_frameWidth - value_x->value() - rec->boundingRect().width();
962         } else {
963             posX = value_x->value();
964         }
965
966         int posY;
967         if (origin_y_top->isChecked()) {
968             /* Same for y axis */
969             posY = m_frameHeight - value_y->value() - rec->boundingRect().height();
970         } else {
971             posY = value_y->value();
972         }
973
974         rec->setPos(posX, posY);
975
976     } else if (i->type() == RECTITEM) {
977
978         QGraphicsRectItem *rec = static_cast <QGraphicsRectItem *>(i);
979
980         int posX;
981         if (origin_x_left->isChecked()) {
982             posX = m_frameWidth - value_x->value() - rec->rect().width();
983         } else {
984             posX = value_x->value();
985         }
986
987         int posY;
988         if (origin_y_top->isChecked()) {
989             posY = m_frameHeight - value_y->value() - rec->rect().height();
990         } else {
991             posY = value_y->value();
992         }
993
994         rec->setPos(posX, posY);
995
996     } else if (i->type() == IMAGEITEM) {
997         int posX;
998         if (origin_x_left->isChecked()) {
999             // Use the sceneBoundingRect because this also regards transformations like zoom
1000             posX = m_frameWidth - value_x->value() - i->sceneBoundingRect().width();
1001         } else {
1002             posX = value_x->value();
1003         }
1004
1005         int posY;
1006         if (origin_y_top->isChecked()) {
1007             posY = m_frameHeight - value_y->value() - i->sceneBoundingRect().height();
1008         } else {
1009             posY = value_y->value();
1010         }
1011
1012         i->setPos(posX, posY);
1013
1014     }
1015
1016 }
1017
1018 void TitleWidget::updateTextOriginX()
1019 {
1020     if (origin_x_left->isChecked()) {
1021         origin_x_left->setText(i18n("\u2212X"));
1022     } else {
1023         origin_x_left->setText(i18n("+X"));
1024     }
1025 }
1026
1027 void TitleWidget::slotOriginXClicked()
1028 {
1029     // Update the text displayed on the button.
1030     updateTextOriginX();
1031
1032     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1033     if (l.size() >= 1) {
1034         updateCoordinates(l.at(0));
1035
1036         // Remember x axis setting
1037         l.at(0)->setData(TitleDocument::OriginXLeft, origin_x_left->isChecked() ?
1038                          TitleDocument::AxisInverted : TitleDocument::AxisDefault);
1039     }
1040     graphicsView->setFocus();
1041 }
1042
1043 void TitleWidget::updateTextOriginY()
1044 {
1045     if (origin_y_top->isChecked()) {
1046         origin_y_top->setText(i18n("\u2212Y"));
1047     } else {
1048         origin_y_top->setText(i18n("+Y"));
1049     }
1050 }
1051
1052 void TitleWidget::slotOriginYClicked()
1053 {
1054     // Update the text displayed on the button.
1055     updateTextOriginY();
1056
1057     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1058     if (l.size() >= 1) {
1059         updateCoordinates(l.at(0));
1060
1061         l.at(0)->setData(TitleDocument::OriginYTop, origin_y_top->isChecked() ?
1062                          TitleDocument::AxisInverted : TitleDocument::AxisDefault);
1063
1064     }
1065     graphicsView->setFocus();
1066 }
1067
1068 void TitleWidget::updateAxisButtons(QGraphicsItem *i)
1069 {
1070     int xAxis = i->data(TitleDocument::OriginXLeft).toInt();
1071     int yAxis = i->data(TitleDocument::OriginYTop).toInt();
1072     origin_x_left->blockSignals(true);
1073     origin_y_top->blockSignals(true);
1074
1075     if (xAxis == TitleDocument::AxisInverted) {
1076         origin_x_left->setChecked(true);
1077     } else {
1078         origin_x_left->setChecked(false);
1079     }
1080     updateTextOriginX();
1081
1082     if (yAxis == TitleDocument::AxisInverted) {
1083         origin_y_top->setChecked(true);
1084     } else {
1085         origin_y_top->setChecked(false);
1086     }
1087     updateTextOriginY();
1088
1089     origin_x_left->blockSignals(false);
1090     origin_y_top->blockSignals(false);
1091 }
1092
1093 void TitleWidget::slotChangeBackground()
1094 {
1095     QColor color = kcolorbutton->color();
1096     color.setAlpha(horizontalSlider->value());
1097     m_frameBorder->setBrush(QBrush(color));
1098 }
1099
1100 /**
1101  * Something (yeah) has changed in our QGraphicsScene.
1102  */
1103 void TitleWidget::slotChanged()
1104 {
1105     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1106     if (l.size() >= 1 && l.at(0)->type() == TEXTITEM) {
1107         textChanged(static_cast <QGraphicsTextItem *>(l.at(0)));
1108     }
1109 }
1110
1111 /**
1112  * If the user has set origin_x_left (everything also for y),
1113  * we need to look whether a text element has been selected. If yes,
1114  * we need to ensure that the right border of the text field
1115  * remains fixed also when some text has been entered.
1116  *
1117  * This is also known as right-justified, with the difference that
1118  * it is not valid for text but for its boundingRect. Text may still
1119  * be left-justified.
1120  */
1121 void TitleWidget::textChanged(QGraphicsTextItem *i)
1122 {
1123
1124     updateDimension(i);
1125
1126     if (origin_x_left->isChecked() || origin_y_top->isChecked()) {
1127
1128         if (!i->toPlainText().isEmpty()) {
1129             updatePosition(i);
1130         } else {
1131             /*
1132              * Don't do anything if the string is empty. If the position
1133              * would be updated here, a newly created text field would
1134              * be set to the position of the last selected text field.
1135              */
1136         }
1137     }
1138 }
1139
1140 void TitleWidget::slotInsertUnicode()
1141 {
1142     m_unicodeDialog->exec();
1143 }
1144
1145 void TitleWidget::slotInsertUnicodeString(QString text)
1146 {
1147     QList<QGraphicsItem *> l = graphicsView->scene()->selectedItems();
1148     if (l.size() > 0) {
1149         if (l.at(0)->type() == TEXTITEM) {
1150             QGraphicsTextItem *t = static_cast <QGraphicsTextItem *>(l.at(0));
1151             t->textCursor().insertText(text);
1152         }
1153     }
1154 }
1155
1156 void TitleWidget::slotUpdateText()
1157 {
1158     QFont font = font_family->currentFont();
1159     font.setPixelSize(font_size->value());
1160     font.setItalic(buttonItalic->isChecked());
1161     font.setUnderline(buttonUnder->isChecked());
1162     font.setWeight(font_weight_box->itemData(font_weight_box->currentIndex()).toInt());
1163     QColor color = fontColorButton->color();
1164     color.setAlpha(textAlpha->value());
1165
1166     QGraphicsTextItem* item = NULL;
1167     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1168     if (l.size() == 1 && l.at(0)->type() == TEXTITEM) {
1169         item = static_cast <QGraphicsTextItem *>(l.at(0));
1170     }
1171     if (!item) return;
1172     //if (item->textCursor().selection ().isEmpty())
1173     QTextCursor cur = item->textCursor();
1174     QTextBlockFormat format = cur.blockFormat();
1175     if (buttonAlignLeft->isChecked() || buttonAlignCenter->isChecked() || buttonAlignRight->isChecked()) {
1176         item->setTextWidth(item->boundingRect().width());
1177         if (buttonAlignCenter->isChecked()) format.setAlignment(Qt::AlignHCenter);
1178         else if (buttonAlignRight->isChecked()) format.setAlignment(Qt::AlignRight);
1179         else if (buttonAlignLeft->isChecked()) format.setAlignment(Qt::AlignLeft);
1180     } else {
1181         format.setAlignment(Qt::AlignLeft);
1182         item->setTextWidth(-1);
1183     }
1184
1185     {
1186         item->setFont(font);
1187         item->setDefaultTextColor(color);
1188         cur.select(QTextCursor::Document);
1189         cur.setBlockFormat(format);
1190         item->setTextCursor(cur);
1191         cur.clearSelection();
1192         item->setTextCursor(cur);
1193
1194     }
1195 }
1196
1197 void TitleWidget::rectChanged()
1198 {
1199     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1200     if (l.size() == 1 && l.at(0)->type() == RECTITEM && !settingUp) {
1201         QGraphicsRectItem *rec = static_cast<QGraphicsRectItem *>(l.at(0));
1202         QColor f = rectFColor->color();
1203         f.setAlpha(rectFAlpha->value());
1204         QPen penf(f);
1205         penf.setWidth(rectLineWidth->value());
1206         rec->setPen(penf);
1207         QColor b = rectBColor->color();
1208         b.setAlpha(rectBAlpha->value());
1209         rec->setBrush(QBrush(b));
1210     }
1211 }
1212
1213 void TitleWidget::itemScaled(int val)
1214 {
1215     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1216     if (l.size() == 1) {
1217         Transform x = m_transformations.value(l.at(0));
1218         x.scalex = (double)val / 100.0;
1219         x.scaley = (double)val / 100.0;
1220         QTransform qtrans;
1221         qtrans.scale(x.scalex, x.scaley);
1222         qtrans.rotate(x.rotate);
1223         l[0]->setTransform(qtrans);
1224         m_transformations[l.at(0)] = x;
1225         updateDimension(l.at(0));
1226     }
1227 }
1228
1229 void TitleWidget::itemRotate(int val)
1230 {
1231     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1232     if (l.size() == 1) {
1233         Transform x = m_transformations[l.at(0)];
1234         x.rotate = (double)val;
1235         QTransform qtrans;
1236         qtrans.scale(x.scalex, x.scaley);
1237         qtrans.rotate(x.rotate);
1238         l[0]->setTransform(qtrans);
1239         m_transformations[l.at(0)] = x;
1240         updateDimension(l.at(0));
1241     }
1242 }
1243
1244 void TitleWidget::itemHCenter()
1245 {
1246     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1247     if (l.size() == 1) {
1248         QGraphicsItem *item = l.at(0);
1249         QRectF br;
1250         br = item->sceneBoundingRect();
1251         int width = (int)br.width();
1252         int newPos = (int)((m_frameWidth - width) / 2);
1253         newPos += item->pos().x() - br.left(); // Check item transformation
1254         item->setPos(newPos, item->pos().y());
1255         updateCoordinates(item);
1256     }
1257 }
1258
1259 void TitleWidget::itemVCenter()
1260 {
1261     QList<QGraphicsItem*> l = graphicsView->scene()->selectedItems();
1262     if (l.size() == 1) {
1263         QGraphicsItem *item = l.at(0);
1264         QRectF br;
1265         br = item->sceneBoundingRect();
1266         int height = (int)br.height();
1267         int newPos = (int)((m_frameHeight - height) / 2);
1268         newPos += item->pos().y() - br.top(); // Check item transformation
1269         item->setPos(item->pos().x(), newPos);
1270         updateCoordinates(item);
1271     }
1272 }
1273
1274 void TitleWidget::setupViewports()
1275 {
1276     //double aspect_ratio = 4.0 / 3.0;//read from project
1277     //better zoom centered, but render uses only the created rect, so no problem to change the zoom function
1278     QRectF sp(0, 0, startViewportSize->value() * m_frameWidth / 100.0 , startViewportSize->value()* m_frameHeight / 100.0);
1279     QRectF ep(0, 0, endViewportSize->value() * m_frameWidth / 100.0, endViewportSize->value() * m_frameHeight / 100.0);
1280     // use a polygon thiat uses 16:9 and 4:3 rects forpreview the size in all aspect ratios ?
1281     QPolygonF spoly(sp);
1282     QPolygonF epoly(ep);
1283     spoly.translate(startViewportX->value(), startViewportY->value());
1284     epoly.translate(endViewportX->value(), endViewportY->value());
1285     m_startViewport->setPolygon(spoly);
1286     m_endViewport->setPolygon(epoly);
1287     if (! insertingValues) {
1288         m_startViewport->setData(0, startViewportX->value());
1289         m_startViewport->setData(1, startViewportY->value());
1290         m_startViewport->setData(2, startViewportSize->value());
1291
1292         m_endViewport->setData(0, endViewportX->value());
1293         m_endViewport->setData(1, endViewportY->value());
1294         m_endViewport->setData(2, endViewportSize->value());
1295     }
1296 }
1297
1298 void TitleWidget::loadTitle()
1299 {
1300     KUrl url = KFileDialog::getOpenUrl(KUrl(m_projectTitlePath), "*.kdenlivetitle", this, i18n("Load Title"));
1301     if (!url.isEmpty()) {
1302         QList<QGraphicsItem *> items = m_scene->items();
1303         for (int i = 0; i < items.size(); i++) {
1304             if (items.at(i)->zValue() > -1000) delete items.at(i);
1305         }
1306         m_scene->clearTextSelection();
1307         m_count = m_titledocument.loadDocument(url, m_startViewport, m_endViewport) + 1;
1308         insertingValues = true;
1309         startViewportX->setValue(m_startViewport->data(0).toInt());
1310         startViewportY->setValue(m_startViewport->data(1).toInt());
1311         startViewportSize->setValue(m_startViewport->data(2).toInt());
1312         endViewportX->setValue(m_endViewport->data(0).toInt());
1313         endViewportY->setValue(m_endViewport->data(1).toInt());
1314         endViewportSize->setValue(m_endViewport->data(2).toInt());
1315         insertingValues = false;
1316         slotSelectTool();
1317     }
1318 }
1319
1320 void TitleWidget::saveTitle(KUrl url)
1321 {
1322     if (url.isEmpty()) url = KFileDialog::getSaveUrl(KUrl(m_projectTitlePath), "*.kdenlivetitle", this, i18n("Save Title"));
1323     if (!url.isEmpty()) {
1324         if (m_titledocument.saveDocument(url, m_startViewport, m_endViewport) == false)
1325             KMessageBox::error(this, i18n("Cannot write to file %1", url.path()));
1326     }
1327 }
1328
1329 QDomDocument TitleWidget::xml()
1330 {
1331     QDomDocument doc = m_titledocument.xml(m_startViewport, m_endViewport);
1332     if (cropImage->isChecked()) {
1333         doc.documentElement().setAttribute("crop", 1);
1334     }
1335     return doc;
1336 }
1337
1338 void TitleWidget::setXml(QDomDocument doc)
1339 {
1340     m_count = m_titledocument.loadFromXml(doc, m_startViewport, m_endViewport);
1341     QDomElement e = doc.documentElement();
1342     cropImage->setChecked(e.hasAttribute("crop"));
1343     m_transformations.clear();
1344     QList <QGraphicsItem *> items = graphicsView->scene()->items();
1345     const double PI = 4.0 * atan(1.0);
1346     for (int i = 0; i < items.count(); i++) {
1347         QTransform t = items.at(i)->transform();
1348         Transform x;
1349         x.scalex = t.m11();
1350         x.scaley = t.m22();
1351         x.rotate = 180. / PI * atan2(-t.m21(), t.m11());
1352         m_transformations[items.at(i)] = x;
1353     }
1354     // mbd: Update the GUI color selectors to match the stuff from the loaded document
1355     QColor background_color = m_titledocument.getBackgroundColor();
1356     horizontalSlider->blockSignals(true);
1357     kcolorbutton->blockSignals(true);
1358     horizontalSlider->setValue(background_color.alpha());
1359     background_color.setAlpha(255);
1360     kcolorbutton->setColor(background_color);
1361     horizontalSlider->blockSignals(false);
1362     kcolorbutton->blockSignals(false);
1363
1364     slotSelectTool();
1365 }
1366
1367 const QRect TitleWidget::renderedRect()
1368 {
1369     int minX = 0;
1370     int minY = 0;
1371     int maxX = m_frameWidth;
1372     int maxY = m_frameHeight;
1373     if (!cropImage->isChecked()) {
1374         m_scene->removeItem(m_startViewport);
1375         m_scene->removeItem(m_endViewport);
1376         QRect boundingRect = m_scene->itemsBoundingRect().toRect();
1377         if (boundingRect.left() < 0) minX = boundingRect.left();
1378         if (boundingRect.top() < 0) minY = boundingRect.top();
1379         if (boundingRect.right() > maxX) maxX = boundingRect.right();
1380         if (boundingRect.bottom() > maxY) maxY = boundingRect.bottom();
1381         if (minX < 0) {
1382             maxX = maxX - minX;
1383         }
1384         if (minY < 0) {
1385             maxY = maxY - minY;
1386         }
1387     }
1388     QRect rect(minX, minY, maxX, maxY);
1389     return rect;
1390 }
1391
1392 QImage TitleWidget::renderedPixmap()
1393 {
1394     QRect rect = renderedRect();
1395     QImage pix(rect.width(), rect.height(), QImage::Format_ARGB32);
1396     pix.fill(Qt::transparent);
1397     QPainter painter(&pix);
1398     painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing | QPainter::HighQualityAntialiasing);
1399     m_scene->clearTextSelection();
1400     QPen framepen = m_frameBorder->pen();
1401     m_frameBorder->setPen(Qt::NoPen);
1402     m_startViewport->setVisible(false);
1403     m_endViewport->setVisible(false);
1404     m_frameImage->setVisible(false);
1405
1406     m_scene->render(&painter, QRectF(), rect); //QRectF(minX, minY, maxX - minX, maxY - minY));
1407     painter.end();
1408     m_frameBorder->setPen(framepen);
1409     m_startViewport->setVisible(true);
1410     m_endViewport->setVisible(true);
1411     m_frameImage->setVisible(true);
1412     return pix;
1413 }
1414
1415 /** \brief Connected to the accepted signal - calls writeChoices */
1416 void TitleWidget::slotAccepted()
1417 {
1418     writeChoices();
1419 }
1420
1421 /** \brief Store the current choices of font, background and rect values */
1422 void TitleWidget::writeChoices()
1423 {
1424     // Get a pointer to a shared configuration instance, then get the TitleWidget group.
1425     KSharedConfigPtr config = KGlobal::config();
1426     KConfigGroup titleConfig(config, "TitleWidget");
1427     // Write the entries
1428     titleConfig.writeEntry("font_family", font_family->currentFont());
1429     //titleConfig.writeEntry("font_size", font_size->value());
1430     titleConfig.writeEntry("font_pixel_size", font_size->value());
1431     titleConfig.writeEntry("font_color", fontColorButton->color());
1432     titleConfig.writeEntry("font_alpha", textAlpha->value());
1433     titleConfig.writeEntry("font_weight", font_weight_box->itemData(font_weight_box->currentIndex()).toInt());
1434     titleConfig.writeEntry("font_italic", buttonItalic->isChecked());
1435     titleConfig.writeEntry("font_underlined", buttonUnder->isChecked());
1436
1437     titleConfig.writeEntry("rect_foreground_color", rectFColor->color());
1438     titleConfig.writeEntry("rect_foreground_alpha", rectFAlpha->value());
1439     titleConfig.writeEntry("rect_background_color", rectBColor->color());
1440     titleConfig.writeEntry("rect_background_alpha", rectBAlpha->value());
1441     titleConfig.writeEntry("rect_line_width", rectLineWidth->value());
1442
1443     titleConfig.writeEntry("background_color", kcolorbutton->color());
1444     titleConfig.writeEntry("background_alpha", horizontalSlider->value());
1445
1446     titleConfig.writeEntry("crop_image", cropImage->isChecked());
1447
1448     //! \todo Not sure if I should sync - it is probably safe to do it
1449     config->sync();
1450
1451 }
1452
1453 /** \brief Read the last stored choices into the dialog */
1454 void TitleWidget::readChoices()
1455 {
1456     // Get a pointer to a shared configuration instance, then get the TitleWidget group.
1457     KSharedConfigPtr config = KGlobal::config();
1458     KConfigGroup titleConfig(config, "TitleWidget");
1459     // read the entries
1460     font_family->setCurrentFont(titleConfig.readEntry("font_family", font_family->currentFont()));
1461     font_size->setValue(titleConfig.readEntry("font_pixel_size", font_size->value()));
1462     fontColorButton->setColor(titleConfig.readEntry("font_color", fontColorButton->color()));
1463     textAlpha->setValue(titleConfig.readEntry("font_alpha", textAlpha->value()));
1464     int weight;
1465     if (titleConfig.readEntry("font_bold", false)) weight = QFont::Bold;
1466     else weight = titleConfig.readEntry("font_weight", font_weight_box->itemData(font_weight_box->currentIndex()).toInt());
1467     setFontBoxWeight(weight);
1468     buttonItalic->setChecked(titleConfig.readEntry("font_italic", buttonItalic->isChecked()));
1469     buttonUnder->setChecked(titleConfig.readEntry("font_underlined", buttonUnder->isChecked()));
1470
1471     rectFColor->setColor(titleConfig.readEntry("rect_foreground_color", rectFColor->color()));
1472     rectFAlpha->setValue(titleConfig.readEntry("rect_foreground_alpha", rectFAlpha->value()));
1473     rectBColor->setColor(titleConfig.readEntry("rect_background_color", rectBColor->color()));
1474     rectBAlpha->setValue(titleConfig.readEntry("rect_background_alpha", rectBAlpha->value()));
1475     rectLineWidth->setValue(titleConfig.readEntry("rect_line_width", rectLineWidth->value()));
1476
1477     kcolorbutton->setColor(titleConfig.readEntry("background_color", kcolorbutton->color()));
1478     horizontalSlider->setValue(titleConfig.readEntry("background_alpha", horizontalSlider->value()));
1479
1480     cropImage->setChecked(titleConfig.readEntry("crop_image", cropImage->isChecked()));
1481 }
1482