File: annotationPanel.py

package info (click to toggle)
pychess 0.12~beta3-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 12,976 kB
  • ctags: 3,647
  • sloc: python: 27,592; makefile: 15; sh: 6
file content (600 lines) | stat: -rw-r--r-- 24,290 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
# -*- coding: UTF-8 -*-

import datetime

import gtk
import pango

from pychess.Utils.const import *
from pychess.System import conf
from pychess.System.glock import glock_connect
from pychess.System.prefix import addDataPrefix
from pychess.Utils.lutils.lmove import toSAN, toFAN
from pychess.Savers.pgn import move_count
from pychess.Savers.pgnbase import nag2symbol
from pychess.widgets.ChessClock import formatTime

__title__ = _("Annotation")
__active__ = True
__icon__ = addDataPrefix("glade/panel_annotation.svg")
__desc__ = _("Annotated game")


class Sidepanel(gtk.TextView):
    def __init__(self):
        gtk.TextView.__init__(self)

        self.set_editable(False)
        self.set_cursor_visible(False)
        self.set_wrap_mode(gtk.WRAP_WORD)

        self.cursor_standard = gtk.gdk.Cursor(gtk.gdk.LEFT_PTR)
        self.cursor_hand = gtk.gdk.Cursor(gtk.gdk.HAND2)
        
        self.textview = self
        
        self.nodeIters = []
        self.commentIters = []
        self.oldWidth = 0
        self.autoUpdateSelected = True
        
        self.connect("motion-notify-event", self.motion_notify_event)
        self.connect("button-press-event", self.button_press_event)
        
        self.textbuffer = self.get_buffer()
        
        self.textbuffer.create_tag("head1")
        self.textbuffer.create_tag("head2", weight=pango.WEIGHT_BOLD)
        self.textbuffer.create_tag("node", weight=pango.WEIGHT_BOLD)
        self.textbuffer.create_tag("clock", foreground="darkgrey")
        self.textbuffer.create_tag("comment", foreground="darkblue")
        self.textbuffer.create_tag("variation-toplevel")
        self.textbuffer.create_tag("variation-even", foreground="darkgreen", style="italic")
        self.textbuffer.create_tag("variation-uneven", foreground="darkred", style="italic")
        self.textbuffer.create_tag("selected", background_full_height=True, background="black", foreground="white")
        self.textbuffer.create_tag("margin", left_margin=4)
        self.textbuffer.create_tag("variation-margin0", left_margin=20)
        self.textbuffer.create_tag("variation-margin1", left_margin=36)
        self.textbuffer.create_tag("variation-margin2", left_margin=52)

    def load(self, gmwidg):
        __widget__ = gtk.ScrolledWindow()
        __widget__.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_ALWAYS)
        __widget__.add(self.textview)

        self.boardview = gmwidg.board.view
        self.boardview.connect("shown_changed", self.shown_changed)

        self.gamemodel = gmwidg.board.view.model
        glock_connect(self.gamemodel, "game_loaded", self.update)
        glock_connect(self.gamemodel, "game_changed", self.game_changed)
        glock_connect(self.gamemodel, "game_started", self.update)
        glock_connect(self.gamemodel, "game_ended", self.update)
        glock_connect(self.gamemodel, "moves_undoing", self.moves_undoing)
        glock_connect(self.gamemodel, "opening_changed", self.update)
        glock_connect(self.gamemodel, "players_changed", self.update)
        glock_connect(self.gamemodel, "variations_changed", self.update)

        # Connect to preferences
        self.fan = conf.get("figuresInNotation", False)
        def figuresInNotationCallback(none):
            self.fan = conf.get("figuresInNotation", False)
            self.update()
        conf.notify_add("figuresInNotation", figuresInNotationCallback)
        
        self.showClocks = conf.get("showClocks", False)
        def showClocksCallback(none):
            self.showClocks = conf.get("showClocks", False)
            self.update()
        conf.notify_add("showClocks", showClocksCallback)

        return __widget__

    def motion_notify_event(self, widget, event):
        if (event.is_hint):
            (x, y, state) = event.window.get_pointer()
        else:
            x = event.x
            y = event.y
            state = event.state
            
        if self.textview.get_window_type(event.window) != gtk.TEXT_WINDOW_TEXT:
            event.window.set_cursor(self.cursor_standard)
            return True
            
        (x, y) = self.textview.window_to_buffer_coords(gtk.TEXT_WINDOW_WIDGET, int(x), int(y))
        it = self.textview.get_iter_at_location(x, y)
        offset = it.get_offset()
        for ni in self.nodeIters:
            if offset >= ni["start"] and offset < ni["end"]:
                event.window.set_cursor(self.cursor_hand)
                return True
        for ci in self.commentIters:
            if offset >= ci["start"] and offset < ci["end"]:
                event.window.set_cursor(self.cursor_hand)
                return True
        event.window.set_cursor(self.cursor_standard)
        return True

    def button_press_event(self, widget, event):
        (wx, wy) = event.get_coords()
        (x, y) = self.textview.window_to_buffer_coords(gtk.TEXT_WINDOW_WIDGET, int(wx), int(wy))
        it = self.textview.get_iter_at_location(x, y)
        offset = it.get_offset()

        node = None
        for ni in self.nodeIters:
            if offset >= ni["start"] and offset < ni["end"]:
                node = ni
                board = ni["node"]
                parent = ni["parent"]
                if event.button == 1:
                    self.boardview.setShownBoard(board.pieceBoard)
                    self.update_selected_node()
                break
        
        if node is None and event.button == 1:
            for ci in self.commentIters:
                if offset >= ci["start"] and offset < ci["end"]:
                    self.edit_comment(board=ci["node"], index=ci["index"])
                    break

        elif event.button == 3:
            if node is not None:
                menu = gtk.Menu()
                position = -1
                for index, child in enumerate(board.children):
                    if isinstance(child, basestring):
                        position = index
                        break

                if board == self.gamemodel.boards[1].board and not self.gamemodel.boards[0].board.children:
                    menuitem = gtk.MenuItem(_("Add start comment"))
                    menuitem.connect('activate', self.edit_comment, self.gamemodel.boards[0], 0)
                    menu.append(menuitem)

                if position == -1:
                    menuitem = gtk.MenuItem(_("Add comment"))
                    menuitem.connect('activate', self.edit_comment, board, 0)
                    menu.append(menuitem)
                else:
                    menuitem = gtk.MenuItem(_("Edit comment"))
                    menuitem.connect('activate', self.edit_comment, board, position)
                    menu.append(menuitem)

                symbol_menu1 = gtk.Menu()
                for nag, menutext in (("$1", "!"),
                                      ("$2", "?"),
                                      ("$3", "!!"),
                                      ("$4", "??"),
                                      ("$5", "!?"),
                                      ("$6", "?!"),
                                      ("$7", _("Forced move"))):
                    menuitem = gtk.MenuItem(menutext)
                    menuitem.connect('activate', self.symbol_menu1_activate, board, nag)
                    symbol_menu1.append(menuitem)

                menuitem = gtk.MenuItem(_("Add move symbol"))
                menuitem.set_submenu(symbol_menu1)
                menu.append(menuitem)
                
                symbol_menu2 = gtk.Menu()
                for nag, menutext in (("$10", "="),
                                      ("$13", _("Unclear position")),
                                      ("$14", "+="),
                                      ("$15", "=+"),
                                      ("$16", "±"),
                                      ("$17", "∓"),
                                      ("$18", "+-"),
                                      ("$19", "-+"),
                                      ("$20", "+--"),
                                      ("$21", "--+"),
                                      ("$22", _("Zugzwang")),
                                      ("$32", _("Development adv.")),
                                      ("$36", _("Initiative")),
                                      ("$40", _("With attack")),
                                      ("$44", _("Compensation")),
                                      ("$132", _("Counterplay")),
                                      ("$138", _("Time pressure"))):
                    menuitem = gtk.MenuItem(menutext)
                    menuitem.connect('activate', self.symbol_menu2_activate, board, nag)
                    symbol_menu2.append(menuitem)

                menuitem = gtk.MenuItem(_("Add evaluation symbol"))
                menuitem.set_submenu(symbol_menu2)
                menu.append(menuitem)

                menuitem = gtk.MenuItem(_("Remove symols"))
                menuitem.connect('activate', self.remove_symbols, board)
                menu.append(menuitem)

                if board.pieceBoard not in self.gamemodel.variations[0]:
                    for vari in self.gamemodel.variations[1:]:
                        if board.pieceBoard in vari:
                            menuitem = gtk.MenuItem(_("Remove variation"))
                            menuitem.connect('activate', self.remove_variation, board, parent, vari)
                            menu.append(menuitem)
                            break

                menu.show_all()
                menu.popup( None, None, None, event.button, event.time)
        return True

    def edit_comment(self, widget=None, board=None, index=0):
        dialog = gtk.Dialog(_("Edit comment"),
                     None,
                     gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
                     (gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT,
                      gtk.STOCK_OK, gtk.RESPONSE_ACCEPT))

        textedit = gtk.TextView()
        textedit.set_editable(True)
        textedit.set_cursor_visible(True)
        textedit.set_wrap_mode(gtk.WRAP_WORD)

        textbuffer = textedit.get_buffer()
        if not board.children:
            board.children.append("")
        elif not isinstance(board.children[index], basestring):
            board.children.insert(index, "")
        textbuffer.set_text(board.children[index])
        
        sw = gtk.ScrolledWindow()
        sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        sw.add(textedit)

        dialog.vbox.add(sw)
        dialog.resize(300, 200)
        dialog.show_all()

        response = dialog.run()
        if response == gtk.RESPONSE_ACCEPT:
            dialog.destroy()
            (iter_first, iter_last) = textbuffer.get_bounds()
            comment = textbuffer.get_text(iter_first, iter_last)
            if board.children[index] != comment:
                board.children[index] = comment
                self.gamemodel.needsSave = True
                self.update()
        else:
            dialog.destroy()

    def symbol_menu1_activate(self, widget, board, nag):
        if len(board.nags) == 0:
            board.nags.append(nag)
            self.gamemodel.needsSave = True
        else:
            if board.nags[0] != nag:
                board.nags[0] = nag
                self.gamemodel.needsSave = True
        if self.gamemodel.needsSave:
            self.update()

    def symbol_menu2_activate(self, widget, board, nag):
        color = board.color
        if color == WHITE and nag in ("$22", "$32", "$36", "$40", "$44", "$132", "$138"):
            nag = "$%s" % (int(nag[1:]) + 1)

        if len(board.nags) == 0:
            board.nags.append("")
            board.nags.append(nag)
            self.gamemodel.needsSave = True
        if len(board.nags) == 1:
            board.nags.append(nag)
            self.gamemodel.needsSave = True
        else:
            if board.nags[1] != nag:
                board.nags[1] = nag
                self.gamemodel.needsSave = True
        if self.gamemodel.needsSave:
            self.update()

    def remove_symbols(self, widget, board):
        if board.nags:
            board.nags = []
            self.update()
            self.gamemodel.needsSave = True

    def remove_variation(self, widget, board, parent, vari):
        for child in parent.children:
            if isinstance(child, list) and board in child:
                parent.children.remove(child)
                break

        if self.gamemodel.getBoardAtPly(self.boardview.shown, self.boardview.shownVariationIdx) in vari:
            if parent.pieceBoard is None:
                # variation without played move at game end 
                self.boardview.setShownBoard(self.gamemodel.boards[-1])
            else:
                self.boardview.setShownBoard(parent.pieceBoard)
        self.gamemodel.variations.remove(vari)

        if parent.pieceBoard is None:
            self.boardview.shownVariationIdx = 0
            parent.prev.next = None
        else:
            for vari in self.gamemodel.variations:
                if parent.pieceBoard in vari:
                    self.boardview.shownVariationIdx = self.gamemodel.variations.index(vari)
                    break

        self.update()
        self.gamemodel.needsSave = True
        
    # Update the selected node highlight
    def update_selected_node(self):
        self.textbuffer.remove_tag_by_name("selected", self.textbuffer.get_start_iter(), self.textbuffer.get_end_iter())
        shown_board = self.gamemodel.getBoardAtPly(self.boardview.shown, self.boardview.shownVariationIdx)
        start = None
        for ni in self.nodeIters:
            if ni["node"] == shown_board.board:
                start = self.textbuffer.get_iter_at_offset(ni["start"])
                end = self.textbuffer.get_iter_at_offset(ni["end"])
                self.textbuffer.apply_tag_by_name("selected", start, end)
                break

        if start:
            self.textview.scroll_to_iter(start, 0, use_align=False, yalign=0.1)

    # Recursively insert the node tree
    def insert_nodes(self, node, level=0, ply=0, parent=None, result=None):
        buf = self.textbuffer
        end_iter = buf.get_end_iter # Convenience shortcut to the function
        new_line = False

        if self.boardview.shown >= self.gamemodel.lowply:
            shown_board = self.gamemodel.getBoardAtPly(self.boardview.shown, self.boardview.shownVariationIdx)
        
        while True: 
            start = end_iter().get_offset()
            
            if node is None:
                break
            
            # Initial game or variation comment
            if node.prev is None:
                for index, child in enumerate(node.children):
                    if isinstance(child, basestring):
                        if 0: # TODO node.plyCount == self.gamemodel.lowply:
                            self.insert_comment(child + "\n", node, index, level)
                        else:
                            self.insert_comment(child, node, index, level)
                node = node.next
                continue
            
            if hasattr(node, "hist_move"):
                if ply > 0 and not new_line:
                    buf.insert(end_iter(), " ")
                
                ply += 1

                movestr = self.__movestr(node)
                buf.insert(end_iter(), movestr)
                
                startIter = buf.get_iter_at_offset(start)
                endIter = buf.get_iter_at_offset(end_iter().get_offset())
                
                if level == 0:
                    buf.apply_tag_by_name("node", startIter, endIter)
                    buf.apply_tag_by_name("margin", startIter, endIter)
                elif level == 1:
                    buf.apply_tag_by_name("variation-toplevel", startIter, endIter)
                    buf.apply_tag_by_name("variation-margin0", startIter, endIter)
                elif level % 2 == 0:
                    buf.apply_tag_by_name("variation-even", startIter, endIter)
                    buf.apply_tag_by_name("variation-margin1", startIter, endIter)
                else:
                    buf.apply_tag_by_name("variation-uneven", startIter, endIter)
                    buf.apply_tag_by_name("variation-margin2", startIter, endIter)

                if self.boardview.shown >= self.gamemodel.lowply and node == shown_board.board:
                    buf.apply_tag_by_name("selected", startIter, endIter)
                    
                ni = {}
                ni["node"] = node
                ni["start"] = start       
                ni["end"] = end_iter().get_offset()
                ni["parent"] = parent
                self.nodeIters.append(ni)
                
                buf.insert(end_iter(), " ")

            if self.showClocks and node.clock is not None:
                self.textbuffer.insert_with_tags_by_name(end_iter(), formatTime(node.clock), "clock")

            new_line = False
            for index, child in enumerate(node.children):
                if isinstance(child, basestring):
                    # comment
                    self.insert_comment(child, node, index, level)
                else:
                    # variation
                    if not new_line:
                        buf.insert(end_iter(), "\n")
                        new_line = True
                    
                    if level == 0:
                        buf.insert_with_tags_by_name(end_iter(), "[", "variation-toplevel", "variation-margin0")
                    elif (level+1) % 2 == 0:
                        buf.insert_with_tags_by_name(end_iter(), "(", "variation-even", "variation-margin1")
                    else:
                        buf.insert_with_tags_by_name(end_iter(), "(", "variation-uneven", "variation-margin2")
                    
                    self.insert_nodes(child[0], level+1, ply-1, parent=node)

                    if level == 0:
                        buf.insert_with_tags_by_name(end_iter(), "]\n", "variation-toplevel", "variation-margin0")
                    elif (level+1) % 2 == 0:
                        buf.insert_with_tags_by_name(end_iter(), ")\n", "variation-even", "variation-margin1")
                    else:
                        buf.insert_with_tags_by_name(end_iter(), ")\n", "variation-uneven", "variation-margin2")
            
            if node.next:
                node = node.next
            else:
                break

        if result and result != "*":
            buf.insert_with_tags_by_name(end_iter(), " "+result, "node")

    def insert_comment(self, comment, node, index, level=0):
        buf = self.textbuffer
        end_iter = buf.get_end_iter
        start = end_iter().get_offset()

        if level > 0:
            buf.insert_with_tags_by_name(end_iter(), comment, "comment", "margin")
        else:
            buf.insert_with_tags_by_name(end_iter(), comment, "comment")

        ci = {}
        ci["node"] = node
        ci["comment"] = comment
        ci["index"] = index
        ci["start"] = start     
        ci["end"] = end_iter().get_offset()
        self.commentIters.append(ci)
        
        buf.insert(end_iter(), " ")

    def insert_header(self, gm):
        buf = self.textbuffer
        end_iter = buf.get_end_iter

        #try:
        #    text = gm.tags['White']
        #except:
        #    # pgn not processed yet
        #    return
        text = repr(gm.players[0])

        buf.insert_with_tags_by_name(end_iter(), text, "head2")
        white_elo = gm.tags.get('WhiteElo')
        if white_elo:
            buf.insert_with_tags_by_name(end_iter(), " %s" % white_elo, "head1")

        buf.insert_with_tags_by_name(end_iter(), " - ", "head1")

        #text = gm.tags['Black']
        text = repr(gm.players[1])
        buf.insert_with_tags_by_name(end_iter(), text, "head2")
        black_elo = gm.tags.get('BlackElo')
        if black_elo:
            buf.insert_with_tags_by_name(end_iter(), " %s" % black_elo, "head1")

        status = reprResult[gm.status]
        if status != '*':
            result = status
        else:
            result = gm.tags['Result']
        buf.insert_with_tags_by_name(end_iter(), ' ' + result + '\n', "head2")

        text = ""
        event = gm.tags['Event']
        if event and event != "?":
            text += event

        site = gm.tags['Site']
        if site and site != "?":
            if len(text) > 0:
                text += ', '
            text += site

        round = gm.tags['Round']
        if round and round != "?":
            if len(text) > 0:
                text += ', '
            text += _('round %s') % round

        game_date = gm.tags.get('Date')
        if game_date is None:
            game_date = "%02d.%02d.%02d" % (gm.tags['Year'], gm.tags['Month'], gm.tags['Day'])
        if (not '?' in game_date) and game_date.count('.') == 2:
            y, m, d = map(int, game_date.split('.'))
            # strftime() is limited to > 1900 dates
            try:
                text += ', ' + datetime.date(y, m, d).strftime('%x')
            except ValueError:
                text += ', ' + game_date
        elif not '?' in game_date[:4]:
            text += ', ' + game_date[:4]
        buf.insert_with_tags_by_name(end_iter(), text, "head1")

        eco = gm.tags.get('ECO')
        if eco:
            buf.insert_with_tags_by_name(end_iter(), "\n" + eco, "head2")
            opening = gm.tags.get('Opening')
            if opening:
                buf.insert_with_tags_by_name(end_iter(), " - ", "head1")
                buf.insert_with_tags_by_name(end_iter(), opening, "head2")
            variation = gm.tags.get('Variation')
            if variation:
                buf.insert_with_tags_by_name(end_iter(), ", ", "head1")
                buf.insert_with_tags_by_name(end_iter(), variation, "head2")

        buf.insert(end_iter(), "\n\n")

    # Update the entire notation tree
    def update(self, *args):
        self.textbuffer.set_text('')
        self.nodeIters = []
        self.insert_header(self.gamemodel)

        status = reprResult[self.gamemodel.status]
        if status != '*':
            result = status
        else:
            result = self.gamemodel.tags['Result']

        self.insert_nodes(self.gamemodel.boards[0].board, result=result)

    def shown_changed(self, boardview, shown):
        self.update_selected_node()

    def moves_undoing(self, game, moves):
        assert game.ply > 0, "Can't undo when ply <= 0"
        start = self.textbuffer.get_start_iter()
        end = self.textbuffer.get_end_iter()
        for ni in reversed(self.nodeIters):
            if ni["node"].pieceBoard == self.gamemodel.variations[0][-moves]:
                start = self.textbuffer.get_iter_at_offset(ni["start"])
                break
        self.textbuffer.delete(start, end)

    def game_changed(self, game):
        if game.status != RUNNING:
            return

        node = game.getBoardAtPly(game.ply, variation=0).board
        buf = self.textbuffer
        end_iter = buf.get_end_iter
        start = end_iter().get_offset()

        buf.insert(end_iter(), self.__movestr(node) + " ")

        startIter = buf.get_iter_at_offset(start)
        endIter = buf.get_iter_at_offset(end_iter().get_offset())

        buf.apply_tag_by_name("node", startIter, endIter)

        ni = {}
        ni["node"] = node
        ni["start"] = startIter.get_offset()        
        ni["end"] = end_iter().get_offset()
        ni["parent"] = None

        self.nodeIters.append(ni)

        if self.showClocks and node.clock is not None:
            self.textbuffer.insert_with_tags_by_name(end_iter(), formatTime(node.clock), "clock")
        self.update_selected_node()

    def __movestr(self, node):
        move = node.lastMove
        if self.fan:
            movestr = toFAN(node.prev, move)
        else:
            movestr =  toSAN(node.prev, move, True)
        nagsymbols = "".join([nag2symbol(nag) for nag in node.nags])
        # To prevent wrap castling we will use hyphen bullet (U+2043)
        return "%s%s%s" % (move_count(node), movestr.replace("-","⁃"), nagsymbols)