Replaced all std::cout with kDebug.
[tagua/yd.git] / src / movelist.cpp
blob769a19016a9290a1763e1f769fa8ed8125e32246
1 /*
2 Copyright (c) 2006 Paolo Capriotti <p.capriotti@gmail.com>
3 (c) 2006 Maurizio Monge <maurizio.monge@kdemail.net>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
9 */
10 #include <QApplication>
11 #include <QPainter>
12 #include <QPaintEvent>
13 #include <QMouseEvent>
14 #include <QTextEdit>
15 #include <QMenu>
16 #include <QHBoxLayout>
17 #include <QVBoxLayout>
18 #include <QScrollArea>
19 #include <QToolButton>
20 #include <QScrollBar>
21 #include <QTimer>
22 #include <cmath>
23 #include <KDebug>
24 #include <KStandardDirs>
26 #include "movelist_widget.h"
27 #include "movelist_table.h"
28 #include "movelist_notifier.h"
29 #include "movelist_p.h"
30 #include "mastersettings.h"
31 #include "pref_theme.h"
33 namespace MoveList {
35 #define MARGIN_LEFT 2
36 #define MARGIN_RIGHT 4
37 #define MARGIN_TOP 1
38 #define MARGIN_BOTTOM 0
39 #define MIDDLE_PAD 3
40 #define COMMENT_INDENTATION 4
41 #define VAR_INDENTATION 16
42 #define BORDER_LEFT 3
43 #define BORDER_RIGHT 3
44 #define BORDER_TOP 3
45 #define BORDER_BOTTOM 3
46 #define MIN_COL_WIDTH 5.0
48 #define DEFAULT_ANIMATION_TIME 350.0
50 //BEGIN FancyItem--------------------------------------------------------------
52 bool FancyItem::showing() {
53 return !(time_opacity!=-1 && target_opacity == 0) &&
54 ((time_opacity!=-1 && target_opacity == 255) || (visible() && opacity() == 255));
57 void FancyItem::appear() {
58 if((time_opacity!=-1 && target_opacity == 255)
59 || (visible() && opacity() == 255))
60 return;
62 Widget *m = dynamic_cast<Widget*>(topLevelCanvas());
63 if(!m->m_settings->anim_enabled || !m->m_settings->anim_hideshow)
64 show();
65 else {
66 old_opacity = 0;
67 target_opacity = 255;
68 time_opacity = m->layout_time;
69 setAnimated(true);
73 void FancyItem::disappear() {
74 if((time_opacity!=-1 && target_opacity == 0)
75 || !visible() || opacity() == 0)
76 return;
78 Widget *m = dynamic_cast<Widget*>(topLevelCanvas());
79 setHighlight(false);
80 if(!m->m_settings->anim_enabled || !m->m_settings->anim_hideshow)
81 hide();
82 else {
83 old_opacity = 255;
84 target_opacity = 0;
85 time_opacity = m->layout_time;
86 setAnimated(true);
90 void FancyItem::goTo(QPoint p) {
91 if((time_pos!=-1 && target_pos == p) || (time_pos==-1 && pos() == p))
92 return;
94 Widget *m = dynamic_cast<Widget*>(topLevelCanvas());
95 if(!m->m_settings->anim_enabled || !m->m_settings->anim_moving)
96 moveTo(p);
97 else {
98 old_pos = pos();
99 target_pos = p;
100 time_pos = m->layout_time;
101 /*kDebug() << m->layout_time << " start " << this << " "
102 << prettyTypeName(typeid(*this).name());*/
103 setAnimated(true);
107 void FancyItem::setHighlight(bool h) {
108 if(highlighted == h)
109 return;
111 Widget *m = dynamic_cast<Widget*>(topLevelCanvas());
112 if(!m->m_settings->anim_enabled || !m->m_settings->anim_highlight) {
113 curr_highlight = h ? 255 : 0;
114 highlighted = h;
115 changed();
117 else {
118 old_highlight = highlighted ? 255 : 0;
119 target_highlight = h ? 255 : 0;
120 highlighted = h;
121 time_highlight = m->mSecs();
122 setAnimated(true);
126 void FancyItem::advance(int time) {
127 Widget *m = dynamic_cast<Widget*>(topLevelCanvas());
128 /*kDebug() << time << " anim " << this << " "
129 << prettyTypeName(typeid(*this).name());*/
130 if(time_highlight != -1) {
131 float fact = (time - time_highlight) / m->m_settings->anim_time;
132 if(fact >= 1.0) {
133 curr_highlight = target_highlight;
134 time_highlight = -1;
136 else
137 curr_highlight = int(target_highlight*fact + old_highlight*(1-fact));
138 changed();
140 if(time_opacity != -1) {
141 float fact = (time - time_opacity) / m->m_settings->anim_time;
142 if(fact >= 1.0) {
143 setOpacity(target_opacity);
144 setVisible(target_opacity != 0);
145 time_opacity = -1;
147 else {
148 setOpacity( int(target_opacity*fact + old_opacity*(1-fact)) );
149 setVisible(true);
152 if(time_pos != -1) {
153 float fact = (time - time_pos) / m->m_settings->anim_time;
154 if(fact >= 1.0) {
155 /*kDebug() << time << " done " << this << " "
156 << prettyTypeName(typeid(*this).name());*/
157 moveTo(target_pos);
158 time_pos = -1;
160 else {
161 /*kDebug() << time << " move " << this << " "
162 << prettyTypeName(typeid(*this).name());*/
163 moveTo( int(target_pos.x()*fact + old_pos.x()*(1-fact)+0.5),
164 int(target_pos.y()*fact + old_pos.y()*(1-fact)+0.5));
167 if(canStop()) {
168 /*kDebug() << time << " stop " << this << " "
169 << prettyTypeName(typeid(*this).name());*/
170 setAnimated(false);
174 bool FancyItem::layered() const {
175 return false;
178 //END FancyItem----------------------------------------------------------------
181 //BEGIN Brace------------------------------------------------------------------
183 void Brace::setHeight(int h) {
184 if(h<0) h=0;
185 if((animated() && target_height == h) || height == h)
186 return;
188 Widget *m = dynamic_cast<Widget*>(topLevelCanvas());
189 if(!m->m_settings->anim_enabled || !m->m_settings->anim_moving) {
190 height = h;
191 changed();
193 else {
194 old_height = height;
195 target_height = h;
196 time_height = m->layout_time;
197 if(visible())
198 setAnimated(true);
202 void Brace::advance(int time) {
203 if(time_height != -1) {
204 Widget *m = dynamic_cast<Widget*>(topLevelCanvas());
205 float fact = (time - time_height) / m->m_settings->anim_time;
206 if(fact >= 1.0) {
207 height = target_height;
208 time_height = -1;
210 else
211 height = int(target_height*fact + old_height*(1-fact) + 0.5);
212 changed();
214 FancyItem::advance(time);
217 void Brace::paint (QPainter *p) {
218 Widget *m = dynamic_cast<Widget*>(topLevelCanvas());
219 if(height < m->entry_size)
220 return;
221 QPointF p1((pos().x()*2+width)/2.0, (pos().y()*2+m->entry_size)/2.0);
222 QPointF p2((pos().x()*2+width)/2.0, (pos().y()*2+height*2-m->entry_size)/2.0);
223 p->save();
224 QPen q;
225 if(depth % 2) {
226 p->setBrush(QColor(255,192,224));
227 q = QColor(128,0,64);
229 else {
230 p->setBrush(QColor(192,255,224));
231 q = QColor(0,128,64);
233 q.setWidth(2);
234 p->setPen(q);
235 p->setRenderHint(QPainter::Antialiasing);
236 int s = std::min(m->entry_size, width);
237 float cs1 = (0.4 + 0.2*(curr_highlight/255.0)) * s;
238 float cs2 = 0.2 * s;
240 p->drawLine(p1,p2);
241 p->drawEllipse(QRectF(-cs1/2,-cs1/2,cs1,cs1).translated(p1));
242 p->setBrush(p->pen().color());
243 p->drawEllipse(QRectF(-cs2/2,-cs2/2,cs2,cs2).translated(p2));
244 p->restore();
247 QRect Brace::rect () const {
248 return QRect(pos(), QSize(width, height));
251 //END Brace--------------------------------------------------------------------
254 //BEGIN Text-------------------------------------------------------------------
256 void Text::paint (QPainter *p) {
257 Widget *m = dynamic_cast<Widget*>(topLevelCanvas());
258 if(curr_highlight != 0) {
259 p->setBrush(QColor(192,224,208, curr_highlight));
260 p->setPen(QColor(64,128,96, curr_highlight));
261 p->drawRect(rect().adjusted(0,0,-1,-1));
263 p->setFont(selected ? m->m_settings->sel_mv_font : m->m_settings->mv_font);
264 p->setPen(selected ? m->m_settings->select_color : Qt::black);
265 p->drawText(pos()+QPoint(MARGIN_LEFT, MARGIN_TOP+m->m_settings->mv_fmetrics.ascent()), text);
268 QRect Text::rect () const {
269 return QRect(pos(), QSize(width, height));
272 void Text::doUpdate () {
273 if(!needs_update)
274 return;
276 Widget *m = dynamic_cast<Widget*>(topLevelCanvas());
277 width = (selected ? m->m_settings->sel_mv_fmetrics
278 : m->m_settings->mv_fmetrics).boundingRect(text).right()
279 + MARGIN_LEFT + MARGIN_RIGHT;
280 height = m->entry_size;
282 needs_update = false;
283 changed();
286 //END Text---------------------------------------------------------------------
289 //BEGIN Comment----------------------------------------------------------------
291 void Comment::paint (QPainter *p) {
292 Widget *m = dynamic_cast<Widget*>(topLevelCanvas());
294 if(curr_highlight != 0) {
295 p->setBrush(QColor(255,255,255, curr_highlight));
296 p->setPen(QColor(192,192,192, curr_highlight));
297 p->drawRect(rect().adjusted(0,0,-1,-1));
299 p->setFont(m->m_settings->comm_font);
300 p->setPen(m->m_settings->comment_color);
301 p->drawText(pos().x() + MARGIN_RIGHT,
302 pos().y(),
303 width - MARGIN_LEFT - MARGIN_RIGHT, 9999,
304 Qt::AlignLeft|Qt::AlignTop|Qt::TextWordWrap, text);
307 QRect Comment::rect () const {
308 return QRect(pos(), QSize(width, height));
311 void Comment::doUpdate () {
312 if(!needs_update)
313 return;
315 Widget *m = dynamic_cast<Widget*>(topLevelCanvas());
316 QPoint dest = ((time_pos != -1) ? target_pos : pos());
317 width = std::max(m->width() - dest.x(), m->entry_size);
318 height = m->m_settings->comm_fmetrics.boundingRect(0,0,width - MARGIN_LEFT - MARGIN_RIGHT, 99999,
319 Qt::AlignLeft|Qt::AlignTop|Qt::TextWordWrap, text).height()
320 + MARGIN_TOP + MARGIN_BOTTOM;
322 needs_update = false;
323 changed();
326 //END Comment------------------------------------------------------------------
329 //BEGIN Entry------------------------------------------------------------------
331 void Entry::paint (QPainter *p) {
332 Widget *m = dynamic_cast<Widget*>(topLevelCanvas());
333 if(curr_highlight != 0) {
334 p->setBrush(QColor(192,224,255, curr_highlight));
335 p->setPen(QColor(64,96,128, curr_highlight));
336 p->drawRect(rect().adjusted(0,0,-1,-1));
338 p->setPen(selected ? m->m_settings->select_color : Qt::black);
339 int x = pos().x()+MARGIN_LEFT;
340 int y = pos().y()+MARGIN_TOP+m_ascent;
342 p->setRenderHint(QPainter::TextAntialiasing);
343 QFont tf = selected ? m->m_settings->sel_mv_font : m->m_settings->mv_font;
344 QFontMetrics& fm = selected ? m->m_settings->sel_mv_fmetrics : m->m_settings->mv_fmetrics;
345 QRect r(0,0,0,0);
347 for(int i=0;i<(int)move.size();i++) {
348 if(move[i].m_type == MovePart::Text) {
349 p->setFont(tf);
350 p->drawText(QPoint(x+r.width(), y), move[i].m_string);
351 QRect b = fm.boundingRect(move[i].m_string);
352 r |= b.translated(r.width()-b.x(), 0);
354 else if(move[i].m_type == MovePart::Figurine) {
355 ::Loader::Glyph g = m->m_loader.getValue< ::Loader::Glyph>(move[i].m_string);
356 QFont font = g.fontValid() ? g.font() : tf;
357 p->setFont(font);
358 p->drawText(QPoint(x+r.width(), y), g.str());
359 QFontMetrics fi(font);
360 QRect b = fi.boundingRect(g.str());
361 r |= b.translated(r.width()-b.x(), 0);
366 QRect Entry::rect () const {
367 return m_rect.translated(pos().x()+MARGIN_LEFT, pos().y()+MARGIN_TOP+m_ascent);
370 void Entry::doUpdate () {
371 if(!needs_update)
372 return;
374 Widget *m = dynamic_cast<Widget*>(topLevelCanvas());
375 QFont tf = selected ? m->m_settings->sel_mv_font : m->m_settings->mv_font;
376 QFontMetrics& fm = selected ? m->m_settings->sel_mv_fmetrics : m->m_settings->mv_fmetrics;
377 m_ascent = m->m_settings->mv_fmetrics.ascent();
378 m_rect = QRect(0,0,0,0);
380 for(int i=0;i<(int)move.size();i++) {
381 if(move[i].m_type == MovePart::Text) {
382 QRect b = fm.boundingRect(move[i].m_string);
383 m_rect |= b.translated(m_rect.width()-b.x(), 0);
385 else if(move[i].m_type == MovePart::Figurine) {
386 ::Loader::Glyph g = m->m_loader.getValue< ::Loader::Glyph>(move[i].m_string);
387 QFontMetrics fi(g.fontValid() ? g.font() : tf);
388 QRect b = fi.boundingRect(g.str());
389 m_rect |= b.translated(m_rect.width()-b.x(), 0);
392 m_rect = QRect(m_rect.x(),m_rect.y(),m_rect.width()+MARGIN_RIGHT,m_rect.height());
394 needs_update = false;
395 changed();
398 //END Entry--------------------------------------------------------------------
401 //BEGIN Settings---------------------------------------------------------------
403 void Settings::load() {
404 ::Settings s = settings().group("move-list");
405 ::Settings s_anim = s.group("animations");
407 anim_enabled = s.group("animations").flag("enabled", true);
408 anim_moving = s_anim.group("moving").flag("enabled", true);
409 anim_hideshow = s_anim.group("hideshow").flag("enabled", true);
410 anim_highlight = s_anim.group("highlight").flag("enabled", true);
411 anim_speed = s_anim["speed"] | 16;
412 anim_time = DEFAULT_ANIMATION_TIME*pow(5.0, 1.0 - anim_speed/16.0);
413 anim_smoothness = s_anim["smoothness"] | 16;
414 select_color = s["select-color"] | QColor(Qt::red);
415 comment_color = s["comment-color"] | QColor(64,64,64);
416 mv_font = QApplication::font();
417 if ((use_mv_font = s.group("moves-font").flag("enabled", true)))
418 mv_font = s["moves-font"] | mv_font;
419 sel_mv_font = mv_font;
420 sel_mv_font.setBold(true);
421 comm_font = QApplication::font();
422 comm_font.setItalic(true);
423 if ((use_comm_font = s.group("comment-font").flag("enabled", true)))
424 comm_font = s["CommentFont"] | comm_font;
425 mv_fmetrics = QFontMetrics(mv_font);
426 sel_mv_fmetrics = QFontMetrics(sel_mv_font);
427 comm_fmetrics = QFontMetrics(comm_font);
430 void Settings::save() {
431 ::Settings s = settings().group("move-list");
432 ::Settings s_anim = s.group("animations");
434 s.group("animations").setFlag("enabled", anim_enabled);
435 s_anim.group("moving").setFlag("enabled", anim_moving);
436 s_anim.group("hideshow").setFlag("enabled", anim_hideshow);
437 s_anim.group("highlight").setFlag("enabled", anim_highlight);
438 s_anim["speed"] = anim_speed;
439 s_anim["smoothness"] = anim_smoothness;
440 s["select-color"] = select_color;
441 s["comment-color"] = comment_color;
442 s.group("moves-font").flag("enabled", use_mv_font);
443 s["moves-font"] = mv_font;
444 s.group("comment-font").flag("enabled", use_comm_font);
445 s["comment-font"] = comm_font;
448 //END Settings-----------------------------------------------------------------
451 //BEGIN Widget-----------------------------------------------------------------
453 Widget::Widget(QWidget *parent, Table *o)
454 : KGameCanvasWidget(parent)
455 , curr_highlight(-1)
456 , curr_selected(-1)
457 , comment_editor(NULL)
458 , layout_pending(false)
459 , layout_style(0)
460 , layout_goto_selected(false)
461 , layout_width_changed(true)
462 , layout_must_relayout(true)
463 , notifier(NULL)
464 , owner_table(o)
465 , m_settings(new Settings) {
467 resize(50,100);
468 setSizePolicy ( QSizePolicy::MinimumExpanding, QSizePolicy::Minimum );
470 setMouseTracking(true);
471 settingsChanged();
472 reset();
475 Widget::~Widget() {
476 delete m_settings;
479 void Widget::reset() {
480 curr_highlight = Index(-1);
481 curr_selected = Index(-1);
482 if(comment_editor) {
483 delete comment_editor;
484 comment_editor = NULL;
487 DecoratedMove mv;
488 mv.push_back(MovePart(QString("Mainline:")));
489 history.clear();
490 history.push_back( EntryPtr(new Entry(-1, mv, Index(0), this)) );
492 layout();
495 EntryPtr Widget::fetch(const Index& ix) {
496 int at;
497 History *vec = fetchRef(ix, &at);
498 return vec ? (*vec)[at] : EntryPtr();
501 History* Widget::fetchRef(const Index& ix, int* idx) {
502 if(ix.num_moves >= (int)history.size() || ix.num_moves < 0 )
503 return NULL;
505 History* aretv = &history;
506 EntryPtr retv = history[ix.num_moves];
507 if(idx) *idx = ix.num_moves;
509 for(int i=0; i<(int)ix.nested.size();i++) {
510 Variations::iterator it = retv->variations.find(ix.nested[i].variation);
511 if(it == retv->variations.end() || ix.nested[i].num_moves >= (int)it->second.size()
512 || ix.nested[i].num_moves < 0 )
513 return NULL;
515 aretv = &it->second;
516 retv = it->second[ix.nested[i].num_moves];
517 if(idx) *idx = ix.nested[i].num_moves;
519 return aretv;
522 Notifier* Widget::getNotifier() {
523 return notifier;
526 void Widget::setNotifier(Notifier* n, bool detach_prev){
527 if(detach_prev && notifier && notifier != n)
528 notifier->onDetachNotifier();
529 notifier = n;
532 void Widget::settingsChanged() {
533 m_settings->load();
535 setAnimationDelay( int(70.0*pow(10.0, -m_settings->anim_smoothness/32.0)) );
537 entry_size = m_settings->mv_fmetrics.height()+MARGIN_TOP+MARGIN_BOTTOM;
538 owner_table->m_scroll_area->setMinimumSize(entry_size*6, entry_size*9);
540 m_loader.setSize(m_settings->mv_font.pointSize());
542 layout_must_relayout = true;
543 layout();
546 void Widget::mouseMoveEvent ( QMouseEvent * event ) {
547 KGameCanvasItem *i = itemAt(event->pos());
548 Entry* e = i ? dynamic_cast<Entry*>(i) : NULL;
549 Text* f = i ? dynamic_cast<Text*>(i) : NULL;
550 Brace* b = i ? dynamic_cast<Brace*>(i) : NULL;
551 Comment* c = i ? dynamic_cast<Comment*>(i) : NULL;
552 EntryPtr olde = fetch(curr_highlight);
553 f = f && f->type == 1 ? f : NULL;
555 int oldtype = curr_highlight_type;
557 if(e) {
558 if(curr_highlight == e->index && curr_highlight_type==-1)
559 return;
560 e->setHighlight(true);
561 curr_highlight = e->index;
562 curr_highlight_type = -1;
564 else if(f) {
565 if(curr_highlight == f->entry->index && curr_highlight_type==-2)
566 return;
567 f->setHighlight(true);
568 curr_highlight = f->entry->index;
569 curr_highlight_type = -2;
571 else if(c) {
572 if( (curr_highlight==c->entry->index) &&
573 ((c->variation==-1) ? (curr_highlight_type == -3) :
574 (curr_highlight_type == -1000-c->variation) ) )
575 return;
576 c->setHighlight(true);
577 curr_highlight = c->entry->index;
578 curr_highlight_type = (c->variation==-1) ? -3 : (-1000-c->variation);
580 else if(b) {
581 if(curr_highlight == b->entry->index && curr_highlight_type==b->variation)
582 return;
583 b->setHighlight(true);
584 curr_highlight = b->entry->index;
585 curr_highlight_type = b->variation;
587 else
588 curr_highlight = Index(-1);
590 if(olde) {
591 if(oldtype==-1)
592 olde->setHighlight(false);
593 else if(oldtype==-2 && olde->fregna)
594 olde->fregna->setHighlight(false);
595 else if(oldtype==-3 && olde->comment)
596 olde->comment->setHighlight(false);
597 else if(oldtype<=-1000 && olde->vcomments.count(-1000-oldtype)==1)
598 olde->vcomments[-1000-oldtype]->setHighlight(false);
599 else if(oldtype>=0 && olde->braces.count(oldtype)==1)
600 olde->braces[oldtype]->setHighlight(false);
604 void Widget::startEditing(const Index& i, int v) {
605 stopEditing();
607 EntryPtr e = fetch(i);
608 if(!e) {
609 kError() << "Invalid index " << i;
610 return;
613 CommentPtr c = v == -1 ? e->comment : (e->vcomments.count(v) ?
614 e->vcomments[v] : CommentPtr());
615 QRect rect;
616 if(c)
617 rect = c->rect();
618 else {
619 TextPtr n = e->number;
620 if(!n && i > Index(0))
621 n = fetch(i.prev())->number;
622 int x = (n ? n->pos().x() : e->pos().x()) + ((v == -1) ? 0 : VAR_INDENTATION);
624 rect = QRect(x, e->pos().y()+entry_size, width()-x, 0);
627 edited_comment_variation = v;
628 edited_comment = boost::weak_ptr<Entry>(e);
629 comment_editor = new QTextEdit(c ? c->text : QString(), this);
630 comment_editor->setGeometry(rect.adjusted(0,0,0,entry_size*3));
631 comment_editor->show();
632 comment_editor->setFocus(Qt::MouseFocusReason);
633 comment_editor->installEventFilter(this);
636 bool Widget::eventFilter(QObject *obj, QEvent *event) {
637 if(obj == comment_editor && event->type() == QEvent::FocusOut ) {
638 stopEditing();
639 return true;
641 return false;
644 void Widget::stopEditing() {
645 EntryPtr e = edited_comment.lock();
646 if(e) {
647 if(comment_editor && notifier) {
648 QString c = comment_editor->toPlainText();
649 c.replace(QRegExp("(?:[ \t]\r?\n\r?|\r?\n\r?[ \t]|\r?\n\r?)"), " ");
650 if(edited_comment_variation == -1)
651 notifier->onUserSetComment(e->index, c);
652 else
653 notifier->onUserSetVComment(e->index, edited_comment_variation, c);
655 edited_comment.reset();
657 if(comment_editor) {
658 comment_editor->deleteLater();
659 comment_editor = NULL;
663 void Widget::mousePressEvent ( QMouseEvent * event ) {
664 stopEditing();
666 KGameCanvasItem *i = itemAt(event->pos());
667 if(!i)
668 return;
670 Text *t = dynamic_cast<Text*>(i);
671 if(t && t->type == 1) {
672 Entry *e = t->entry;
673 if(e->hide_next) {
674 e->hide_next = false;
675 e->expanded = true;
677 else
678 e->expanded = !e->expanded;
679 layout();
680 return;
683 Brace *b = dynamic_cast<Brace*>(i);
684 if(b) {
685 if(event->button() == Qt::LeftButton) {
686 Entry* e = b->entry;
687 EntryPtr first = e->variations[b->variation][0];
688 first->hide_next = !first->hide_next;
689 layout();
691 else if(event->button() == Qt::RightButton) {
692 QAction *a;
693 QMenu m(this);
694 a = m.addAction(KIcon("pen"), "&Set comment");
695 a->setData("comment");
696 m.addSeparator();
697 a = m.addAction(KIcon(), "&Promote variation");
698 a->setData("promote");
699 a = m.addAction(KIcon("edit-delete"), "&Remove variation");
700 a->setData("remove");
701 boost::weak_ptr<Entry> ewptr = boost::weak_ptr<Entry>(fetch(b->entry->index));
702 int v = b->variation;
704 a = m.exec(event->globalPos());
706 /* beware, here, after exec, e could be a dangling pointer */
707 EntryPtr eptr = ewptr.lock();
708 if(a && notifier && eptr && eptr->variations.count(v)) {
709 if(a->data() == "comment")
710 startEditing(eptr->index, v);
711 else if(a->data() == "promote")
712 notifier->onUserPromoteVariation(eptr->index.next(v));
713 else if(a->data() == "remove")
714 notifier->onUserRemoveVariation(eptr->index.next(v));
717 return;
720 Comment *c = dynamic_cast<Comment*>(i);
721 if(c) {
722 startEditing(c->entry->index, c->variation);
723 return;
726 Entry *e = dynamic_cast<Entry*>(i);
727 if(e) {
728 if(event->button() == Qt::LeftButton) {
729 if(notifier)
730 notifier->onUserSelectMove(e->index);
732 else if(event->button() == Qt::RightButton) {
733 QAction *a;
734 QMenu m(this);
735 a = m.addAction(KIcon("pen"), "&Set comment");
736 a->setData("comment");
737 a = m.addAction(KIcon("eraser"), "&Clear variations");
738 a->setEnabled(!e->variations.empty());
739 a->setData("clear");
740 a = m.addAction(KIcon("cut"), "&Truncate");
741 a->setEnabled(fetch(e->index.next()));
742 a->setData("truncate");
743 m.addSeparator();
744 a = m.addAction(KIcon(), "&Promote variation");
745 a->setEnabled(e->index.nested.size());
746 a->setData("promote");
747 a = m.addAction(KIcon("edit-delete"), "&Remove variation");
748 a->setEnabled(e->index.nested.size());
749 a->setData("remove");
750 boost::weak_ptr<Entry> ewptr = boost::weak_ptr<Entry>(fetch(e->index));
752 a = m.exec(event->globalPos());
754 /* beware, here, after exec, e could be a dangling pointer */
755 EntryPtr eptr = ewptr.lock();
756 if(a && notifier && eptr) {
757 if(a->data() == "comment")
758 startEditing(eptr->index, -1);
759 else if(a->data() == "clear")
760 notifier->onUserClearVariations(eptr->index);
761 else if(a->data() == "truncate")
762 notifier->onUserTruncate(eptr->index);
763 else if(a->data() == "promote")
764 notifier->onUserPromoteVariation(eptr->index);
765 else if(a->data() == "remove")
766 notifier->onUserRemoveVariation(eptr->index);
769 return;
773 void Widget::mouseReleaseEvent ( QMouseEvent * /*event*/ ) {
777 void Widget::resizeEvent ( QResizeEvent * event ) {
778 stopEditing();
779 if(event->size().width() != event->oldSize().width()) {
780 layout_width_changed = true;
781 layout();
785 void Widget::layout() {
786 if(layout_pending)
787 return;
789 layout_pending = true;
790 QTimer::singleShot( 0, this, SLOT(doLayout()) );
793 void Widget::doLayout() {
794 layout_time = mSecs();
795 layout_pending = false;
796 layout_max_width = 0;
797 //kDebug() << "layout_must_relayout = " << layout_must_relayout;
798 int h = layoutHistory(history, BORDER_LEFT, BORDER_TOP, -1, 0, 0, true);
800 QSize s(std::max(entry_size*7, layout_max_width+BORDER_RIGHT),
801 std::max(entry_size*10, h+BORDER_BOTTOM) );
802 setMinimumSize(s);
804 layout_width_changed = false;
805 layout_must_relayout = false;
806 if(layout_goto_selected) {
807 EntryPtr e = fetch(curr_selected);
808 if(e)
809 owner_table->m_scroll_area->ensureVisible( int(e->pos().x() + e->m_rect.width()*0.5),
810 int(e->pos().y() + e->m_rect.height()*0.5) );
811 layout_goto_selected = false;
815 int Widget::layoutHistory(History& array, int at_x, int at_y,
816 int a_prev_turn, int mv_num, int sub_mv_num, bool visible) {
817 int flow_y = at_y;
818 int flow_x = at_x;
819 int nflow_x = at_x;
820 int col_num = 0;
821 int prev_turn = a_prev_turn;
823 for(int i=0;i<(int)array.size();i++) {
824 EntryPtr e = array[i];
826 /* if this is not visible, hide the item and hide all the number/fregna tags */
827 if(!visible) {
828 e->disappear();
829 if(e->number)
830 e->number->disappear();
831 if(e->fregna)
832 e->fregna->disappear();
833 if(e->comment)
834 e->comment->disappear();
836 /* hide the subvariations */
837 for(Variations::iterator it = e->variations.begin(); it != e->variations.end(); ++it)
838 layoutHistory(it->second, 0, 0, e->move_turn, mv_num, sub_mv_num, false);
839 for(Braces::iterator it = e->braces.begin(); it != e->braces.end(); ++it)
840 it->second->disappear();
841 for(VComments::iterator it = e->vcomments.begin(); it != e->vcomments.end(); ++it)
842 it->second->disappear();
843 mv_num++;
844 continue;
847 /* adjust the position if this is paired on the right */
848 bool draw_num = false;
851 if(e->move_turn != prev_turn) {
852 mv_num++;
853 sub_mv_num = 0;
855 else
856 sub_mv_num++;
858 if(layout_style==0) {
859 if(e->move_turn == 0 || i==0 || array[i-1]->childs_height != 0) {
860 if(mv_num>=1 && (e->move_turn != prev_turn || i==0 || array[i-1]->childs_height != 0)) {
861 draw_num = true;
862 flow_x = at_x;
864 else
865 flow_x = (mv_num>=1) ? nflow_x : at_x;
867 else {
868 if(e->move_turn != prev_turn) {
869 flow_x = std::max(flow_x + MIDDLE_PAD, int(MIN_COL_WIDTH*entry_size));
870 flow_y -= entry_size;
872 else
873 flow_x = int(MIN_COL_WIDTH*entry_size);
876 else {
877 if(e->move_turn != prev_turn || i==0 || array[i-1]->childs_height != 0) {
878 col_num = 0;
879 flow_x = at_x;
880 if(mv_num>=1)
881 draw_num = true;
883 else if(col_num == layout_style) {
884 col_num = 0;
885 flow_x = nflow_x;
887 else {
888 flow_y -= entry_size;
889 flow_x = std::max(flow_x + MIDDLE_PAD,
890 at_x + col_num*int(MIN_COL_WIDTH*entry_size));
895 col_num++;
897 /* update the number */
898 if(draw_num) {
899 TextPtr& n = e->number;
900 if(!n) {
901 n = TextPtr(new Text(e.get(), 0, this));
902 if(layout_style==0)
903 n->text = QString::number((mv_num+1)/2)+(mv_num&1 ? "." : ". ...");
904 else
905 n->text = QString::number(mv_num)+
906 (sub_mv_num ? "+"+QString::number(sub_mv_num) : QString())+".";
907 n->needs_update = true;
909 else if( !n->showing() || layout_must_relayout)
910 n->needs_update = true;
912 /* Mh, the number should never change, only appear disappear.
913 should this change, add here the code to enable number changes. */
914 QPoint dest(flow_x, flow_y);
916 if(n->pos() != dest)
917 if(n->visible())
918 n->goTo(dest);
919 else
920 n->moveTo(dest);
921 n->doUpdate();
922 n->appear();
924 flow_x += n->width;
925 nflow_x = flow_x;
927 else if(e->number)
928 e->number->disappear();
931 /* update the entry */
932 QPoint dest(flow_x, flow_y);
933 if(e->pos() != dest)
934 if(e->visible())
935 e->goTo(dest);
936 else
937 e->moveTo(dest);
938 if( !e->showing() || layout_must_relayout)
939 e->needs_update = true;
940 e->doUpdate();
941 e->appear();
942 e->childs_height = 0;
943 flow_x += e->m_rect.width();
946 /* Update the fregna. The fregna is visible if there are subvariations in this
947 entry, or if this entry is the first one of a variation where the remaining
948 entries are hidden and that contains the current position */
949 bool expandable = !e->variations.empty() || e->comment;
950 bool sel = (e->hide_next && e->index<curr_selected)
951 || (!e->expanded && expandable &&
952 e->index<curr_selected && !(e->index.next()<=curr_selected));
953 if(expandable || sel ) {
954 if(!e->fregna)
955 e->fregna = TextPtr(new Text(e.get(), 1, this));
957 /* update the data, if needed */
958 TextPtr f = e->fregna;
959 const char *text = (sel||!e->expanded||e->hide_next) ? "[+]" : "[-]";
960 if(f->text != text || f->selected != sel) {
961 f->text = text;
962 f->selected = sel;
963 f->needs_update = true;
965 else if( !f->showing() || layout_must_relayout)
966 f->needs_update = true;
968 QPoint dest(flow_x, flow_y);
970 if(f->pos() != dest)
971 if(f->visible())
972 f->goTo(QPoint(flow_x, flow_y));
973 else
974 f->moveTo(QPoint(flow_x, flow_y));
975 f->doUpdate();
976 f->appear();
978 flow_x += f->width;
980 else if(e->fregna)
981 e->fregna->disappear();
983 /* update the flow information */
984 flow_y += entry_size;
985 layout_max_width = std::max(flow_x, layout_max_width);
986 int prev_pos = flow_y;
988 /* update the comment */
989 if(e->comment) {
990 CommentPtr c = e->comment;
992 if(e->expanded && !e->hide_next) {
993 QPoint dest(at_x + COMMENT_INDENTATION, flow_y);
995 if(c->pos() != dest ) {
996 if(c->visible())
997 c->goTo(dest);
998 else
999 c->moveTo(dest);
1000 c->needs_update = true;
1002 else if( !c->showing() || layout_width_changed || layout_must_relayout)
1003 c->needs_update = true;
1004 c->doUpdate();
1005 c->appear();
1006 flow_y += c->height;
1008 else
1009 c->disappear();
1012 /* update the variations */
1013 for(Variations::iterator it = e->variations.begin(); it != e->variations.end(); ++it) {
1014 int old_pos = flow_y;
1016 /* update the variation's comment */
1017 if(e->vcomments.count(it->first)) {
1018 CommentPtr c = e->vcomments[it->first];
1020 if(e->expanded && !e->hide_next) {
1021 QPoint dest(at_x + VAR_INDENTATION + COMMENT_INDENTATION, flow_y);
1023 if( !c->showing() || layout_must_relayout)
1024 c->needs_update = true;
1025 if(c->pos() != dest)
1026 if(c->visible())
1027 c->goTo(dest);
1028 else
1029 c->moveTo(dest);
1030 c->doUpdate();
1031 c->appear();
1032 flow_y += c->height;
1034 else
1035 c->disappear();
1038 /* layout the variation */
1039 flow_y = layoutHistory(it->second, at_x + VAR_INDENTATION, flow_y,
1040 e->move_turn, mv_num, sub_mv_num, e->expanded && !e->hide_next);
1042 /* update the brace of the variation */
1043 BracePtr b = e->braces[it->first];
1044 if(e->expanded && !e->hide_next) {
1045 b->depth = e->index.nested.size();
1046 b->setHeight((it->second.size() && it->second[0]->hide_next) ? entry_size : flow_y - old_pos);
1047 b->width = VAR_INDENTATION;
1048 if(b->visible())
1049 b->goTo(QPoint(at_x, old_pos));
1050 else
1051 b->moveTo(QPoint(at_x, old_pos));
1052 b->appear();
1054 else
1055 b->disappear();
1058 e->childs_height = flow_y - prev_pos;
1060 if(e->hide_next)
1061 visible = false;
1062 prev_turn = e->move_turn;
1064 return flow_y;
1067 QPixmap Widget::getPixmap(const QString& s, bool selected) {
1068 QString k = selected ? s+"_sel":s;
1069 if(loaded_pixmaps.contains(k))
1070 return loaded_pixmaps[k];
1072 QString iconFile = KStandardDirs::locate("appdata", "piece_icons/" + s + ".png");
1073 QImage img(iconFile);
1075 if(selected) {
1076 QPainter p(&img);
1077 p.setCompositionMode(QPainter::CompositionMode_SourceAtop );
1078 p.fillRect(0,0,img.width(), img.height(), m_settings->select_color);
1080 return loaded_pixmaps[k] = QPixmap::fromImage(img.scaled(m_settings->mv_fmetrics.ascent(),
1081 m_settings->mv_fmetrics.ascent(),
1082 Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
1085 void Widget::setComment(EntryPtr e, int v, const QString& comment) {
1086 if(comment.isEmpty()) {
1087 if(v == -1) {
1088 if(e->comment)
1089 e->comment = CommentPtr();
1091 else {
1092 if(e->vcomments.count(v))
1093 e->vcomments.erase(v);
1096 else {
1097 CommentPtr p;
1099 if(v == -1) {
1100 if(!e->comment)
1101 e->comment = CommentPtr(new Comment(e.get(), this));
1102 p = e->comment;
1104 else {
1105 if(!e->variations.count(v))
1106 return;
1108 if(!e->vcomments.count(v))
1109 p = e->vcomments[v] = CommentPtr(new Comment(e.get(), this, v));
1110 else
1111 p = e->vcomments[v];
1114 if(p->text == comment)
1115 return;
1116 p->text = comment;
1117 p->needs_update = true;
1120 layout();
1123 void Widget::setComment(const Index& index, const QString& comment) {
1124 EntryPtr e = fetch(index);
1125 if(!e) {
1126 kError() << "Invalid index" << index;
1127 return;
1129 setComment(e, -1, comment);
1132 void Widget::setVComment(const Index& index, int v, const QString& comment) {
1133 EntryPtr e = fetch(index);
1134 if(!e || !e->variations.count(v)) {
1135 kError() << "Invalid index" << index;
1136 return;
1138 setComment(e, v, comment);
1141 void Widget::setMove(const Index& index,
1142 int turn, const QString& move, const QString& comment) {
1143 DecoratedMove mv;
1144 #if 1
1145 mv.push_back(MovePart(move));
1146 #else
1147 //TODO: move this code in some other place, it really should not stay here
1148 QRegExp reg("[KQRBNP]");
1149 int x = 0;
1150 while(reg.indexIn(move, x) != -1) {
1151 if(reg.pos() > x)
1152 mv.push_back(MovePart(MoveText, move.mid(x, reg.pos()-x)));
1153 mv.push_back(MovePart(MovePixmap, reg.cap().toLower()));
1154 x = reg.pos() + reg.matchedLength();
1156 if(x<move.length())
1157 mv.push_back(MovePart(MoveText, move.mid(x)));
1158 #endif
1159 setMove(index, turn, mv, comment);
1162 void Widget::setMove(const Index& index,
1163 int turn, const DecoratedMove& move, const QString& comment) {
1164 EntryPtr e = fetch(index);
1165 if(e) {
1166 e->move_turn = turn;
1167 e->move = move;
1168 e->needs_update = true;
1169 setComment(e, -1, comment);
1170 layout();
1171 return;
1174 int at;
1175 History *vec = fetchRef(index.prev(), &at);
1176 if(!vec) {
1177 kError() << "Invalid index" << index;
1178 return;
1181 if(index.nested.size() && index.nested.back().num_moves == 0) {
1182 History var;
1183 int v = index.nested.back().variation;
1184 var.push_back(e = EntryPtr( new Entry(turn, move, index, this)) );
1185 (*vec)[at]->variations[v] = var;
1186 (*vec)[at]->braces[v] = BracePtr( new Brace( (*vec)[at].get(), v, this) );
1188 else
1189 vec->push_back(e = EntryPtr( new Entry(turn, move, index, this)) );
1191 setComment(e, -1, comment);
1192 e->hide();
1193 layout();
1196 void Widget::remove(const Index& index) {
1198 if(index.atVariationStart() ) {
1199 EntryPtr e = fetch(index.prev());
1200 if(!e)
1201 return;
1203 int v = index.nested.back().variation;
1204 if(!e->variations.count(v))
1205 return;
1207 e->variations.erase(v);
1208 e->braces.erase(v);
1209 e->vcomments.erase(v);
1211 else {
1212 int at;
1213 History *vec = fetchRef(index, &at);
1214 if(!vec)
1215 return;
1217 while((int)vec->size() > at)
1218 vec->pop_back();
1220 layout();
1223 void Widget::fixIndices(const Index& ix) {
1224 int at;
1225 History *vec = fetchRef(ix, &at);
1226 if(!vec) {
1227 kError() << "Invalid index" << ix;
1228 return;
1230 Index index = ix;
1231 for(int i=at;i<(int)vec->size();i++) {
1232 EntryPtr e = (*vec)[i];
1233 e->index = index;
1235 for(Variations::const_iterator it = e->variations.begin();
1236 it != e->variations.end(); ++it)
1237 fixIndices(index.next(it->first));
1238 index = index.next();
1242 void Widget::promoteVariation(const Index& ix, int v) {
1243 int at;
1244 History *vec = fetchRef(ix, &at);
1245 if(!vec) {
1246 kError() << "Invalid index" << ix;
1247 return;
1250 History vold = (*vec)[at]->variations[v];
1251 History vnew;
1252 for(int i=at+1; i<(int)vec->size(); i++)
1253 vnew.push_back((*vec)[i]);
1254 while((int)vec->size()>at+1)
1255 vec->pop_back();
1256 for(int i=0; i<(int)vold.size(); i++)
1257 vec->push_back(vold[i]);
1258 (*vec)[at]->variations[v] = vnew;
1260 Q_ASSERT((int)vec->size()>at+1);
1261 (*vec)[at+1]->hide_next = false;
1263 fixIndices(ix.next());
1264 fixIndices(ix.next(v));
1266 curr_selected = curr_selected.flipVariation(ix, v);
1267 curr_highlight = curr_highlight.flipVariation(ix, v);
1268 layout();
1271 void Widget::select(const Index& index) {
1272 if(curr_selected == index)
1273 return;
1274 EntryPtr e = fetch(index);
1275 EntryPtr olde = fetch(curr_selected);
1276 if(olde) {
1277 olde->selected = false;
1278 olde->needs_update = true;
1280 if(e) {
1281 e->selected = true;
1282 e->needs_update = true;
1283 layout_goto_selected = true;
1285 curr_selected = index;
1286 layout();
1289 void Widget::setLoaderTheme(const ThemeInfo& theme) {
1290 m_loader.setTheme(theme);
1293 //END Widget-------------------------------------------------------------------
1295 } //end namespace MoveList