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