First attempt at distutils support now that the locations have been updated
[gc-dialer] / dialcentral / 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__), "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         @qt_compat.Slot()
130         @qt_compat.Slot(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._window.resized.connect(self._on_window_resized)
259                 self._errorLog = self._app.errorLog
260
261                 self._session = session.Session(self._errorLog, constants._data_path_)
262                 self._session.error.connect(self._on_session_error)
263                 self._session.loggedIn.connect(self._on_login)
264                 self._session.loggedOut.connect(self._on_logout)
265                 self._session.draft.recipientsChanged.connect(self._on_recipients_changed)
266                 self._session.newMessages.connect(self._on_new_message_alert)
267                 self._app.alarmHandler.applicationNotifySignal.connect(self._on_app_alert)
268                 self._voicemailRefreshDelay = QtCore.QTimer()
269                 self._voicemailRefreshDelay.setInterval(30 * 1000)
270                 self._voicemailRefreshDelay.timeout.connect(self._on_call_missed)
271                 self._voicemailRefreshDelay.setSingleShot(True)
272                 self._callHandler = None
273                 self._updateVoicemailOnMissedCall = False
274
275                 self._defaultCredentials = "", ""
276                 self._curentCredentials = "", ""
277                 self._currentTab = 0
278
279                 self._credentialsDialog = None
280                 self._smsEntryDialog = None
281                 self._accountDialog = None
282
283                 self._tabsContents = [
284                         DelayedWidget(self._app, self._TAB_SETTINGS_NAMES[i])
285                         for i in xrange(self.MAX_TABS)
286                 ]
287                 for tab in self._tabsContents:
288                         tab.disable()
289
290                 self._tabWidget = QtGui.QTabWidget()
291                 if qui_utils.screen_orientation() == QtCore.Qt.Vertical:
292                         self._tabWidget.setTabPosition(QtGui.QTabWidget.South)
293                 else:
294                         self._tabWidget.setTabPosition(QtGui.QTabWidget.West)
295                 defaultTabIconSize = self._tabWidget.iconSize()
296                 defaultTabIconWidth, defaultTabIconHeight = defaultTabIconSize.width(), defaultTabIconSize.height()
297                 for tabIndex, (tabTitle, tabIcon) in enumerate(
298                         zip(self._TAB_TITLES, self._TAB_ICONS)
299                 ):
300                         icon = self._app.get_icon(tabIcon)
301                         if constants.IS_MAEMO and icon is not None:
302                                 tabTitle = ""
303
304                         if icon is None:
305                                 self._tabWidget.addTab(self._tabsContents[tabIndex].toplevel, tabTitle)
306                         else:
307                                 iconSize = icon.availableSizes()[0]
308                                 defaultTabIconWidth = max(defaultTabIconWidth, iconSize.width())
309                                 defaultTabIconHeight = max(defaultTabIconHeight, iconSize.height())
310                                 self._tabWidget.addTab(self._tabsContents[tabIndex].toplevel, icon, tabTitle)
311                 defaultTabIconWidth = max(defaultTabIconWidth, 32)
312                 defaultTabIconHeight = max(defaultTabIconHeight, 32)
313                 self._tabWidget.setIconSize(QtCore.QSize(defaultTabIconWidth, defaultTabIconHeight))
314                 self._tabWidget.currentChanged.connect(self._on_tab_changed)
315                 self._tabWidget.setContentsMargins(0, 0, 0, 0)
316
317                 self._layout.addWidget(self._tabWidget)
318
319                 self._loginAction = QtGui.QAction(None)
320                 self._loginAction.setText("Login")
321                 self._loginAction.triggered.connect(self._on_login_requested)
322
323                 self._importAction = QtGui.QAction(None)
324                 self._importAction.setText("Import")
325                 self._importAction.triggered.connect(self._on_import)
326
327                 self._accountAction = QtGui.QAction(None)
328                 self._accountAction.setText("Account")
329                 self._accountAction.triggered.connect(self._on_account)
330
331                 self._refreshConnectionAction = QtGui.QAction(None)
332                 self._refreshConnectionAction.setText("Refresh Connection")
333                 self._refreshConnectionAction.setShortcut(QtGui.QKeySequence("CTRL+a"))
334                 self._refreshConnectionAction.triggered.connect(self._on_refresh_connection)
335
336                 self._refreshTabAction = QtGui.QAction(None)
337                 self._refreshTabAction.setText("Refresh Tab")
338                 self._refreshTabAction.setShortcut(QtGui.QKeySequence("CTRL+r"))
339                 self._refreshTabAction.triggered.connect(self._on_refresh)
340
341                 fileMenu = self._window.menuBar().addMenu("&File")
342                 fileMenu.addAction(self._loginAction)
343                 fileMenu.addAction(self._refreshTabAction)
344                 fileMenu.addAction(self._refreshConnectionAction)
345
346                 toolsMenu = self._window.menuBar().addMenu("&Tools")
347                 toolsMenu.addAction(self._accountAction)
348                 toolsMenu.addAction(self._importAction)
349                 toolsMenu.addAction(self._app.aboutAction)
350
351                 self._initialize_tab(self._tabWidget.currentIndex())
352                 self.set_fullscreen(self._app.fullscreenAction.isChecked())
353                 self.update_orientation(self._app.orientation)
354
355         def _init_call_handler(self):
356                 if self._callHandler is not None:
357                         return
358                 import call_handler
359                 self._callHandler = call_handler.MissedCallWatcher()
360                 self._callHandler.callMissed.connect(self._voicemailRefreshDelay.start)
361
362         def set_default_credentials(self, username, password):
363                 self._defaultCredentials = username, password
364
365         def get_default_credentials(self):
366                 return self._defaultCredentials
367
368         def walk_children(self):
369                 if self._smsEntryDialog is not None:
370                         return (self._smsEntryDialog, )
371                 else:
372                         return ()
373
374         def start(self):
375                 qwrappers.WindowWrapper.start(self)
376                 assert self._session.state == self._session.LOGGEDOUT_STATE, "Initialization messed up"
377                 if self._defaultCredentials != ("", ""):
378                         username, password = self._defaultCredentials[0], self._defaultCredentials[1]
379                         self._curentCredentials = username, password
380                         self._session.login(username, password)
381                 else:
382                         self._prompt_for_login()
383
384         def close(self):
385                 for diag in (
386                         self._credentialsDialog,
387                         self._accountDialog,
388                 ):
389                         if diag is not None:
390                                 diag.close()
391                 for child in self.walk_children():
392                         child.window.destroyed.disconnect(self._on_child_close)
393                         child.window.closed.disconnect(self._on_child_close)
394                         child.close()
395                 self._window.close()
396
397         def destroy(self):
398                 qwrappers.WindowWrapper.destroy(self)
399                 if self._session.state != self._session.LOGGEDOUT_STATE:
400                         self._session.logout()
401
402         def get_current_tab(self):
403                 return self._currentTab
404
405         def set_current_tab(self, tabIndex):
406                 self._tabWidget.setCurrentIndex(tabIndex)
407
408         def load_settings(self, config):
409                 blobs = "", ""
410                 isFullscreen = False
411                 orientation = self._app.orientation
412                 tabIndex = 0
413                 try:
414                         blobs = [
415                                 config.get(constants.__pretty_app_name__, "bin_blob_%i" % i)
416                                 for i in xrange(len(self.get_default_credentials()))
417                         ]
418                         isFullscreen = config.getboolean(constants.__pretty_app_name__, "fullscreen")
419                         tabIndex = config.getint(constants.__pretty_app_name__, "tab")
420                         orientation = config.get(constants.__pretty_app_name__, "orientation")
421                 except ConfigParser.NoOptionError, e:
422                         _moduleLogger.info(
423                                 "Settings file %s is missing option %s" % (
424                                         constants._user_settings_,
425                                         e.option,
426                                 ),
427                         )
428                 except ConfigParser.NoSectionError, e:
429                         _moduleLogger.info(
430                                 "Settings file %s is missing section %s" % (
431                                         constants._user_settings_,
432                                         e.section,
433                                 ),
434                         )
435                 except Exception:
436                         _moduleLogger.exception("Unknown loading error")
437
438                 try:
439                         self._app.alarmHandler.load_settings(config, "alarm")
440                         self._app.notifyOnMissed = config.getboolean("2 - Account Info", "notifyOnMissed")
441                         self._app.notifyOnVoicemail = config.getboolean("2 - Account Info", "notifyOnVoicemail")
442                         self._app.notifyOnSms = config.getboolean("2 - Account Info", "notifyOnSms")
443                         self._updateVoicemailOnMissedCall = config.getboolean("2 - Account Info", "updateVoicemailOnMissedCall")
444                 except ConfigParser.NoOptionError, e:
445                         _moduleLogger.info(
446                                 "Settings file %s is missing option %s" % (
447                                         constants._user_settings_,
448                                         e.option,
449                                 ),
450                         )
451                 except ConfigParser.NoSectionError, e:
452                         _moduleLogger.info(
453                                 "Settings file %s is missing section %s" % (
454                                         constants._user_settings_,
455                                         e.section,
456                                 ),
457                         )
458                 except Exception:
459                         _moduleLogger.exception("Unknown loading error")
460
461                 creds = (
462                         base64.b64decode(blob)
463                         for blob in blobs
464                 )
465                 self.set_default_credentials(*creds)
466                 self._app.fullscreenAction.setChecked(isFullscreen)
467                 self._app.set_orientation(orientation)
468                 self.set_current_tab(tabIndex)
469
470                 backendId = 2 # For backwards compatibility
471                 for tabIndex, tabTitle in enumerate(self._TAB_TITLES):
472                         sectionName = "%s - %s" % (backendId, tabTitle)
473                         settings = self._tabsContents[tabIndex].get_settings()
474                         for settingName in settings.iterkeys():
475                                 try:
476                                         settingValue = config.get(sectionName, settingName)
477                                 except ConfigParser.NoOptionError, 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 ConfigParser.NoSectionError, e:
486                                         _moduleLogger.info(
487                                                 "Settings file %s is missing section %s" % (
488                                                         constants._user_settings_,
489                                                         e.section,
490                                                 ),
491                                         )
492                                         return
493                                 except Exception:
494                                         _moduleLogger.exception("Unknown loading error")
495                                         return
496                                 settings[settingName] = settingValue
497                         self._tabsContents[tabIndex].set_settings(settings)
498
499         def save_settings(self, config):
500                 config.add_section(constants.__pretty_app_name__)
501                 config.set(constants.__pretty_app_name__, "tab", str(self.get_current_tab()))
502                 config.set(constants.__pretty_app_name__, "fullscreen", str(self._app.fullscreenAction.isChecked()))
503                 config.set(constants.__pretty_app_name__, "orientation", str(self._app.orientation))
504                 for i, value in enumerate(self.get_default_credentials()):
505                         blob = base64.b64encode(value)
506                         config.set(constants.__pretty_app_name__, "bin_blob_%i" % i, blob)
507
508                 config.add_section("alarm")
509                 self._app.alarmHandler.save_settings(config, "alarm")
510                 config.add_section("2 - Account Info")
511                 config.set("2 - Account Info", "notifyOnMissed", repr(self._app.notifyOnMissed))
512                 config.set("2 - Account Info", "notifyOnVoicemail", repr(self._app.notifyOnVoicemail))
513                 config.set("2 - Account Info", "notifyOnSms", repr(self._app.notifyOnSms))
514                 config.set("2 - Account Info", "updateVoicemailOnMissedCall", repr(self._updateVoicemailOnMissedCall))
515
516                 backendId = 2 # For backwards compatibility
517                 for tabIndex, tabTitle in enumerate(self._TAB_TITLES):
518                         sectionName = "%s - %s" % (backendId, tabTitle)
519                         config.add_section(sectionName)
520                         tabSettings = self._tabsContents[tabIndex].get_settings()
521                         for settingName, settingValue in tabSettings.iteritems():
522                                 config.set(sectionName, settingName, settingValue)
523
524         def update_orientation(self, orientation):
525                 qwrappers.WindowWrapper.update_orientation(self, orientation)
526                 windowOrientation = self.idealWindowOrientation
527                 if windowOrientation == QtCore.Qt.Horizontal:
528                         self._tabWidget.setTabPosition(QtGui.QTabWidget.West)
529                 else:
530                         self._tabWidget.setTabPosition(QtGui.QTabWidget.South)
531
532         def _initialize_tab(self, index):
533                 assert index < self.MAX_TABS, "Invalid tab"
534                 if not self._tabsContents[index].has_child():
535                         tab = self._TAB_CLASS[index](self._app, self._session, self._errorLog)
536                         self._tabsContents[index].set_child(tab)
537                 self._tabsContents[index].refresh(force=False)
538
539         def _prompt_for_login(self):
540                 if self._credentialsDialog is None:
541                         import dialogs
542                         self._credentialsDialog = dialogs.CredentialsDialog(self._app)
543                 credentials = self._credentialsDialog.run(
544                         self._defaultCredentials[0], self._defaultCredentials[1], self.window
545                 )
546                 if credentials is None:
547                         return
548                 username, password = credentials
549                 self._curentCredentials = username, password
550                 self._session.login(username, password)
551
552         def _show_account_dialog(self):
553                 if self._accountDialog is None:
554                         import dialogs
555                         self._accountDialog = dialogs.AccountDialog(self._window, self._app, self._app.errorLog)
556                         self._accountDialog.setIfNotificationsSupported(self._app.alarmHandler.backgroundNotificationsSupported)
557                         self._accountDialog.settingsApproved.connect(self._on_settings_approved)
558
559                 if self._callHandler is not None and not self._callHandler.isSupported:
560                         self._accountDialog.updateVMOnMissedCall = self._accountDialog.VOICEMAIL_CHECK_NOT_SUPPORTED
561                 elif self._updateVoicemailOnMissedCall:
562                         self._accountDialog.updateVMOnMissedCall = self._accountDialog.VOICEMAIL_CHECK_ENABLED
563                 else:
564                         self._accountDialog.updateVMOnMissedCall = self._accountDialog.VOICEMAIL_CHECK_DISABLED
565                 self._accountDialog.notifications = self._app.alarmHandler.alarmType
566                 self._accountDialog.notificationTime = self._app.alarmHandler.recurrence
567                 self._accountDialog.notifyOnMissed = self._app.notifyOnMissed
568                 self._accountDialog.notifyOnVoicemail = self._app.notifyOnVoicemail
569                 self._accountDialog.notifyOnSms = self._app.notifyOnSms
570                 self._accountDialog.set_callbacks(
571                         self._session.get_callback_numbers(), self._session.get_callback_number()
572                 )
573                 accountNumberToDisplay = self._session.get_account_number()
574                 if not accountNumberToDisplay:
575                         accountNumberToDisplay = "Not Available (%s)" % self._session.state
576                 self._accountDialog.set_account_number(accountNumberToDisplay)
577                 self._accountDialog.orientation = self._app.orientation
578
579                 self._accountDialog.run()
580
581         @qt_compat.Slot()
582         @misc_utils.log_exception(_moduleLogger)
583         def _on_settings_approved(self):
584                 if self._accountDialog.doClear:
585                         self._session.logout_and_clear()
586                         self._defaultCredentials = "", ""
587                         self._curentCredentials = "", ""
588                         for tab in self._tabsContents:
589                                 tab.disable()
590                 else:
591                         callbackNumber = self._accountDialog.selectedCallback
592                         self._session.set_callback_number(callbackNumber)
593
594                 if self._accountDialog.updateVMOnMissedCall == self._accountDialog.VOICEMAIL_CHECK_NOT_SUPPORTED:
595                         pass
596                 elif self._accountDialog.updateVMOnMissedCall == self._accountDialog.VOICEMAIL_CHECK_ENABLED:
597                         self._updateVoicemailOnMissedCall = True
598                         self._init_call_handler()
599                         self._callHandler.start()
600                 else:
601                         self._updateVoicemailOnMissedCall = False
602                         if self._callHandler is not None:
603                                 self._callHandler.stop()
604                 if (
605                         self._accountDialog.notifyOnMissed or
606                         self._accountDialog.notifyOnVoicemail or
607                         self._accountDialog.notifyOnSms
608                 ):
609                         notifications = self._accountDialog.notifications
610                 else:
611                         notifications = self._accountDialog.ALARM_NONE
612                 self._app.alarmHandler.apply_settings(notifications, self._accountDialog.notificationTime)
613
614                 self._app.notifyOnMissed = self._accountDialog.notifyOnMissed
615                 self._app.notifyOnVoicemail = self._accountDialog.notifyOnVoicemail
616                 self._app.notifyOnSms = self._accountDialog.notifyOnSms
617                 self._app.set_orientation(self._accountDialog.orientation)
618                 self._app.save_settings()
619
620         @qt_compat.Slot()
621         @misc_utils.log_exception(_moduleLogger)
622         def _on_window_resized(self):
623                 with qui_utils.notify_error(self._app.errorLog):
624                         windowOrientation = self.idealWindowOrientation
625                         if windowOrientation == QtCore.Qt.Horizontal:
626                                 self._tabWidget.setTabPosition(QtGui.QTabWidget.West)
627                         else:
628                                 self._tabWidget.setTabPosition(QtGui.QTabWidget.South)
629
630         @qt_compat.Slot()
631         @misc_utils.log_exception(_moduleLogger)
632         def _on_new_message_alert(self):
633                 with qui_utils.notify_error(self._errorLog):
634                         if self._app.alarmHandler.alarmType == self._app.alarmHandler.ALARM_APPLICATION:
635                                 if self._currentTab == self.MESSAGES_TAB or not self._app.ledHandler.isReal:
636                                         self._errorLog.push_message("New messages")
637                                 else:
638                                         self._app.ledHandler.on()
639
640         @qt_compat.Slot()
641         @misc_utils.log_exception(_moduleLogger)
642         def _on_call_missed(self):
643                 with qui_utils.notify_error(self._errorLog):
644                         self._session.update_messages(self._session.MESSAGE_VOICEMAILS, force=True)
645
646         @qt_compat.Slot(str)
647         @misc_utils.log_exception(_moduleLogger)
648         def _on_session_error(self, message):
649                 with qui_utils.notify_error(self._errorLog):
650                         self._errorLog.push_error(message)
651
652         @qt_compat.Slot()
653         @misc_utils.log_exception(_moduleLogger)
654         def _on_login(self):
655                 with qui_utils.notify_error(self._errorLog):
656                         changedAccounts = self._defaultCredentials != self._curentCredentials
657                         noCallback = not self._session.get_callback_number()
658                         if changedAccounts or noCallback:
659                                 self._show_account_dialog()
660
661                         self._defaultCredentials = self._curentCredentials
662
663                         for tab in self._tabsContents:
664                                 tab.enable()
665                         self._initialize_tab(self._currentTab)
666                         if self._updateVoicemailOnMissedCall:
667                                 self._init_call_handler()
668                                 self._callHandler.start()
669
670         @qt_compat.Slot()
671         @misc_utils.log_exception(_moduleLogger)
672         def _on_logout(self):
673                 with qui_utils.notify_error(self._errorLog):
674                         for tab in self._tabsContents:
675                                 tab.disable()
676                         if self._callHandler is not None:
677                                 self._callHandler.stop()
678
679         @qt_compat.Slot()
680         @misc_utils.log_exception(_moduleLogger)
681         def _on_app_alert(self):
682                 with qui_utils.notify_error(self._errorLog):
683                         if self._session.state == self._session.LOGGEDIN_STATE:
684                                 messageType = {
685                                         (True, True): self._session.MESSAGE_ALL,
686                                         (True, False): self._session.MESSAGE_TEXTS,
687                                         (False, True): self._session.MESSAGE_VOICEMAILS,
688                                 }[(self._app.notifyOnSms, self._app.notifyOnVoicemail)]
689                                 self._session.update_messages(messageType, force=True)
690
691         @qt_compat.Slot()
692         @misc_utils.log_exception(_moduleLogger)
693         def _on_recipients_changed(self):
694                 with qui_utils.notify_error(self._errorLog):
695                         if self._session.draft.get_num_contacts() == 0:
696                                 return
697
698                         if self._smsEntryDialog is None:
699                                 import dialogs
700                                 self._smsEntryDialog = dialogs.SMSEntryWindow(self.window, self._app, self._session, self._errorLog)
701                                 self._smsEntryDialog.window.destroyed.connect(self._on_child_close)
702                                 self._smsEntryDialog.window.closed.connect(self._on_child_close)
703                                 self._smsEntryDialog.window.show()
704
705         @misc_utils.log_exception(_moduleLogger)
706         def _on_child_close(self, obj = None):
707                 self._smsEntryDialog = None
708
709         @qt_compat.Slot()
710         @qt_compat.Slot(bool)
711         @misc_utils.log_exception(_moduleLogger)
712         def _on_login_requested(self, checked = True):
713                 with qui_utils.notify_error(self._errorLog):
714                         self._prompt_for_login()
715
716         @qt_compat.Slot(int)
717         @misc_utils.log_exception(_moduleLogger)
718         def _on_tab_changed(self, index):
719                 with qui_utils.notify_error(self._errorLog):
720                         self._currentTab = index
721                         self._initialize_tab(index)
722                         if self._app.alarmHandler.alarmType == self._app.alarmHandler.ALARM_APPLICATION:
723                                 self._app.ledHandler.off()
724
725         @qt_compat.Slot()
726         @qt_compat.Slot(bool)
727         @misc_utils.log_exception(_moduleLogger)
728         def _on_refresh(self, checked = True):
729                 with qui_utils.notify_error(self._errorLog):
730                         self._tabsContents[self._currentTab].refresh(force=True)
731
732         @qt_compat.Slot()
733         @qt_compat.Slot(bool)
734         @misc_utils.log_exception(_moduleLogger)
735         def _on_refresh_connection(self, checked = True):
736                 with qui_utils.notify_error(self._errorLog):
737                         self._session.refresh_connection()
738
739         @qt_compat.Slot()
740         @qt_compat.Slot(bool)
741         @misc_utils.log_exception(_moduleLogger)
742         def _on_import(self, checked = True):
743                 with qui_utils.notify_error(self._errorLog):
744                         csvName = QtGui.QFileDialog.getOpenFileName(self._window, caption="Import", filter="CSV Files (*.csv)")
745                         csvName = unicode(csvName)
746                         if not csvName:
747                                 return
748                         import shutil
749                         shutil.copy2(csvName, self._app.fsContactsPath)
750                         if self._tabsContents[self.CONTACTS_TAB].has_child:
751                                 self._tabsContents[self.CONTACTS_TAB].child.update_addressbooks()
752
753         @qt_compat.Slot()
754         @qt_compat.Slot(bool)
755         @misc_utils.log_exception(_moduleLogger)
756         def _on_account(self, checked = True):
757                 with qui_utils.notify_error(self._errorLog):
758                         assert self._session.state == self._session.LOGGEDIN_STATE, "Must be logged in for settings"
759                         self._show_account_dialog()
760
761
762 def run():
763         try:
764                 os.makedirs(constants._data_path_)
765         except OSError, e:
766                 if e.errno != 17:
767                         raise
768
769         logFormat = '(%(relativeCreated)5d) %(levelname)-5s %(threadName)s.%(name)s.%(funcName)s: %(message)s'
770         logging.basicConfig(level=logging.DEBUG, format=logFormat)
771         rotating = logging.handlers.RotatingFileHandler(constants._user_logpath_, maxBytes=512*1024, backupCount=1)
772         rotating.setFormatter(logging.Formatter(logFormat))
773         root = logging.getLogger()
774         root.addHandler(rotating)
775         _moduleLogger.info("%s %s-%s" % (constants.__app_name__, constants.__version__, constants.__build__))
776         _moduleLogger.info("OS: %s" % (os.uname()[0], ))
777         _moduleLogger.info("Kernel: %s (%s) for %s" % os.uname()[2:])
778         _moduleLogger.info("Hostname: %s" % os.uname()[1])
779
780         try:
781                 import gobject
782                 gobject.threads_init()
783         except ImportError:
784                 _moduleLogger.info("GObject support not available")
785         try:
786                 import dbus
787                 try:
788                         from dbus.mainloop.qt import DBusQtMainLoop
789                         DBusQtMainLoop(set_as_default=True)
790                         _moduleLogger.info("Using Qt mainloop")
791                 except ImportError:
792                         try:
793                                 from dbus.mainloop.glib import DBusGMainLoop
794                                 DBusGMainLoop(set_as_default=True)
795                                 _moduleLogger.info("Using GObject mainloop")
796                         except ImportError:
797                                 _moduleLogger.info("Mainloop not available")
798         except ImportError:
799                 _moduleLogger.info("DBus support not available")
800
801         app = QtGui.QApplication([])
802         handle = Dialcentral(app)
803         qtpie.init_pies()
804         return app.exec_()
805
806
807 if __name__ == "__main__":
808         import sys
809
810         val = run()
811         sys.exit(val)