Fix error on close
[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
324                 self._credentialsDialog = None
325                 self._smsEntryDialog = None
326                 self._accountDialog = None
327
328                 self._errorLog = qui_utils.QErrorLog()
329                 self._errorDisplay = qui_utils.ErrorDisplay(self._errorLog)
330
331                 self._tabsContents = [
332                         DelayedWidget(self._app, self._TAB_SETTINGS_NAMES[i])
333                         for i in xrange(self.MAX_TABS)
334                 ]
335                 for tab in self._tabsContents:
336                         tab.disable()
337
338                 self._tabWidget = QtGui.QTabWidget()
339                 if qui_utils.screen_orientation() == QtCore.Qt.Vertical:
340                         self._tabWidget.setTabPosition(QtGui.QTabWidget.South)
341                 else:
342                         self._tabWidget.setTabPosition(QtGui.QTabWidget.West)
343                 _dataPath = None
344                 for tabIndex, (tabTitle, tabIcon) in enumerate(
345                         zip(self._TAB_TITLES, self._TAB_ICONS)
346                 ):
347                         if _dataPath is None:
348                                 for path in self._app._DATA_PATHS:
349                                         if os.path.exists(os.path.join(path, tabIcon)):
350                                                 _dataPath = path
351                                                 break
352                         if IS_MAEMO:
353                                 if _dataPath is None:
354                                         self._tabWidget.addTab(self._tabsContents[tabIndex].toplevel, tabTitle)
355                                 else:
356                                         icon = QtGui.QIcon(os.path.join(_dataPath, tabIcon))
357                                         self._tabWidget.addTab(self._tabsContents[tabIndex].toplevel, icon, "")
358                         else:
359                                 icon = QtGui.QIcon(os.path.join(_dataPath, tabIcon))
360                                 self._tabWidget.addTab(self._tabsContents[tabIndex].toplevel, icon, tabTitle)
361                 self._tabWidget.currentChanged.connect(self._on_tab_changed)
362                 self._tabWidget.setContentsMargins(0, 0, 0, 0)
363
364                 self._layout = QtGui.QVBoxLayout()
365                 self._layout.setContentsMargins(0, 0, 0, 0)
366                 self._layout.addWidget(self._errorDisplay.toplevel)
367                 self._layout.addWidget(self._tabWidget)
368
369                 centralWidget = QtGui.QWidget()
370                 centralWidget.setLayout(self._layout)
371                 centralWidget.setContentsMargins(0, 0, 0, 0)
372
373                 self._window = QtGui.QMainWindow(parent)
374                 self._window.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
375                 qui_utils.set_autorient(self._window, True)
376                 qui_utils.set_stackable(self._window, True)
377                 self._window.setWindowTitle("%s" % constants.__pretty_app_name__)
378                 self._window.setCentralWidget(centralWidget)
379
380                 self._loginTabAction = QtGui.QAction(None)
381                 self._loginTabAction.setText("Login")
382                 self._loginTabAction.triggered.connect(self._on_login_requested)
383
384                 self._importTabAction = QtGui.QAction(None)
385                 self._importTabAction.setText("Import")
386                 self._importTabAction.triggered.connect(self._on_import)
387
388                 self._accountTabAction = QtGui.QAction(None)
389                 self._accountTabAction.setText("Account")
390                 self._accountTabAction.triggered.connect(self._on_account)
391
392                 self._refreshTabAction = QtGui.QAction(None)
393                 self._refreshTabAction.setText("Refresh")
394                 self._refreshTabAction.setShortcut(QtGui.QKeySequence("CTRL+r"))
395                 self._refreshTabAction.triggered.connect(self._on_refresh)
396
397                 self._closeWindowAction = QtGui.QAction(None)
398                 self._closeWindowAction.setText("Close")
399                 self._closeWindowAction.setShortcut(QtGui.QKeySequence("CTRL+w"))
400                 self._closeWindowAction.triggered.connect(self._on_close_window)
401
402                 if IS_MAEMO:
403                         fileMenu = self._window.menuBar().addMenu("&File")
404                         fileMenu.addAction(self._loginTabAction)
405                         fileMenu.addAction(self._refreshTabAction)
406
407                         toolsMenu = self._window.menuBar().addMenu("&Tools")
408                         toolsMenu.addAction(self._accountTabAction)
409                         toolsMenu.addAction(self._importTabAction)
410
411                         self._window.addAction(self._closeWindowAction)
412                         self._window.addAction(self._app.quitAction)
413                         self._window.addAction(self._app.fullscreenAction)
414                 else:
415                         fileMenu = self._window.menuBar().addMenu("&File")
416                         fileMenu.addAction(self._loginTabAction)
417                         fileMenu.addAction(self._refreshTabAction)
418                         fileMenu.addAction(self._closeWindowAction)
419                         fileMenu.addAction(self._app.quitAction)
420
421                         viewMenu = self._window.menuBar().addMenu("&View")
422                         viewMenu.addAction(self._app.fullscreenAction)
423
424                         toolsMenu = self._window.menuBar().addMenu("&Tools")
425                         toolsMenu.addAction(self._accountTabAction)
426                         toolsMenu.addAction(self._importTabAction)
427
428                 self._window.addAction(self._app.logAction)
429
430                 self._initialize_tab(self._tabWidget.currentIndex())
431                 self.set_fullscreen(self._app.fullscreenAction.isChecked())
432
433         @property
434         def window(self):
435                 return self._window
436
437         def set_default_credentials(self, username, password):
438                 self._defaultCredentials = username, password
439
440         def get_default_credentials(self):
441                 return self._defaultCredentials
442
443         def walk_children(self):
444                 return ()
445
446         def start(self):
447                 assert self._session.state == self._session.LOGGEDOUT_STATE
448                 if self._defaultCredentials != ("", ""):
449                         username, password = self._defaultCredentials[0], self._defaultCredentials[1]
450                         self._curentCredentials = username, password
451                         self._session.login(username, password)
452                 else:
453                         self._prompt_for_login()
454
455         def close(self):
456                 for child in self.walk_children():
457                         child.window.destroyed.disconnect(self._on_child_close)
458                         child.close()
459                 self._window.close()
460
461         def destroy(self):
462                 if self._session.state != self._session.LOGGEDOUT_STATE:
463                         self._session.logout()
464
465         def get_current_tab(self):
466                 return self._tabWidget.currentIndex()
467
468         def set_current_tab(self, tabIndex):
469                 self._tabWidget.setCurrentIndex(tabIndex)
470
471         def load_settings(self, config):
472                 backendId = 2 # For backwards compatibility
473                 for tabIndex, tabTitle in enumerate(self._TAB_TITLES):
474                         sectionName = "%s - %s" % (backendId, tabTitle)
475                         settings = self._tabsContents[tabIndex].get_settings()
476                         for settingName in settings.iterkeys():
477                                 try:
478                                         settingValue = config.get(sectionName, settingName)
479                                 except ConfigParser.NoOptionError, e:
480                                         _moduleLogger.info(
481                                                 "Settings file %s is missing section %s" % (
482                                                         constants._user_settings_,
483                                                         e.section,
484                                                 ),
485                                         )
486                                         return
487                                 except ConfigParser.NoSectionError, e:
488                                         _moduleLogger.info(
489                                                 "Settings file %s is missing section %s" % (
490                                                         constants._user_settings_,
491                                                         e.section,
492                                                 ),
493                                         )
494                                         return
495                                 except Exception:
496                                         _moduleLogger.exception("Unknown loading error")
497                                         return
498                                 settings[settingName] = settingValue
499                         self._tabsContents[tabIndex].set_settings(settings)
500
501         def save_settings(self, config):
502                 backendId = 2 # For backwards compatibility
503                 for tabIndex, tabTitle in enumerate(self._TAB_TITLES):
504                         sectionName = "%s - %s" % (backendId, tabTitle)
505                         config.add_section(sectionName)
506                         tabSettings = self._tabsContents[tabIndex].get_settings()
507                         for settingName, settingValue in tabSettings.iteritems():
508                                 config.set(sectionName, settingName, settingValue)
509
510         def show(self):
511                 self._window.show()
512                 for child in self.walk_children():
513                         child.show()
514
515         def hide(self):
516                 for child in self.walk_children():
517                         child.hide()
518                 self._window.hide()
519
520         def set_fullscreen(self, isFullscreen):
521                 if isFullscreen:
522                         self._window.showFullScreen()
523                 else:
524                         self._window.showNormal()
525                 for child in self.walk_children():
526                         child.set_fullscreen(isFullscreen)
527
528         def _initialize_tab(self, index):
529                 assert index < self.MAX_TABS
530                 if not self._tabsContents[index].has_child():
531                         tab = self._TAB_CLASS[index](self._app, self._session, self._errorLog)
532                         self._tabsContents[index].set_child(tab)
533                         self._tabsContents[index].refresh(force=False)
534
535         def _prompt_for_login(self):
536                 if self._credentialsDialog is None:
537                         import dialogs
538                         self._credentialsDialog = dialogs.CredentialsDialog(self._app)
539                 username, password = self._credentialsDialog.run(
540                         self._defaultCredentials[0], self._defaultCredentials[1], self.window
541                 )
542                 self._curentCredentials = username, password
543                 self._session.login(username, password)
544
545         def _show_account_dialog(self):
546                 if self._accountDialog is None:
547                         import dialogs
548                         self._accountDialog = dialogs.AccountDialog(self._app)
549                 self._accountDialog.accountNumber = self._session.get_account_number()
550                 response = self._accountDialog.run()
551                 if response == QtGui.QDialog.Accepted:
552                         if self._accountDialog.doClear:
553                                 self._session.logout_and_clear()
554                 elif response == QtGui.QDialog.Rejected:
555                         _moduleLogger.info("Cancelled")
556                 else:
557                         _moduleLogger.info("Unknown response")
558
559         @QtCore.pyqtSlot(str)
560         @misc_utils.log_exception(_moduleLogger)
561         def _on_session_error(self, message):
562                 self._errorLog.push_message(message)
563
564         @QtCore.pyqtSlot()
565         @misc_utils.log_exception(_moduleLogger)
566         def _on_login(self):
567                 if self._defaultCredentials != self._curentCredentials:
568                         self._show_account_dialog()
569                 self._defaultCredentials = self._curentCredentials
570                 for tab in self._tabsContents:
571                         tab.enable()
572
573         @QtCore.pyqtSlot()
574         @misc_utils.log_exception(_moduleLogger)
575         def _on_logout(self):
576                 for tab in self._tabsContents:
577                         tab.disable()
578
579         @QtCore.pyqtSlot()
580         @misc_utils.log_exception(_moduleLogger)
581         def _on_recipients_changed(self):
582                 if self._session.draft.get_num_contacts() == 0:
583                         return
584
585                 if self._smsEntryDialog is None:
586                         import dialogs
587                         self._smsEntryDialog = dialogs.SMSEntryWindow(self.window, self._app, self._session, self._errorLog)
588                 pass
589
590         @QtCore.pyqtSlot()
591         @QtCore.pyqtSlot(bool)
592         @misc_utils.log_exception(_moduleLogger)
593         def _on_login_requested(self, checked = True):
594                 self._prompt_for_login()
595
596         @QtCore.pyqtSlot(int)
597         @misc_utils.log_exception(_moduleLogger)
598         def _on_tab_changed(self, index):
599                 self._initialize_tab(index)
600
601         @QtCore.pyqtSlot()
602         @QtCore.pyqtSlot(bool)
603         @misc_utils.log_exception(_moduleLogger)
604         def _on_refresh(self, checked = True):
605                 index = self._tabWidget.currentIndex()
606                 self._tabsContents[index].refresh(force=True)
607
608         @QtCore.pyqtSlot()
609         @QtCore.pyqtSlot(bool)
610         @misc_utils.log_exception(_moduleLogger)
611         def _on_import(self, checked = True):
612                 csvName = QtGui.QFileDialog.getOpenFileName(self._window, caption="Import", filter="CSV Files (*.csv)")
613                 if not csvName:
614                         return
615                 import shutil
616                 shutil.copy2(csvName, self._app.fsContactsPath)
617                 self._tabsContents[self.CONTACTS_TAB].update_addressbooks()
618
619         @QtCore.pyqtSlot()
620         @QtCore.pyqtSlot(bool)
621         @misc_utils.log_exception(_moduleLogger)
622         def _on_account(self, checked = True):
623                 self._show_account_dialog()
624
625         @QtCore.pyqtSlot()
626         @QtCore.pyqtSlot(bool)
627         @misc_utils.log_exception(_moduleLogger)
628         def _on_close_window(self, checked = True):
629                 self.close()
630
631
632 def run():
633         app = QtGui.QApplication([])
634         handle = Dialcentral(app)
635         qtpie.init_pies()
636         return app.exec_()
637
638
639 if __name__ == "__main__":
640         import sys
641
642         logFormat = '(%(relativeCreated)5d) %(levelname)-5s %(threadName)s.%(name)s.%(funcName)s: %(message)s'
643         logging.basicConfig(level=logging.DEBUG, format=logFormat)
644         try:
645                 os.makedirs(constants._data_path_)
646         except OSError, e:
647                 if e.errno != 17:
648                         raise
649
650         val = run()
651         sys.exit(val)