Removing more errors on various forms of closing
[gc-dialer] / src / dialcentral_qt.py
1 #!/usr/bin/env python
2 # -*- coding: UTF8 -*-
3
4 from __future__ import with_statement
5
6 import os
7 import base64
8 import ConfigParser
9 import functools
10 import logging
11
12 from PyQt4 import QtGui
13 from PyQt4 import QtCore
14
15 import constants
16 from util import qtpie
17 from util import qui_utils
18 from util import misc as misc_utils
19
20 import session
21
22
23 _moduleLogger = logging.getLogger(__name__)
24 IS_MAEMO = True
25
26
27 class Dialcentral(object):
28
29         _DATA_PATHS = [
30                 os.path.join(os.path.dirname(__file__), "../share"),
31                 os.path.join(os.path.dirname(__file__), "../data"),
32         ]
33
34         def __init__(self, app):
35                 self._app = app
36                 self._recent = []
37                 self._hiddenCategories = set()
38                 self._hiddenUnits = {}
39                 self._clipboard = QtGui.QApplication.clipboard()
40
41                 self._mainWindow = None
42
43                 self._fullscreenAction = QtGui.QAction(None)
44                 self._fullscreenAction.setText("Fullscreen")
45                 self._fullscreenAction.setCheckable(True)
46                 self._fullscreenAction.setShortcut(QtGui.QKeySequence("CTRL+Enter"))
47                 self._fullscreenAction.toggled.connect(self._on_toggle_fullscreen)
48
49                 self._logAction = QtGui.QAction(None)
50                 self._logAction.setText("Log")
51                 self._logAction.setShortcut(QtGui.QKeySequence("CTRL+l"))
52                 self._logAction.triggered.connect(self._on_log)
53
54                 self._quitAction = QtGui.QAction(None)
55                 self._quitAction.setText("Quit")
56                 self._quitAction.setShortcut(QtGui.QKeySequence("CTRL+q"))
57                 self._quitAction.triggered.connect(self._on_quit)
58
59                 self._app.lastWindowClosed.connect(self._on_app_quit)
60                 self._mainWindow = MainWindow(None, self)
61                 self._mainWindow.window.destroyed.connect(self._on_child_close)
62
63                 self.load_settings()
64
65                 self._mainWindow.show()
66                 self._idleDelay = QtCore.QTimer()
67                 self._idleDelay.setSingleShot(True)
68                 self._idleDelay.setInterval(0)
69                 self._idleDelay.timeout.connect(lambda: self._mainWindow.start())
70                 self._idleDelay.start()
71
72         def load_settings(self):
73                 try:
74                         config = ConfigParser.SafeConfigParser()
75                         config.read(constants._user_settings_)
76                 except IOError, e:
77                         _moduleLogger.info("No settings")
78                         return
79                 except ValueError:
80                         _moduleLogger.info("Settings were corrupt")
81                         return
82                 except ConfigParser.MissingSectionHeaderError:
83                         _moduleLogger.info("Settings were corrupt")
84                         return
85                 except Exception:
86                         _moduleLogger.exception("Unknown loading error")
87
88                 blobs = "", ""
89                 isFullscreen = False
90                 tabIndex = 0
91                 try:
92                         blobs = (
93                                 config.get(constants.__pretty_app_name__, "bin_blob_%i" % i)
94                                 for i in xrange(len(self._mainWindow.get_default_credentials()))
95                         )
96                         isFullscreen = config.getboolean(constants.__pretty_app_name__, "fullscreen")
97                         tabIndex = config.getint(constants.__pretty_app_name__, "tab")
98                 except ConfigParser.NoOptionError, e:
99                         _moduleLogger.info(
100                                 "Settings file %s is missing option %s" % (
101                                         constants._user_settings_,
102                                         e.option,
103                                 ),
104                         )
105                 except ConfigParser.NoSectionError, e:
106                         _moduleLogger.info(
107                                 "Settings file %s is missing section %s" % (
108                                         constants._user_settings_,
109                                         e.section,
110                                 ),
111                         )
112                         return
113                 except Exception:
114                         _moduleLogger.exception("Unknown loading error")
115                         return
116
117                 creds = (
118                         base64.b64decode(blob)
119                         for blob in blobs
120                 )
121                 self._mainWindow.set_default_credentials(*creds)
122                 self._fullscreenAction.setChecked(isFullscreen)
123                 self._mainWindow.set_current_tab(tabIndex)
124                 self._mainWindow.load_settings(config)
125
126         def save_settings(self):
127                 _moduleLogger.info("Saving settings")
128                 config = ConfigParser.SafeConfigParser()
129
130                 config.add_section(constants.__pretty_app_name__)
131                 config.set(constants.__pretty_app_name__, "tab", str(self._mainWindow.get_current_tab()))
132                 config.set(constants.__pretty_app_name__, "fullscreen", str(self._fullscreenAction.isChecked()))
133                 for i, value in enumerate(self._mainWindow.get_default_credentials()):
134                         blob = base64.b64encode(value)
135                         config.set(constants.__pretty_app_name__, "bin_blob_%i" % i, blob)
136
137                 self._mainWindow.save_settings(config)
138
139                 with open(constants._user_settings_, "wb") as configFile:
140                         config.write(configFile)
141
142         @property
143         def fsContactsPath(self):
144                 return os.path.join(constants._data_path_, "contacts")
145
146         @property
147         def fullscreenAction(self):
148                 return self._fullscreenAction
149
150         @property
151         def logAction(self):
152                 return self._logAction
153
154         @property
155         def quitAction(self):
156                 return self._quitAction
157
158         def _close_windows(self):
159                 if self._mainWindow is not None:
160                         self.save_settings()
161                         self._mainWindow.window.destroyed.disconnect(self._on_child_close)
162                         self._mainWindow.close()
163                         self._mainWindow = None
164
165         @QtCore.pyqtSlot()
166         @QtCore.pyqtSlot(bool)
167         @misc_utils.log_exception(_moduleLogger)
168         def _on_app_quit(self, checked = False):
169                 if self._mainWindow is not None:
170                         self.save_settings()
171                         self._mainWindow.destroy()
172
173         @QtCore.pyqtSlot(QtCore.QObject)
174         @misc_utils.log_exception(_moduleLogger)
175         def _on_child_close(self, obj = None):
176                 if self._mainWindow is not None:
177                         self.save_settings()
178                         self._mainWindow = None
179
180         @QtCore.pyqtSlot()
181         @QtCore.pyqtSlot(bool)
182         @misc_utils.log_exception(_moduleLogger)
183         def _on_toggle_fullscreen(self, checked = False):
184                 for window in self._walk_children():
185                         window.set_fullscreen(checked)
186
187         @QtCore.pyqtSlot()
188         @QtCore.pyqtSlot(bool)
189         @misc_utils.log_exception(_moduleLogger)
190         def _on_log(self, checked = False):
191                 with open(constants._user_logpath_, "r") as f:
192                         logLines = f.xreadlines()
193                         log = "".join(logLines)
194                         self._clipboard.setText(log)
195
196         @QtCore.pyqtSlot()
197         @QtCore.pyqtSlot(bool)
198         @misc_utils.log_exception(_moduleLogger)
199         def _on_quit(self, checked = False):
200                 self._close_windows()
201
202
203 class DelayedWidget(object):
204
205         def __init__(self, app, settingsNames):
206                 self._layout = QtGui.QVBoxLayout()
207                 self._layout.setContentsMargins(0, 0, 0, 0)
208                 self._widget = QtGui.QWidget()
209                 self._widget.setContentsMargins(0, 0, 0, 0)
210                 self._widget.setLayout(self._layout)
211                 self._settings = dict((name, "") for name in settingsNames)
212
213                 self._child = None
214                 self._isEnabled = True
215
216         @property
217         def toplevel(self):
218                 return self._widget
219
220         def has_child(self):
221                 return self._child is not None
222
223         def set_child(self, child):
224                 if self._child is not None:
225                         self._layout.removeWidget(self._child.toplevel)
226                 self._child = child
227                 if self._child is not None:
228                         self._layout.addWidget(self._child.toplevel)
229
230                 self._child.set_settings(self._settings)
231
232                 if self._isEnabled:
233                         self._child.enable()
234                 else:
235                         self._child.disable()
236
237         def enable(self):
238                 self._isEnabled = True
239                 if self._child is not None:
240                         self._child.enable()
241
242         def disable(self):
243                 self._isEnabled = False
244                 if self._child is not None:
245                         self._child.disable()
246
247         def clear(self):
248                 if self._child is not None:
249                         self._child.clear()
250
251         def refresh(self, force=True):
252                 if self._child is not None:
253                         self._child.refresh(force)
254
255         def get_settings(self):
256                 if self._child is not None:
257                         return self._child.get_settings()
258                 else:
259                         return self._settings
260
261         def set_settings(self, settings):
262                 if self._child is not None:
263                         self._child.set_settings(settings)
264                 else:
265                         self._settings = settings
266
267
268 def _tab_factory(tab, app, session, errorLog):
269         import gv_views
270         return gv_views.__dict__[tab](app, session, errorLog)
271
272
273 class MainWindow(object):
274
275         KEYPAD_TAB = 0
276         RECENT_TAB = 1
277         MESSAGES_TAB = 2
278         CONTACTS_TAB = 3
279         MAX_TABS = 4
280
281         _TAB_TITLES = [
282                 "Dialpad",
283                 "History",
284                 "Messages",
285                 "Contacts",
286         ]
287         assert len(_TAB_TITLES) == MAX_TABS
288
289         _TAB_ICONS = [
290                 "dialpad.png",
291                 "history.png",
292                 "messages.png",
293                 "contacts.png",
294         ]
295         assert len(_TAB_ICONS) == MAX_TABS
296
297         _TAB_CLASS = [
298                 functools.partial(_tab_factory, "Dialpad"),
299                 functools.partial(_tab_factory, "History"),
300                 functools.partial(_tab_factory, "Messages"),
301                 functools.partial(_tab_factory, "Contacts"),
302         ]
303         assert len(_TAB_CLASS) == MAX_TABS
304
305         # Hack to allow delay importing/loading of tabs
306         _TAB_SETTINGS_NAMES = [
307                 (),
308                 ("filter", ),
309                 ("status", "type"),
310                 ("selectedAddressbook", ),
311         ]
312         assert len(_TAB_SETTINGS_NAMES) == MAX_TABS
313
314         def __init__(self, parent, app):
315                 self._app = app
316                 self._session = session.Session(constants._data_path_)
317                 self._session.error.connect(self._on_session_error)
318                 self._session.loggedIn.connect(self._on_login)
319                 self._session.loggedOut.connect(self._on_logout)
320                 self._session.draft.recipientsChanged.connect(self._on_recipients_changed)
321                 self._defaultCredentials = "", ""
322                 self._curentCredentials = "", ""
323                 self._currentTab = 0
324
325                 self._credentialsDialog = None
326                 self._smsEntryDialog = None
327                 self._accountDialog = None
328
329                 self._errorLog = qui_utils.QErrorLog()
330                 self._errorDisplay = qui_utils.ErrorDisplay(self._errorLog)
331
332                 self._tabsContents = [
333                         DelayedWidget(self._app, self._TAB_SETTINGS_NAMES[i])
334                         for i in xrange(self.MAX_TABS)
335                 ]
336                 for tab in self._tabsContents:
337                         tab.disable()
338
339                 self._tabWidget = QtGui.QTabWidget()
340                 if qui_utils.screen_orientation() == QtCore.Qt.Vertical:
341                         self._tabWidget.setTabPosition(QtGui.QTabWidget.South)
342                 else:
343                         self._tabWidget.setTabPosition(QtGui.QTabWidget.West)
344                 _dataPath = None
345                 for tabIndex, (tabTitle, tabIcon) in enumerate(
346                         zip(self._TAB_TITLES, self._TAB_ICONS)
347                 ):
348                         if _dataPath is None:
349                                 for path in self._app._DATA_PATHS:
350                                         if os.path.exists(os.path.join(path, tabIcon)):
351                                                 _dataPath = path
352                                                 break
353                         if IS_MAEMO:
354                                 if _dataPath is None:
355                                         self._tabWidget.addTab(self._tabsContents[tabIndex].toplevel, tabTitle)
356                                 else:
357                                         icon = QtGui.QIcon(os.path.join(_dataPath, tabIcon))
358                                         self._tabWidget.addTab(self._tabsContents[tabIndex].toplevel, icon, "")
359                         else:
360                                 icon = QtGui.QIcon(os.path.join(_dataPath, tabIcon))
361                                 self._tabWidget.addTab(self._tabsContents[tabIndex].toplevel, icon, tabTitle)
362                 self._tabWidget.currentChanged.connect(self._on_tab_changed)
363                 self._tabWidget.setContentsMargins(0, 0, 0, 0)
364
365                 self._layout = QtGui.QVBoxLayout()
366                 self._layout.setContentsMargins(0, 0, 0, 0)
367                 self._layout.addWidget(self._errorDisplay.toplevel)
368                 self._layout.addWidget(self._tabWidget)
369
370                 centralWidget = QtGui.QWidget()
371                 centralWidget.setLayout(self._layout)
372                 centralWidget.setContentsMargins(0, 0, 0, 0)
373
374                 self._window = QtGui.QMainWindow(parent)
375                 self._window.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
376                 qui_utils.set_autorient(self._window, True)
377                 qui_utils.set_stackable(self._window, True)
378                 self._window.setWindowTitle("%s" % constants.__pretty_app_name__)
379                 self._window.setCentralWidget(centralWidget)
380
381                 self._loginTabAction = QtGui.QAction(None)
382                 self._loginTabAction.setText("Login")
383                 self._loginTabAction.triggered.connect(self._on_login_requested)
384
385                 self._importTabAction = QtGui.QAction(None)
386                 self._importTabAction.setText("Import")
387                 self._importTabAction.triggered.connect(self._on_import)
388
389                 self._accountTabAction = QtGui.QAction(None)
390                 self._accountTabAction.setText("Account")
391                 self._accountTabAction.triggered.connect(self._on_account)
392
393                 self._refreshTabAction = QtGui.QAction(None)
394                 self._refreshTabAction.setText("Refresh")
395                 self._refreshTabAction.setShortcut(QtGui.QKeySequence("CTRL+r"))
396                 self._refreshTabAction.triggered.connect(self._on_refresh)
397
398                 self._closeWindowAction = QtGui.QAction(None)
399                 self._closeWindowAction.setText("Close")
400                 self._closeWindowAction.setShortcut(QtGui.QKeySequence("CTRL+w"))
401                 self._closeWindowAction.triggered.connect(self._on_close_window)
402
403                 if IS_MAEMO:
404                         fileMenu = self._window.menuBar().addMenu("&File")
405                         fileMenu.addAction(self._loginTabAction)
406                         fileMenu.addAction(self._refreshTabAction)
407
408                         toolsMenu = self._window.menuBar().addMenu("&Tools")
409                         toolsMenu.addAction(self._accountTabAction)
410                         toolsMenu.addAction(self._importTabAction)
411
412                         self._window.addAction(self._closeWindowAction)
413                         self._window.addAction(self._app.quitAction)
414                         self._window.addAction(self._app.fullscreenAction)
415                 else:
416                         fileMenu = self._window.menuBar().addMenu("&File")
417                         fileMenu.addAction(self._loginTabAction)
418                         fileMenu.addAction(self._refreshTabAction)
419                         fileMenu.addAction(self._closeWindowAction)
420                         fileMenu.addAction(self._app.quitAction)
421
422                         viewMenu = self._window.menuBar().addMenu("&View")
423                         viewMenu.addAction(self._app.fullscreenAction)
424
425                         toolsMenu = self._window.menuBar().addMenu("&Tools")
426                         toolsMenu.addAction(self._accountTabAction)
427                         toolsMenu.addAction(self._importTabAction)
428
429                 self._window.addAction(self._app.logAction)
430
431                 self._initialize_tab(self._tabWidget.currentIndex())
432                 self.set_fullscreen(self._app.fullscreenAction.isChecked())
433
434         @property
435         def window(self):
436                 return self._window
437
438         def set_default_credentials(self, username, password):
439                 self._defaultCredentials = username, password
440
441         def get_default_credentials(self):
442                 return self._defaultCredentials
443
444         def walk_children(self):
445                 return ()
446
447         def start(self):
448                 assert self._session.state == self._session.LOGGEDOUT_STATE
449                 if self._defaultCredentials != ("", ""):
450                         username, password = self._defaultCredentials[0], self._defaultCredentials[1]
451                         self._curentCredentials = username, password
452                         self._session.login(username, password)
453                 else:
454                         self._prompt_for_login()
455
456         def close(self):
457                 for child in self.walk_children():
458                         child.window.destroyed.disconnect(self._on_child_close)
459                         child.close()
460                 self._window.close()
461
462         def destroy(self):
463                 if self._session.state != self._session.LOGGEDOUT_STATE:
464                         self._session.logout()
465
466         def get_current_tab(self):
467                 return self._currentTab
468
469         def set_current_tab(self, tabIndex):
470                 self._tabWidget.setCurrentIndex(tabIndex)
471
472         def load_settings(self, config):
473                 backendId = 2 # For backwards compatibility
474                 for tabIndex, tabTitle in enumerate(self._TAB_TITLES):
475                         sectionName = "%s - %s" % (backendId, tabTitle)
476                         settings = self._tabsContents[tabIndex].get_settings()
477                         for settingName in settings.iterkeys():
478                                 try:
479                                         settingValue = config.get(sectionName, settingName)
480                                 except ConfigParser.NoOptionError, e:
481                                         _moduleLogger.info(
482                                                 "Settings file %s is missing section %s" % (
483                                                         constants._user_settings_,
484                                                         e.section,
485                                                 ),
486                                         )
487                                         return
488                                 except ConfigParser.NoSectionError, e:
489                                         _moduleLogger.info(
490                                                 "Settings file %s is missing section %s" % (
491                                                         constants._user_settings_,
492                                                         e.section,
493                                                 ),
494                                         )
495                                         return
496                                 except Exception:
497                                         _moduleLogger.exception("Unknown loading error")
498                                         return
499                                 settings[settingName] = settingValue
500                         self._tabsContents[tabIndex].set_settings(settings)
501
502         def save_settings(self, config):
503                 backendId = 2 # For backwards compatibility
504                 for tabIndex, tabTitle in enumerate(self._TAB_TITLES):
505                         sectionName = "%s - %s" % (backendId, tabTitle)
506                         config.add_section(sectionName)
507                         tabSettings = self._tabsContents[tabIndex].get_settings()
508                         for settingName, settingValue in tabSettings.iteritems():
509                                 config.set(sectionName, settingName, settingValue)
510
511         def show(self):
512                 self._window.show()
513                 for child in self.walk_children():
514                         child.show()
515
516         def hide(self):
517                 for child in self.walk_children():
518                         child.hide()
519                 self._window.hide()
520
521         def set_fullscreen(self, isFullscreen):
522                 if isFullscreen:
523                         self._window.showFullScreen()
524                 else:
525                         self._window.showNormal()
526                 for child in self.walk_children():
527                         child.set_fullscreen(isFullscreen)
528
529         def _initialize_tab(self, index):
530                 assert index < self.MAX_TABS
531                 if not self._tabsContents[index].has_child():
532                         tab = self._TAB_CLASS[index](self._app, self._session, self._errorLog)
533                         self._tabsContents[index].set_child(tab)
534                         self._tabsContents[index].refresh(force=False)
535
536         def _prompt_for_login(self):
537                 if self._credentialsDialog is None:
538                         import dialogs
539                         self._credentialsDialog = dialogs.CredentialsDialog(self._app)
540                 username, password = self._credentialsDialog.run(
541                         self._defaultCredentials[0], self._defaultCredentials[1], self.window
542                 )
543                 self._curentCredentials = username, password
544                 self._session.login(username, password)
545
546         def _show_account_dialog(self):
547                 if self._accountDialog is None:
548                         import dialogs
549                         self._accountDialog = dialogs.AccountDialog(self._app)
550                 self._accountDialog.accountNumber = self._session.get_account_number()
551                 response = self._accountDialog.run()
552                 if response == QtGui.QDialog.Accepted:
553                         if self._accountDialog.doClear:
554                                 self._session.logout_and_clear()
555                 elif response == QtGui.QDialog.Rejected:
556                         _moduleLogger.info("Cancelled")
557                 else:
558                         _moduleLogger.info("Unknown response")
559
560         @QtCore.pyqtSlot(str)
561         @misc_utils.log_exception(_moduleLogger)
562         def _on_session_error(self, message):
563                 self._errorLog.push_message(message)
564
565         @QtCore.pyqtSlot()
566         @misc_utils.log_exception(_moduleLogger)
567         def _on_login(self):
568                 if self._defaultCredentials != self._curentCredentials:
569                         self._show_account_dialog()
570                 self._defaultCredentials = self._curentCredentials
571                 for tab in self._tabsContents:
572                         tab.enable()
573
574         @QtCore.pyqtSlot()
575         @misc_utils.log_exception(_moduleLogger)
576         def _on_logout(self):
577                 for tab in self._tabsContents:
578                         tab.disable()
579
580         @QtCore.pyqtSlot()
581         @misc_utils.log_exception(_moduleLogger)
582         def _on_recipients_changed(self):
583                 if self._session.draft.get_num_contacts() == 0:
584                         return
585
586                 if self._smsEntryDialog is None:
587                         import dialogs
588                         self._smsEntryDialog = dialogs.SMSEntryWindow(self.window, self._app, self._session, self._errorLog)
589                 pass
590
591         @QtCore.pyqtSlot()
592         @QtCore.pyqtSlot(bool)
593         @misc_utils.log_exception(_moduleLogger)
594         def _on_login_requested(self, checked = True):
595                 self._prompt_for_login()
596
597         @QtCore.pyqtSlot(int)
598         @misc_utils.log_exception(_moduleLogger)
599         def _on_tab_changed(self, index):
600                 self._currentTab = index
601                 self._initialize_tab(index)
602
603         @QtCore.pyqtSlot()
604         @QtCore.pyqtSlot(bool)
605         @misc_utils.log_exception(_moduleLogger)
606         def _on_refresh(self, checked = True):
607                 self._tabsContents[self._currentTab].refresh(force=True)
608
609         @QtCore.pyqtSlot()
610         @QtCore.pyqtSlot(bool)
611         @misc_utils.log_exception(_moduleLogger)
612         def _on_import(self, checked = True):
613                 csvName = QtGui.QFileDialog.getOpenFileName(self._window, caption="Import", filter="CSV Files (*.csv)")
614                 if not csvName:
615                         return
616                 import shutil
617                 shutil.copy2(csvName, self._app.fsContactsPath)
618                 self._tabsContents[self.CONTACTS_TAB].update_addressbooks()
619
620         @QtCore.pyqtSlot()
621         @QtCore.pyqtSlot(bool)
622         @misc_utils.log_exception(_moduleLogger)
623         def _on_account(self, checked = True):
624                 self._show_account_dialog()
625
626         @QtCore.pyqtSlot()
627         @QtCore.pyqtSlot(bool)
628         @misc_utils.log_exception(_moduleLogger)
629         def _on_close_window(self, checked = True):
630                 self.close()
631
632
633 def run():
634         app = QtGui.QApplication([])
635         handle = Dialcentral(app)
636         qtpie.init_pies()
637         return app.exec_()
638
639
640 if __name__ == "__main__":
641         import sys
642
643         logFormat = '(%(relativeCreated)5d) %(levelname)-5s %(threadName)s.%(name)s.%(funcName)s: %(message)s'
644         logging.basicConfig(level=logging.DEBUG, format=logFormat)
645         try:
646                 os.makedirs(constants._data_path_)
647         except OSError, e:
648                 if e.errno != 17:
649                         raise
650
651         val = run()
652         sys.exit(val)