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