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