Use std::vector<>::back() to make the code more readable.
[tagua/yd.git] / src / movelist.cpp
blob054ed9237f9bbcac985a1ffe14b0b9415bf77411
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 */
11 #include <iostream>
12 #include <QApplication>
13 #include <QPainter>
14 #include <QPaintEvent>
15 #include <QMouseEvent>
16 #include <QTextEdit>
17 #include <QMenu>
18 #include <QHBoxLayout>
19 #include <QVBoxLayout>
20 #include <QScrollArea>
21 #include <QToolButton>
22 #include <QScrollBar>
23 #include <QTimer>
24 #include <cmath>
25 #include <iostream>
26 #include <kstandarddirs.h>
27 #include "mastersettings.h"
28 #include "pref_theme.h"
29 #include "movelist_widget.h"
30 #include "movelist_table.h"
31 #include "movelist_notifier.h"
32 #include "movelist_p.h"
34 namespace MoveList {
36 #define MARGIN_LEFT 2
37 #define MARGIN_RIGHT 4
38 #define MARGIN_TOP 1
39 #define MARGIN_BOTTOM 0
40 #define MIDDLE_PAD 3
41 #define COMMENT_INDENTATION 4
42 #define VAR_INDENTATION 16
43 #define BORDER_LEFT 3
44 #define BORDER_RIGHT 3
45 #define BORDER_TOP 3
46 #define BORDER_BOTTOM 3
47 #define MIN_COL_WIDTH 5.0
49 #define DEFAULT_ANIMATION_TIME 350.0
51 //BEGIN FancyItem--------------------------------------------------------------
53 bool FancyItem::showing() {
54 return !(time_opacity!=-1 && target_opacity == 0) &&
55 ((time_opacity!=-1 && target_opacity == 255) || (visible() && opacity() == 255));
58 void FancyItem::appear() {
59 if((time_opacity!=-1 && target_opacity == 255)
60 || (visible() && opacity() == 255))
61 return;
63 Widget *m = dynamic_cast<Widget*>(topLevelCanvas());
64 if(!m->m_settings->anim_enabled || !m->m_settings->anim_hideshow)
65 show();
66 else {
67 old_opacity = 0;
68 target_opacity = 255;
69 time_opacity = m->layout_time;
70 setAnimated(true);
74 void FancyItem::disappear() {
75 if((time_opacity!=-1 && target_opacity == 0)
76 || !visible() || opacity() == 0)
77 return;
79 Widget *m = dynamic_cast<Widget*>(topLevelCanvas());
80 setHighlight(false);
81 if(!m->m_settings->anim_enabled || !m->m_settings->anim_hideshow)
82 hide();
83 else {
84 old_opacity = 255;
85 target_opacity = 0;
86 time_opacity = m->layout_time;
87 setAnimated(true);
91 void FancyItem::goTo(QPoint p) {
92 if((time_pos!=-1 && target_pos == p) || (time_pos==-1 && pos() == p))
93 return;
95 Widget *m = dynamic_cast<Widget*>(topLevelCanvas());
96 if(!m->m_settings->anim_enabled || !m->m_settings->anim_moving)
97 moveTo(p);
98 else {
99 old_pos = pos();
100 target_pos = p;
101 time_pos = m->layout_time;
102 /*std::cout << m->layout_time << " start " << this << " "
103 << prettyTypeName(typeid(*this).name()) << std::endl;*/
104 setAnimated(true);
108 void FancyItem::setHighlight(bool h) {
109 if(highlighted == h)
110 return;
112 Widget *m = dynamic_cast<Widget*>(topLevelCanvas());
113 if(!m->m_settings->anim_enabled || !m->m_settings->anim_highlight) {
114 curr_highlight = h ? 255 : 0;
115 highlighted = h;
116 changed();
118 else {
119 old_highlight = highlighted ? 255 : 0;
120 target_highlight = h ? 255 : 0;
121 highlighted = h;
122 time_highlight = m->mSecs();
123 setAnimated(true);
127 void FancyItem::advance(int time) {
128 Widget *m = dynamic_cast<Widget*>(topLevelCanvas());
129 /*std::cout << time << " anim " << this << " "
130 << prettyTypeName(typeid(*this).name()) << std::endl;*/
131 if(time_highlight != -1) {
132 float fact = (time - time_highlight) / m->m_settings->anim_time;
133 if(fact >= 1.0) {
134 curr_highlight = target_highlight;
135 time_highlight = -1;
137 else
138 curr_highlight = int(target_highlight*fact + old_highlight*(1-fact));
139 changed();
141 if(time_opacity != -1) {
142 float fact = (time - time_opacity) / m->m_settings->anim_time;
143 if(fact >= 1.0) {
144 setOpacity(target_opacity);
145 setVisible(target_opacity != 0);
146 time_opacity = -1;
148 else {
149 setOpacity( int(target_opacity*fact + old_opacity*(1-fact)) );
150 setVisible(true);
153 if(time_pos != -1) {
154 float fact = (time - time_pos) / m->m_settings->anim_time;
155 if(fact >= 1.0) {
156 /*std::cout << time << " done " << this << " "
157 << prettyTypeName(typeid(*this).name()) << std::endl;*/
158 moveTo(target_pos);
159 time_pos = -1;
161 else {
162 /*std::cout << time << " move " << this << " "
163 << prettyTypeName(typeid(*this).name()) << std::endl;*/
164 moveTo( int(target_pos.x()*fact + old_pos.x()*(1-fact)+0.5),
165 int(target_pos.y()*fact + old_pos.y()*(1-fact)+0.5));
168 if(canStop()) {
169 /*std::cout << time << " stop " << this << " "
170 << prettyTypeName(typeid(*this).name()) << std::endl;*/
171 setAnimated(false);
175 bool FancyItem::layered() const {
176 return false;
179 //END FancyItem----------------------------------------------------------------
182 //BEGIN Brace------------------------------------------------------------------
184 void Brace::setHeight(int h) {
185 if(h<0) h=0;
186 if((animated() && target_height == h) || height == h)
187 return;
189 Widget *m = dynamic_cast<Widget*>(topLevelCanvas());
190 if(!m->m_settings->anim_enabled || !m->m_settings->anim_moving) {
191 height = h;
192 changed();
194 else {
195 old_height = height;
196 target_height = h;
197 time_height = m->layout_time;
198 if(visible())
199 setAnimated(true);
203 void Brace::advance(int time) {
204 if(time_height != -1) {
205 Widget *m = dynamic_cast<Widget*>(topLevelCanvas());
206 float fact = (time - time_height) / m->m_settings->anim_time;
207 if(fact >= 1.0) {
208 height = target_height;
209 time_height = -1;
211 else
212 height = int(target_height*fact + old_height*(1-fact) + 0.5);
213 changed();
215 FancyItem::advance(time);
218 void Brace::paint (QPainter *p) {
219 Widget *m = dynamic_cast<Widget*>(topLevelCanvas());
220 if(height < m->entry_size)
221 return;
222 QPointF p1((pos().x()*2+width)/2.0, (pos().y()*2+m->entry_size)/2.0);
223 QPointF p2((pos().x()*2+width)/2.0, (pos().y()*2+height*2-m->entry_size)/2.0);
224 p->save();
225 QPen q;
226 if(depth % 2) {
227 p->setBrush(QColor(255,192,224));
228 q = QColor(128,0,64);
230 else {
231 p->setBrush(QColor(192,255,224));
232 q = QColor(0,128,64);
234 q.setWidth(2);
235 p->setPen(q);
236 p->setRenderHint(QPainter::Antialiasing);
237 int s = std::min(m->entry_size, width);
238 float cs1 = (0.4 + 0.2*(curr_highlight/255.0)) * s;
239 float cs2 = 0.2 * s;
241 p->drawLine(p1,p2);
242 p->drawEllipse(QRectF(-cs1/2,-cs1/2,cs1,cs1).translated(p1));
243 p->setBrush(p->pen().color());
244 p->drawEllipse(QRectF(-cs2/2,-cs2/2,cs2,cs2).translated(p2));
245 p->restore();
248 QRect Brace::rect () const {
249 return QRect(pos(), QSize(width, height));
252 //END Brace--------------------------------------------------------------------
255 //BEGIN Text-------------------------------------------------------------------
257 void Text::paint (QPainter *p) {
258 Widget *m = dynamic_cast<Widget*>(topLevelCanvas());
259 if(curr_highlight != 0) {
260 p->setBrush(QColor(192,224,208, curr_highlight));
261 p->setPen(QColor(64,128,96, curr_highlight));
262 p->drawRect(rect().adjusted(0,0,-1,-1));
264 p->setFont(selected ? m->m_settings->sel_mv_font : m->m_settings->mv_font);
265 p->setPen(selected ? m->m_settings->select_color : Qt::black);
266 p->drawText(pos()+QPoint(MARGIN_LEFT, MARGIN_TOP+m->m_settings->mv_fmetrics.ascent()), text);
269 QRect Text::rect () const {
270 return QRect(pos(), QSize(width, height));
273 void Text::doUpdate () {
274 if(!needs_update)
275 return;
277 Widget *m = dynamic_cast<Widget*>(topLevelCanvas());
278 width = (selected ? m->m_settings->sel_mv_fmetrics
279 : m->m_settings->mv_fmetrics).boundingRect(text).right()
280 + MARGIN_LEFT + MARGIN_RIGHT;
281 height = m->entry_size;
283 needs_update = false;
284 changed();
287 //END Text---------------------------------------------------------------------
290 //BEGIN Comment----------------------------------------------------------------
292 void Comment::paint (QPainter *p) {
293 Widget *m = dynamic_cast<Widget*>(topLevelCanvas());
295 if(curr_highlight != 0) {
296 p->setBrush(QColor(255,255,255, curr_highlight));
297 p->setPen(QColor(192,192,192, curr_highlight));
298 p->drawRect(rect().adjusted(0,0,-1,-1));
300 p->setFont(m->m_settings->comm_font);
301 p->setPen(m->m_settings->comment_color);
302 p->drawText(pos().x() + MARGIN_RIGHT,
303 pos().y(),
304 width - MARGIN_LEFT - MARGIN_RIGHT, 9999,
305 Qt::AlignLeft|Qt::AlignTop|Qt::TextWordWrap, text);
308 QRect Comment::rect () const {
309 return QRect(pos(), QSize(width, height));
312 void Comment::doUpdate () {
313 if(!needs_update)
314 return;
316 Widget *m = dynamic_cast<Widget*>(topLevelCanvas());
317 QPoint dest = ((time_pos != -1) ? target_pos : pos());
318 width = std::max(m->width() - dest.x(), m->entry_size);
319 height = m->m_settings->comm_fmetrics.boundingRect(0,0,width - MARGIN_LEFT - MARGIN_RIGHT, 99999,
320 Qt::AlignLeft|Qt::AlignTop|Qt::TextWordWrap, text).height()
321 + MARGIN_TOP + MARGIN_BOTTOM;
323 needs_update = false;
324 changed();
327 //END Comment------------------------------------------------------------------
330 //BEGIN Entry------------------------------------------------------------------
332 void Entry::paint (QPainter *p) {
333 Widget *m = dynamic_cast<Widget*>(topLevelCanvas());
334 if(curr_highlight != 0) {
335 p->setBrush(QColor(192,224,255, curr_highlight));
336 p->setPen(QColor(64,96,128, curr_highlight));
337 p->drawRect(rect().adjusted(0,0,-1,-1));
339 p->setPen(selected ? m->m_settings->select_color : Qt::black);
340 int x = pos().x()+MARGIN_LEFT;
341 int y = pos().y()+MARGIN_TOP+m_ascent;
343 p->setRenderHint(QPainter::TextAntialiasing);
344 QFont tf = selected ? m->m_settings->sel_mv_font : m->m_settings->mv_font;
345 QFontMetrics& fm = selected ? m->m_settings->sel_mv_fmetrics : m->m_settings->mv_fmetrics;
346 QRect r(0,0,0,0);
348 for(int i=0;i<(int)move.size();i++) {
349 if(move[i].m_type == MovePart::Text) {
350 p->setFont(tf);
351 p->drawText(QPoint(x+r.width(), y), move[i].m_string);
352 QRect b = fm.boundingRect(move[i].m_string);
353 r |= b.translated(r.width()-b.x(), 0);
355 else if(move[i].m_type == MovePart::Figurine) {
356 ::Loader::Glyph g = m->m_loader.getValue< ::Loader::Glyph>(move[i].m_string);
357 QFont font = g.fontValid() ? g.font() : tf;
358 p->setFont(font);
359 p->drawText(QPoint(x+r.width(), y), g.str());
360 QFontMetrics fi(font);
361 QRect b = fi.boundingRect(g.str());
362 r |= b.translated(r.width()-b.x(), 0);
367 QRect Entry::rect () const {
368 return m_rect.translated(pos().x()+MARGIN_LEFT, pos().y()+MARGIN_TOP+m_ascent);
371 void Entry::doUpdate () {
372 if(!needs_update)
373 return;
375 Widget *m = dynamic_cast<Widget*>(topLevelCanvas());
376 QFont tf = selected ? m->m_settings->sel_mv_font : m->m_settings->mv_font;
377 QFontMetrics& fm = selected ? m->m_settings->sel_mv_fmetrics : m->m_settings->mv_fmetrics;
378 m_ascent = m->m_settings->mv_fmetrics.ascent();
379 m_rect = QRect(0,0,0,0);
381 for(int i=0;i<(int)move.size();i++) {
382 if(move[i].m_type == MovePart::Text) {
383 QRect b = fm.boundingRect(move[i].m_string);
384 m_rect |= b.translated(m_rect.width()-b.x(), 0);
386 else if(move[i].m_type == MovePart::Figurine) {
387 ::Loader::Glyph g = m->m_loader.getValue< ::Loader::Glyph>(move[i].m_string);
388 QFontMetrics fi(g.fontValid() ? g.font() : tf);
389 QRect b = fi.boundingRect(g.str());
390 m_rect |= b.translated(m_rect.width()-b.x(), 0);
393 m_rect = QRect(m_rect.x(),m_rect.y(),m_rect.width()+MARGIN_RIGHT,m_rect.height());
395 needs_update = false;
396 changed();
399 //END Entry--------------------------------------------------------------------
402 //BEGIN Settings---------------------------------------------------------------
404 void Settings::load() {
405 ::Settings s = settings().group("move-list");
406 ::Settings s_anim = s.group("animations");
408 anim_enabled = s.group("animations").flag("enabled", true);
409 anim_moving = s_anim.group("moving").flag("enabled", true);
410 anim_hideshow = s_anim.group("hideshow").flag("enabled", true);
411 anim_highlight = s_anim.group("highlight").flag("enabled", true);
412 anim_speed = s_anim["speed"] | 16;
413 anim_time = DEFAULT_ANIMATION_TIME*pow(5.0, 1.0 - anim_speed/16.0);
414 anim_smoothness = s_anim["smoothness"] | 16;
415 select_color = s["select-color"] | QColor(Qt::red);
416 comment_color = s["comment-color"] | QColor(64,64,64);
417 mv_font = QApplication::font();
418 if ((use_mv_font = s.group("moves-font").flag("enabled", true)))
419 mv_font = s["moves-font"] | mv_font;
420 sel_mv_font = mv_font;
421 sel_mv_font.setBold(true);
422 comm_font = QApplication::font();
423 comm_font.setItalic(true);
424 if ((use_comm_font = s.group("comment-font").flag("enabled", true)))
425 comm_font = s["CommentFont"] | comm_font;
426 mv_fmetrics = QFontMetrics(mv_font);
427 sel_mv_fmetrics = QFontMetrics(sel_mv_font);
428 comm_fmetrics = QFontMetrics(comm_font);
431 void Settings::save() {
432 ::Settings s = settings().group("move-list");
433 ::Settings s_anim = s.group("animations");
435 s.group("animations").setFlag("enabled", anim_enabled);
436 s_anim.group("moving").setFlag("enabled", anim_moving);
437 s_anim.group("hideshow").setFlag("enabled", anim_hideshow);
438 s_anim.group("highlight").setFlag("enabled", anim_highlight);
439 s_anim["speed"] = anim_speed;
440 s_anim["smoothness"] = anim_smoothness;
441 s["select-color"] = select_color;
442 s["comment-color"] = comment_color;
443 s.group("moves-font").flag("enabled", use_mv_font);
444 s["moves-font"] = mv_font;
445 s.group("comment-font").flag("enabled", use_comm_font);
446 s["comment-font"] = comm_font;
449 //END Settings-----------------------------------------------------------------
452 //BEGIN Widget-----------------------------------------------------------------
454 Widget::Widget(QWidget *parent, Table *o)
455 : KGameCanvasWidget(parent)
456 , curr_highlight(-1)
457 , curr_selected(-1)
458 , comment_editor(NULL)
459 , layout_pending(false)
460 , layout_style(0)
461 , layout_goto_selected(false)
462 , layout_width_changed(true)
463 , layout_must_relayout(true)
464 , notifier(NULL)
465 , owner_table(o)
466 , m_settings(new Settings) {
468 resize(50,100);
469 setSizePolicy ( QSizePolicy::MinimumExpanding, QSizePolicy::Minimum );
471 setMouseTracking(true);
472 settingsChanged();
473 reset();
476 Widget::~Widget() {
477 delete m_settings;
480 void Widget::reset() {
481 curr_highlight = Index(-1);
482 curr_selected = Index(-1);
483 if(comment_editor) {
484 delete comment_editor;
485 comment_editor = NULL;
488 DecoratedMove mv;
489 mv.push_back(MovePart(QString("Mainline:")));
490 history.clear();
491 history.push_back( EntryPtr(new Entry(-1, mv, Index(0), this)) );
493 layout();
496 EntryPtr Widget::fetch(const Index& ix) {
497 int at;
498 History *vec = fetchRef(ix, &at);
499 return vec ? (*vec)[at] : EntryPtr();
502 History* Widget::fetchRef(const Index& ix, int* idx) {
503 if(ix.num_moves >= (int)history.size() || ix.num_moves < 0 )
504 return NULL;
506 History* aretv = &history;
507 EntryPtr retv = history[ix.num_moves];
508 if(idx) *idx = ix.num_moves;
510 for(int i=0; i<(int)ix.nested.size();i++) {
511 Variations::iterator it = retv->variations.find(ix.nested[i].variation);
512 if(it == retv->variations.end() || ix.nested[i].num_moves >= (int)it->second.size()
513 || ix.nested[i].num_moves < 0 )
514 return NULL;
516 aretv = &it->second;
517 retv = it->second[ix.nested[i].num_moves];
518 if(idx) *idx = ix.nested[i].num_moves;
520 return aretv;
523 Notifier* Widget::getNotifier() {
524 return notifier;
527 void Widget::setNotifier(Notifier* n, bool detach_prev){
528 if(detach_prev && notifier && notifier != n)
529 notifier->onDetachNotifier();
530 notifier = n;
533 void Widget::settingsChanged() {
534 m_settings->load();
536 setAnimationDelay( int(70.0*pow(10.0, -m_settings->anim_smoothness/32.0)) );
538 entry_size = m_settings->mv_fmetrics.height()+MARGIN_TOP+MARGIN_BOTTOM;
539 owner_table->m_scroll_area->setMinimumSize(entry_size*6, entry_size*9);
541 m_loader.setSize(m_settings->mv_font.pointSize());
543 layout_must_relayout = true;
544 layout();
547 void Widget::mouseMoveEvent ( QMouseEvent * event ) {
548 KGameCanvasItem *i = itemAt(event->pos());
549 Entry* e = i ? dynamic_cast<Entry*>(i) : NULL;
550 Text* f = i ? dynamic_cast<Text*>(i) : NULL;
551 Brace* b = i ? dynamic_cast<Brace*>(i) : NULL;
552 Comment* c = i ? dynamic_cast<Comment*>(i) : NULL;
553 EntryPtr olde = fetch(curr_highlight);
554 f = f && f->type == 1 ? f : NULL;
556 int oldtype = curr_highlight_type;
558 if(e) {
559 if(curr_highlight == e->index && curr_highlight_type==-1)
560 return;
561 e->setHighlight(true);
562 curr_highlight = e->index;
563 curr_highlight_type = -1;
565 else if(f) {
566 if(curr_highlight == f->entry->index && curr_highlight_type==-2)
567 return;
568 f->setHighlight(true);
569 curr_highlight = f->entry->index;
570 curr_highlight_type = -2;
572 else if(c) {
573 if( (curr_highlight==c->entry->index) &&
574 ((c->variation==-1) ? (curr_highlight_type == -3) :
575 (curr_highlight_type == -1000-c->variation) ) )
576 return;
577 c->setHighlight(true);
578 curr_highlight = c->entry->index;
579 curr_highlight_type = (c->variation==-1) ? -3 : (-1000-c->variation);
581 else if(b) {
582 if(curr_highlight == b->entry->index && curr_highlight_type==b->variation)
583 return;
584 b->setHighlight(true);
585 curr_highlight = b->entry->index;
586 curr_highlight_type = b->variation;
588 else
589 curr_highlight = Index(-1);
591 if(olde) {
592 if(oldtype==-1)
593 olde->setHighlight(false);
594 else if(oldtype==-2 && olde->fregna)
595 olde->fregna->setHighlight(false);
596 else if(oldtype==-3 && olde->comment)
597 olde->comment->setHighlight(false);
598 else if(oldtype<=-1000 && olde->vcomments.count(-1000-oldtype)==1)
599 olde->vcomments[-1000-oldtype]->setHighlight(false);
600 else if(oldtype>=0 && olde->braces.count(oldtype)==1)
601 olde->braces[oldtype]->setHighlight(false);
605 void Widget::startEditing(const Index& i, int v) {
606 stopEditing();
608 EntryPtr e = fetch(i);
609 if(!e) {
610 ERROR("Invalid index " << i);
611 return;
614 CommentPtr c = v == -1 ? e->comment : (e->vcomments.count(v) ?
615 e->vcomments[v] : CommentPtr());
616 QRect rect;
617 if(c)
618 rect = c->rect();
619 else {
620 TextPtr n = e->number;
621 if(!n && i > Index(0))
622 n = fetch(i.prev())->number;
623 int x = (n ? n->pos().x() : e->pos().x()) + ((v == -1) ? 0 : VAR_INDENTATION);
625 rect = QRect(x, e->pos().y()+entry_size, width()-x, 0);
628 edited_comment_variation = v;
629 edited_comment = boost::weak_ptr<Entry>(e);
630 comment_editor = new QTextEdit(c ? c->text : QString(), this);
631 comment_editor->setGeometry(rect.adjusted(0,0,0,entry_size*3));
632 comment_editor->show();
633 comment_editor->setFocus(Qt::MouseFocusReason);
634 comment_editor->installEventFilter(this);
637 bool Widget::eventFilter(QObject *obj, QEvent *event) {
638 if(obj == comment_editor && event->type() == QEvent::FocusOut ) {
639 stopEditing();
640 return true;
642 return false;
645 void Widget::stopEditing() {
646 EntryPtr e = edited_comment.lock();
647 if(e) {
648 if(comment_editor && notifier) {
649 QString c = comment_editor->toPlainText();
650 c.replace(QRegExp("(?:[ \t]\r?\n\r?|\r?\n\r?[ \t]|\r?\n\r?)"), " ");
651 if(edited_comment_variation == -1)
652 notifier->onUserSetComment(e->index, c);
653 else
654 notifier->onUserSetVComment(e->index, edited_comment_variation, c);
656 edited_comment.reset();
658 if(comment_editor) {
659 comment_editor->deleteLater();
660 comment_editor = NULL;
664 void Widget::mousePressEvent ( QMouseEvent * event ) {
665 stopEditing();
667 KGameCanvasItem *i = itemAt(event->pos());
668 if(!i)
669 return;
671 Text *t = dynamic_cast<Text*>(i);
672 if(t && t->type == 1) {
673 Entry *e = t->entry;
674 if(e->hide_next) {
675 e->hide_next = false;
676 e->expanded = true;
678 else
679 e->expanded = !e->expanded;
680 layout();
681 return;
684 Brace *b = dynamic_cast<Brace*>(i);
685 if(b) {
686 if(event->button() == Qt::LeftButton) {
687 Entry* e = b->entry;
688 EntryPtr first = e->variations[b->variation][0];
689 first->hide_next = !first->hide_next;
690 layout();
692 else if(event->button() == Qt::RightButton) {
693 QAction *a;
694 QMenu m(this);
695 a = m.addAction(KIcon("pen"), "&Set comment");
696 a->setData("comment");
697 m.addSeparator();
698 a = m.addAction(KIcon(), "&Promote variation");
699 a->setData("promote");
700 a = m.addAction(KIcon("edit-delete"), "&Remove variation");
701 a->setData("remove");
702 boost::weak_ptr<Entry> ewptr = boost::weak_ptr<Entry>(fetch(b->entry->index));
703 int v = b->variation;
705 a = m.exec(event->globalPos());
707 /* beware, here, after exec, e could be a dangling pointer */
708 EntryPtr eptr = ewptr.lock();
709 if(a && notifier && eptr && eptr->variations.count(v)) {
710 if(a->data() == "comment")
711 startEditing(eptr->index, v);
712 else if(a->data() == "promote")
713 notifier->onUserPromoteVariation(eptr->index.next(v));
714 else if(a->data() == "remove")
715 notifier->onUserRemoveVariation(eptr->index.next(v));
718 return;
721 Comment *c = dynamic_cast<Comment*>(i);
722 if(c) {
723 startEditing(c->entry->index, c->variation);
724 return;
727 Entry *e = dynamic_cast<Entry*>(i);
728 if(e) {
729 if(event->button() == Qt::LeftButton) {
730 if(notifier)
731 notifier->onUserSelectMove(e->index);
733 else if(event->button() == Qt::RightButton) {
734 QAction *a;
735 QMenu m(this);
736 a = m.addAction(KIcon("pen"), "&Set comment");
737 a->setData("comment");
738 a = m.addAction(KIcon("eraser"), "&Clear variations");
739 a->setEnabled(!e->variations.empty());
740 a->setData("clear");
741 a = m.addAction(KIcon("cut"), "&Truncate");
742 a->setEnabled(fetch(e->index.next()));
743 a->setData("truncate");
744 m.addSeparator();
745 a = m.addAction(KIcon(), "&Promote variation");
746 a->setEnabled(e->index.nested.size());
747 a->setData("promote");
748 a = m.addAction(KIcon("edit-delete"), "&Remove variation");
749 a->setEnabled(e->index.nested.size());
750 a->setData("remove");
751 boost::weak_ptr<Entry> ewptr = boost::weak_ptr<Entry>(fetch(e->index));
753 a = m.exec(event->globalPos());
755 /* beware, here, after exec, e could be a dangling pointer */
756 EntryPtr eptr = ewptr.lock();
757 if(a && notifier && eptr) {
758 if(a->data() == "comment")
759 startEditing(eptr->index, -1);
760 else if(a->data() == "clear")
761 notifier->onUserClearVariations(eptr->index);
762 else if(a->data() == "truncate")
763 notifier->onUserTruncate(eptr->index);
764 else if(a->data() == "promote")
765 notifier->onUserPromoteVariation(eptr->index);
766 else if(a->data() == "remove")
767 notifier->onUserRemoveVariation(eptr->index);
770 return;
774 void Widget::mouseReleaseEvent ( QMouseEvent * /*event*/ ) {
778 void Widget::resizeEvent ( QResizeEvent * event ) {
779 stopEditing();
780 if(event->size().width() != event->oldSize().width()) {
781 layout_width_changed = true;
782 layout();
786 void Widget::layout() {
787 if(layout_pending)
788 return;
790 layout_pending = true;
791 QTimer::singleShot( 0, this, SLOT(doLayout()) );
794 void Widget::doLayout() {
795 layout_time = mSecs();
796 layout_pending = false;
797 layout_max_width = 0;
798 //std::cout << "layout_must_relayout = " << layout_must_relayout << std::endl;
799 int h = layoutHistory(history, BORDER_LEFT, BORDER_TOP, -1, 0, 0, true);
801 QSize s(std::max(entry_size*7, layout_max_width+BORDER_RIGHT),
802 std::max(entry_size*10, h+BORDER_BOTTOM) );
803 setMinimumSize(s);
805 layout_width_changed = false;
806 layout_must_relayout = false;
807 if(layout_goto_selected) {
808 EntryPtr e = fetch(curr_selected);
809 if(e)
810 owner_table->m_scroll_area->ensureVisible( int(e->pos().x() + e->m_rect.width()*0.5),
811 int(e->pos().y() + e->m_rect.height()*0.5) );
812 layout_goto_selected = false;
816 int Widget::layoutHistory(History& array, int at_x, int at_y,
817 int a_prev_turn, int mv_num, int sub_mv_num, bool visible) {
818 int flow_y = at_y;
819 int flow_x = at_x;
820 int nflow_x = at_x;
821 int col_num = 0;
822 int prev_turn = a_prev_turn;
824 for(int i=0;i<(int)array.size();i++) {
825 EntryPtr e = array[i];
827 /* if this is not visible, hide the item and hide all the number/fregna tags */
828 if(!visible) {
829 e->disappear();
830 if(e->number)
831 e->number->disappear();
832 if(e->fregna)
833 e->fregna->disappear();
834 if(e->comment)
835 e->comment->disappear();
837 /* hide the subvariations */
838 for(Variations::iterator it = e->variations.begin(); it != e->variations.end(); ++it)
839 layoutHistory(it->second, 0, 0, e->move_turn, mv_num, sub_mv_num, false);
840 for(Braces::iterator it = e->braces.begin(); it != e->braces.end(); ++it)
841 it->second->disappear();
842 for(VComments::iterator it = e->vcomments.begin(); it != e->vcomments.end(); ++it)
843 it->second->disappear();
844 mv_num++;
845 continue;
848 /* adjust the position if this is paired on the right */
849 bool draw_num = false;
852 if(e->move_turn != prev_turn) {
853 mv_num++;
854 sub_mv_num = 0;
856 else
857 sub_mv_num++;
859 if(layout_style==0) {
860 if(e->move_turn == 0 || i==0 || array[i-1]->childs_height != 0) {
861 if(mv_num>=1 && (e->move_turn != prev_turn || i==0 || array[i-1]->childs_height != 0)) {
862 draw_num = true;
863 flow_x = at_x;
865 else
866 flow_x = (mv_num>=1) ? nflow_x : at_x;
868 else {
869 if(e->move_turn != prev_turn) {
870 flow_x = std::max(flow_x + MIDDLE_PAD, int(MIN_COL_WIDTH*entry_size));
871 flow_y -= entry_size;
873 else
874 flow_x = int(MIN_COL_WIDTH*entry_size);
877 else {
878 if(e->move_turn != prev_turn || i==0 || array[i-1]->childs_height != 0) {
879 col_num = 0;
880 flow_x = at_x;
881 if(mv_num>=1)
882 draw_num = true;
884 else if(col_num == layout_style) {
885 col_num = 0;
886 flow_x = nflow_x;
888 else {
889 flow_y -= entry_size;
890 flow_x = std::max(flow_x + MIDDLE_PAD,
891 at_x + col_num*int(MIN_COL_WIDTH*entry_size));
896 col_num++;
898 /* update the number */
899 if(draw_num) {
900 TextPtr& n = e->number;
901 if(!n) {
902 n = TextPtr(new Text(e.get(), 0, this));
903 if(layout_style==0)
904 n->text = QString::number((mv_num+1)/2)+(mv_num&1 ? "." : ". ...");
905 else
906 n->text = QString::number(mv_num)+
907 (sub_mv_num ? "+"+QString::number(sub_mv_num) : QString())+".";
908 n->needs_update = true;
910 else if( !n->showing() || layout_must_relayout)
911 n->needs_update = true;
913 /* Mh, the number should never change, only appear disappear.
914 should this change, add here the code to enable number changes. */
915 QPoint dest(flow_x, flow_y);
917 if(n->pos() != dest)
918 if(n->visible())
919 n->goTo(dest);
920 else
921 n->moveTo(dest);
922 n->doUpdate();
923 n->appear();
925 flow_x += n->width;
926 nflow_x = flow_x;
928 else if(e->number)
929 e->number->disappear();
932 /* update the entry */
933 QPoint dest(flow_x, flow_y);
934 if(e->pos() != dest)
935 if(e->visible())
936 e->goTo(dest);
937 else
938 e->moveTo(dest);
939 if( !e->showing() || layout_must_relayout)
940 e->needs_update = true;
941 e->doUpdate();
942 e->appear();
943 e->childs_height = 0;
944 flow_x += e->m_rect.width();
947 /* Update the fregna. The fregna is visible if there are subvariations in this
948 entry, or if this entry is the first one of a variation where the remaining
949 entries are hidden and that contains the current position */
950 bool expandable = !e->variations.empty() || e->comment;
951 bool sel = (e->hide_next && e->index<curr_selected)
952 || (!e->expanded && expandable &&
953 e->index<curr_selected && !(e->index.next()<=curr_selected));
954 if(expandable || sel ) {
955 if(!e->fregna)
956 e->fregna = TextPtr(new Text(e.get(), 1, this));
958 /* update the data, if needed */
959 TextPtr f = e->fregna;
960 const char *text = (sel||!e->expanded||e->hide_next) ? "[+]" : "[-]";
961 if(f->text != text || f->selected != sel) {
962 f->text = text;
963 f->selected = sel;
964 f->needs_update = true;
966 else if( !f->showing() || layout_must_relayout)
967 f->needs_update = true;
969 QPoint dest(flow_x, flow_y);
971 if(f->pos() != dest)
972 if(f->visible())
973 f->goTo(QPoint(flow_x, flow_y));
974 else
975 f->moveTo(QPoint(flow_x, flow_y));
976 f->doUpdate();
977 f->appear();
979 flow_x += f->width;
981 else if(e->fregna)
982 e->fregna->disappear();
984 /* update the flow information */
985 flow_y += entry_size;
986 layout_max_width = std::max(flow_x, layout_max_width);
987 int prev_pos = flow_y;
989 /* update the comment */
990 if(e->comment) {
991 CommentPtr c = e->comment;
993 if(e->expanded && !e->hide_next) {
994 QPoint dest(at_x + COMMENT_INDENTATION, flow_y);
996 if(c->pos() != dest ) {
997 if(c->visible())
998 c->goTo(dest);
999 else
1000 c->moveTo(dest);
1001 c->needs_update = true;
1003 else if( !c->showing() || layout_width_changed || layout_must_relayout)
1004 c->needs_update = true;
1005 c->doUpdate();
1006 c->appear();
1007 flow_y += c->height;
1009 else
1010 c->disappear();
1013 /* update the variations */
1014 for(Variations::iterator it = e->variations.begin(); it != e->variations.end(); ++it) {
1015 int old_pos = flow_y;
1017 /* update the variation's comment */
1018 if(e->vcomments.count(it->first)) {
1019 CommentPtr c = e->vcomments[it->first];
1021 if(e->expanded && !e->hide_next) {
1022 QPoint dest(at_x + VAR_INDENTATION + COMMENT_INDENTATION, flow_y);
1024 if( !c->showing() || layout_must_relayout)
1025 c->needs_update = true;
1026 if(c->pos() != dest)
1027 if(c->visible())
1028 c->goTo(dest);
1029 else
1030 c->moveTo(dest);
1031 c->doUpdate();
1032 c->appear();
1033 flow_y += c->height;
1035 else
1036 c->disappear();
1039 /* layout the variation */
1040 flow_y = layoutHistory(it->second, at_x + VAR_INDENTATION, flow_y,
1041 e->move_turn, mv_num, sub_mv_num, e->expanded && !e->hide_next);
1043 /* update the brace of the variation */
1044 BracePtr b = e->braces[it->first];
1045 if(e->expanded && !e->hide_next) {
1046 b->depth = e->index.nested.size();
1047 b->setHeight((it->second.size() && it->second[0]->hide_next) ? entry_size : flow_y - old_pos);
1048 b->width = VAR_INDENTATION;
1049 if(b->visible())
1050 b->goTo(QPoint(at_x, old_pos));
1051 else
1052 b->moveTo(QPoint(at_x, old_pos));
1053 b->appear();
1055 else
1056 b->disappear();
1059 e->childs_height = flow_y - prev_pos;
1061 if(e->hide_next)
1062 visible = false;
1063 prev_turn = e->move_turn;
1065 return flow_y;
1068 QPixmap Widget::getPixmap(const QString& s, bool selected) {
1069 QString k = selected ? s+"_sel":s;
1070 if(loaded_pixmaps.contains(k))
1071 return loaded_pixmaps[k];
1073 QString iconFile = KStandardDirs::locate("appdata", "piece_icons/" + s + ".png");
1074 QImage img(iconFile);
1076 if(selected) {
1077 QPainter p(&img);
1078 p.setCompositionMode(QPainter::CompositionMode_SourceAtop );
1079 p.fillRect(0,0,img.width(), img.height(), m_settings->select_color);
1081 return loaded_pixmaps[k] = QPixmap::fromImage(img.scaled(m_settings->mv_fmetrics.ascent(),
1082 m_settings->mv_fmetrics.ascent(),
1083 Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
1086 void Widget::setComment(EntryPtr e, int v, const QString& comment) {
1087 if(comment.isEmpty()) {
1088 if(v == -1) {
1089 if(e->comment)
1090 e->comment = CommentPtr();
1092 else {
1093 if(e->vcomments.count(v))
1094 e->vcomments.erase(v);
1097 else {
1098 CommentPtr p;
1100 if(v == -1) {
1101 if(!e->comment)
1102 e->comment = CommentPtr(new Comment(e.get(), this));
1103 p = e->comment;
1105 else {
1106 if(!e->variations.count(v))
1107 return;
1109 if(!e->vcomments.count(v))
1110 p = e->vcomments[v] = CommentPtr(new Comment(e.get(), this, v));
1111 else
1112 p = e->vcomments[v];
1115 if(p->text == comment)
1116 return;
1117 p->text = comment;
1118 p->needs_update = true;
1121 layout();
1124 void Widget::setComment(const Index& index, const QString& comment) {
1125 EntryPtr e = fetch(index);
1126 if(!e) {
1127 ERROR("Invalid index " << index);
1128 return;
1130 setComment(e, -1, comment);
1133 void Widget::setVComment(const Index& index, int v, const QString& comment) {
1134 EntryPtr e = fetch(index);
1135 if(!e || !e->variations.count(v)) {
1136 ERROR("Invalid index " << index);
1137 return;
1139 setComment(e, v, comment);
1142 void Widget::setMove(const Index& index,
1143 int turn, const QString& move, const QString& comment) {
1144 DecoratedMove mv;
1145 #if 1
1146 mv.push_back(MovePart(move));
1147 #else
1148 //TODO: move this code in some other place, it really should not stay here
1149 QRegExp reg("[KQRBNP]");
1150 int x = 0;
1151 while(reg.indexIn(move, x) != -1) {
1152 if(reg.pos() > x)
1153 mv.push_back(MovePart(MoveText, move.mid(x, reg.pos()-x)));
1154 mv.push_back(MovePart(MovePixmap, reg.cap().toLower()));
1155 x = reg.pos() + reg.matchedLength();
1157 if(x<move.length())
1158 mv.push_back(MovePart(MoveText, move.mid(x)));
1159 #endif
1160 setMove(index, turn, mv, comment);
1163 void Widget::setMove(const Index& index,
1164 int turn, const DecoratedMove& move, const QString& comment) {
1165 EntryPtr e = fetch(index);
1166 if(e) {
1167 e->move_turn = turn;
1168 e->move = move;
1169 e->needs_update = true;
1170 setComment(e, -1, comment);
1171 layout();
1172 return;
1175 int at;
1176 History *vec = fetchRef(index.prev(), &at);
1177 if(!vec) {
1178 ERROR("Invalid index " << index);
1179 return;
1182 if(index.nested.size() && index.nested.back().num_moves == 0) {
1183 History var;
1184 int v = index.nested.back().variation;
1185 var.push_back(e = EntryPtr( new Entry(turn, move, index, this)) );
1186 (*vec)[at]->variations[v] = var;
1187 (*vec)[at]->braces[v] = BracePtr( new Brace( (*vec)[at].get(), v, this) );
1189 else
1190 vec->push_back(e = EntryPtr( new Entry(turn, move, index, this)) );
1192 setComment(e, -1, comment);
1193 e->hide();
1194 layout();
1197 void Widget::remove(const Index& index) {
1199 if(index.atVariationStart() ) {
1200 EntryPtr e = fetch(index.prev());
1201 if(!e)
1202 return;
1204 int v = index.nested.back().variation;
1205 if(!e->variations.count(v))
1206 return;
1208 e->variations.erase(v);
1209 e->braces.erase(v);
1210 e->vcomments.erase(v);
1212 else {
1213 int at;
1214 History *vec = fetchRef(index, &at);
1215 if(!vec)
1216 return;
1218 while((int)vec->size() > at)
1219 vec->pop_back();
1221 layout();
1224 void Widget::fixIndices(const Index& ix) {
1225 int at;
1226 History *vec = fetchRef(ix, &at);
1227 if(!vec) {
1228 ERROR("Invalid index " << ix);
1229 return;
1231 Index index = ix;
1232 for(int i=at;i<(int)vec->size();i++) {
1233 EntryPtr e = (*vec)[i];
1234 e->index = index;
1236 for(Variations::const_iterator it = e->variations.begin();
1237 it != e->variations.end(); ++it)
1238 fixIndices(index.next(it->first));
1239 index = index.next();
1243 void Widget::promoteVariation(const Index& ix, int v) {
1244 int at;
1245 History *vec = fetchRef(ix, &at);
1246 if(!vec) {
1247 ERROR("Invalid index " << ix);
1248 return;
1251 History vold = (*vec)[at]->variations[v];
1252 History vnew;
1253 for(int i=at+1; i<(int)vec->size(); i++)
1254 vnew.push_back((*vec)[i]);
1255 while((int)vec->size()>at+1)
1256 vec->pop_back();
1257 for(int i=0; i<(int)vold.size(); i++)
1258 vec->push_back(vold[i]);
1259 (*vec)[at]->variations[v] = vnew;
1261 Q_ASSERT((int)vec->size()>at+1);
1262 (*vec)[at+1]->hide_next = false;
1264 fixIndices(ix.next());
1265 fixIndices(ix.next(v));
1267 curr_selected = curr_selected.flipVariation(ix, v);
1268 curr_highlight = curr_highlight.flipVariation(ix, v);
1269 layout();
1272 void Widget::select(const Index& index) {
1273 if(curr_selected == index)
1274 return;
1275 EntryPtr e = fetch(index);
1276 EntryPtr olde = fetch(curr_selected);
1277 if(olde) {
1278 olde->selected = false;
1279 olde->needs_update = true;
1281 if(e) {
1282 e->selected = true;
1283 e->needs_update = true;
1284 layout_goto_selected = true;
1286 curr_selected = index;
1287 layout();
1290 void Widget::setLoaderTheme(const ThemeInfo& theme) {
1291 m_loader.setTheme(theme);
1294 //END Widget-------------------------------------------------------------------
1296 } //end namespace MoveList