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