~emesene-team/emesene/master

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
# -*- coding: utf-8 -*-

#    This file is part of emesene.
#
#    emesene 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; either version 3 of the License, or
#    (at your option) any later version.
#
#    emesene 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 emesene; if not, write to the Free Software
#    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

'''a module that defines the api of objects that display dialogs'''

import logging

from PyQt4 import QtCore
from PyQt4 import QtGui
from PyQt4.QtCore import Qt

from gui.qt4ui import Utils
from gui.qt4ui.Utils import tr
from gui.qt4ui import widgets
from PyQt4 import QtWebKit

import e3
import gui
import extension
log = logging.getLogger('qt4ui.Dialog')


class Dialog(object):
    '''a class full of static methods to handle dialogs, dont instantiate it'''
    NAME = 'Dialog'
    DESCRIPTION = 'Class to show all the dialogs of the application'
    AUTHOR = 'Gabriele "Whisky" Visconti'
    WEBSITE = ''

    @classmethod
    def broken_profile(cls, close_cb, url):
        '''a dialog that asks you to fix your profile'''
        message = tr('''\
Your live profile seems to be broken,
which will cause you to experience issues
with your display name, picture
and/or personal message.

You can fix it now by re-uploading
your profile picture on the
Live Messenger website that will open,
or you can choose to fix it later.
To fix your profile, emesene must be closed.
Clicking Yes will close emesene.

Do you want to fix your profile now?''')
        gui.base.Desktop.open(url)

        reply = QtGui.QMessageBox.warning(None, tr("You have a broken profile"),
                                          message, QtGui.QMessageBox.Yes |
                                          QtGui.QMessageBox.No, QtGui.QMessageBox.No)

        if reply == QtGui.QMessageBox.Yes:
            close_cb()

    @classmethod
    def add_contact(cls, groups, group_selected, response_cb,
                    title="Add user"):
        '''show a dialog asking for an user address, and (optional)
        the group(s) where the user should be added, the response callback
        receives the response type (stock.ADD, stock.CANCEL or stock.CLOSE)
        the account and a tuple of group names where the user should be
        added (give a empty tuple if you don't implement this feature,
        the controls are made by the callback, you just ask for the email,
        don't make any control, you are just implementing a GUI! :P'''
        dialog = OkCancelDialog(title)
        text_label = QtGui.QLabel(tr('E-mail:'))
        text_edit = QtGui.QLineEdit()
        group_label = QtGui.QLabel(tr('Group:'))
        group_combo = QtGui.QComboBox()

        lay = QtGui.QGridLayout()
        lay.addWidget(text_label, 0, 0)
        lay.addWidget(text_edit, 0, 1)
        lay.addWidget(group_label, 1, 0)
        lay.addWidget(group_combo, 1, 1)
        dialog.setLayout(lay)

        dialog.set_accept_response(gui.stock.ADD)
        text_label.setAlignment(Qt.AlignRight |
                                Qt.AlignVCenter)
        group_label.setAlignment(Qt.AlignRight |
                                 Qt.AlignVCenter)
        dialog.setMinimumWidth(300)

        groups = list(groups)
        log.debug(groups)
        groups.sort()

        group_combo.addItem('<i>' + tr('No Group') + '</i>', '')
        for group in groups:
            group_combo.addItem(group.name, group.name)

        response = dialog.exec_()

        email = unicode(text_edit.text().lower())
        group = group_combo.itemData(group_combo.currentIndex()).toPyObject()
        log.debug('[%s,%s]' % (email, group))
        response_cb(response, email, group)

    @classmethod
    def add_group(cls, response_cb, title=tr('Add group')):
        '''show a dialog asking for a group name, the response callback
        receives the response (stock.ADD, stock.CANCEL, stock.CLOSE)
        and the name of the group, the control for a valid group is made
        on the controller, so if the group is empty you just call the
        callback, to make a unified behaviour, and also, to only implement
        GUI logic on your code and not client logic
        cb args: response, group_name'''
        dialog = OkCancelDialog(title)
        group_label = QtGui.QLabel(tr("Group name"))
        group_edit = QtGui.QLineEdit()

        lay = QtGui.QHBoxLayout()
        lay.addWidget(group_label)
        lay.addWidget(group_edit)
        dialog.setLayout(lay)

        dialog.setWindowTitle(title)
        dialog.setMinimumWidth(380)

        response = dialog.exec_()

        group_name = unicode(group_edit.text())

        response_cb(response, group_name)

    @classmethod
    def rename_group(cls, group, response_cb, title=tr('Rename group')):
        '''show a dialog with the group name and ask to rename it, the
        response callback receives stock.ACCEPT, stock.CANCEL or stock.CLOSE
        the old and the new name.
        cb args: response, group, new_name
        '''
        dialog = EntryDialog(tr('New group name:'), group.name, title)
        response = dialog.exec_()
        response_cb(response, group, dialog.text())

    @classmethod
    def web_window(cls, title, url, callback):
        '''returns a window with a webview'''
        dialog = WebWindow(title, url, callback)
        dialog.exec_()

    @classmethod
    def contact_added_you(cls, accounts, response_cb,
                          title=tr("User invitation")):
        '''show a dialog displaying information about users
        that added you to their userlists, the accounts parameter is
        a tuple of mail, nick that represent all the users that added you,
        the way you confirm (one or more dialogs) doesn't matter, but
        you should call the response callback only once with a dict
        with two keys 'accepted' and 'rejected' and a list of mail
        addresses as values
        '''
        def debug_response_cb(results):
            '''Simply prints the results instead of invocating the
            real response_cb'''
            print results
        dialog = ContactAdded(accounts, response_cb)
        dialog.show()
        response = dialog.exec_()

    @classmethod
    def invite_dialog(cls, session, callback, l_buddy_exclude):
        '''select a contact to add to the conversation, receives a session
        object of the current session the callback receives the response and
        a string containing the selected account
        '''
        dialog = InviteWindow(session, callback, l_buddy_exclude)

    @classmethod
    def crop_image(cls, response_cb, filename, title=tr('Select image area')):
        '''Shows a dialog to select a portion of an image.'''
        dialog = OkCancelDialog(title, expanding=True)

        # Actions
        act_dict = {}
        act_dict['rotate_left'] = QtGui.QAction(tr('Rotate Left'), dialog)
        act_dict['rotate_right'] = QtGui.QAction(tr('Rotate right'), dialog)
        act_dict['fit_zoom'] = QtGui.QAction(tr('Zoom to fit'), dialog)
        act_dict['fit_zoom'] = QtGui.QAction(tr('Zoom to fit'), dialog)
        act_dict['reset_zoom'] = QtGui.QAction(tr('Reset zoom'), dialog)
        act_dict['select_all'] = QtGui.QAction(tr('Select All'), dialog)
        act_dict['select_unsc'] = QtGui.QAction(tr('Select Unscaled'), dialog)

        # widgets
        toolbar = QtGui.QToolBar()
        scroll_area = QtGui.QScrollArea()
        area_selector = extension.get_and_instantiate(
                                                      'image area selector', QtGui.QPixmap(filename))

        # layout
        lay = QtGui.QVBoxLayout()
        lay.addWidget(toolbar)
        lay.addWidget(scroll_area)
        dialog.setLayout(lay)

        # widget setup
        toolbar.addAction(act_dict['rotate_left'])
        toolbar.addAction(act_dict['rotate_right'])
        toolbar.addSeparator()
        toolbar.addAction(act_dict['fit_zoom'])
        toolbar.addAction(act_dict['reset_zoom'])
        toolbar.addSeparator()
        toolbar.addAction(act_dict['select_all'])
        toolbar.addAction(act_dict['select_unsc'])
        scroll_area.setWidget(area_selector)
        scroll_area.setWidgetResizable(True)

        # Signal connection:
        act_dict['rotate_left'].triggered.connect(area_selector.rotate_left)
        act_dict['rotate_right'].triggered.connect(area_selector.rotate_right)
        act_dict['fit_zoom'].triggered.connect(area_selector.fit_zoom)
        act_dict['reset_zoom'].triggered.connect(
                                                 lambda: area_selector.set_zoom(1))
        act_dict['select_all'].triggered.connect(area_selector.select_all)
        act_dict['select_unsc'].triggered.connect(
                                                  area_selector.select_unscaled)
        # test:
        if (False):
            preview = QtGui.QLabel()
            lay.addWidget(preview)
            area_selector.selection_changed.connect(
                                                    lambda: preview.setPixmap(area_selector.get_selected_pixmap()))

            zoom_sli = QtGui.QSlider(Qt.Horizontal)
            zoom_sli.setMinimum(1)
            zoom_sli.setMaximum(40)
            zoom_sli.setValue(20)
            zoom_sli.setSingleStep(1)
            lay.addWidget(zoom_sli)
            zoom_sli.valueChanged.connect(
                                          lambda z:area_selector.set_zoom(z / 10.0))
        # Dialog execution:
        response = dialog.exec_()

        selected_pixmap = area_selector.get_selected_pixmap()

        response_cb(response, selected_pixmap)

    @classmethod
    def about_dialog(cls, name, version, copyright, comments, license, website,
        authors, translators, logo_path):
        '''show an about dialog of the application:
        * title: the title of the window
        * name: the name of the appliaction
        * version: version as string
        * copyright: the name of the copyright holder
        * comments: a description of the application
        * license: the license text
        * website: the website url
        * authors: a list or tuple of strings containing the contributors
        * translators: a string containing the translators
        '''
        dialog = StandardButtonDialog('About emesene')
        def reject_response():
            pass
        dialog.reject_response = reject_response
        info = (logo_path, name, version, comments, copyright, website, website)
        body = '''<center><img src= %s ><H1>%s %s</H1> <H4>%s</H4>
               %s<H6><a href="%s">%s</a></H6></center>''' % info
        body_label = QtGui.QLabel(unicode(body))
        body_label.setWordWrap(True)
        body_label.setAlignment(Qt.AlignCenter)
        def _on_link_clicked(link):
            gui.base.Desktop.open(link)

        body_label.linkActivated.connect(_on_link_clicked)
        button_box = QtGui.QDialogButtonBox()
        body_box = QtGui.QHBoxLayout()
        body_box.addWidget(body_label)
        dialog.setLayout(body_box)
        dialog.add_button(button_box.Close)
        dialog.setMinimumWidth(400)
        dialog.setMaximumWidth(400)
        dialog.setMaximumHeight(330)
        dialog.setMinimumHeight(330)
        body_label.setAlignment(Qt.AlignCenter)
        dialog.exec_()

    @classmethod
    def error(cls, message, response_cb=None, title=tr('Error!')):
        '''show an error dialog displaying the message, this dialog should
        have only the option to close and the response callback is optional
        since in few cases one want to know when the error dialog was closed,
        but it can happen, so return stock.CLOSE to the callback if its set'''
        dialog = StandardButtonDialog(title)

        def accept_response():
            pass
        dialog.accept_response = accept_response
        icon = QtGui.QLabel()
        message = QtGui.QLabel(unicode(message))
        message.setTextFormat(Qt.RichText)
        message.setWordWrap(True)
        message.setAlignment(Qt.AlignCenter)
        lay = QtGui.QHBoxLayout()
        lay.addWidget(icon)
        lay.addWidget(message)
        dialog.setLayout(lay)

        dialog.add_button(QtGui.QDialogButtonBox.Ok)
        dialog.setMinimumWidth(250)
        icon.setPixmap(QtGui.QIcon.fromTheme('dialog-error').pixmap(64, 64))
        dialog.exec_()

    @classmethod
    def information(cls, message, response_cb=None, title=tr('Information')):
        '''show an error dialog displaying the message, this dialog should
        have only the option to close and the response callback is optional
        since in few cases one want to know when the error dialog was closed,
        but it can happen, so return stock.CLOSE to the callback if its set'''
        '''show a warning dialog displaying the messge, this dialog should
        have only the option to accept, like the error dialog, the response
        callback is optional, but you have to check if it's not None and
        send the response (that can be stock.ACCEPT or stock.CLOSE, if
        the user closed the window with the x)'''
        dialog = StandardButtonDialog(title)

        def accept_response():
            pass
        dialog.accept_response = accept_response
        icon = QtGui.QLabel()
        message = QtGui.QLabel(unicode(message))
        message.setTextFormat(Qt.RichText)
        lay = QtGui.QHBoxLayout()
        lay.addWidget(icon)
        lay.addWidget(message)
        dialog.setLayout(lay)

        dialog.add_button(QtGui.QDialogButtonBox.Ok)
        dialog.setMinimumWidth(250)
        icon.setPixmap(QtGui.QIcon.fromTheme('dialog-warning').pixmap(64, 64))
        message.setWordWrap(True)
        message.setAlignment(Qt.AlignCenter)
        dialog.exec_()

    @classmethod
    def login_preferences(cls, service, ext,
                          callback, use_http, use_ipv6, proxy):
        """
        display the preferences dialog for the login window

        cls -- the dialog class
        service -- the service string identifier (for example 'gtalk')
        callback -- callback to call if the user press accept, call with the
            new values
        use_http -- boolean that indicates if the e3 should use http
            method
        use_ipv6 -- boolean that indicates if the xmpp should use ipv6
            to established connection
        proxy -- a e3.Proxy object
        """
        def on_use_auth_toggled(is_enabled, is_checked):
            '''called when the auth check button is toggled, receive a set
            of entries, enable or disable auth related widgets deppending
            on the state of the check button'''
            auth_settings = (user_lbl, user_edit, pwd_lbl, pwd_edit)
            state = (is_enabled and is_checked)
            for widget in auth_settings:
                widget.setEnabled(state)

        def on_use_proxy_toggled(is_checked, *args):
            '''Callback invoked when the 'use proxy' checkbox is toggled.
            enables or disables widgets to insert proxy settings accordingly'''
            proxy_settings = (host_lbl, proxy_host_edit, port_lbl,
                              proxy_port_edit, auth_chk)
            for widget in proxy_settings:
                widget.setEnabled(is_checked)
            on_use_auth_toggled(is_checked, auth_chk.isChecked())

        def response_cb(response):
            '''called on any response (close, accept, cancel) if accept
            get the new values and call callback with those values'''
            if response == gui.stock.ACCEPT:
                use_http = http_chk.isChecked()
                use_ipv6 = ipv6_chk.isChecked()
                use_proxy = proxy_chk.isChecked()
                use_auth = auth_chk.isChecked()
                proxy_host = str(proxy_host_edit.text())
                proxy_port = str(proxy_port_edit.text())
                server_host = str(server_host_edit.text())
                server_port = str(server_port_edit.text())
                user = str(user_edit.text())
                passwd = str(pwd_edit.text())

                proxy = e3.Proxy(use_proxy, proxy_host, proxy_port,
                                    use_auth, user, passwd)

                callback(use_http, use_ipv6, proxy, service,
                         server_host, server_port)
            dialog.hide()

        dialog = OkCancelDialog(unicode(tr('Connection preferences')))
        session_lbl = QtGui.QLabel(unicode(tr('Session:')))
        session_cmb = QtGui.QLabel(service)
        server_host_lbl = QtGui.QLabel(unicode(tr('Server')))
        server_host_edit = QtGui.QLineEdit()
        server_port_lbl = QtGui.QLabel(unicode(tr('Port')))
        server_port_edit = QtGui.QLineEdit()
        ipv6_chk = QtGui.QCheckBox(unicode(tr('Use IPv6 connecion')))
        http_chk = QtGui.QCheckBox(unicode(tr('Use HTTP method')))
        proxy_chk = QtGui.QCheckBox(unicode(tr('Use proxy')))
        host_lbl = QtGui.QLabel(unicode(tr('Host')))
        proxy_host_edit = QtGui.QLineEdit()
        port_lbl = QtGui.QLabel(unicode(tr('Port')))
        proxy_port_edit = QtGui.QLineEdit()
        auth_chk = QtGui.QCheckBox(unicode(tr('Use authentication')))
        user_lbl = QtGui.QLabel(unicode(tr('User')))
        user_edit = QtGui.QLineEdit()
        pwd_lbl = QtGui.QLabel(unicode(tr('Password')))
        pwd_edit = QtGui.QLineEdit()

        grid_lay = QtGui.QGridLayout()
        grid_lay.setHorizontalSpacing(20)
        grid_lay.setVerticalSpacing(4)
        grid_lay.addWidget(session_lbl, 0, 0)
        grid_lay.addWidget(session_cmb, 0, 2)
        grid_lay.addWidget(server_host_lbl, 1, 0)
        grid_lay.addWidget(server_host_edit, 1, 2)
        grid_lay.addWidget(server_port_lbl, 2, 0)
        grid_lay.addWidget(server_port_edit, 2, 2)
        if service == 'gtalk' or service == 'facebook':
            grid_lay.addWidget(ipv6_chk, 3, 0, 1, -1)
        grid_lay.addWidget(http_chk, 4, 0, 1, -1)

        # TODO: FIXME: Temporary hack for 2.0 release.
        # msn (papylib) automagically gets system proxies
        if service != 'msn':
            grid_lay.addWidget(proxy_chk, 5, 0, 1, -1)
            grid_lay.addWidget(host_lbl, 6, 0)
            grid_lay.addWidget(proxy_host_edit, 6, 2)
            grid_lay.addWidget(port_lbl, 7, 0)
            grid_lay.addWidget(proxy_port_edit, 7, 2)
            grid_lay.addWidget(auth_chk, 8, 0, 1, -1)
            grid_lay.addWidget(user_lbl, 9, 0)
            grid_lay.addWidget(user_edit, 9, 2)
            grid_lay.addWidget(pwd_lbl, 10, 0)
            grid_lay.addWidget(pwd_edit, 10, 2)
        dialog.setLayout(grid_lay)

        service_data = ext.SERVICES[service]

        dialog.setWindowTitle(tr('Preferences'))
        server_host_edit.setText(service_data['host'])
        server_port_edit.setText(service_data['port'])
        proxy_host_edit.setText(proxy.host or '')
        proxy_port_edit.setText(proxy.port or '')
        user_edit.setText(proxy.user or '')
        pwd_edit.setText(proxy.passwd or '')
        http_chk.setChecked(use_http)
        ipv6_chk.setChecked(use_ipv6)

        proxy_chk.toggled.connect(on_use_proxy_toggled)
        auth_chk.toggled.connect(lambda checked:
                                 on_use_auth_toggled(auth_chk.isEnabled(), checked))

        # putting these there to trigger the slots:
        proxy_chk.setChecked(not proxy.use_proxy)
        proxy_chk.setChecked(proxy.use_proxy)
        auth_chk.setChecked(not proxy.use_auth)
        auth_chk.setChecked(proxy.use_auth)

        dialog.show()

        #for widget in proxy_settings:
            #widget.hide()

        response = dialog.exec_()

        if response == QtGui.QDialog.Accepted:
            response = gui.stock.ACCEPT
        elif response == QtGui.QDialog.Rejected:
            response = gui.stock.CANCEL

        response_cb(response)

    @classmethod
    def set_contact_alias(cls, account, alias, response_cb,
                          title=tr('Set alias')):
        '''show a dialog showing the current alias and asking for the new
        one, the response callback receives,  the response
        (stock.ACCEPT, stock.CANCEL, stock.CLEAR <- to remove the alias
        or stock.CLOSE), the account, the old and the new alias.
        cb args: response, account, old_alias, new_alias'''
        def _on_reset():
            dialog.done(gui.stock.CLEAR)

        dialog = EntryDialog(label=tr('New alias:'), text=alias, title=title)
        reset_btn = dialog.add_button(QtGui.QDialogButtonBox.Reset)
        reset_btn.clicked.connect(_on_reset)

        response = dialog.exec_()
        response_cb(response, account, alias, dialog.text())

    @classmethod
    def yes_no(cls, message, response_cb, *args):
        '''show a confirm dialog displaying a question and two buttons:
        Yes and No, return the response as stock.YES or stock.NO or
        stock.CLOSE if the user closes the window'''
        dialog = YesNoDialog('')
        icon = QtGui.QLabel()
        message = QtGui.QLabel(unicode(message))

        lay = QtGui.QHBoxLayout()
        lay.addWidget(icon)
        lay.addWidget(message)
        dialog.setLayout(lay)

        icon.setPixmap(QtGui.QIcon.fromTheme('dialog-warning').pixmap(64, 64))

        response = dialog.exec_()

        response_cb(response, *args)

    @classmethod
    def contact_information_dialog(cls, session, account):
        '''shows information about the account'''
        raise NotImplementedError

    @classmethod
    def select_font(cls, style, callback):
        '''select font and if available size and style, receives a
        e3.Message.Style object with the current style
        the callback receives a new style object with the new selection
        '''
        new_qt_font, result = QtGui.QFontDialog.getFont()
        if result:
            estyle = Utils.qfont_to_style(new_qt_font, style.color)
            callback(estyle)

    @classmethod
    def select_emote(cls, session, theme, callback, max_width=16):
        '''select an emoticon, receives a gui.Theme object with the theme
        settings the callback receives the response and a string representing
        the selected emoticon
        '''
        smiley_chooser_cls = extension.get_default('smiley chooser')
        smiley_chooser = smiley_chooser_cls()
        smiley_chooser.emoticon_selected.connect(callback)
        smiley_chooser.show()

    @classmethod
    def select_color(cls, color, callback):
        '''select color, receives a e3.Message.Color with the current
        color the callback receives a new color object woth the new selection
        '''
        qt_color = Utils.e3_color_to_qcolor(color)
        new_qt_color = QtGui.QColorDialog.getColor(qt_color)
        if new_qt_color.isValid() and not new_qt_color == qt_color:
            color = Utils.qcolor_to_e3_color(new_qt_color)
            callback(color)

    @classmethod
    def close_all(cls):
        #FIXME: close the hidden dialogs
        pass

    @classmethod
    def edit_profile(cls, handler, user_nick, user_message, last_avatar):

        dialog = OkCancelDialog(unicode(tr('Change profile')))
        dialog.setWindowTitle(tr('Change profile'))

        hbox = QtGui.QHBoxLayout()
        hbox.setContentsMargins(0, 0, 0, 0)

        Avatar = extension.get_default('avatar')
        avatar = Avatar(handler.session, size=96)
        avatar.set_from_file(last_avatar)
        if handler.session.session_has_service(e3.Session.SERVICE_PROFILE_PICTURE):
            avatar.clicked.connect(lambda *args: handler.on_set_picture_selected(handler.session))
            avatar.setToolTip(tr('Click here to set your avatar'))

            def on_picture_change_succeed(self, account, path):
                '''callback called when the picture of an account is changed'''
                # our account
                if account == handler.session.account.account:
                    avatar.set_from_file(path)
            handler.session.signals.picture_change_succeed.subscribe(
                on_picture_change_succeed)

        vbox = QtGui.QVBoxLayout()
        vbox.setContentsMargins(0, 0, 0, 0)

        hbox.addWidget(avatar)
        hbox.addLayout(vbox)
        dialog.setLayout(hbox)

        nick_label = QtGui.QLabel(unicode(tr('Nick:')))

        nick = QtGui.QLineEdit()
        nick.setText(unicode(user_nick))

        pm_label = QtGui.QLabel(unicode(tr('Message:')))

        pm = QtGui.QLineEdit()
        pm.setText(unicode(user_message))

        vbox.addWidget(nick_label)
        vbox.addWidget(nick)
        vbox.addWidget(pm_label)
        vbox.addWidget(pm)

        def save_profile():
            '''save the new profile'''
            new_nick = nick.text()
            new_pm = pm.text()
            handler.save_profile(new_nick, new_pm)

        dialog.accept_response = save_profile

        dialog.show()
        dialog.exec_()
        dialog.hide()


class StandardButtonDialog (QtGui.QDialog):
    '''Skeleton for a dialog window with standard buttons'''
    def __init__(self, title, expanding=False, parent=None):
        '''Constructor'''

        QtGui.QDialog.__init__(self, parent)

        self.central_widget = QtGui.QWidget()
        self.button_box = QtGui.QDialogButtonBox()

        vlay = QtGui.QVBoxLayout()
        vlay.addWidget(self.central_widget)
        vlay.addSpacing(10)
        vlay.addWidget(self.button_box)
        if not expanding:
            vlay.addStretch()
        QtGui.QDialog.setLayout(self, vlay)

        self.setWindowTitle(title)

        self.button_box.accepted.connect(self._on_accept)
        self.button_box.rejected.connect(self._on_reject)

    def add_button(self, button):
        return self.button_box.addButton(button)

    def add_button_by_text_and_role(self, text, role):
        r = self.button_box.addButton(text, role)
        return r

    def _on_accept(self):
        '''Slot called when Ok is clicked'''
        self.done(QtGui.QDialog.Accepted)

    def _on_reject(self):
        '''Slot called when Cancel is clicked'''
        self.done(QtGui.QDialog.Rejected)

    def exec_(self):
        response = QtGui.QDialog.exec_(self)

        if response == QtGui.QDialog.Accepted:
            response = self.accept_response()
        elif response == QtGui.QDialog.Rejected:
            response = self.reject_response()

        return response

    def accept_response(self):
        raise NotImplementedError()

    def reject_response(self):
        raise NotImplementedError()

# -------------------- QT_OVERRIDE

    def setLayout(self, layout):
        '''Overrides setLayout. Sets the layout directly on
        this dialog's central widget.'''
        # pylint: disable=C0103
        self.central_widget.setLayout(layout)


class OkCancelDialog (StandardButtonDialog):
    '''Skeleton for a dialog window having Ok and Cancel buttons'''
    def __init__(self, title, expanding=False, parent=None):
        '''Constructor'''
        StandardButtonDialog.__init__(self, title, expanding, parent)

        self.add_button(QtGui.QDialogButtonBox.Cancel)
        self.add_button(QtGui.QDialogButtonBox.Ok)
        self._accept_response = gui.stock.ACCEPT
        self._reject_response = gui.stock.CANCEL

    def accept_response(self):
        return self._accept_response

    def set_accept_response(self, response):
        self._accept_response = response

    def reject_response(self):
        return self._reject_response

    def set_reject_response(self, response):
        self._reject_response = response


class YesNoDialog (StandardButtonDialog):
    '''Skeleton for a dialog window having Ok and Cancel buttons'''
    def __init__(self, title, expanding=False, parent=None):
        '''Constructor'''
        StandardButtonDialog.__init__(self, title, expanding, parent)

        self.add_button(QtGui.QDialogButtonBox.No)
        self.add_button(QtGui.QDialogButtonBox.Yes)
        self._accept_response = gui.stock.YES
        self._reject_response = gui.stock.NO

    def accept_response(self):
        return self._accept_response

    def set_accept_response(self, response):
        self._accept_response = response

    def reject_response(self):
        return self._reject_response

    def set_reject_response(self, response):
        self._reject_response = response

class ContactAdded(QtGui.QDialog):

    def __init__(self, accounts, done_cb, expanding=False, parent=None):
        '''I intialize {tab, gridLayout, add_btn, reject_btn, remind_btn, quit_btn, text_lbl, icon_lbl}
            because every index of these lists represent an account
            N.B: if someone has a better solution just share it :)'''

        self._done_cb = done_cb
        self._tabs = {}
        self._results = {'accepted': [],
                        'rejected': []}

        tab = []
        gridLayout = []
        add_btn = []
        reject_btn = []
        remind_btn = []
        quit_btn = []
        text_lbl = []
        icon_lbl = []

        text = None
        icon_info = QtGui.QIcon.fromTheme('dialog-information')
        icon_add = QtGui.QIcon.fromTheme('add')
        icon_reject = QtGui.QIcon.fromTheme('edit-delete')
        icon_remind_me = QtGui.QIcon.fromTheme('go-next')
        icon_quit = QtGui.QIcon.fromTheme('application-exit')
        icon_next = QtGui.QIcon.fromTheme('go-next')
        icon_back = QtGui.QIcon.fromTheme('go-previous')
        QtGui.QWidget.__init__(self)
        self.setWindowTitle(tr("Add contact"))
        self.center()

        hbox = QtGui.QHBoxLayout()
        hbox.addStretch(1)
        self.back_btn = QtGui.QToolButton()
        self.back_btn.setAutoRaise(True)
        self.back_btn.setIcon(icon_back)
        self.back_btn.clicked.connect(self._go_back)
        hbox.addWidget(self.back_btn)
        self.count_lbl = QtGui.QLabel()
        hbox.addWidget(self.count_lbl)
        self.next_btn = QtGui.QToolButton()
        self.next_btn.setAutoRaise(True)
        self.next_btn.setIcon(icon_next)
        self.next_btn.clicked.connect(self._go_next)
        hbox.addWidget(self.next_btn)

        self.tab_widget = QtGui.QTabWidget()
        self.tab_widget.setDocumentMode(True)
        self.tab_widget.tabBar().hide()
        for i in range(len(accounts)):
            tab.append(QtGui.QWidget())
            self._tabs[accounts[i][0]] = tab[i]
            gridLayout = QtGui.QGridLayout(tab[i])
            self.tab_widget.addTab(tab[i], accounts[i][0])
            text_lbl.append(QtGui.QLabel())
            icon_lbl.append(QtGui.QLabel())
            if accounts[i][0] != accounts[i][1]:
                text = '<b>%s</b>\n<b>(%s)</b>' % (accounts[i][0], accounts[i][1])
            else:
                text = '<b>%s</b>' % accounts[i][0]
            text += tr(' has added you.\nDo you want to add '
                       'him/her to your contact list?\n')
            text = text.replace('\n', '<br />')
            text_lbl[i].setText(text)
            icon_lbl[i].setPixmap(icon_info.pixmap(30, 30))
            add_btn.append(QtGui.QPushButton(tr("Add")))
            reject_btn.append(QtGui.QPushButton(tr("Remove")))
            remind_btn.append(QtGui.QPushButton(tr("Remind me later")))
            quit_btn.append(QtGui.QPushButton(tr("Quit")))
            add_btn[i].setIcon(icon_add)
            reject_btn[i].setIcon(icon_reject)
            remind_btn[i].setIcon(icon_remind_me)
            quit_btn[i].setIcon(icon_quit)
            QtCore.QObject.connect(add_btn[i],QtCore.SIGNAL('clicked()'),
                 lambda account=accounts[i][0]:self.add(account))
            QtCore.QObject.connect(reject_btn[i],QtCore.SIGNAL('clicked()'),
                 lambda account=accounts[i][0]:self.reject_(account))
            QtCore.QObject.connect(remind_btn[i],QtCore.SIGNAL('clicked()'), self.remove_tab)
            QtCore.QObject.connect(quit_btn[i],QtCore.SIGNAL('clicked()'), self.close)
            gridLayout.addWidget(icon_lbl[i], 3, 0)
            gridLayout.addWidget(text_lbl[i], 3, 1, 1, 3)
            gridLayout.addWidget(add_btn[i], 4, 0)
            gridLayout.addWidget(reject_btn[i], 4, 2)
            gridLayout.addWidget(remind_btn[i], 4, 3)
            gridLayout.addWidget(quit_btn[i], 4, 4)

        vbox = QtGui.QVBoxLayout()
        vbox.addStretch(1)
        vbox.addLayout(hbox)
        vbox.addWidget(self.tab_widget)
        self.setLayout(vbox)

        self.tab_widget.currentChanged.connect(self._update_label_cb)
        #refresh button before show the dialog
        self._update_label_cb(0)

    def _update_label_cb(self, index):
        text = "(%d/%d)" % (index + 1, self.tab_widget.count())
        self.count_lbl.setText(text)
        current_index = self.tab_widget.currentIndex()
        can_back = current_index != 0
        self.back_btn.setEnabled(can_back)
        can_next = not current_index == self.tab_widget.count() - 1
        self.next_btn.setEnabled(can_next)

    def _go_back(self):
        back = self.tab_widget.currentIndex() - 1
        self.tab_widget.setCurrentIndex(back)

    def _go_next(self):
        next_ = self.tab_widget.currentIndex() + 1
        self.tab_widget.setCurrentIndex(next_)

    def add(self, account):
        self._results['accepted'].append(account)
        self._finish(account)
        self.remove_tab()

    def reject_(self, account):
        self._results['rejected'].append(account)
        self._finish(account)
        self.remove_tab()

    def remove_tab(self):
        widget = self.tab_widget.currentWidget()
        if widget is not None:
            self.tab_widget.removeTab(self.tab_widget.indexOf(widget))
            widget.deleteLater()
            if self.tab_widget.count() < 1:
                self.close()

    def _finish(self, account):
        del self._tabs[account]
        if len(self._tabs) == 0:
            self._done_cb(self._results)

    def center(self):
        screen = QtGui.QDesktopWidget().screenGeometry()
        size = self.geometry()
        self.move((screen.width()-size.width())/2, (screen.height()-size.height())/2)

class EntryDialog (OkCancelDialog):
    '''Dialog window with a text entry.'''
    def __init__(self, label, text, title, expanding=True, parent=None):
        OkCancelDialog.__init__(self, title, expanding, parent)

        label = QtGui.QLabel(label)
        self.edit = QtGui.QLineEdit(unicode(text))

        lay = QtGui.QHBoxLayout()
        lay.addWidget(label, 100)
        lay.addWidget(self.edit)
        self.setLayout(lay)

    def text(self):
        return unicode(self.edit.text())


class InviteWindow(OkCancelDialog):

    def __init__(self, session, callback, l_buddy_exclude):
        """
        A window that display a list of users to select the ones to invite to
        the conversarion
        """
        OkCancelDialog.__init__(self, tr('Invite friend'))
        self.session = session
        self.callback = callback
        ContactList = extension.get_default('contact list')
        self.contact_list = ContactList(session)
        #FIXME: allow multiple selection
        self.contact_list.nick_template = \
            '[$DISPLAY_NAME][$NL][$small][$ACCOUNT][$/small]'

        order_by_group = self.contact_list.session.config.b_order_by_group
        show_blocked = self.contact_list.session.config.b_show_blocked
        show_offline = self.contact_list.session.config.b_show_offline
        self.contact_list.order_by_group = False
        self.contact_list.show_blocked = False
        self.contact_list.show_offline = False
        self.contact_list.hide_on_filtering = True

        self.search_entry = widgets.SearchEntry()
        self.search_entry.textChanged.connect(
                                    self._on_search_changed)

        vbox = QtGui.QVBoxLayout()
        vbox.addWidget(self.contact_list)
        vbox.addWidget(self.search_entry)
        self.central_widget.setLayout(vbox)

        self.show()
        response = self.exec_()
        self.contact_list.session.config.b_order_by_group = order_by_group
        self.contact_list.session.config.b_show_blocked = show_blocked
        self.contact_list.session.config.b_show_offline = show_offline
        if response == QtGui.QDialog.Accepted:
            self.on_add_clicked()
        self.contact_list.remove_subscriptions()
        self.hide()

    def _on_search_changed(self, new_text):
        """
        called when the content of the entry changes
        """
        self.contact_list.filter_text = new_text.toLower()
        if not new_text.isEmpty():
            self.contact_list.is_searching = True
            self.contact_list.expand_groups()
        else:
            self.contact_list.is_searching = False
            self.contact_list.un_expand_groups()

    def keyPressEvent(self, event):
        if event.key() in (Qt.Key_Return, Qt.Key_Enter):
            self.done(QtGui.QDialog.Accepted)
            return
        if event.key() == Qt.Key_Escape:
            self.done(QtGui.QDialog.Rejected)
            return
        QtGui.QWidget.keyPressEvent(self, event)

    def on_add_clicked(self):
        """
        method called when the add button is clicked
        """
        #FIXME: multiple contact selection
        contacts = self.contact_list.get_contact_selected()

        if contacts is None:
            Dialog.error(tr("No contact selected"))
            return

        self.callback(contacts.account)


class WebWindow(StandardButtonDialog):
    '''A class for a progressbar dialog'''

    def __init__(self, title, url, callback=None, parent=None):
        '''Constructor. Packs widgets'''
        StandardButtonDialog.__init__(self, title, False, parent)
        self.add_button(QtGui.QDialogButtonBox.Cancel)
        self._callback = callback

        bro = QtWebKit.QWebView()
        vbox = QtGui.QVBoxLayout()
        vbox.addWidget(bro)
        self.setLayout(vbox)
        bro.setMinimumWidth(250)
        bro.setMinimumHeight(250)
        bro.urlChanged.connect(self._url_changed_cb)
        qurl = QtCore.QUrl.fromEncoded(url)
        bro.load(qurl)

    def _url_changed_cb(self, qurl):
        #FIXME: this is ugly
        if qurl.host() == 'emesene.github.com':
            self._callback(unicode(qurl.toString()))

    def reject_response(self):
        pass