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