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