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