history_window.py 26.9 KB
Newer Older
roidelapluie's avatar
roidelapluie committed
1
# -*- coding:utf-8 -*-
roidelapluie's avatar
roidelapluie committed
2
## src/history_window.py
3
##
Dicson's avatar
Dicson committed
4
## Copyright (C) 2003-2014 Yann Leboulanger <asterix AT lagaule.org>
roidelapluie's avatar
roidelapluie committed
5
6
7
8
9
10
11
## Copyright (C) 2005 Vincent Hanquez <tab AT snarc.org>
## Copyright (C) 2005-2006 Nikos Kouremenos <kourem AT gmail.com>
## Copyright (C) 2006 Dimitur Kirov <dkirov AT gmail.com>
##                    Travis Shirk <travis AT pobox.com>
## Copyright (C) 2006-2008 Jean-Marie Traissard <jim AT lapin.org>
## Copyright (C) 2007-2008 Stephan Erb <steve-e AT h3c.de>
## Copyright (C) 2008 Brendan Taylor <whateley AT gmail.com>
12
##
13
14
15
## This file is part of Gajim.
##
## Gajim is free software; you can redistribute it and/or modify
16
## it under the terms of the GNU General Public License as published
17
## by the Free Software Foundation; version 3 only.
18
##
19
## Gajim is distributed in the hope that it will be useful,
20
## but WITHOUT ANY WARRANTY; without even the implied warranty of
roidelapluie's avatar
roidelapluie committed
21
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22
23
## GNU General Public License for more details.
##
24
## You should have received a copy of the GNU General Public License
roidelapluie's avatar
roidelapluie committed
25
## along with Gajim. If not, see <http://www.gnu.org/licenses/>.
26
##
27

28
from gi.repository import Gtk
Yann Leboulanger's avatar
Yann Leboulanger committed
29
from gi.repository import Gdk
Yann Leboulanger's avatar
Yann Leboulanger committed
30
from gi.repository import GLib
31
import time
32
import calendar
33

34
import gtkgui_helpers
35
import conversation_textview
36
import dialogs
37

38
from common import gajim
39
from common import helpers
Yann Leboulanger's avatar
Yann Leboulanger committed
40
from common import exceptions
41

42
43
44
45
from common.logger import Constants

constants = Constants()

steve-e's avatar
steve-e committed
46
47
# Completion dict
(
48
49
50
51
        C_INFO_JID,
        C_INFO_ACCOUNT,
        C_INFO_NAME,
        C_INFO_COMPLETION
steve-e's avatar
steve-e committed
52
53
) = range(4)

54
# contact_name, date, message, time
55
(
56
57
58
59
60
        C_LOG_JID,
        C_CONTACT_NAME,
        C_UNIXTIME,
        C_MESSAGE,
        C_TIME
61
) = range(5)
62

63
class HistoryWindow:
64
65
66
67
68
69
70
71
72
73
    """
    Class for browsing logs of conversations with contacts
    """

    def __init__(self, jid = None, account = None):
        xml = gtkgui_helpers.get_gtk_builder('history_window.ui')
        self.window = xml.get_object('history_window')
        self.calendar = xml.get_object('calendar')
        scrolledwindow = xml.get_object('scrolledwindow')
        self.history_textview = conversation_textview.ConversationTextview(
Yann Leboulanger's avatar
Yann Leboulanger committed
74
            account, used_in_history_window = True)
75
76
77
        scrolledwindow.add(self.history_textview.tv)
        self.history_buffer = self.history_textview.tv.get_buffer()
        self.history_buffer.create_tag('highlight', background = 'yellow')
78
        self.history_buffer.create_tag('invisible', invisible=True)
79
80
        self.checkbutton = xml.get_object('log_history_checkbutton')
        self.checkbutton.connect('toggled',
Yann Leboulanger's avatar
Yann Leboulanger committed
81
            self.on_log_history_checkbutton_toggled)
82
        self.show_status_checkbutton = xml.get_object('show_status_checkbutton')
Yann Leboulanger's avatar
Yann Leboulanger committed
83
84
85
        self.search_entry = xml.get_object('search_entry')
        self.query_liststore = xml.get_object('query_liststore')
        self.jid_entry = xml.get_object('query_entry')
86
87
88
        self.jid_entry.connect('activate', self.on_jid_entry_activate)
        self.results_treeview = xml.get_object('results_treeview')
        self.results_window = xml.get_object('results_scrolledwindow')
Dicson's avatar
Dicson committed
89
        self.search_in_date = xml.get_object('search_in_date')
90
91

        # contact_name, date, message, time
92
        model = Gtk.ListStore(str, str, str, str, str)
93
        self.results_treeview.set_model(model)
94
        col = Gtk.TreeViewColumn(_('Name'))
95
        self.results_treeview.append_column(col)
96
        renderer = Gtk.CellRendererText()
Yann Leboulanger's avatar
Yann Leboulanger committed
97
98
        col.pack_start(renderer, True)
        col.add_attribute(renderer, 'text', C_CONTACT_NAME)
99
100
101
        col.set_sort_column_id(C_CONTACT_NAME) # user can click this header and sort
        col.set_resizable(True)

102
        col = Gtk.TreeViewColumn(_('Date'))
103
        self.results_treeview.append_column(col)
104
        renderer = Gtk.CellRendererText()
Yann Leboulanger's avatar
Yann Leboulanger committed
105
106
        col.pack_start(renderer, True)
        col.add_attribute(renderer, 'text', C_UNIXTIME)
107
108
109
        col.set_sort_column_id(C_UNIXTIME) # user can click this header and sort
        col.set_resizable(True)

110
        col = Gtk.TreeViewColumn(_('Message'))
111
        self.results_treeview.append_column(col)
112
        renderer = Gtk.CellRendererText()
Yann Leboulanger's avatar
Yann Leboulanger committed
113
114
        col.pack_start(renderer, True)
        col.add_attribute(renderer, 'text', C_MESSAGE)
115
116
117
118
119
120
121
122
123
        col.set_resizable(True)

        self.jid = None # The history we are currently viewing
        self.account = None
        self.completion_dict = {}
        self.accounts_seen_online = [] # Update dict when new accounts connect
        self.jids_to_search = []

        # This will load history too
Yann Leboulanger's avatar
Yann Leboulanger committed
124
        task = self._fill_completion_dict()
Yann Leboulanger's avatar
Yann Leboulanger committed
125
        GLib.idle_add(next, task)
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

        if jid:
            self.jid_entry.set_text(jid)
        else:
            self._load_history(None)

        gtkgui_helpers.resize_window(self.window,
                gajim.config.get('history_window_width'),
                gajim.config.get('history_window_height'))
        gtkgui_helpers.move_window(self.window,
                gajim.config.get('history_window_x-position'),
                gajim.config.get('history_window_y-position'))

        xml.connect_signals(self)
        self.window.show_all()

    def _fill_completion_dict(self):
        """
        Fill completion_dict for key auto completion. Then load history for
        current jid (by calling another function)

        Key will be either jid or full_completion_name (contact name or long
        description like "pm-contact from groupchat....").

        {key : (jid, account, nick_name, full_completion_name}
        This is a generator and does pseudo-threading via idle_add().
        """
        liststore = gtkgui_helpers.get_completion_liststore(self.jid_entry)

        # Add all jids in logs.db:
        db_jids = gajim.logger.get_jids_in_db()
        completion_dict = dict.fromkeys(db_jids)

Yann Leboulanger's avatar
Yann Leboulanger committed
159
        self.accounts_seen_online = list(gajim.contacts.get_accounts())
160
161
162
163
164
165
166
167
168
169

        # Enhance contacts of online accounts with contact. Needed for mapping below
        for account in self.accounts_seen_online:
            completion_dict.update(helpers.get_contact_dict_for_account(account))

        muc_active_img = gtkgui_helpers.load_icon('muc_active')
        contact_img = gajim.interface.jabber_state_images['16']['online']
        muc_active_pix = muc_active_img.get_pixbuf()
        contact_pix = contact_img.get_pixbuf()

Yann Leboulanger's avatar
Yann Leboulanger committed
170
        keys = list(completion_dict.keys())
171
        # Move the actual jid at first so we load history faster
172
        actual_jid = self.jid_entry.get_text()
173
174
175
        if actual_jid in keys:
            keys.remove(actual_jid)
            keys.insert(0, actual_jid)
Yann Leboulanger's avatar
Yann Leboulanger committed
176
177
        if '' in keys:
            keys.remove('')
178
179
        if None in keys:
            keys.remove(None)
180
181
182
183
        # Map jid to info tuple
        # Warning : This for is time critical with big DB
        for key in keys:
            completed = key
184
            completed2 = None
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
            contact = completion_dict[completed]
            if contact:
                info_name = contact.get_shown_name()
                info_completion = info_name
                info_jid = contact.jid
            else:
                # Corrensponding account is offline, we know nothing
                info_name = completed.split('@')[0]
                info_completion = completed
                info_jid = completed

            info_acc = self._get_account_for_jid(info_jid)

            if gajim.logger.jid_is_room_jid(completed) or\
            gajim.logger.jid_is_from_pm(completed):
                pix = muc_active_pix
                if gajim.logger.jid_is_from_pm(completed):
                    # It's PM. Make it easier to find
                    room, nick = gajim.get_room_and_nick_from_fjid(completed)
                    info_completion = '%s from %s' % (nick, room)
                    completed = info_completion
206
207
                    info_completion2 = '%s/%s' % (room, nick)
                    completed2 = info_completion2
208
209
210
211
                    info_name = nick
            else:
                pix = contact_pix

212
213
            if len(completed) > 70:
                completed = completed[:70] + '[\u2026]'
214
215
            liststore.append((pix, completed))
            self.completion_dict[key] = (info_jid, info_acc, info_name,
216
                info_completion)
217
            self.completion_dict[completed] = (info_jid, info_acc,
218
219
220
221
222
223
224
                info_name, info_completion)
            if completed2:
                if len(completed2) > 70:
                    completed2 = completed2[:70] + '[\u2026]'
                liststore.append((pix, completed2))
                self.completion_dict[completed2] = (info_jid, info_acc,
                    info_name, info_completion2)
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
            if key == actual_jid:
                self._load_history(info_jid, info_acc)
            yield True
        keys.sort()
        yield False

    def _get_account_for_jid(self, jid):
        """
        Return the corresponding account of the jid. May be None if an account
        could not be found
        """
        accounts = gajim.contacts.get_accounts()
        account = None
        for acc in accounts:
            jid_list = gajim.contacts.get_jid_list(acc)
            gc_list = gajim.contacts.get_gc_list(acc)
            if jid in jid_list or jid in gc_list:
                account = acc
                break
        return account

    def on_history_window_destroy(self, widget):
        self.history_textview.del_handlers()
        del gajim.interface.instances['logs']

    def on_history_window_key_press_event(self, widget, event):
251
        if event.keyval == Gdk.KEY_Escape:
252
253
254
255
256
257
258
259
            self.save_state()
            self.window.destroy()

    def on_close_button_clicked(self, widget):
        self.save_state()
        self.window.destroy()

    def on_jid_entry_activate(self, widget):
260
        jid = self.jid_entry.get_text()
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
        account = None # we don't know the account, could be any. Search for it!
        self._load_history(jid, account)
        self.results_window.set_property('visible', False)

    def on_jid_entry_focus(self, widget, event):
        widget.select_region(0, -1) # select text

    def _load_history(self, jid_or_name, account=None):
        """
        Load history for the given jid/name and show it
        """
        if jid_or_name and jid_or_name in self.completion_dict:
        # a full qualified jid or a contact name was entered
            info_jid, info_account, info_name, info_completion = self.completion_dict[jid_or_name]
            self.jids_to_search = [info_jid]
            self.jid = info_jid

            if account:
                self.account = account
            else:
                self.account = info_account
            if self.account is None:
                # We don't know account. Probably a gc not opened or an
                # account not connected.
                # Disable possibility to say if we want to log or not
                self.checkbutton.set_sensitive(False)
            else:
                # Are log disabled for account ?
                if self.account in gajim.config.get_per('accounts', self.account,
                        'no_log_for').split(' '):
                    self.checkbutton.set_active(False)
                    self.checkbutton.set_sensitive(False)
                else:
                    # Are log disabled for jid ?
                    log = True
                    if self.jid in gajim.config.get_per('accounts', self.account,
                            'no_log_for').split(' '):
                        log = False
                    self.checkbutton.set_active(log)
                    self.checkbutton.set_sensitive(True)

            self.jids_to_search = [info_jid]

            # select logs for last date we have logs with contact
            self.calendar.set_sensitive(True)
            last_log = \
                    gajim.logger.get_last_date_that_has_logs(self.jid, self.account)

            date = time.localtime(last_log)

            y, m, d = date[0], date[1], date[2]
            gtk_month = gtkgui_helpers.make_python_month_gtk_month(m)
            self.calendar.select_month(gtk_month, y)
            self.calendar.select_day(d)

Yann Leboulanger's avatar
Yann Leboulanger committed
316
317
            self.search_entry.set_sensitive(True)
            self.search_entry.grab_focus()
318
319
320
321
322
323
324
325
326
327
328

            title = _('Conversation History with %s') % info_name
            self.window.set_title(title)
            self.jid_entry.set_text(info_completion)

        else:   # neither a valid jid, nor an existing contact name was entered
            # we have got nothing to show or to search in
            self.jid = None
            self.account = None

            self.history_buffer.set_text('') # clear the buffer
Yann Leboulanger's avatar
Yann Leboulanger committed
329
            self.search_entry.set_sensitive(False)
330
331
332
333
334
335
336
337
338
339
340
341
342

            self.checkbutton.set_sensitive(False)
            self.calendar.set_sensitive(False)
            self.calendar.clear_marks()

            self.results_window.set_property('visible', False)

            title = _('Conversation History')
            self.window.set_title(title)

    def on_calendar_day_selected(self, widget):
        if not self.jid:
            return
343
        year, month, day = self.calendar.get_date() # integers
344
345
346
347
348
349
350
351
352
353
        month = gtkgui_helpers.make_gtk_month_python_month(month)
        self._add_lines_for_date(year, month, day)

    def on_calendar_month_changed(self, widget):
        """
        Ask for days in this month, if they have logs it bolds them (marks them)
        """
        if not self.jid:
            return
        year, month, day = widget.get_date() # integers
354
355
356
357
358
        if year < 1900:
            widget.select_month(0, 1900)
            widget.select_day(1)
            return

359
360
361
362
363
364
365
366
        # in gtk January is 1, in python January is 0,
        # I want the second
        # first day of month is 1 not 0
        widget.clear_marks()
        month = gtkgui_helpers.make_gtk_month_python_month(month)
        days_in_this_month = calendar.monthrange(year, month)[1]
        try:
            log_days = gajim.logger.get_days_with_logs(self.jid, year, month,
367
                days_in_this_month, self.account)
Yann Leboulanger's avatar
Yann Leboulanger committed
368
        except exceptions.PysqliteOperationalError as e:
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
            dialogs.ErrorDialog(_('Disk Error'), str(e))
            return
        for day in log_days:
            widget.mark_day(day)

    def _get_string_show_from_constant_int(self, show):
        if show == constants.SHOW_ONLINE:
            show = 'online'
        elif show == constants.SHOW_CHAT:
            show = 'chat'
        elif show == constants.SHOW_AWAY:
            show = 'away'
        elif show == constants.SHOW_XA:
            show = 'xa'
        elif show == constants.SHOW_DND:
            show = 'dnd'
        elif show == constants.SHOW_OFFLINE:
            show = 'offline'

        return show

    def _add_lines_for_date(self, year, month, day):
        """
        Add all the lines for given date in textbuffer
        """
        self.history_buffer.set_text('') # clear the buffer first
        self.last_time_printout = 0
396
        show_status = self.show_status_checkbutton.get_active()
397
398
399
400
401
402

        lines = gajim.logger.get_conversation_for_date(self.jid, year, month, day, self.account)
        # lines holds list with tupples that have:
        # contact_name, time, kind, show, message
        for line in lines:
            # line[0] is contact_name, line[1] is time of message
403
404
            # line[2] is kind, line[3] is show, line[4] is message, line[5] is subject
            # line[6] is additional_data
405
406
407
            if not show_status and line[2] in (constants.KIND_GCSTATUS,
            constants.KIND_STATUS):
                continue
408
            self._add_new_line(line[0], line[1], line[2], line[3], line[4],
409
                    line[5], line[6])
410

411
    def _add_new_line(self, contact_name, tim, kind, show, message, subject, additional_data):
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
        """
        Add a new line in textbuffer
        """
        if not message and kind not in (constants.KIND_STATUS,
                constants.KIND_GCSTATUS):
            return
        buf = self.history_buffer
        end_iter = buf.get_end_iter()

        if gajim.config.get('print_time') == 'always':
            timestamp_str = gajim.config.get('time_stamp')
            timestamp_str = helpers.from_one_line(timestamp_str)
            tim = time.strftime(timestamp_str, time.localtime(float(tim)))
            buf.insert(end_iter, tim) # add time
        elif gajim.config.get('print_time') == 'sometimes':
            every_foo_seconds = 60 * gajim.config.get(
                    'print_ichat_every_foo_minutes')
            seconds_passed = tim - self.last_time_printout
            if seconds_passed > every_foo_seconds:
                self.last_time_printout = tim
                tim = time.strftime('%X ', time.localtime(float(tim)))
                buf.insert_with_tags_by_name(end_iter, tim + '\n',
                        'time_sometimes')
435
436
437
438
439
440
        else: # don't print time. So we print it as invisible to be able to
              # search for it
            timestamp_str = gajim.config.get('time_stamp')
            timestamp_str = helpers.from_one_line(timestamp_str)
            tim = time.strftime(timestamp_str, time.localtime(float(tim)))
            buf.insert_with_tags_by_name(end_iter, tim, 'invisible')
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460

        tag_name = ''
        tag_msg = ''

        show = self._get_string_show_from_constant_int(show)

        if kind == constants.KIND_GC_MSG:
            tag_name = 'incoming'
        elif kind in (constants.KIND_SINGLE_MSG_RECV,
        constants.KIND_CHAT_MSG_RECV):
            contact_name = self.completion_dict[self.jid][C_INFO_NAME]
            tag_name = 'incoming'
            tag_msg = 'incomingtxt'
        elif kind in (constants.KIND_SINGLE_MSG_SENT,
        constants.KIND_CHAT_MSG_SENT):
            if self.account:
                contact_name = gajim.nicks[self.account]
            else:
                # we don't have roster, we don't know our own nick, use first
                # account one (urk!)
Dicson's avatar
Dicson committed
461
                account = list(gajim.contacts.get_accounts())[0]
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
                contact_name = gajim.nicks[account]
            tag_name = 'outgoing'
            tag_msg = 'outgoingtxt'
        elif kind == constants.KIND_GCSTATUS:
            # message here (if not None) is status message
            if message:
                message = _('%(nick)s is now %(status)s: %(status_msg)s') %\
                        {'nick': contact_name, 'status': helpers.get_uf_show(show),
                        'status_msg': message }
            else:
                message = _('%(nick)s is now %(status)s') % {'nick': contact_name,
                        'status': helpers.get_uf_show(show) }
            tag_msg = 'status'
        else: # 'status'
            # message here (if not None) is status message
            if show is None: # it means error
                if message:
                    message = _('Error: %s') % message
                else:
                    message = _('Error')
            elif message:
                message = _('Status is now: %(status)s: %(status_msg)s') % \
                        {'status': helpers.get_uf_show(show), 'status_msg': message}
            else:
                message = _('Status is now: %(status)s') % { 'status':
                        helpers.get_uf_show(show) }
            tag_msg = 'status'

        if message.startswith('/me ') or message.startswith('/me\n'):
            tag_msg = tag_name
        else:
            # do not do this if gcstats, avoid dupping contact_name
            # eg. nkour: nkour is now Offline
            if contact_name and kind != constants.KIND_GCSTATUS:
                # add stuff before and after contact name
                before_str = gajim.config.get('before_nickname')
                before_str = helpers.from_one_line(before_str)
                after_str = gajim.config.get('after_nickname')
                after_str = helpers.from_one_line(after_str)
                format = before_str + contact_name + after_str + ' '
502
503
504
505
                if tag_name:
                    buf.insert_with_tags_by_name(end_iter, format, tag_name)
                else:
                    buf.insert(end_iter, format)
506
507
        if subject:
            message = _('Subject: %s\n') % subject + message
508
509
510
511
        xhtml = None
        if message.startswith('<body '):
            xhtml = message

512
513
        if tag_msg:
            self.history_textview.print_real_text(message, [tag_msg],
514
                    name=contact_name, xhtml=xhtml, additional_data=additional_data)
515
        else:
516
            self.history_textview.print_real_text(message, name=contact_name,
517
                xhtml=xhtml, additional_data=additional_data)
518
519
520
        buffer_ = self.history_textview.tv.get_buffer()
        eob = buffer_.get_end_iter()
        buffer_.insert_with_tags_by_name(eob, '\n', 'eol')
521

Yann Leboulanger's avatar
Yann Leboulanger committed
522
523
    def on_search_entry_activate(self, widget):
        text = self.search_entry.get_text()
524
525
526
527
528
529
530
531
532
        model = self.results_treeview.get_model()
        model.clear()
        if text == '':
            self.results_window.set_property('visible', False)
            return
        else:
            self.results_window.set_property('visible', True)

        # perform search in preselected jids
Yann Leboulanger's avatar
Yann Leboulanger committed
533
        # jids are preselected with the query_entry
534
535
536
537
538
539
540
        for jid in self.jids_to_search:
            account = self.completion_dict[jid][C_INFO_ACCOUNT]
            if account is None:
                # We do not know an account. This can only happen if the contact is offine,
                # or if we browse a groupchat history. The account is not needed, a dummy can
                # be set.
                # This may leed to wrong self nick in the displayed history (Uggh!)
Dicson's avatar
Dicson committed
541
                account = list(gajim.contacts.get_accounts())[0]
542

Dicson's avatar
Dicson committed
543
544
545
546
547
            year, month, day = False, False, False
            if self.search_in_date.get_active():
                year, month, day = self.calendar.get_date() # integers
                month = gtkgui_helpers.make_gtk_month_python_month(month)

548
549
            show_status = self.show_status_checkbutton.get_active()

550
551
            # contact_name, time, kind, show, message, subject
            results = gajim.logger.get_search_results_for_query(
Dicson's avatar
Dicson committed
552
                                    jid, text, account, year, month, day)
553
554
555
556
            #FIXME:
            # add "subject:  | message: " in message column if kind is single
            # also do we need show at all? (we do not search on subject)
            for row in results:
557
558
559
                if not show_status and row[2] in (constants.KIND_GCSTATUS,
                constants.KIND_STATUS):
                    continue
560
561
562
563
564
565
566
567
568
569
570
571
572
573
                contact_name = row[0]
                if not contact_name:
                    kind = row[2]
                    if kind == constants.KIND_CHAT_MSG_SENT: # it's us! :)
                        contact_name = gajim.nicks[account]
                    else:
                        contact_name = self.completion_dict[jid][C_INFO_NAME]
                tim = row[1]
                message = row[4]
                local_time = time.localtime(tim)
                date = time.strftime('%Y-%m-%d', local_time)

                #  jid (to which log is assigned to), name, date, message,
                # time (full unix time)
Yann Leboulanger's avatar
Yann Leboulanger committed
574
                model.append((jid, contact_name, date, message, str(tim)))
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
601
602
603
604
605
606
607
608
609
610
611
612
613

    def on_results_treeview_row_activated(self, widget, path, column):
        """
        A row was double clicked, get date from row, and select it in calendar
        which results to showing conversation logs for that date
        """
        # get currently selected date
        cur_year, cur_month = self.calendar.get_date()[0:2]
        cur_month = gtkgui_helpers.make_gtk_month_python_month(cur_month)
        model = widget.get_model()
        # make it a tupple (Y, M, D, 0, 0, 0...)
        tim = time.strptime(model[path][C_UNIXTIME], '%Y-%m-%d')
        year = tim[0]
        gtk_month = tim[1]
        month = gtkgui_helpers.make_python_month_gtk_month(gtk_month)
        day = tim[2]

        # switch to belonging logfile if necessary
        log_jid = model[path][C_LOG_JID]
        if log_jid != self.jid:
            self._load_history(log_jid, None)

        # avoid reruning mark days algo if same month and year!
        if year != cur_year or gtk_month != cur_month:
            self.calendar.select_month(month, year)

        self.calendar.select_day(day)
        unix_time = model[path][C_TIME]
        self._scroll_to_result(unix_time)
        #FIXME: one day do not search just for unix_time but the whole and user
        # specific format of the textbuffer line [time] nick: message
        # and highlight all that

    def _scroll_to_result(self, unix_time):
        """
        Scroll to the result using unix_time and highlight line
        """
        start_iter = self.history_buffer.get_start_iter()
        local_time = time.localtime(float(unix_time))
614
615
616
        timestamp_str = gajim.config.get('time_stamp')
        timestamp_str = helpers.from_one_line(timestamp_str)
        tim = time.strftime(timestamp_str, local_time)
617
618
        result = start_iter.forward_search(tim, Gtk.TextSearchFlags.TEXT_ONLY,
            None)
619
620
621
622
623
624
        if result is not None:
            match_start_iter, match_end_iter = result
            match_start_iter.backward_char() # include '[' or other character before time
            match_end_iter.forward_line() # highlight all message not just time
            self.history_buffer.apply_tag_by_name('highlight', match_start_iter,
                    match_end_iter)
625
626
627
            mark = self.history_buffer.create_mark('match', match_start_iter, True)
            GLib.idle_add(self.history_textview.tv.scroll_to_mark, mark,
                0, True, 0.0, 0.5)
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644

    def on_log_history_checkbutton_toggled(self, widget):
        # log conversation history?
        oldlog = True
        no_log_for = gajim.config.get_per('accounts', self.account,
                'no_log_for').split()
        if self.jid in no_log_for:
            oldlog = False
        log = widget.get_active()
        if not log and not self.jid in no_log_for:
            no_log_for.append(self.jid)
        if log and self.jid in no_log_for:
            no_log_for.remove(self.jid)
        if oldlog != log:
            gajim.config.set_per('accounts', self.account, 'no_log_for',
                    ' '.join(no_log_for))

645
646
647
648
    def on_show_status_checkbutton_toggled(self, widget):
        # reload logs
        self.on_calendar_day_selected(None)

649
650
651
652
653
654
655
    def open_history(self, jid, account):
        """
        Load chat history of the specified jid
        """
        self.jid_entry.set_text(jid)
        if account and account not in self.accounts_seen_online:
            # Update dict to not only show bare jid
Yann Leboulanger's avatar
Yann Leboulanger committed
656
            GLib.idle_add(next, self._fill_completion_dict())
657
658
659
660
661
662
663
        else:
            # Only in that case because it's called by self._fill_completion_dict()
            # otherwise
            self._load_history(jid, account)
        self.results_window.set_property('visible', False)

    def save_state(self):
Yann Leboulanger's avatar
Yann Leboulanger committed
664
        x, y = self.window.get_window().get_root_origin()
665
666
667
668
669
670
        width, height = self.window.get_size()

        gajim.config.set('history_window_x-position', x)
        gajim.config.set('history_window_y-position', y)
        gajim.config.set('history_window_width', width);
        gajim.config.set('history_window_height', height);