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