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