Welcome to mirror list, hosted at ThFree Co, Russian Federation.

xml_console.py « gtk « gajim - dev.gajim.org/gajim/gajim.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 7759c41de160e520cae2f1c34288bbcc3778a946 (plain)
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
# This file is part of Gajim.
#
# Gajim is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published
# by the Free Software Foundation; version 3 only.
#
# Gajim is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Gajim. If not, see <http://www.gnu.org/licenses/>.

from typing import Any

import time

import nbxmpp
from gi.repository import Gdk
from gi.repository import GLib
from gi.repository import GObject
from gi.repository import Gtk
from gi.repository import GtkSource

from gajim.common import app
from gajim.common import ged
from gajim.common.const import Direction
from gajim.common.events import AccountDisabled
from gajim.common.events import AccountEnabled
from gajim.common.events import StanzaReceived
from gajim.common.events import StanzaSent
from gajim.common.i18n import _
from gajim.common.logging_helpers import get_log_console_handler

from gajim.gtk.builder import get_builder
from gajim.gtk.const import Setting
from gajim.gtk.const import SettingKind
from gajim.gtk.const import SettingType
from gajim.gtk.dialogs import ErrorDialog
from gajim.gtk.settings import SettingsDialog
from gajim.gtk.util import at_the_end
from gajim.gtk.util import EventHelper
from gajim.gtk.util import MaxWidthComboBoxText
from gajim.gtk.util import scroll_to_end


class XMLConsoleWindow(Gtk.ApplicationWindow, EventHelper):
    def __init__(self) -> None:
        Gtk.ApplicationWindow.__init__(self)
        EventHelper.__init__(self)
        self.set_application(app.app)
        self.set_position(Gtk.WindowPosition.CENTER)
        self.set_default_size(800, 600)
        self.set_resizable(True)
        self.set_show_menubar(False)
        self.set_name('XMLConsoleWindow')

        self._selected_account = 'AllAccounts'
        self._selected_send_account: str | None = None
        self._filter_dialog: SettingsDialog | None = None
        self._sent_stanzas = SentSzanzas()
        self._last_selected_ts = 0
        self._last_search: str = ''

        self._presence = True
        self._message = True
        self._iq = True
        self._stream = True
        self._incoming = True
        self._outgoing = True

        self._ui = get_builder('xml_console.ui')
        self.set_titlebar(self._ui.headerbar)
        self._set_titlebar()
        self.add(self._ui.stack)

        self._ui.paned.set_position(
            self._ui.paned.get_property('max-position'))

        self._combo = MaxWidthComboBoxText()
        self._combo.set_max_size(200)
        self._combo.set_hexpand(False)
        self._combo.set_halign(Gtk.Align.END)
        self._combo.set_no_show_all(True)
        self._combo.set_visible(False)
        self._combo.connect('changed', self._on_value_change)
        available_accounts = self._get_accounts()
        for account, label in available_accounts:
            self._combo.append(account, label)
        if available_accounts:
            self._combo.set_active(0)
        self._ui.actionbox.pack_end(self._combo, False, False, 0)
        self._ui.actionbox.reorder_child(self._combo, 1)

        self._create_tags()

        source_manager = GtkSource.LanguageManager.get_default()
        lang = source_manager.get_language('xml')
        self._ui.protocol_view.get_buffer().set_language(lang)
        self._ui.input_entry.get_buffer().set_language(lang)

        style_scheme_manager = GtkSource.StyleSchemeManager.get_default()
        style_scheme = style_scheme_manager.get_scheme('solarized-dark')
        if style_scheme is not None:
            self._ui.protocol_view.get_buffer().set_style_scheme(style_scheme)
            self._ui.input_entry.get_buffer().set_style_scheme(style_scheme)
            self._ui.log_view.get_buffer().set_style_scheme(style_scheme)

        for record in app.logging_records:
            self._add_log_record(record)

        log_handler = get_log_console_handler()
        log_handler.set_callback(self._add_log_record)

        self._ui.stack.connect('notify::visible-child-name',
                               self._on_stack_child_changed)

        self.show_all()

        self.connect('key-press-event', self._on_key_press)
        self.connect('destroy', self._on_destroy)
        self._ui.connect_signals(self)

        self.register_events([
            ('stanza-received', ged.GUI1, self._on_stanza_received),
            ('stanza-sent', ged.GUI1, self._on_stanza_sent),
            ('account-enabled', ged.GUI1, self._on_account_changed),
            ('account-disabled', ged.GUI1, self._on_account_changed)
        ])

    def _on_destroy(self, *args: Any) -> None:
        get_log_console_handler().set_callback(None)
        self._ui.popover.destroy()
        app.check_finalize(self)

    def _on_value_change(self, combo: Gtk.ComboBox) -> None:
        self._selected_send_account = combo.get_active_id()

    def _set_titlebar(self) -> None:
        if self._selected_account == 'AllAccounts':
            title = _('All Accounts')
        elif self._selected_account == 'AccountWizard':
            title = _('Account Wizard')
        else:
            title = app.get_jid_from_account(self._selected_account)
        self._ui.headerbar.set_subtitle(title)

    def _on_account_changed(self,
                            event: AccountEnabled | AccountDisabled
                            ) -> None:
        buf = self._ui.protocol_view.get_buffer()

        if isinstance(event, AccountEnabled):
            buf.create_tag(event.account)
        else:
            start, end = buf.get_bounds()
            buf.remove_tag_by_name(event.account, start, end)

    def _on_stack_child_changed(self,
                                _widget: Gtk.Stack,
                                _pspec: GObject.ParamSpec
                                ) -> None:

        name = self._ui.stack.get_visible_child_name()
        self._ui.search_toggle.set_sensitive(name == 'protocol')

    def _create_tags(self) -> None:
        tags = [
            'incoming',
            'outgoing',
            'presence',
            'message',
            'stream',
            'iq'
        ]

        accounts = app.settings.get_active_accounts()
        tags.extend(accounts)

        tags.append('AccountWizard')

        for tag_name in tags:
            self._ui.protocol_view.get_buffer().create_tag(tag_name)

    def _add_log_record(self, message: str) -> None:
        buf = self._ui.log_view.get_buffer()
        end_iter = buf.get_end_iter()
        buf.insert(end_iter, message)

    def _on_key_press(self, _widget: Gtk.Widget, event: Gdk.EventKey) -> None:
        if event.keyval == Gdk.KEY_Escape:
            if self._ui.search_revealer.get_child_revealed():
                self._ui.search_revealer.set_reveal_child(False)
                return
            self.destroy()
        if (event.state & Gdk.ModifierType.CONTROL_MASK and
                event.keyval == Gdk.KEY_Return or
                event.keyval == Gdk.KEY_KP_Enter):
            self._on_send()
        if (event.state & Gdk.ModifierType.CONTROL_MASK and
                event.keyval == Gdk.KEY_Up):
            self._on_paste_previous()
        if (event.state & Gdk.ModifierType.CONTROL_MASK and
                event.keyval == Gdk.KEY_Down):
            self._on_paste_next()
        if (event.state & Gdk.ModifierType.CONTROL_MASK and
                event.keyval == Gdk.KEY_f):
            self._ui.search_toggle.set_active(
                not self._ui.search_revealer.get_child_revealed())
        if event.keyval == Gdk.KEY_F3:
            self._find(Direction.NEXT)

    def _on_row_activated(self,
                          _listbox: Gtk.ListBox,
                          row: Gtk.ListBoxRow
                          ) -> None:
        child = row.get_child()
        assert isinstance(child, Gtk.Label)
        text = child.get_text()

        input_text = None
        if text == 'Presence':
            input_text = (
                '<presence xmlns="jabber:client">\n'
                '<show></show>\n'
                '<status></status>\n'
                '<priority></priority>\n'
                '</presence>')
        elif text == 'Message':
            input_text = (
                '<message to="" type="" xmlns="jabber:client">\n'
                '<body></body>\n'
                '</message>')
        elif text == 'Iq':
            input_text = (
                '<iq to="" type="" xmlns="jabber:client">\n'
                '<query xmlns=""></query>\n'
                '</iq>')
        elif text == 'Disco Info':
            input_text = (
                '<iq to="" type="get" xmlns="jabber:client">\n'
                '<query xmlns="http://jabber.org/protocol/disco#info">'
                '</query>\n</iq>')

        if input_text is not None:
            buffer_ = self._ui.input_entry.get_buffer()
            buffer_.set_text(input_text)
            self._ui.input_entry.grab_focus()

    def _on_send(self, *args: Any) -> None:
        if not self._selected_send_account:
            return
        if not app.account_is_available(self._selected_send_account):
            # If offline or connecting
            ErrorDialog(
                _('Connection not available'),
                _('Please make sure you are connected with "%s".') %
                self._selected_send_account)
            return
        buffer_ = self._ui.input_entry.get_buffer()
        begin_iter, end_iter = buffer_.get_bounds()
        stanza = buffer_.get_text(begin_iter, end_iter, True)
        if stanza:
            try:
                node = nbxmpp.Node(node=stanza)
            except Exception as error:
                ErrorDialog(_('Invalid Node'), str(error))
                return

            if node.getName() in ('message', 'presence', 'iq'):
                # Parse stanza again if its a message, presence or iq and
                # set jabber:client as toplevel namespace
                # Use type Protocol so nbxmpp counts the stanza for
                # stream management
                node = nbxmpp.Protocol(node=stanza,
                                       attrs={'xmlns': 'jabber:client'})
            client = app.get_client(self._selected_send_account)
            assert isinstance(node, nbxmpp.Protocol)
            client.connection.send_stanza(node)
            self._sent_stanzas.add(stanza)
            buffer_.set_text('')

    def _on_paste_previous(self, *args: Any) -> None:
        buffer_ = self._ui.input_entry.get_buffer()
        buffer_.set_text(self._sent_stanzas.get_previous())
        self._ui.input_entry.grab_focus()

    def _on_paste_next(self, *args: Any) -> None:
        buffer_ = self._ui.input_entry.get_buffer()
        buffer_.set_text(self._sent_stanzas.get_next())
        self._ui.input_entry.grab_focus()

    def _on_input(self, button: Gtk.ToggleButton) -> None:
        child2 = self._ui.paned.get_child2()
        assert child2 is not None
        if button.get_active():
            child2.show()
            self._ui.send.show()
            self._ui.paste.show()
            self._ui.account_label.show()
            self._combo.show()
            self._ui.menubutton.show()
            self._ui.input_entry.grab_focus()
        else:
            child2.hide()
            self._ui.send.hide()
            self._ui.paste.hide()
            self._ui.account_label.hide()
            self._combo.hide()
            self._ui.menubutton.hide()

    def _on_search_toggled(self, button: Gtk.ToggleButton) -> None:
        self._ui.search_revealer.set_reveal_child(button.get_active())
        self._ui.search_entry.grab_focus()

    def _on_search_activate(self, _entry: Gtk.SearchEntry) -> None:
        self._find(Direction.NEXT)

    def _on_search_clicked(self, button: Gtk.ToolButton) -> None:
        if button is self._ui.search_forward:
            direction = Direction.NEXT
        else:
            direction = Direction.PREV
        self._find(direction)

    def _find(self, direction: Direction) -> None:
        search_str = self._ui.search_entry.get_text()
        textbuffer = self._ui.protocol_view.get_buffer()
        cursor_mark = textbuffer.get_insert()
        current_pos = textbuffer.get_iter_at_mark(cursor_mark)

        if current_pos.get_offset() == textbuffer.get_char_count():
            current_pos = textbuffer.get_start_iter()

        last_pos_mark = textbuffer.get_mark('last_pos')
        if last_pos_mark is not None:
            current_pos = textbuffer.get_iter_at_mark(last_pos_mark)

        if search_str != self._last_search:
            current_pos = textbuffer.get_start_iter()

        if direction == Direction.NEXT:
            match = current_pos.forward_search(
                search_str,
                Gtk.TextSearchFlags.VISIBLE_ONLY |
                Gtk.TextSearchFlags.CASE_INSENSITIVE,
                None)
        else:
            current_pos.backward_cursor_position()
            match = current_pos.backward_search(
                search_str,
                Gtk.TextSearchFlags.VISIBLE_ONLY |
                Gtk.TextSearchFlags.CASE_INSENSITIVE,
                None)

        if match is not None:
            match_start, match_end = match
            textbuffer.select_range(match_start, match_end)
            mark = textbuffer.create_mark('last_pos', match_end, True)
            self._ui.protocol_view.scroll_to_mark(mark, 0, True, 0.5, 0.5)
        self._last_search = search_str

    @staticmethod
    def _get_accounts() -> list[tuple[str | None, str]]:
        accounts = app.get_accounts_sorted()
        combo_accounts: list[tuple[str | None, str]] = []
        for account in accounts:
            label = app.get_account_label(account)
            combo_accounts.append((account, label))
        combo_accounts.append(('AccountWizard', 'Account Wizard'))
        return combo_accounts

    def _on_filter_options(self, _button: Gtk.Button) -> None:
        if self._filter_dialog is not None:
            self._filter_dialog.present()
            return

        combo_accounts = self._get_accounts()
        combo_accounts.insert(0, ('AllAccounts', _('All Accounts')))

        settings = [
            Setting(SettingKind.COMBO,
                    _('Account'),
                    SettingType.VALUE,
                    self._selected_account,
                    callback=self._set_account,
                    props={'combo_items': combo_accounts}),

            Setting(SettingKind.SWITCH,
                    'Presence',
                    SettingType.VALUE,
                    self._presence,
                    callback=self._on_setting,
                    data='presence'),

            Setting(SettingKind.SWITCH,
                    'Message',
                    SettingType.VALUE,
                    self._message,
                    callback=self._on_setting,
                    data='message'),

            Setting(SettingKind.SWITCH,
                    'IQ', SettingType.VALUE,
                    self._iq,
                    callback=self._on_setting,
                    data='iq'),

            Setting(SettingKind.SWITCH,
                    'Stream Management',
                    SettingType.VALUE,
                    self._stream,
                    callback=self._on_setting,
                    data='stream'),

            Setting(SettingKind.SWITCH,
                    'In',
                    SettingType.VALUE,
                    self._incoming,
                    callback=self._on_setting,
                    data='incoming'),

            Setting(SettingKind.SWITCH,
                    'Out',
                    SettingType.VALUE,
                    self._outgoing,
                    callback=self._on_setting,
                    data='outgoing'),
        ]

        self._filter_dialog = SettingsDialog(
            self,
            _('Filter'),
            Gtk.DialogFlags.DESTROY_WITH_PARENT,
            settings,
            self._selected_account or 'AllAccounts')
        self._filter_dialog.connect('destroy', self._on_filter_destroyed)

    def _on_filter_destroyed(self, _widget: Gtk.Widget) -> None:
        self._filter_dialog = None

    def _on_clear(self, _button: Gtk.Button) -> None:
        self._ui.protocol_view.get_buffer().set_text('')

    def _set_account(self, value: str, _data: Any) -> None:
        self._selected_account = value
        self._set_titlebar()

        active_accounts = app.settings.get_active_accounts()
        active_accounts.append('AccountWizard')

        table = self._ui.protocol_view.get_buffer().get_tag_table()

        if value == 'AllAccounts':
            for account in active_accounts:
                tag = table.lookup(account)
                if tag is not None:
                    tag.set_property('invisible', False)
            return

        for account in active_accounts:
            tag = table.lookup(account)
            if tag is not None:
                tag.set_property('invisible', account != value)

    def _on_setting(self, value: bool, data: str) -> None:
        setattr(self, f'_{data}', value)
        value = not value
        table = self._ui.protocol_view.get_buffer().get_tag_table()
        tag = table.lookup(data)
        if tag is None:
            return

        if data in ('incoming', 'outgoing'):
            if value:
                tag.set_priority(table.get_size() - 1)
            else:
                tag.set_priority(0)

        tag.set_property('invisible', value)

    def _on_stanza_received(self, event: StanzaReceived):
        self._print_stanza(event, 'incoming')

    def _on_stanza_sent(self, event: StanzaSent):
        self._print_stanza(event, 'outgoing')

    def _print_stanza(self,
                      event: StanzaReceived | StanzaSent,
                      kind: str
                      ) -> None:
        if event.account == 'AccountWizard':
            account_label = 'Account Wizard'
        else:
            account_label = app.get_account_label(event.account)

        stanza = event.stanza
        if not isinstance(stanza, str):
            # pylint: disable=unnecessary-dunder-call
            stanza = stanza.__str__(fancy=True)

        if not stanza:
            return

        is_at_the_end = at_the_end(self._ui.scrolled)

        buffer_ = self._ui.protocol_view.get_buffer()
        end_iter = buffer_.get_end_iter()

        type_ = kind
        if stanza.startswith('<presence'):
            type_ = 'presence'
        elif stanza.startswith('<message'):
            type_ = 'message'
        elif stanza.startswith('<iq'):
            type_ = 'iq'
        elif stanza.startswith(('<r', '<a')):
            type_ = 'stream'

        text = '<!-- {kind} {time} ({account}) -->\n{stanza}\n\n'.format(
            kind=kind.capitalize(),
            time=time.strftime('%c'),
            account=account_label,
            stanza=stanza)
        buffer_.insert_with_tags_by_name(
            end_iter, text, type_, kind, event.account)

        if is_at_the_end:
            GLib.idle_add(scroll_to_end, self._ui.scrolled)


class SentSzanzas:
    def __init__(self) -> None:
        self._sent_stanzas: dict[float, str] = {}
        self._last_selected_ts = 0

    def add(self, stanza: str) -> None:
        self._sent_stanzas[time.time()] = stanza
        self._last_selected_ts = 0

    def get_previous(self) -> str:
        return self._get(Direction.PREV)

    def get_next(self) -> str:
        return self._get(Direction.NEXT)

    def _get(self, direction: Direction) -> str:
        if not self._sent_stanzas:
            return ''

        if direction == Direction.PREV:
            for timestamp, stanza in reversed(self._sent_stanzas.items()):
                if timestamp >= self._last_selected_ts:
                    continue
                self._last_selected_ts = timestamp
                return stanza
        else:
            for timestamp, stanza in self._sent_stanzas.items():
                if timestamp <= self._last_selected_ts:
                    continue
                self._last_selected_ts = timestamp
                return stanza

        self._last_selected_ts = list(self._sent_stanzas.keys())[-1]
        return self._sent_stanzas[self._last_selected_ts]