Rough PGN save support.
[tagua/yd.git] / src / movelist.cpp
blobd3393a70029f1bd0c01046619dda7d3782210106
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 p->setFont(g.fontValid() ? g.font() : tf);
358 p->drawText(QPoint(x+r.width(), y), g.ch());
359 QFontMetrics fi(g.fontValid() ? g.font() : tf);
360 QRect b = fi.boundingRect(g.ch());
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.ch());
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 ERROR("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 //std::cout << "layout_must_relayout = " << layout_must_relayout << std::endl;
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 ERROR("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 ERROR("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 ERROR("Invalid index " << index);
1178 return;
1181 if(index.nested.size() && index.nested[index.nested.size()-1].num_moves == 0) {
1182 History var;
1183 int v = index.nested[index.nested.size()-1].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[index.nested.size()-1].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 ERROR("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 ERROR("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