File: main.py

package info (click to toggle)
tryton-client 7.0.27-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,476 kB
  • sloc: python: 27,180; sh: 37; makefile: 18
file content (1087 lines) | stat: -rw-r--r-- 42,452 bytes parent folder | download | duplicates (2)
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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
# This file is part of Tryton.  The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.

import gettext
import json
import logging
import os
import sys
import threading
import traceback
import webbrowser
from functools import partial
from urllib.parse import parse_qsl, unquote, urlparse

from gi.repository import Gdk, GdkPixbuf, Gio, GLib, Gtk

import tryton.common as common
import tryton.plugins
import tryton.rpc as rpc
import tryton.translate as translate
from tryton.action import Action
from tryton.common import RPCContextReload, RPCException, RPCExecute
from tryton.common.cellrendererclickablepixbuf import (
    CellRendererClickablePixbuf)
from tryton.config import CONFIG, TRYTON_ICON, get_config_dir
from tryton.exceptions import TrytonError, TrytonServerUnavailable
from tryton.gui.window import Window
from tryton.jsonrpc import object_hook
from tryton.pyson import PYSONDecoder

_ = gettext.gettext
logger = logging.getLogger(__name__)
_PRIORITIES = [getattr(Gio.NotificationPriority, p)
    for p in ('LOW', 'NORMAL', 'HIGH', 'URGENT')]


class Main(Gtk.Application):
    window = None
    _instance = None

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super().__new__(cls, *args, **kwargs)
        return cls._instance

    def do_startup(self):
        Gtk.Application.do_startup(self)

        action = Gio.SimpleAction.new('preferences', None)
        action.connect('activate', lambda *a: self.preferences())
        self.add_action(action)
        self.set_accels_for_action('app.preferences', ['<Primary>comma'])

        action = Gio.SimpleAction.new('menu-search', None)
        action.connect(
            'activate', lambda *a: self.global_search_entry.grab_focus())
        self.add_action(action)
        self.set_accels_for_action('app.menu-search', ['<Primary>k'])

        action = Gio.SimpleAction.new('menu-toggle', None)
        action.connect('activate', lambda *a: self.menu_toggle())
        self.add_action(action)
        self.set_accels_for_action('app.menu-toggle', ['<Primary>m'])

        toolbar_variant = GLib.Variant.new_string(
            CONFIG['client.toolbar'] or 'both')
        action = Gio.SimpleAction.new_stateful(
            'toolbar', toolbar_variant.get_type(), toolbar_variant)
        action.connect('change-state', self.on_change_toolbar)
        self.add_action(action)

        def on_change_action_boolean(action, value, key):
            action.set_state(value)
            CONFIG[key] = value.get_boolean()
            if key == 'client.check_version' and CONFIG[key]:
                common.check_version(self.info)

        for name, key in [
                ('mode-pda', 'client.modepda'),
                ('save-tree-width', 'client.save_tree_width'),
                ('save-tree-state', 'client.save_tree_state'),
                ('code-scanner-sound', 'client.code_scanner_sound'),
                ('spell-checking', 'client.spellcheck'),
                ('check-version', 'client.check_version'),
                ]:
            variant = GLib.Variant.new_boolean(CONFIG[key])
            action = Gio.SimpleAction.new_stateful(name, None, variant)
            action.connect('change-state', on_change_action_boolean, key)
            self.add_action(action)

        action = Gio.SimpleAction.new('tab-previous', None)
        action.connect('activate', lambda *a: self.win_prev())
        self.add_action(action)
        self.set_accels_for_action('app.tab-previous', ['<Primary><Shift>Tab'])

        action = Gio.SimpleAction.new('tab-next', None)
        action.connect('activate', lambda *a: self.win_next())
        self.add_action(action)
        self.set_accels_for_action('app.tab-next', ['<Primary>Tab'])

        action = Gio.SimpleAction.new('search-limit', None)
        action.connect('activate', lambda *a: self.edit_limit())
        self.add_action(action)

        action = Gio.SimpleAction.new('documentation', None)
        action.connect('activate', lambda *a: common.open_documentation())
        self.add_action(action)

        self._shortcuts = None
        action = Gio.SimpleAction.new('shortcuts', None)
        action.connect('activate', lambda *a: self.shortcuts())
        self.add_action(action)
        self.set_accels_for_action('app.shortcuts', ['<Primary>F1'])

        action = Gio.SimpleAction.new('about', None)
        action.connect('activate', lambda *a: self.about())
        self.add_action(action)

        action = Gio.SimpleAction.new('quit', None)
        action.connect('activate', self.on_quit)
        self.add_action(action)
        self.set_accels_for_action('app.quit', ['<Primary>q'])

    def do_activate(self):
        if self.window:
            self.window.present()
            return

        self.window = Gtk.ApplicationWindow(application=self, title="Tryton")
        self.window.set_default_size(1280, 960)
        self.window.maximize()
        self.window.set_position(Gtk.WindowPosition.CENTER)
        self.window.set_resizable(True)
        self.window.set_icon(TRYTON_ICON)
        self.window.connect("destroy", self.on_quit)
        self.window.connect("delete_event", self.on_quit)
        common.setup_window(self.window)

        self.header = Gtk.HeaderBar.new()
        self.header.set_show_close_button(True)
        self.window.set_titlebar(self.header)
        self.set_title()

        self.primary_menu = Gtk.MenuButton.new()
        self.primary_menu.set_menu_model(self._get_primary_menu())
        self.header.pack_end(self.primary_menu)

        menu = Gtk.Button.new()
        menu.set_relief(Gtk.ReliefStyle.NONE)
        menu.set_image(
            common.IconFactory.get_image('tryton-menu', Gtk.IconSize.BUTTON))
        menu.connect('clicked', self.menu_toggle)
        self.header.pack_start(menu)

        favorite = Gtk.MenuButton.new()
        favorite.set_relief(Gtk.ReliefStyle.NONE)
        favorite.set_image(common.IconFactory.get_image(
                'tryton-bookmarks', Gtk.IconSize.BUTTON))
        self.menu_favorite = Gtk.Menu.new()
        favorite.set_popup(self.menu_favorite)
        favorite.connect('button-press-event', self.favorite_set)
        self.header.pack_start(favorite)

        self.set_global_search()
        self.header.pack_start(self.global_search_entry)

        self.accel_group = Gtk.AccelGroup()
        self.window.add_accel_group(self.accel_group)

        Gtk.AccelMap.add_entry(
            '<tryton>/Form/New', Gdk.KEY_N, Gdk.ModifierType.CONTROL_MASK)
        Gtk.AccelMap.add_entry(
            '<tryton>/Form/Save', Gdk.KEY_S, Gdk.ModifierType.CONTROL_MASK)
        Gtk.AccelMap.add_entry(
            '<tryton>/Form/Duplicate', Gdk.KEY_D,
            Gdk.ModifierType.CONTROL_MASK | Gdk.ModifierType.SHIFT_MASK)
        Gtk.AccelMap.add_entry(
            '<tryton>/Form/Delete', Gdk.KEY_D, Gdk.ModifierType.CONTROL_MASK)
        Gtk.AccelMap.add_entry(
            '<tryton>/Form/Next', Gdk.KEY_Down, Gdk.ModifierType.CONTROL_MASK)
        Gtk.AccelMap.add_entry(
            '<tryton>/Form/Previous',
            Gdk.KEY_Up, Gdk.ModifierType.CONTROL_MASK)
        Gtk.AccelMap.add_entry(
            '<tryton>/Form/Switch View', Gdk.KEY_L,
            Gdk.ModifierType.CONTROL_MASK)
        Gtk.AccelMap.add_entry(
            '<tryton>/Form/Close', Gdk.KEY_W, Gdk.ModifierType.CONTROL_MASK)
        Gtk.AccelMap.add_entry(
            '<tryton>/Form/Reload', Gdk.KEY_R, Gdk.ModifierType.CONTROL_MASK)
        Gtk.AccelMap.add_entry(
            '<tryton>/Form/Attachments', Gdk.KEY_T,
            Gdk.ModifierType.CONTROL_MASK | Gdk.ModifierType.SHIFT_MASK)
        Gtk.AccelMap.add_entry(
            '<tryton>/Form/Notes', Gdk.KEY_O,
            Gdk.ModifierType.CONTROL_MASK | Gdk.ModifierType.SHIFT_MASK)
        Gtk.AccelMap.add_entry(
            '<tryton>/Form/Relate', Gdk.KEY_R,
            Gdk.ModifierType.CONTROL_MASK | Gdk.ModifierType.SHIFT_MASK)
        Gtk.AccelMap.add_entry(
            '<tryton>/Form/Actions', Gdk.KEY_E, Gdk.ModifierType.CONTROL_MASK)
        Gtk.AccelMap.add_entry(
            '<tryton>/Form/Report', Gdk.KEY_P, Gdk.ModifierType.CONTROL_MASK)
        Gtk.AccelMap.add_entry(
            '<tryton>/Form/Email', Gdk.KEY_E,
            Gdk.ModifierType.CONTROL_MASK | Gdk.ModifierType.SHIFT_MASK)
        Gtk.AccelMap.add_entry(
            '<tryton>/Form/Search', Gdk.KEY_F,
            Gdk.ModifierType.CONTROL_MASK | Gdk.ModifierType.SHIFT_MASK)

        Gtk.AccelMap.load(os.path.join(get_config_dir(), 'accel.map'))

        self.tooltips = common.Tooltips()

        self.vbox = Gtk.VBox()
        self.window.add(self.vbox)

        self.buttons = {}

        self.info = Gtk.VBox()
        self.vbox.pack_start(self.info, expand=False, fill=True, padding=0)
        if CONFIG['client.check_version']:
            common.check_version(self.info)
            GLib.timeout_add_seconds(
                int(CONFIG['download.frequency']), common.check_version,
                self.info)

        self.pane = Gtk.HPaned()
        self.vbox.pack_start(self.pane, expand=True, fill=True, padding=0)
        self.pane.set_position(int(CONFIG['menu.pane']))

        self.menu_screen = None
        self.menu = Gtk.VBox()
        self.menu.set_vexpand(True)
        self.pane.add1(self.menu)

        self.notebook = Gtk.Notebook()
        self.notebook.popup_enable()
        self.notebook.set_scrollable(True)
        self.notebook.connect_after('switch-page', self._sig_page_changt)
        self.pane.add2(self.notebook)

        self.window.show_all()

        self.pages = []
        self.previous_pages = {}
        self.current_page = 0
        self.last_page = 0
        self.dialogs = []

        # Register plugins
        tryton.plugins.register()

        self.set_title()  # Adds username/profile while password is asked
        try:
            common.get_credentials()
        except Exception as exception:
            if not isinstance(exception, TrytonError):
                common.error(exception, traceback.format_exc())
            elif exception.faultCode == 'SessionFailed':
                common.message(
                    _("Could not get a session."),
                    msg_type=Gtk.MessageType.ERROR)
            return self.quit()
        self.get_preferences()

    def do_command_line(self, cmd):
        self.do_activate()
        arguments = cmd.get_arguments()
        if len(arguments) > 1:
            url = arguments[1]
            self.open_url(url)
        return True

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)
        common.Logout()
        CONFIG.save()
        Gtk.AccelMap.save(os.path.join(get_config_dir(), 'accel.map'))

    def on_quit(self, *args):
        try:
            if not self.close_pages():
                return True
        except TrytonServerUnavailable:
            pass
        rpc.logout()
        self.quit()

    def add_window(self, window):
        super().add_window(window)
        common.setup_window(window)

    def _get_primary_menu(self):
        menu = Gio.Menu.new()
        menu.append(_("Preferences..."), 'app.preferences')

        section = Gio.Menu.new()
        toolbar = Gio.Menu.new()
        section.append_submenu(_("Toolbar"), toolbar)
        toolbar.append(_("Default"), 'app.toolbar::default')
        toolbar.append(_("Text and Icons"), 'app.toolbar::both')
        toolbar.append(_("Text"), 'app.toolbar::text')
        toolbar.append(_("Icons"), 'app.toolbar::icons')

        form = Gio.Menu.new()
        section.append_submenu(_("Form"), form)
        form.append(_("Save Column Width"), 'app.save-tree-width')
        form.append(_("Save Tree State"), 'app.save-tree-state')
        form.append(_("Spell Checking"), 'app.spell-checking')
        form.append(_("Play Sound for Code Scanner"), 'app.code-scanner-sound')

        section.append(_("PDA Mode"), 'app.mode-pda')
        section.append(_("Search Limit..."), 'app.search-limit')
        # Debian: check_version not for us
        # section.append(_("Check Version"), 'app.check-version')

        menu.append_section(_("Options"), section)

        section = Gio.Menu.new()
        section.append(_("Documentation..."), 'app.documentation')
        section.append(_("Keyboard Shortcuts..."), 'app.shortcuts')
        section.append(_("About..."), 'app.about')
        menu.append_section(_("Help"), section)
        return menu

    def set_global_search(self):
        self.global_search_entry = Gtk.Entry.new()
        self.global_search_entry.set_width_chars(20)
        global_search_completion = Gtk.EntryCompletion()
        global_search_completion.set_match_func(lambda *a: True)
        global_search_completion.set_model(
            Gtk.ListStore(GdkPixbuf.Pixbuf, str, str, int, str))
        pixbuf_cell = Gtk.CellRendererPixbuf()
        global_search_completion.pack_start(pixbuf_cell, expand=True)
        global_search_completion.add_attribute(pixbuf_cell, 'pixbuf', 0)
        text_cell = Gtk.CellRendererText()
        global_search_completion.pack_start(text_cell, expand=True)
        global_search_completion.add_attribute(text_cell, "markup", 1)
        global_search_completion.props.popup_set_width = True
        self.global_search_entry.set_completion(global_search_completion)

        def match_selected(completion, model, iter_):
            model, record_id, model_name = model.get(iter_, 2, 3, 4)
            if model == self.menu_screen.model_name:
                # ids is not defined to prevent to add suffix
                Action.exec_keyword('tree_open', {
                        'model': model,
                        'id': record_id,
                        })
            else:
                Window.create(model,
                    res_id=record_id,
                    mode=['form', 'tree'],
                    name=model_name)
            self.global_search_entry.set_text('')
            return True

        global_search_completion.connect('match-selected', match_selected)

        def update(widget, search_text, callback=None):
            def end():
                if callback:
                    callback()
                return False
            if search_text != widget.get_text():
                return end()
            gmodel = global_search_completion.get_model()
            if not search_text or not gmodel:
                gmodel.clear()
                gmodel.search_text = search_text
                return end()
            if getattr(gmodel, 'search_text', None) == search_text:
                return end()

            def set_result(result):
                try:
                    result = result()
                except RPCException:
                    result = []
                if search_text != widget.get_text():
                    if callback:
                        callback()
                    return False
                gmodel.clear()
                for r in result:
                    _, model, model_name, record_id, record_name, icon = r
                    if icon:
                        text = common.to_xml(record_name)
                        pixbuf = common.IconFactory.get_pixbuf(
                            icon, Gtk.IconSize.BUTTON)
                    else:
                        text = '<b>%s:</b>\n %s' % (
                            common.to_xml(model_name),
                            common.to_xml(record_name))
                        pixbuf = None
                    gmodel.append([pixbuf, text, model, record_id, model_name])
                gmodel.search_text = search_text
                # Force display of popup
                widget.emit('changed')
                end()

            RPCExecute('model', 'ir.model', 'global_search', search_text,
                CONFIG['client.limit'], self.menu_screen.model_name,
                context=self.menu_screen.context, callback=set_result)
            return False

        def changed(widget):
            search_text = widget.get_text()
            GLib.timeout_add(300, update, widget, search_text)

        def activate(widget):
            def message():
                gmodel = global_search_completion.get_model()
                if not len(gmodel):
                    common.message(_('No result found.'))
                else:
                    widget.emit('changed')
            search_text = widget.get_text()
            update(widget, search_text, message)

        self.global_search_entry.connect('changed', changed)
        self.global_search_entry.connect('activate', activate)

    def set_title(self, value=''):
        if CONFIG['login.profile']:
            login_info = CONFIG['login.profile']
        else:
            login_info = '%s@%s/%s' % (
                CONFIG['login.login'],
                CONFIG['login.host'],
                CONFIG['login.db'])
        titles = []
        if value:
            titles.append(value)
        titles.append(CONFIG['client.title'])
        self.header.set_title(' - '.join(titles))
        self.header.set_subtitle(login_info)
        try:
            style_context = self.header.get_style_context()
        except AttributeError:
            pass
        else:
            for name in style_context.list_classes():
                if name.startswith('profile-'):
                    style_context.remove_class(name)
            if CONFIG['login.profile']:
                style_context.add_class(
                    'profile-%s' % CONFIG['login.profile'])

    def favorite_set(self, *args):
        if self.menu_favorite.get_children():
            return

        def _action_favorite(widget, id_):
            event = Gtk.get_current_event()
            allow_similar = (event.state & Gdk.ModifierType.MOD1_MASK
                or event.state & Gdk.ModifierType.SHIFT_MASK)
            with Window(allow_similar=allow_similar):
                # ids is not defined to prevent to add suffix
                Action.exec_keyword('tree_open', {
                        'model': self.menu_screen.model_name,
                        'id': id_,
                        })

        def _manage_favorites(widget):
            Window.create(self.menu_screen.model_name + '.favorite',
                mode=['tree', 'form'],
                name=_("Favorites"))
        try:
            favorites = RPCExecute('model',
                self.menu_screen.model_name + '.favorite', 'get',
                process_exception=False)
        except Exception:
            return False
        for id_, name, icon in favorites:
            menuitem = Gtk.MenuItem(label=name)
            menuitem.connect('activate', _action_favorite, id_)
            self.menu_favorite.add(menuitem)
        self.menu_favorite.add(Gtk.SeparatorMenuItem())
        manage_favorites = Gtk.MenuItem(label=_("Manage..."),
            use_underline=True)
        manage_favorites.connect('activate', _manage_favorites)
        self.menu_favorite.add(manage_favorites)
        self.menu_favorite.show_all()

    def favorite_unset(self):
        for child in self.menu_favorite.get_children():
            self.menu_favorite.remove(child)

    def on_change_toolbar(self, action, value):
        action.set_state(value)
        option = value.get_string()
        CONFIG['client.toolbar'] = option
        if option == 'default':
            barstyle = False
        elif option == 'both':
            barstyle = Gtk.ToolbarStyle.BOTH
        elif option == 'text':
            barstyle = Gtk.ToolbarStyle.TEXT
        elif option == 'icons':
            barstyle = Gtk.ToolbarStyle.ICONS
        for page_idx in range(self.notebook.get_n_pages()):
            page = self.get_page(page_idx)
            if page.toolbar:
                page.toolbar.set_style(barstyle)

    def edit_limit(self):
        from tryton.gui.window.limit import Limit
        Limit().run()

    def win_next(self):
        page = self.notebook.get_current_page()
        if page == len(self.pages) - 1:
            page = -1
        self.notebook.set_current_page(page + 1)

    def win_prev(self):
        page = self.notebook.get_current_page()
        self.notebook.set_current_page(page - 1)

    def get_preferences(self):
        RPCContextReload()
        try:
            prefs = RPCExecute('model', 'res.user', 'get_preferences', False)
        except RPCException:
            prefs = {}

        targets = [
            common.IconFactory.load_icons,
            common.MODELACCESS.load_models,
            common.MODELHISTORY.load_history,
            common.MODELNOTIFICATION.load_names,
            common.VIEW_SEARCH.load_searches,
            ]
        if CONFIG['thread']:
            threads = []
            for target in targets:
                t = threading.Thread(target=target)
                threads.append(t)
                t.start()
            for t in threads:
                t.join()
        else:
            for target in targets:
                target()

        if prefs and 'language_direction' in prefs:
            translate.set_language_direction(prefs['language_direction'])
            CONFIG['client.language_direction'] = \
                prefs['language_direction']
        self.sig_win_menu(prefs=prefs)
        for action_id in prefs.get('actions', []):
            Action.execute(action_id, {})
        self.set_title(prefs.get('status_bar', ''))
        if prefs and 'language' in prefs:
            translate.setlang(prefs['language'], prefs.get('locale'))
            if CONFIG['client.lang'] != prefs['language']:
                self.favorite_unset()
                self.primary_menu.set_menu_model(self._get_primary_menu())
            CONFIG['client.lang'] = prefs['language']
        common.MODELNAME.clear()
        # Set placeholder after language is set to get correct translation
        self.global_search_entry.set_placeholder_text(_("Action"))
        CONFIG.save()

    def preferences(self):
        from tryton.gui.window.preference import Preference
        if not self.close_pages():
            return False
        Preference(rpc._USER, self.get_preferences)

    def sig_win_close(self, widget=None):
        self._sig_remove_book(widget,
            self.notebook.get_nth_page(self.notebook.get_current_page()))

    def close_pages(self):
        if self.notebook.get_n_pages():
            if not common.sur(
                    _('The following action requires to close all tabs.\n'
                    'Do you want to continue?')):
                return False
        res = True
        while res:
            wid = self.get_page()
            if wid:
                if not wid.sig_close():
                    return False
                res = self._win_del()
            else:
                res = False
        if self.menu_screen:
            self.menu_screen.save_tree_state()
        if self.menu.get_visible():
            CONFIG['menu.pane'] = self.pane.get_position()
        return True

    def about(self):
        from tryton.gui.window.about import About
        About()

    def shortcuts(self):
        if self._shortcuts:
            self._shortcuts.destroy()
        self._shortcuts = window = Gtk.ShortcutsWindow()
        window.set_transient_for(common.get_toplevel_window())
        window.set_position(Gtk.WindowPosition.CENTER_ALWAYS)
        window.set_destroy_with_parent(True)
        self.add_window(window)

        section = Gtk.ShortcutsSection()
        section.props.section_name = 'app'
        section.props.title = _("Application Shortcuts")
        section.props.visible = True

        group = Gtk.ShortcutsGroup()
        group.props.title = _("Global")
        section.add(group)

        for action, title in [
                ('app.preferences', _("Preferences")),
                ('app.menu-search', _("Search menu")),
                ('app.menu-toggle', _("Toggle menu")),
                ('app.tab-previous', _("Previous tab"), ),
                ('app.tab-next', _("Next tab")),
                ('app.shortcuts', _("Shortcuts")),
                ('app.quit', _("Quit")),
                ]:
            shortcut = Gtk.ShortcutsShortcut()
            shortcut.props.title = title
            accels = self.get_accels_for_action(action)
            if accels:
                shortcut.props.accelerator = ' '.join(accels)
                group.add(shortcut)

        window.add(section)

        for name, title, groups in [
                ('entry', _("Edition Shortcuts"), [
                        (_("Text Entries"), [
                                ('<Primary>x', _("Cut selected text")),
                                ('<Primary>c', _("Copy selected text")),
                                ('<Primary>v', _("Paste copied text")),
                                ('Tab', _("Next entry")),
                                ('<Shift>Tab', _("Previous entry")),
                                ]),
                        (_("Relation Entries"), [
                                ('F3', _("Create new relation")),
                                ('F2', _("Open/Search relation")),
                                ]),
                        (_("List Entries"), [
                                ('F4', _("Switch view")),
                                ('F3', _("Create/Select new line")),
                                ('F2', _("Open relation")),
                                ('Delete',
                                    _("Mark line for deletion/removal")),
                                ('<Ctrl>Delete', _("Mark line for removal")),
                                ('Insert', _("Unmark line for deletion")),
                                ]),
                        ]),
                ('tree', _("List/Tree Shortcuts"), [
                        (_("Move Cursor"), [
                                ('Right', _("Move right")),
                                ('Left', _("Move left")),
                                ('Up', _("Move up")),
                                ('Down', _("Move down")),
                                ('Page_Up', _("Move up of one page")),
                                ('Page_Down', _("Move down of one page")),
                                ('Home', _("Move to top")),
                                ('End', _("Move to bottom")),
                                ('BackSpace', _("Move to parent")),
                                ]),
                        (_("Edition"), [
                                ('<Primary>c', _("Copy selected rows")),
                                ('<Primary>v', _("Insert copied rows")),
                                ]),
                        (_("Selection"), [
                                ('<Ctrl>a <Ctrl>slash', _("Select all")),
                                ('<Shift><Ctrl>a <Shift><Ctrl>slash',
                                    _("Unselect all")),
                                ('BackSpace', _("Select parent")),
                                ('space', _("Select/Activate current row")),
                                ('<Shift>space Return',
                                    _("Select/Activate current row")),
                                ('<Ctrl>space', _("Toggle selection")),
                                ]),
                        (_("Expand/Collapse"), [
                                ('plus', _("Expand row")),
                                ('minus', _("Collapse row")),
                                ('space', _("Toggle row")),
                                ('<Shift>Left', _("Collapse all rows")),
                                ('<Shift>Right', _("Expand all rows")),
                                ]),
                        ]),
                ]:
            section = Gtk.ShortcutsSection()
            section.props.section_name = name
            section.props.title = title
            section.props.visible = True

            for title, shortcuts in groups:
                group = Gtk.ShortcutsGroup()
                group.props.title = title
                section.add(group)

                for accelerator, title in shortcuts:
                    shortcut = Gtk.ShortcutsShortcut()
                    shortcut.props.title = title
                    shortcut.props.accelerator = accelerator
                    group.add(shortcut)

            window.add(section)

        window.show_all()

    def menu_toggle(self, *args):
        if self.menu.get_visible():
            CONFIG['menu.pane'] = self.pane.get_position()
            self.pane.set_position(0)
            self.notebook.grab_focus()
            self.menu.set_visible(False)
        else:
            self.pane.set_position(int(CONFIG['menu.pane']))
            self.menu.set_visible(True)
            if self.menu_screen:
                self.menu_screen.set_cursor()

    def menu_row_activate(self):
        screen = self.menu_screen
        record_id = (screen.current_record.id
            if screen.current_record else None)
        # ids is not defined to prevent to add suffix
        return Action.exec_keyword('tree_open', {
                'model': screen.model_name,
                'id': record_id,
                }, warning=False)

    def sig_win_menu(self, prefs=None):
        from tryton.gui.window.view_form.screen import Screen

        if not prefs:
            try:
                prefs = RPCExecute('model', 'res.user', 'get_preferences',
                    False)
            except RPCException:
                return False

        if self.menu_screen:
            self.menu_screen.save_tree_state()
        for child in self.menu.get_children():
            self.menu.remove(child)

        action = PYSONDecoder().decode(prefs['pyson_menu'])
        view_ids = []
        if action.get('views', []):
            view_ids = [x[0] for x in action['views']]
        elif action.get('view_id', False):
            view_ids = [action['view_id'][0]]
        ctx = rpc.CONTEXT.copy()
        decoder = PYSONDecoder(ctx)
        action_ctx = decoder.decode(action.get('pyson_context') or '{}')
        domain = decoder.decode(action['pyson_domain'])
        screen = Screen(action['res_model'], mode=['tree'], view_ids=view_ids,
            domain=domain, context=action_ctx, readonly=True, limit=None,
            row_activate=self.menu_row_activate)
        # Use alternate view to not show search box
        screen.screen_container.alternate_view = True
        screen.switch_view(view_type=screen.current_view.view_type)

        self.menu.pack_start(
            screen.screen_container.alternate_viewport,
            expand=True, fill=True, padding=0)
        treeview = screen.current_view.treeview
        treeview.set_headers_visible(False)

        # Favorite column
        column = Gtk.TreeViewColumn()
        column.name = None
        column._type = None
        favorite_renderer = CellRendererClickablePixbuf()
        column.pack_start(favorite_renderer, expand=False)

        def favorite_setter(column, cell, store, iter_, user_data=None):
            menu = store.get_value(iter_, 0)
            favorite = menu.value.get('favorite')
            if favorite:
                icon = 'tryton-star'
            elif favorite is False:
                icon = 'tryton-star-border'
            else:
                icon = None
            if icon:
                pixbuf = common.IconFactory.get_pixbuf(
                    icon, Gtk.IconSize.MENU)
            else:
                pixbuf = None
            cell.set_property('pixbuf', pixbuf)
        column.set_cell_data_func(favorite_renderer, favorite_setter)

        def toggle_favorite(renderer, path, treeview):
            if treeview.props.window:
                self.toggle_favorite(renderer, path, treeview)
        favorite_renderer.connect('clicked',
            lambda *a: GLib.idle_add(toggle_favorite, *a), treeview)
        # Unset fixed height mode to add column
        treeview.set_fixed_height_mode(False)
        treeview.set_property(
            'enable-grid-lines', Gtk.TreeViewGridLines.NONE)
        treeview.append_column(column)

        screen.search_filter()
        screen.display(set_cursor=True)
        self.menu_screen = screen

    def toggle_favorite(self, renderer, path, treeview):
        store = treeview.get_model()
        iter_ = store.get_iter(path)
        menu = store.get_value(iter_, 0)
        favorite = menu.value.get('favorite')
        if favorite:
            value = False
            method = 'unset'
        elif favorite is False:
            value = True
            method = 'set'
        else:
            return
        try:
            RPCExecute('model', self.menu_screen.model_name + '.favorite',
                method, menu.id)
        except RPCException:
            return
        menu.value['favorite'] = value
        store.row_changed(path, iter_)
        self.favorite_unset()

    def win_set(self, page):
        current_page = self.notebook.get_current_page()
        page_num = self.notebook.page_num(page.widget)
        page.widget.props.visible = True
        self.notebook.set_current_page(page_num)
        # In order to focus the page
        if current_page == page_num:
            self._sig_page_changt(self.notebook, None, page_num)

    def win_add(self, page, hide_current=False):
        previous_page_id = self.notebook.get_current_page()
        previous_widget = self.notebook.get_nth_page(previous_page_id)
        if previous_widget and hide_current:
            page_id = previous_page_id + 1
        else:
            page_id = -1
        self.previous_pages[page] = previous_widget
        self.pages.append(page)
        hbox = Gtk.HBox(spacing=3)
        if page.icon:
            hbox.pack_start(
                common.IconFactory.get_image(
                    page.icon, Gtk.IconSize.SMALL_TOOLBAR),
                expand=False, fill=False, padding=0)
        name = page.name
        label = Gtk.Label(
            label=common.ellipsize(name.split(' / ')[-1], 20),
            halign=Gtk.Align.START)
        self.tooltips.set_tip(label, page.name)
        self.tooltips.enable()
        hbox.pack_start(label, expand=True, fill=True, padding=0)

        button = Gtk.Button()
        button.set_relief(Gtk.ReliefStyle.NONE)
        button.set_can_focus(False)
        button.add(common.IconFactory.get_image(
                'tryton-close', Gtk.IconSize.MENU))
        self.tooltips.set_tip(button, _('Close Tab'))
        button.connect('clicked', self._sig_remove_book, page.widget)
        hbox.pack_start(button, expand=False, fill=False, padding=0)
        size = Gtk.IconSize.lookup(Gtk.IconSize.MENU)
        button.set_size_request(size.width, size.height)

        hbox.show_all()
        label_menu = Gtk.Label(
            label=page.name, halign=Gtk.Align.START)
        page.widget.props.margin = 3
        self.notebook.insert_page_menu(page.widget, hbox, label_menu, page_id)
        self.notebook.set_tab_reorderable(page.widget, True)
        self.notebook.set_current_page(page_id)

    def _sig_remove_book(self, widget, page_widget):
        for page in self.pages:
            if page.widget == page_widget:
                if not page.widget.props.sensitive:
                    return
                page_num = self.notebook.page_num(page.widget)
                self.notebook.set_current_page(page_num)
                res = page.sig_close()
                if not res:
                    return
        self._win_del(page_widget)

    def _win_del(self, page_widget=None):
        if page_widget:
            page_id = self.notebook.page_num(page_widget)
        else:
            page_id = int(self.notebook.get_current_page())
            page_widget = self.notebook.get_nth_page(page_id)
        if page_id != -1:
            page = None
            for i in range(len(self.pages)):
                if self.pages[i].widget == page_widget:
                    page = self.pages.pop(i)
                    break
            self.notebook.remove_page(page_id)

            next_page_id = -1
            to_pop = []
            for i in self.previous_pages:
                if self.previous_pages[i] == page_widget:
                    to_pop.append(i)
                if i.widget == page_widget:
                    if self.previous_pages[i]:
                        next_page_id = self.notebook.page_num(
                                self.previous_pages[i])
                    to_pop.append(i)
            to_pop.reverse()
            for i in to_pop:
                self.previous_pages.pop(i)

            if hasattr(page, 'destroy'):
                page.destroy()
            del page

            current_widget = self.notebook.get_nth_page(next_page_id)
            if current_widget:
                current_widget.props.visible = True
            self.notebook.set_current_page(next_page_id)
        if not self.pages and self.menu_screen:
            self.menu_screen.set_cursor()
        return self.notebook.get_current_page() != -1

    def get_page(self, page_id=None):
        if page_id is None:
            page_id = self.notebook.get_current_page()
        if page_id == -1:
            return None
        page_widget = self.notebook.get_nth_page(page_id)
        for page in self.pages:
            if page.widget == page_widget:
                return page
        return None

    def _sig_page_changt(self, notebook, page, page_num):
        self.last_page = self.current_page
        last_form = self.get_page(self.current_page)
        if last_form:
            for dialog in last_form.dialogs:
                dialog.hide()

        self.current_page = self.notebook.get_current_page()
        current_form = self.get_page(self.current_page)

        def set_cursor():
            if self.current_page == self.notebook.get_current_page():
                current_form.set_cursor()
        # Using idle_add because the Gtk.TreeView grabs the focus at the
        # end of the event
        GLib.idle_add(set_cursor)
        for dialog in current_form.dialogs:
            dialog.show()

    def _open_url(self, url):
        loads = partial(json.loads, object_hook=object_hook)
        urlp = urlparse(url)
        if not urlp.scheme == 'tryton':
            return
        urlp = urlparse('http' + url[6:])
        database, path = list(map(unquote,
            (urlp.path[1:].split('/', 1) + [''])[:2]))
        if not path:
            return
        type_, path = (path.split('/', 1) + [''])[:2]
        params = {}
        if urlp.params:
            try:
                params.update(dict(parse_qsl(urlp.params,
                            strict_parsing=True)))
            except ValueError:
                return

        def open_model(path):
            attributes = {}
            model, path = (path.split('/', 1) + [''])[:2]
            if not model:
                return
            attributes = {}
            try:
                attributes['view_ids'] = loads(params.get('views', '[]'))
                if 'limit' in params:
                    attributes['limit'] = loads(params.get('limit', 'null'))
                attributes['name'] = loads(params.get('name', '""'))
                attributes['search_value'] = loads(
                    params.get('search_value', '[]'))
                attributes['domain'] = loads(params.get('domain', '[]'))
                attributes['context'] = loads(params.get('context', '{}'))
                attributes['context_model'] = params.get('context_model')
                attributes['tab_domain'] = loads(
                    params.get('tab_domain', '[]'))
            except ValueError:
                return
            if path:
                try:
                    attributes['res_id'] = int(path)
                except ValueError:
                    return
                attributes['mode'] = ['form', 'tree']
            try:
                Window.create(model, **attributes)
            except Exception:
                # Prevent crashing the client
                return

        def open_wizard(wizard):
            attributes = {}
            if not wizard:
                return
            try:
                attributes['data'] = loads(params.get('data', '{}'))
                attributes['direct_print'] = loads(
                    params.get('direct_print', 'false'))
                attributes['name'] = loads(params.get('name', '""'))
                attributes['window'] = loads(params.get('window', 'false'))
                attributes['context'] = loads(params.get('context', '{}'))
            except ValueError:
                return
            try:
                Window.create_wizard(wizard, **attributes)
            except Exception:
                # Prevent crashing the client
                return

        def open_report(report):
            attributes = {}
            if not report:
                return
            try:
                attributes['data'] = loads(params.get('data', '{}'))
                attributes['direct_print'] = loads(
                    params.get('direct_print', 'false'))
                attributes['context'] = loads(params.get('context', '{}'))
            except ValueError:
                return
            try:
                Action.exec_report(report, **attributes)
            except Exception:
                # Prevent crashing the client
                return

        def open_url():
            try:
                url = loads(params.get('url', 'false'))
            except ValueError:
                return
            if url:
                webbrowser.open(url, new=2)

        if type_ == 'model':
            open_model(path)
        elif type_ == 'wizard':
            open_wizard(path)
        elif type_ == 'report':
            open_report(path)
        elif type_ == 'url':
            open_url()

        self.window.present()

    def open_url(self, url):
        def idle_open_url():
            self._open_url(url)
            return False
        GLib.idle_add(idle_open_url)

    def show_notification(self, title, msg, priority=1):
        notification = Gio.Notification.new(title)
        notification.set_body(msg)
        notification.set_priority(_PRIORITIES[priority])
        if sys.platform != 'win32' or GLib.glib_version >= (2, 57, 0):
            self.send_notification(None, notification)