1377bd2f6031fc5c288c197c7e4abc4e3415fcd3
[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 import logging.handlers
12
13 from PyQt4 import QtGui
14 from PyQt4 import QtCore
15
16 import constants
17 import alarm_handler
18 from util import qtpie
19 from util import qwrappers
20 from util import qui_utils
21 from util import misc as misc_utils
22
23 import session
24
25
26 _moduleLogger = logging.getLogger(__name__)
27
28
29 class Dialcentral(qwrappers.ApplicationWrapper):
30
31         _DATA_PATHS = [
32                 os.path.join(os.path.dirname(__file__), "../share"),
33                 os.path.join(os.path.dirname(__file__), "../data"),
34         ]
35
36         def __init__(self, app):
37                 self._dataPath = None
38                 self._aboutDialog = None
39                 self.notifyOnMissed = False
40                 self.notifyOnVoicemail = False
41                 self.notifyOnSms = False
42
43                 self._streamHandler = None
44                 self._ledHandler = None
45                 self._alarmHandler = alarm_handler.AlarmHandler()
46
47                 qwrappers.ApplicationWrapper.__init__(self, app, constants)
48
49         def load_settings(self):
50                 try:
51                         config = ConfigParser.SafeConfigParser()
52                         config.read(constants._user_settings_)
53                 except IOError, e:
54                         _moduleLogger.info("No settings")
55                         return
56                 except ValueError:
57                         _moduleLogger.info("Settings were corrupt")
58                         return
59                 except ConfigParser.MissingSectionHeaderError:
60                         _moduleLogger.info("Settings were corrupt")
61                         return
62                 except Exception:
63                         _moduleLogger.exception("Unknown loading error")
64
65                 self._mainWindow.load_settings(config)
66
67         def save_settings(self):
68                 _moduleLogger.info("Saving settings")
69                 config = ConfigParser.SafeConfigParser()
70
71                 self._mainWindow.save_settings(config)
72
73                 with open(constants._user_settings_, "wb") as configFile:
74                         config.write(configFile)
75
76         def get_icon(self, name):
77                 if self._dataPath is None:
78                         for path in self._DATA_PATHS:
79                                 if os.path.exists(os.path.join(path, name)):
80                                         self._dataPath = path
81                                         break
82                 if self._dataPath is not None:
83                         icon = QtGui.QIcon(os.path.join(self._dataPath, name))
84                         return icon
85                 else:
86                         return None
87
88         def get_resource(self, name):
89                 if self._dataPath is None:
90                         for path in self._DATA_PATHS:
91                                 if os.path.exists(os.path.join(path, name)):
92                                         self._dataPath = path
93                                         break
94                 if self._dataPath is not None:
95                         return os.path.join(self._dataPath, name)
96                 else:
97                         return None
98
99         def _close_windows(self):
100                 qwrappers.ApplicationWrapper._close_windows(self)
101                 if self._aboutDialog  is not None:
102                         self._aboutDialog.close()
103
104         @property
105         def fsContactsPath(self):
106                 return os.path.join(constants._data_path_, "contacts")
107
108         @property
109         def streamHandler(self):
110                 if self._streamHandler is None:
111                         import stream_handler
112                         self._streamHandler = stream_handler.StreamHandler()
113                 return self._streamHandler
114
115         @property
116         def alarmHandler(self):
117                 return self._alarmHandler
118
119         @property
120         def ledHandler(self):
121                 if self._ledHandler is None:
122                         import led_handler
123                         self._ledHandler = led_handler.LedHandler()
124                 return self._ledHandler
125
126         def _new_main_window(self):
127                 return MainWindow(None, self)
128
129         @QtCore.pyqtSlot()
130         @QtCore.pyqtSlot(bool)
131         @misc_utils.log_exception(_moduleLogger)
132         def _on_about(self, checked = True):
133                 with qui_utils.notify_error(self._errorLog):
134                         if self._aboutDialog is None:
135                                 import dialogs
136                                 self._aboutDialog = dialogs.AboutDialog(self)
137                         response = self._aboutDialog.run(self._mainWindow.window)
138
139
140 class DelayedWidget(object):
141
142         def __init__(self, app, settingsNames):
143                 self._layout = QtGui.QVBoxLayout()
144                 self._layout.setContentsMargins(0, 0, 0, 0)
145                 self._widget = QtGui.QWidget()
146                 self._widget.setContentsMargins(0, 0, 0, 0)
147                 self._widget.setLayout(self._layout)
148                 self._settings = dict((name, "") for name in settingsNames)
149
150                 self._child = None
151                 self._isEnabled = True
152
153         @property
154         def toplevel(self):
155                 return self._widget
156
157         def has_child(self):
158                 return self._child is not None
159
160         def set_child(self, child):
161                 if self._child is not None:
162                         self._layout.removeWidget(self._child.toplevel)
163                 self._child = child
164                 if self._child is not None:
165                         self._layout.addWidget(self._child.toplevel)
166
167                 self._child.set_settings(self._settings)
168
169                 if self._isEnabled:
170                         self._child.enable()
171                 else:
172                         self._child.disable()
173
174         @property
175         def child(self):
176                 return self._child
177
178         def enable(self):
179                 self._isEnabled = True
180                 if self._child is not None:
181                         self._child.enable()
182
183         def disable(self):
184                 self._isEnabled = False
185                 if self._child is not None:
186                         self._child.disable()
187
188         def clear(self):
189                 if self._child is not None:
190                         self._child.clear()
191
192         def refresh(self, force=True):
193                 if self._child is not None:
194                         self._child.refresh(force)
195
196         def get_settings(self):
197                 if self._child is not None:
198                         return self._child.get_settings()
199                 else:
200                         return self._settings
201
202         def set_settings(self, settings):
203                 if self._child is not None:
204                         self._child.set_settings(settings)
205                 else:
206                         self._settings = settings
207
208
209 def _tab_factory(tab, app, session, errorLog):
210         import gv_views
211         return gv_views.__dict__[tab](app, session, errorLog)
212
213
214 class MainWindow(qwrappers.WindowWrapper):
215
216         KEYPAD_TAB = 0
217         RECENT_TAB = 1
218         MESSAGES_TAB = 2
219         CONTACTS_TAB = 3
220         MAX_TABS = 4
221
222         _TAB_TITLES = [
223                 "Dialpad",
224                 "History",
225                 "Messages",
226                 "Contacts",
227         ]
228         assert len(_TAB_TITLES) == MAX_TABS
229
230         _TAB_ICONS = [
231                 "dialpad.png",
232                 "history.png",
233                 "messages.png",
234                 "contacts.png",
235         ]
236         assert len(_TAB_ICONS) == MAX_TABS
237
238         _TAB_CLASS = [
239                 functools.partial(_tab_factory, "Dialpad"),
240                 functools.partial(_tab_factory, "History"),
241                 functools.partial(_tab_factory, "Messages"),
242                 functools.partial(_tab_factory, "Contacts"),
243         ]
244         assert len(_TAB_CLASS) == MAX_TABS
245
246         # Hack to allow delay importing/loading of tabs
247         _TAB_SETTINGS_NAMES = [
248                 (),
249                 ("filter", ),
250                 ("status", "type"),
251                 ("selectedAddressbook", ),
252         ]
253         assert len(_TAB_SETTINGS_NAMES) == MAX_TABS
254
255         def __init__(self, parent, app):
256                 qwrappers.WindowWrapper.__init__(self, parent, app)
257                 self._window.setWindowTitle("%s" % constants.__pretty_app_name__)
258                 self._errorLog = self._app.errorLog
259
260                 self._session = session.Session(self._errorLog, constants._data_path_)
261                 self._session.error.connect(self._on_session_error)
262                 self._session.loggedIn.connect(self._on_login)
263                 self._session.loggedOut.connect(self._on_logout)
264                 self._session.draft.recipientsChanged.connect(self._on_recipients_changed)
265                 self._session.newMessages.connect(self._on_new_message_alert)
266                 self._app.alarmHandler.applicationNotifySignal.connect(self._on_app_alert)
267                 self._voicemailRefreshDelay = QtCore.QTimer()
268                 self._voicemailRefreshDelay.setInterval(30 * 1000)
269                 self._voicemailRefreshDelay.timeout.connect(self._on_call_missed)
270                 self._voicemailRefreshDelay.setSingleShot(True)
271                 self._callHandler = None
272                 self._updateVoicemailOnMissedCall = False
273
274                 self._defaultCredentials = "", ""
275                 self._curentCredentials = "", ""
276                 self._currentTab = 0
277
278                 self._credentialsDialog = None
279                 self._smsEntryDialog = None
280                 self._accountDialog = None
281
282                 self._tabsContents = [
283                         DelayedWidget(self._app, self._TAB_SETTINGS_NAMES[i])
284                         for i in xrange(self.MAX_TABS)
285                 ]
286                 for tab in self._tabsContents:
287                         tab.disable()
288
289                 self._tabWidget = QtGui.QTabWidget()
290                 if qui_utils.screen_orientation() == QtCore.Qt.Vertical:
291                         self._tabWidget.setTabPosition(QtGui.QTabWidget.South)
292                 else:
293                         self._tabWidget.setTabPosition(QtGui.QTabWidget.West)
294                 defaultTabIconSize = self._tabWidget.iconSize()
295                 defaultTabIconWidth, defaultTabIconHeight = defaultTabIconSize.width(), defaultTabIconSize.height()
296                 for tabIndex, (tabTitle, tabIcon) in enumerate(
297                         zip(self._TAB_TITLES, self._TAB_ICONS)
298                 ):
299                         icon = self._app.get_icon(tabIcon)
300                         if constants.IS_MAEMO and icon is not None:
301                                 tabTitle = ""
302
303                         if icon is None:
304                                 self._tabWidget.addTab(self._tabsContents[tabIndex].toplevel, tabTitle)
305                         else:
306                                 iconSize = icon.availableSizes()[0]
307                                 defaultTabIconWidth = max(defaultTabIconWidth, iconSize.width())
308                                 defaultTabIconHeight = max(defaultTabIconHeight, iconSize.height())
309                                 self._tabWidget.addTab(self._tabsContents[tabIndex].toplevel, icon, tabTitle)
310                 defaultTabIconWidth = max(defaultTabIconWidth, 32)
311                 defaultTabIconHeight = max(defaultTabIconHeight, 32)
312                 self._tabWidget.setIconSize(QtCore.QSize(defaultTabIconWidth, defaultTabIconHeight))
313                 self._tabWidget.currentChanged.connect(self._on_tab_changed)
314                 self._tabWidget.setContentsMargins(0, 0, 0, 0)
315
316                 self._layout.addWidget(self._tabWidget)
317
318                 self._loginAction = QtGui.QAction(None)
319                 self._loginAction.setText("Login")
320                 self._loginAction.triggered.connect(self._on_login_requested)
321
322                 self._importAction = QtGui.QAction(None)
323                 self._importAction.setText("Import")
324                 self._importAction.triggered.connect(self._on_import)
325
326                 self._accountAction = QtGui.QAction(None)
327                 self._accountAction.setText("Account")
328                 self._accountAction.triggered.connect(self._on_account)
329
330                 self._refreshConnectionAction = QtGui.QAction(None)
331                 self._refreshConnectionAction.setText("Refresh Connection")
332                 self._refreshConnectionAction.setShortcut(QtGui.QKeySequence("CTRL+a"))
333                 self._refreshConnectionAction.triggered.connect(self._on_refresh_connection)
334
335                 self._refreshTabAction = QtGui.QAction(None)
336                 self._refreshTabAction.setText("Refresh Tab")
337                 self._refreshTabAction.setShortcut(QtGui.QKeySequence("CTRL+r"))
338                 self._refreshTabAction.triggered.connect(self._on_refresh)
339
340                 fileMenu = self._window.menuBar().addMenu("&File")
341                 fileMenu.addAction(self._loginAction)
342                 fileMenu.addAction(self._refreshTabAction)
343                 fileMenu.addAction(self._refreshConnectionAction)
344
345                 toolsMenu = self._window.menuBar().addMenu("&Tools")
346                 toolsMenu.addAction(self._accountAction)
347                 toolsMenu.addAction(self._importAction)
348                 toolsMenu.addAction(self._app.aboutAction)
349
350                 self._initialize_tab(self._tabWidget.currentIndex())
351                 self.set_fullscreen(self._app.fullscreenAction.isChecked())
352                 self.set_orientation(self._app.orientationAction.isChecked())
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                 if self._smsEntryDialog is not None:
362                         return (self._smsEntryDialog, )
363                 else:
364                         return ()
365
366         def start(self):
367                 qwrappers.WindowWrapper.start(self)
368                 assert self._session.state == self._session.LOGGEDOUT_STATE, "Initialization messed up"
369                 if self._defaultCredentials != ("", ""):
370                         username, password = self._defaultCredentials[0], self._defaultCredentials[1]
371                         self._curentCredentials = username, password
372                         self._session.login(username, password)
373                 else:
374                         self._prompt_for_login()
375
376         def close(self):
377                 for diag in (
378                         self._credentialsDialog,
379                         self._accountDialog,
380                 ):
381                         if diag is not None:
382                                 diag.close()
383                 for child in self.walk_children():
384                         child.window.destroyed.disconnect(self._on_child_close)
385                         child.window.closed.disconnect(self._on_child_close)
386                         child.close()
387                 self._window.close()
388
389         def destroy(self):
390                 qwrappers.WindowWrapper.destroy(self)
391                 if self._session.state != self._session.LOGGEDOUT_STATE:
392                         self._session.logout()
393
394         def get_current_tab(self):
395                 return self._currentTab
396
397         def set_current_tab(self, tabIndex):
398                 self._tabWidget.setCurrentIndex(tabIndex)
399
400         def load_settings(self, config):
401                 blobs = "", ""
402                 isFullscreen = False
403                 isPortrait = qui_utils.screen_orientation() == QtCore.Qt.Vertical
404                 tabIndex = 0
405                 try:
406                         blobs = [
407                                 config.get(constants.__pretty_app_name__, "bin_blob_%i" % i)
408                                 for i in xrange(len(self.get_default_credentials()))
409                         ]
410                         isFullscreen = config.getboolean(constants.__pretty_app_name__, "fullscreen")
411                         tabIndex = config.getint(constants.__pretty_app_name__, "tab")
412                         isPortrait = config.getboolean(constants.__pretty_app_name__, "portrait")
413                 except ConfigParser.NoOptionError, e:
414                         _moduleLogger.info(
415                                 "Settings file %s is missing option %s" % (
416                                         constants._user_settings_,
417                                         e.option,
418                                 ),
419                         )
420                 except ConfigParser.NoSectionError, e:
421                         _moduleLogger.info(
422                                 "Settings file %s is missing section %s" % (
423                                         constants._user_settings_,
424                                         e.section,
425                                 ),
426                         )
427                 except Exception:
428                         _moduleLogger.exception("Unknown loading error")
429
430                 try:
431                         self._app.alarmHandler.load_settings(config, "alarm")
432                         self._app.notifyOnMissed = config.getboolean("2 - Account Info", "notifyOnMissed")
433                         self._app.notifyOnVoicemail = config.getboolean("2 - Account Info", "notifyOnVoicemail")
434                         self._app.notifyOnSms = config.getboolean("2 - Account Info", "notifyOnSms")
435                         self._updateVoicemailOnMissedCall = config.getboolean("2 - Account Info", "updateVoicemailOnMissedCall")
436                 except ConfigParser.NoOptionError, e:
437                         _moduleLogger.info(
438                                 "Settings file %s is missing option %s" % (
439                                         constants._user_settings_,
440                                         e.option,
441                                 ),
442                         )
443                 except ConfigParser.NoSectionError, e:
444                         _moduleLogger.info(
445                                 "Settings file %s is missing section %s" % (
446                                         constants._user_settings_,
447                                         e.section,
448                                 ),
449                         )
450                 except Exception:
451                         _moduleLogger.exception("Unknown loading error")
452
453                 creds = (
454                         base64.b64decode(blob)
455                         for blob in blobs
456                 )
457                 self.set_default_credentials(*creds)
458                 self._app.fullscreenAction.setChecked(isFullscreen)
459                 self._app.orientationAction.setChecked(isPortrait)
460                 self.set_current_tab(tabIndex)
461
462                 backendId = 2 # For backwards compatibility
463                 for tabIndex, tabTitle in enumerate(self._TAB_TITLES):
464                         sectionName = "%s - %s" % (backendId, tabTitle)
465                         settings = self._tabsContents[tabIndex].get_settings()
466                         for settingName in settings.iterkeys():
467                                 try:
468                                         settingValue = config.get(sectionName, settingName)
469                                 except ConfigParser.NoOptionError, e:
470                                         _moduleLogger.info(
471                                                 "Settings file %s is missing section %s" % (
472                                                         constants._user_settings_,
473                                                         e.section,
474                                                 ),
475                                         )
476                                         return
477                                 except ConfigParser.NoSectionError, e:
478                                         _moduleLogger.info(
479                                                 "Settings file %s is missing section %s" % (
480                                                         constants._user_settings_,
481                                                         e.section,
482                                                 ),
483                                         )
484                                         return
485                                 except Exception:
486                                         _moduleLogger.exception("Unknown loading error")
487                                         return
488                                 settings[settingName] = settingValue
489                         self._tabsContents[tabIndex].set_settings(settings)
490
491         def save_settings(self, config):
492                 config.add_section(constants.__pretty_app_name__)
493                 config.set(constants.__pretty_app_name__, "tab", str(self.get_current_tab()))
494                 config.set(constants.__pretty_app_name__, "fullscreen", str(self._app.fullscreenAction.isChecked()))
495                 config.set(constants.__pretty_app_name__, "portrait", str(self._app.orientationAction.isChecked()))
496                 for i, value in enumerate(self.get_default_credentials()):
497                         blob = base64.b64encode(value)
498                         config.set(constants.__pretty_app_name__, "bin_blob_%i" % i, blob)
499
500                 config.add_section("alarm")
501                 self._app.alarmHandler.save_settings(config, "alarm")
502                 config.add_section("2 - Account Info")
503                 config.set("2 - Account Info", "notifyOnMissed", repr(self._app.notifyOnMissed))
504                 config.set("2 - Account Info", "notifyOnVoicemail", repr(self._app.notifyOnVoicemail))
505                 config.set("2 - Account Info", "notifyOnSms", repr(self._app.notifyOnSms))
506                 config.set("2 - Account Info", "updateVoicemailOnMissedCall", repr(self._updateVoicemailOnMissedCall))
507
508                 backendId = 2 # For backwards compatibility
509                 for tabIndex, tabTitle in enumerate(self._TAB_TITLES):
510                         sectionName = "%s - %s" % (backendId, tabTitle)
511                         config.add_section(sectionName)
512                         tabSettings = self._tabsContents[tabIndex].get_settings()
513                         for settingName, settingValue in tabSettings.iteritems():
514                                 config.set(sectionName, settingName, settingValue)
515
516         def set_orientation(self, isPortrait):
517                 qwrappers.WindowWrapper.set_orientation(self, isPortrait)
518                 if isPortrait:
519                         self._tabWidget.setTabPosition(QtGui.QTabWidget.South)
520                 else:
521                         self._tabWidget.setTabPosition(QtGui.QTabWidget.West)
522
523         def _initialize_tab(self, index):
524                 assert index < self.MAX_TABS, "Invalid tab"
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                 credentials = self._credentialsDialog.run(
535                         self._defaultCredentials[0], self._defaultCredentials[1], self.window
536                 )
537                 if credentials is None:
538                         return
539                 username, password = credentials
540                 self._curentCredentials = username, password
541                 self._session.login(username, password)
542
543         def _show_account_dialog(self):
544                 if self._accountDialog is None:
545                         import dialogs
546                         self._accountDialog = dialogs.AccountDialog(self._app)
547                         self._accountDialog.setIfNotificationsSupported(self._app.alarmHandler.backgroundNotificationsSupported)
548
549                 if self._callHandler is None or not self._callHandler.isSupported:
550                         self._accountDialog.updateVMOnMissedCall = self._accountDialog.VOICEMAIL_CHECK_NOT_SUPPORTED
551                 elif self._updateVoicemailOnMissedCall:
552                         self._accountDialog.updateVMOnMissedCall = self._accountDialog.VOICEMAIL_CHECK_ENABLED
553                 else:
554                         self._accountDialog.updateVMOnMissedCall = self._accountDialog.VOICEMAIL_CHECK_DISABLED
555                 self._accountDialog.notifications = self._app.alarmHandler.alarmType
556                 self._accountDialog.notificationTime = self._app.alarmHandler.recurrence
557                 self._accountDialog.notifyOnMissed = self._app.notifyOnMissed
558                 self._accountDialog.notifyOnVoicemail = self._app.notifyOnVoicemail
559                 self._accountDialog.notifyOnSms = self._app.notifyOnSms
560                 self._accountDialog.set_callbacks(
561                         self._session.get_callback_numbers(), self._session.get_callback_number()
562                 )
563                 accountNumberToDisplay = self._session.get_account_number()
564                 if not accountNumberToDisplay:
565                         accountNumberToDisplay = "Not Available (%s)" % self._session.state
566                 self._accountDialog.set_account_number(accountNumberToDisplay)
567                 response = self._accountDialog.run(self.window)
568                 if response == QtGui.QDialog.Accepted:
569                         if self._accountDialog.doClear:
570                                 self._session.logout_and_clear()
571                                 self._defaultCredentials = "", ""
572                                 self._curentCredentials = "", ""
573                                 for tab in self._tabsContents:
574                                         tab.disable()
575                         else:
576                                 callbackNumber = self._accountDialog.selectedCallback
577                                 self._session.set_callback_number(callbackNumber)
578
579                         if self._callHandler is None or self._accountDialog.updateVMOnMissedCall == self._accountDialog.VOICEMAIL_CHECK_DISABLEDD:
580                                 pass
581                         elif self._accountDialog.updateVMOnMissedCall == self._accountDialog.VOICEMAIL_CHECK_ENABLED:
582                                 self._updateVoicemailOnMissedCall = True
583                                 self._callHandler.start()
584                         else:
585                                 self._updateVoicemailOnMissedCall = False
586                                 self._callHandler.stop()
587                         if (
588                                 self._accountDialog.notifyOnMissed or
589                                 self._accountDialog.notifyOnVoicemail or
590                                 self._accountDialog.notifyOnSms
591                         ):
592                                 notifications = self._accountDialog.notifications
593                         else:
594                                 notifications = self._accountDialog.ALARM_NONE
595                         self._app.alarmHandler.apply_settings(notifications, self._accountDialog.notificationTime)
596
597                         self._app.notifyOnMissed = self._accountDialog.notifyOnMissed
598                         self._app.notifyOnVoicemail = self._accountDialog.notifyOnVoicemail
599                         self._app.notifyOnSms = self._accountDialog.notifyOnSms
600                         self._app.save_settings()
601                 elif response == QtGui.QDialog.Rejected:
602                         _moduleLogger.info("Cancelled")
603                 else:
604                         _moduleLogger.info("Unknown response")
605
606         @QtCore.pyqtSlot()
607         @misc_utils.log_exception(_moduleLogger)
608         def _on_new_message_alert(self):
609                 with qui_utils.notify_error(self._errorLog):
610                         if self._app.alarmHandler.alarmType == self._app.alarmHandler.ALARM_APPLICATION:
611                                 if self._currentTab == self.MESSAGES_TAB or not self._app.ledHandler.isReal:
612                                         self._errorLog.push_message("New messages available")
613                                 else:
614                                         self._app.ledHandler.on()
615
616         @QtCore.pyqtSlot()
617         @misc_utils.log_exception(_moduleLogger)
618         def _on_call_missed(self):
619                 with qui_utils.notify_error(self._errorLog):
620                         self._session.update_messages(self._session.MESSAGE_VOICEMAILS, force=True)
621
622         @QtCore.pyqtSlot(str)
623         @misc_utils.log_exception(_moduleLogger)
624         def _on_session_error(self, message):
625                 with qui_utils.notify_error(self._errorLog):
626                         self._errorLog.push_error(message)
627
628         @QtCore.pyqtSlot()
629         @misc_utils.log_exception(_moduleLogger)
630         def _on_login(self):
631                 with qui_utils.notify_error(self._errorLog):
632                         changedAccounts = self._defaultCredentials != self._curentCredentials
633                         noCallback = not self._session.get_callback_number()
634                         if changedAccounts or noCallback:
635                                 self._show_account_dialog()
636
637                         self._defaultCredentials = self._curentCredentials
638
639                         for tab in self._tabsContents:
640                                 tab.enable()
641                         self._initialize_tab(self._currentTab)
642                         if self._updateVoicemailOnMissedCall:
643                                 if self._callHandler is None:
644                                         import call_handler
645                                         self._callHandler = call_handler.MissedCallWatcher()
646                                         self._callHandler.callMissed.connect(self._voicemailRefreshDelay.start)
647                                 self._callHandler.start()
648
649         @QtCore.pyqtSlot()
650         @misc_utils.log_exception(_moduleLogger)
651         def _on_logout(self):
652                 with qui_utils.notify_error(self._errorLog):
653                         for tab in self._tabsContents:
654                                 tab.disable()
655                         if self._callHandler is not None:
656                                 self._callHandler.stop()
657
658         @QtCore.pyqtSlot()
659         @misc_utils.log_exception(_moduleLogger)
660         def _on_app_alert(self):
661                 with qui_utils.notify_error(self._errorLog):
662                         if self._session.state == self._session.LOGGEDIN_STATE:
663                                 messageType = {
664                                         (True, True): self._session.MESSAGE_ALL,
665                                         (True, False): self._session.MESSAGE_TEXTS,
666                                         (False, True): self._session.MESSAGE_VOICEMAILS,
667                                 }[(self._app.notifyOnSms, self._app.notifyOnVoicemail)]
668                                 self._session.update_messages(messageType, force=True)
669
670         @QtCore.pyqtSlot()
671         @misc_utils.log_exception(_moduleLogger)
672         def _on_recipients_changed(self):
673                 with qui_utils.notify_error(self._errorLog):
674                         if self._session.draft.get_num_contacts() == 0:
675                                 return
676
677                         if self._smsEntryDialog is None:
678                                 import dialogs
679                                 self._smsEntryDialog = dialogs.SMSEntryWindow(self.window, self._app, self._session, self._errorLog)
680                                 self._smsEntryDialog.window.destroyed.connect(self._on_child_close)
681                                 self._smsEntryDialog.window.closed.connect(self._on_child_close)
682                                 self._smsEntryDialog.window.show()
683
684         @misc_utils.log_exception(_moduleLogger)
685         def _on_child_close(self, obj = None):
686                 self._smsEntryDialog = None
687
688         @QtCore.pyqtSlot()
689         @QtCore.pyqtSlot(bool)
690         @misc_utils.log_exception(_moduleLogger)
691         def _on_login_requested(self, checked = True):
692                 with qui_utils.notify_error(self._errorLog):
693                         self._prompt_for_login()
694
695         @QtCore.pyqtSlot(int)
696         @misc_utils.log_exception(_moduleLogger)
697         def _on_tab_changed(self, index):
698                 with qui_utils.notify_error(self._errorLog):
699                         self._currentTab = index
700                         self._initialize_tab(index)
701                         if self._app.alarmHandler.alarmType == self._app.alarmHandler.ALARM_APPLICATION:
702                                 self._app.ledHandler.off()
703
704         @QtCore.pyqtSlot()
705         @QtCore.pyqtSlot(bool)
706         @misc_utils.log_exception(_moduleLogger)
707         def _on_refresh(self, checked = True):
708                 with qui_utils.notify_error(self._errorLog):
709                         self._tabsContents[self._currentTab].refresh(force=True)
710
711         @QtCore.pyqtSlot()
712         @QtCore.pyqtSlot(bool)
713         @misc_utils.log_exception(_moduleLogger)
714         def _on_refresh_connection(self, checked = True):
715                 with qui_utils.notify_error(self._errorLog):
716                         self._session.refresh_connection()
717
718         @QtCore.pyqtSlot()
719         @QtCore.pyqtSlot(bool)
720         @misc_utils.log_exception(_moduleLogger)
721         def _on_import(self, checked = True):
722                 with qui_utils.notify_error(self._errorLog):
723                         csvName = QtGui.QFileDialog.getOpenFileName(self._window, caption="Import", filter="CSV Files (*.csv)")
724                         csvName = unicode(csvName)
725                         if not csvName:
726                                 return
727                         import shutil
728                         shutil.copy2(csvName, self._app.fsContactsPath)
729                         if self._tabsContents[self.CONTACTS_TAB].has_child:
730                                 self._tabsContents[self.CONTACTS_TAB].child.update_addressbooks()
731
732         @QtCore.pyqtSlot()
733         @QtCore.pyqtSlot(bool)
734         @misc_utils.log_exception(_moduleLogger)
735         def _on_account(self, checked = True):
736                 with qui_utils.notify_error(self._errorLog):
737                         assert self._session.state == self._session.LOGGEDIN_STATE, "Must be logged in for settings"
738                         self._show_account_dialog()
739
740
741 def run():
742         try:
743                 os.makedirs(constants._data_path_)
744         except OSError, e:
745                 if e.errno != 17:
746                         raise
747
748         logFormat = '(%(relativeCreated)5d) %(levelname)-5s %(threadName)s.%(name)s.%(funcName)s: %(message)s'
749         logging.basicConfig(level=logging.DEBUG, format=logFormat)
750         rotating = logging.handlers.RotatingFileHandler(constants._user_logpath_, maxBytes=512*1024, backupCount=1)
751         rotating.setFormatter(logging.Formatter(logFormat))
752         root = logging.getLogger()
753         root.addHandler(rotating)
754         _moduleLogger.info("%s %s-%s" % (constants.__app_name__, constants.__version__, constants.__build__))
755         _moduleLogger.info("OS: %s" % (os.uname()[0], ))
756         _moduleLogger.info("Kernel: %s (%s) for %s" % os.uname()[2:])
757         _moduleLogger.info("Hostname: %s" % os.uname()[1])
758
759         try:
760                 import gobject
761                 gobject.threads_init()
762         except ImportError:
763                 _moduleLogger.info("GObject support not available")
764         try:
765                 import dbus
766                 try:
767                         from dbus.mainloop.qt import DBusQtMainLoop
768                         DBusQtMainLoop(set_as_default=True)
769                         _moduleLogger.info("Using Qt mainloop")
770                 except ImportError:
771                         try:
772                                 from dbus.mainloop.glib import DBusGMainLoop
773                                 DBusGMainLoop(set_as_default=True)
774                                 _moduleLogger.info("Using GObject mainloop")
775                         except ImportError:
776                                 _moduleLogger.info("Mainloop not available")
777         except ImportError:
778                 _moduleLogger.info("DBus support not available")
779
780         app = QtGui.QApplication([])
781         handle = Dialcentral(app)
782         qtpie.init_pies()
783         return app.exec_()
784
785
786 if __name__ == "__main__":
787         import sys
788
789         val = run()
790         sys.exit(val)