Пример #1
0
class MicroblogThread(QThread):

    def __init__(self, app, user, service, updateusers = True):
        QThread.__init__(self, app)
        self.app = app
        self.user = user
        self.service = service
        self.updateusers = updateusers
        self.friends = QSettings("blain", "%s-%s-friends" % (user, service))


    def run(self):
        if not self.service or not self.user:
            self.quit()
            return
        trys = 0
        page = -1
        new_friends = None
        try:
            friendscount = api_call(self.service, 'users/show',
                {'id': self.user})['friends_count']
        except:
            print_exc()
            self.end()
            return
        while friendscount > 0:
            page = next_page(self.service, page, new_friends)
            print "Fetching from friends page %i, %i updates remaining (%s)" % \
                (page, friendscount, self.service),"[%i]"%trys
            new_friends = get_friends(self.service, self.user, page)
            stop = False
            friendscount -= len(new_friends)
            if len(new_friends) == 0:
                trys += 1
            for friend in new_friends:
                id = str(friend['screen_name'])
                if self.friends.contains(id):
                    print id, "(found)", self.service
                    stop = True
                else:
                    print id, "(new)", self.service
                dump = json.dumps(friend)
                self.friends.setValue(id, dump)
            if stop or trys > 3: break
            #self.yieldCurrentThread()
        print "friends list up-to-date. (%s)" % self.service
        self.end()

    def end(self):
        self.app.killThread.emit("__%s__" % self.service)
        # update all users
        if self.updateusers:
            for user in self.friends.allKeys() + [self.user]:
                self.app.updateUser.emit(self.service, user)
        self.app.updates.updates.friends(self.service, user)
        print "done."
        self.quit()
Пример #2
0
 def settingsValue( key, default):
     syslog.syslog( syslog.LOG_DEBUG,
                    "DEBUG  settingsValue %s, default: %s" %
                    (key, str(default)))
     s = QSettings()
     var = s.value(key, default)
     if not s.contains(key): s.setValue( key, var)
     syslog.syslog( syslog.LOG_DEBUG,
                    "DEBUG  settingsValue %s, value:   %s" %
                    (key, var.toString()))
     return var
Пример #3
0
    def read_settings(self):
        logging.debug('Reading settings')

        settings = QSettings()
        read_settings = self.defaults.copy()
        keys = settings.allKeys()

        for k in keys:
            setting_type = QTouTvSettings._settings_types[k]
            read_settings[k] = settings.value(k, type=setting_type)

        self.apply_settings(read_settings)
 def __new__(cls, clear_cache = False):
     if not cls._instance:
         cls._instance = super(Settings, cls).__new__(cls)
         cls._instance.signals = Settings.signals()
         QSettings.setDefaultFormat(QSettings.IniFormat)
         log.DEBUG("saving settings in file %s" %(QSettings().fileName()));
         cls._instance._settings = QSettings()
         cls._defaults = {
              Settings.DOTA_PATH_KEY: dota_path_default,
              Settings.STEAM_PATH_KEY: steam_path_default,
          }
     if clear_cache:
         cls._instance._cache = {}
     return cls._instance
Пример #5
0
 def __new__(cls, clear_cache = False):
     if not cls._instance:
         cls._instance = super(Settings, cls).__new__(cls)
         cls._instance.signals = Settings.signals()
         QSettings.setDefaultFormat(QSettings.IniFormat)
         log.DEBUG("saving settings in file %s" %(QSettings().fileName()));
         cls._instance._settings = QSettings()
         cls._defaults = {
              Settings.DOTA_PATH_KEY: dota_path_default,
              Settings.STEAM_PATH_KEY: steam_path_default,
          }
     if clear_cache:
         cls._instance._cache = {}
     return cls._instance
Пример #6
0
 def closeEvent(self, QCloseEvent):
     settings = QSettings()
     settings.setValue('width', QVariant(self.settings['width']))
     settings.setValue('color', QVariant(self.settings['color']))
     settings.setValue('x_grid', QVariant(self.settings['x_grid']))
     settings.setValue('y_grid', QVariant(self.settings['y_grid']))
     settings.setValue('grid_opacity',
                       QVariant(self.settings['grid_opacity']))
Пример #7
0
 def __init__(self, app, user, service, updateusers = True):
     QThread.__init__(self, app)
     self.app = app
     self.user = user
     self.service = service
     self.updateusers = updateusers
     self.friends = QSettings("blain", "%s-%s-friends" % (user, service))
Пример #8
0
 def __init__(self, app):
     if not hasattr(app, 'db'):
         print("filters: need 'db' from app.")
         exit(1)
     self.app = app
     self._filters = {}
     self._keys = []
     self._instances = ([], [])
     self.settings = QSettings("blain", "filters")
Пример #9
0
class GroupsThread(QThread):

    def __init__(self, app, user, updategroups = True):
        QThread.__init__(self, app)
        self.app = app
        self.user = user
        self.updategroups = updategroups
        self.groups = QSettings("blain", "%s-groups" % user)


    def run(self):
        if not self.user:
            self.quit()
            return
        trys = 0
        new_groups = None
        while trys < 4:
            trys += 1
            new_groups = get_group(self.user)
            if new_groups is not None:
                break
        if new_groups is None:
            self.end()
            return
        for group in new_groups:
            id = str(group['nickname'])
            if self.groups.contains(id):
                print id, "(found)"
            else:
                print id, "(new)"
            dump = json.dumps(clean_urls(group))
            self.groups.setValue(id, dump)
        print "groups list up-to-date. (%s)" % self.user
        self.end()

    def end(self):
        self.app.killThread.emit("%s groups" % self.user)
        # update all groups
        if self.updategroups:
            for group in self.groups.allKeys():
                self.app.updateGroup.emit(group)
        self.app.updates.updates.groups(self.user)
        print "done."
        self.quit()
Пример #10
0
 def __init__(self, app):
     if not hasattr(app, 'preferences'):
         print("update: need 'preferences' from app.")
         exit(1)
     self.app = app
     self.update = {}
     self.timers = []
     self.updates = drug()
     self.timer = QTimer(app)
     self.settings = QSettings("blain", "timers")
Пример #11
0
def steam_path_default():
    path = ""
    if os.name == "nt":
        path = str(QSettings("HKEY_CURRENT_USER\\Software\\Valve\\Steam", QSettings.NativeFormat).value("SteamPath", "").toString())
    elif sys.platform == "darwin":
        path = expanduser("~/Library/Application Support/Steam")
    else:
        path = expanduser("~/.steam/steam")
    if not exists(path): 
        log.CRITICAL("No Steam folder found! Please install it or adjust the settings!")
        Settings.steam_missing = True
    return normpath(path)
Пример #12
0
 def setup(self):
     st = QSettings("blain", "blain")
     st.setValue("_", 0)
     st.sync()
     settingspath = dirname(str(st.fileName()))
     self.db = db = Database(location=pathjoin(settingspath, "blain.sqlite"))
     setup_models(db)
Пример #13
0
    def write_settings(self):
        logging.debug('Writing settings')

        settings = QSettings()
        settings.clear()

        for k in self._settings_dict:
            if k in self.defaults:
                if self._settings_dict[k] != self.defaults[k]:
                    settings.setValue(k, self._settings_dict[k])
            else:
                msg = 'Setting key {} not found in defaults'.format(k)
                logging.warning(msg)
                settings.setValue(k, self._settings_dict[k])
Пример #14
0
 def __init__(self, app):
     if not hasattr(app, 'preferences'):
         print("accounts: need 'preferences' from app.")
         exit(1)
     if not hasattr(app, 'icons'):
         print("accounts: need 'icons' from app.")
         exit(1)
     self.app = app
     self.urls = {}
     self.services = {}
     self.accounts = {}
     self._accounts = []
     self.settings = QSettings("blain", "accounts")
Пример #15
0
    def __set_backup_path(self):

        settings = QSettings("GCI", "vertex-tools")
        settings.beginGroup("BackupSettings")
        default_path = QDir.tempPath()
        backup_path = settings.value("backup_path", default_path)
        self.backup_folder_edit.setText(backup_path)
        settings.endGroup()
Пример #16
0
    def on_backup_folder_button_clicked(self):

        backup_path = self.backup_folder_edit.text()
        if len(backup_path) == 0:
            backup_path = QDir.tempPath()

        backup_path = QFileDialog.getExistingDirectory(self, self.tr("Select Backup Folder"), backup_path,
                                                       QFileDialog.ShowDirsOnly | QFileDialog.DontResolveSymlinks)
        if len(backup_path) == 0:
            return

        self.backup_folder_edit.setText(backup_path)
        settings = QSettings("GCI", "vertex-tools")
        settings.beginGroup("BackupSettings")
        settings.setValue("backup_path", backup_path)
        settings.endGroup()
Пример #17
0
    def load_save_settings(self):
        self.settings = {
            'width': 2,
            'color': 'blue',
            'x_grid': True,
            'y_grid': True,
            'grid_opacity': 0.5
        }
        settings = QSettings()

        self.settings['width'] = settings.value(
            'width', self.settings.get('width')).toInt()[0]
        self.settings['color'] = settings.value(
            'color', self.settings.get('color')).toString()
        self.settings['x_grid'] = settings.value(
            'x_grid', self.settings.get('x_grid')).toBool()
        self.settings['y_grid'] = settings.value(
            'y_grid', self.settings.get('y_grid')).toBool()
        self.settings['grid_opacity'] = settings.value(
            'grid_opacity', self.settings.get('grid_opacity')).toFloat()[0]
Пример #18
0
class Config:
    def __init__(self, organization, product):
        self.config = QSettings(organization, product)

    def setValue(self, option, value):
        self.config.setValue(option, QVariant(value))
        self.config.sync()

    def getBoolValue(self, option):
        default = self._initValue(option, False)
        return self.config.value(option, QVariant(default)).toBool()

    def getNumValue(self, option):
        default = self._initValue(option, 0)
        return self.config.value(option, QVariant(default)).toInt()[0]

    def _initValue(self, option, value):
        if defaults.has_key(option):
            return defaults[option]
        return value
Пример #19
0
class Config:
    def __init__(self, organization, product):
        self.config = QSettings(organization, product)

    def setValue(self, option, value):
        self.config.setValue(option, QVariant(value))
        self.config.sync()

    def getBoolValue(self, option):
        default = self._initValue(option, False)
        return self.config.value(option, QVariant(default)).toBool()

    def getNumValue(self, option):
        default = self._initValue(option, 0)
        return self.config.value(option, QVariant(default)).toInt()[0]

    def _initValue(self, option, value):
        if defaults.has_key(option):
            return defaults[option]
        return value
Пример #20
0
 def __init__(self, organization, product):
     self.config = QSettings(organization, product)
Пример #21
0
            help=_('Show the average rating per item indication in the tag browser'))
    c.add_opt('disable_animations', default=False,
            help=_('Disable UI animations'))

    # This option is no longer used. It remains for compatibility with upgrades
    # so the value can be migrated
    c.add_opt('tag_browser_hidden_categories', default=set(),
            help=_('tag browser categories not to display'))

    c.add_opt
    return ConfigProxy(c)

config = _config()
# }}}

QSettings.setPath(QSettings.IniFormat, QSettings.UserScope, config_dir)
QSettings.setPath(QSettings.IniFormat, QSettings.SystemScope,
        config_dir)
QSettings.setDefaultFormat(QSettings.IniFormat)

# Turn off DeprecationWarnings in windows GUI
if iswindows:
    import warnings
    warnings.simplefilter('ignore', DeprecationWarning)

def available_heights():
    desktop  = QCoreApplication.instance().desktop()
    return map(lambda x: x.height(), map(desktop.availableGeometry, range(desktop.numScreens())))

def available_height():
    desktop  = QCoreApplication.instance().desktop()
Пример #22
0
class PreprocessDialog(QtGui.QMainWindow):
    """
    """
    e = Event()
    filterFinished = pyqtSignal()
    caller = Caller.Instance()
    conditions = []
    settings = QSettings("CIBR", "Eggie")

    def __init__(self):
        """
        Init method for the preprocessing dialog.
        Redirects stdout to dialog's console.
        """
        QtGui.QMainWindow.__init__(self)

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.progressBar.setVisible(False)

        self.installEventFilters()
        self.ui.tableWidgetEvents.setSortingEnabled(False)
        #Signals
        self.ui.tableWidgetEvents.currentItemChanged.connect(self.\
                                            on_currentChanged)
        self.ui.checkBoxLowCutOff.stateChanged.connect(self.on_StateChanged)
        self.ui.checkBoxHighCutOff.stateChanged.connect(self.on_StateChanged)
        self.ui.checkBoxNotch.stateChanged.connect(self.on_StateChanged)
        self.ui.doubleSpinBoxLowCutOff.valueChanged.connect(self.\
                                            ui.pushButtonFilter.setEnabled)
        self.ui.doubleSpinBoxHighCutOff.valueChanged.connect(self.\
                                            ui.pushButtonFilter.setEnabled)
        self.ui.doubleSpinBoxNotchFilter.valueChanged.connect(self.\
                                            ui.pushButtonFilter.setEnabled)

        self.ui.actionDirectOutput.triggered.connect(self.directOutput)
        self.ui.actionOpen.triggered.connect(self.on_actionOpen)
        self.ui.actionExit.triggered.connect(self.on_actionExit)

        sys.stdout = EmittingStream(textWritten=self.normalOutputWritten)
        sys.stderr = EmittingStream(textWritten=self.errorOutputWritten)
        self.on_actionOpen()
        self.ui.lineEditLayout.setText(self.settings.value("Layout", "").\
                                       toString())

    def initialize(self):
        """
        Method for initializing the dialog.
        """
        if not self.caller.raw: return
        self.ui.labelRaw.setText(self.caller.raw.info.get('filename'))

        self.ui.comboBoxChannelSelect.addItems(self.caller.raw.info.\
                                               get('ch_names'))
        index = self.ui.comboBoxChannelSelect.findText('17')
        self.ui.comboBoxChannelSelect.setCurrentIndex(index)
        self.ui.pushButtonFilter.setEnabled(True)

        self.ui.tableWidgetEvents.setSelectionBehavior(1)
        self.ui.tableWidgetEvents.setColumnCount(4)
        self.ui.tableWidgetEvents.setHorizontalHeaderLabels(
            ["Time (s)", "Sample", "Prev. id", "Current id"])

        tmax = np.floor(self.caller.raw.index_as_time(
            self.caller.raw.n_times))  # / 1000.0))
        if len(self.conditions) == 0:
            spectrumWidget = PowerSpectrumWidget(tmax, self)
            spectrumWidget.index = 0
            spectrumWidget.removeWidget.connect(self.on_RemoveWidget_clicked)
            spectrumWidget.channelCopy.connect(self.copyChannels)
            self.ui.verticalLayoutConditions.addWidget(spectrumWidget)
            self.conditions.append(spectrumWidget)

    def directOutput(self):
        """
        Method for directing stdout to the console and back.
        """
        if self.ui.actionDirectOutput.isChecked():
            sys.stdout = EmittingStream(textWritten=self.normalOutputWritten)
            sys.stderr = EmittingStream(textWritten=self.errorOutputWritten)
        else:
            sys.stdout = sys.__stdout__
            sys.stderr = sys.__stderr__

    def on_actionOpen(self):
        """
        Opens a dialog for selecting a file.
        """
        fileDialog = FileSelectionDialog(self)
        fileDialog.fileChanged.connect(self.on_FileChanged)
        fileDialog.show()

    def on_actionExit(self):
        """
        Closes the main window.
        """
        self.close()

    def on_pushButtonFilter_clicked(self, checked=None):
        """
        Called when filter button is clicked.
        """
        if checked is None or not self.caller.raw: return
        self.ui.pushButtonFilter.setEnabled(False)
        QtGui.QApplication.setOverrideCursor(QtGui.\
                                             QCursor(QtCore.Qt.WaitCursor))
        self.e.clear()
        self.thread = Thread(target=self.callFilter)
        self.thread.start()
        #while (self.thread.is_alive()):
        #    time.sleep(1)
        #self.e.wait()
        self.on_FilterFinished()
        QtGui.QApplication.restoreOverrideCursor()

    def callFilter(self):
        """
        A function for calling filtering function in mne.
        Performed in a worker thread.
        """
        if self.ui.checkBoxHighCutOff.isChecked():
            highCutOff = self.ui.doubleSpinBoxHighCutOff.value()
        else:
            highCutOff = None
        if self.ui.checkBoxLowCutOff.isChecked():
            lowCutOff = self.ui.doubleSpinBoxLowCutOff.value()
        else:
            lowCutOff = None
        try:
            self.caller.raw.filter(l_freq=lowCutOff,
                                   h_freq=highCutOff,
                                   n_jobs=2)
        except Exception as e:
            print str(e)
            self.e.set()
            return
        print self.caller.raw.info['bads']
        if self.ui.checkBoxNotch.isChecked():
            print "Applying notch filter...\n"
            notchFreq = self.ui.doubleSpinBoxNotchFilter.value()
            try:
                self.caller.raw.notch_filter(freqs=notchFreq)
            except Exception as e:
                print str(e)
                self.e.set()
                return
        print self.caller.raw.info['bads']
        print "Launching mne_browse_raw...\n"
        self.e.set()

    def on_FilterFinished(self):
        """
        Function for adding bad channels via mne_browse_raw.
        """
        while not (self.e.is_set()):
            sleep(0.5)
            self.updateUi()
            if self.e.is_set(): break

        self.caller.raw.plot(scalings=dict(eeg=40e-6))
        plt.show()
        self.ui.listWidgetBads.clear()
        self.ui.listWidgetBads.addItems(self.caller.raw.info['bads'])
        self.e.clear()
        print "Finished\n"
        self.ui.pushButtonSave.setEnabled(True)

    def on_pushButtonAddBads_clicked(self, checked=None):
        """
        Called as the add-button is clicked.
        Opens a dialog for adding bad channels by hand.
        """
        if checked is None or not self.caller.raw: return

        badsDialog = ChannelSelectionDialog(self.caller.raw.info['bads'],
                                            "Select bad channels:")
        badsDialog.channelsChanged.connect(self.on_BadsChanged)
        badsDialog.exec_()

    def on_pushButtonFindEogEvents_clicked(self, checked=None):
        """
        Finds EOG-events from the raw data.
        Called when find eog events -button is clicked.
        """
        if checked is None or not self.caller.raw: return
        QtGui.QApplication.setOverrideCursor(QtGui.\
                                             QCursor(QtCore.Qt.WaitCursor))
        params = dict()
        event_id = int(self.ui.labelBlinkId.text())
        params['event_id'] = event_id
        params['ch_name'] = str(self.ui.comboBoxChannelSelect.currentText())
        params['l_freq'] = float(self.ui.doubleSpinBoxLowPass.value())
        params['h_freq'] = float(self.ui.doubleSpinBoxHighPass.value())
        params['filter_length'] = str(
            self.ui.spinBoxFilterLength.value()) + 's'
        params['tstart'] = float(self.ui.doubleSpinBoxStart.value())

        try:
            #sfreq = self.caller.raw.info['sfreq']
            eog_events = self.caller.findEogEvents(params)
            #eog_events = self.caller.raw.index_as_time(eog_events)
            self.ui.tableWidgetEvents.clear()
            self.ui.tableWidgetEvents.setRowCount(0)
            for i in range(0, len(eog_events)):
                self.ui.tableWidgetEvents.insertRow(i)
                self.ui.tableWidgetEvents.setItem(i,0,QtGui.\
                            QTableWidgetItem(str(self.caller.raw.index_as_time(eog_events[i][0])[0])))
                self.ui.tableWidgetEvents.setItem(i,1,QtGui.\
                            QTableWidgetItem(str(int(eog_events[i][0]))))
                self.ui.tableWidgetEvents.setItem(i,2,QtGui.\
                            QTableWidgetItem(str(eog_events[i][1])))
                self.ui.tableWidgetEvents.setItem(i,3,QtGui.\
                            QTableWidgetItem(str(eog_events[i][2])))
        except Exception as e:
            print str(e)
        finally:
            self.ui.tableWidgetEvents.setHorizontalHeaderLabels(
                ["Time (s)", "Sample", "Prev. id", "Current id"])
            QtGui.QApplication.restoreOverrideCursor()

    @QtCore.pyqtSlot(int)
    def on_StateChanged(self, checked):
        """
        Slot for activating filter button.
        """
        if checked == 2:
            self.ui.pushButtonFilter.setEnabled(True)

    @QtCore.pyqtSlot()
    def on_FileChanged(self):
        """
        Called when raw file has changed.
        """
        self.ui.listWidgetBads.clear()
        self.ui.listWidgetBads.addItems(self.caller.raw.info['bads'])
        self.ui.tableWidgetEvents.clear()
        self.ui.tableWidgetEvents.setRowCount(0)
        for condition in reversed(self.conditions):
            index = condition.index
            self.on_RemoveWidget_clicked(index)
        self.initialize()

    @QtCore.pyqtSlot()
    def on_currentChanged(self):
        """
        Called when tableWidgetEvent row selection is changed.
        """
        index = self.ui.tableWidgetEvents.currentIndex().row()
        if index < 0:
            self.ui.pushButtonDelete.setEnabled(False)
        else:
            self.ui.pushButtonDelete.setEnabled(True)

    @QtCore.pyqtSlot(list)
    def on_BadsChanged(self, bads):
        """
        Called when bad channels are changed by hand
        Parameters:
        bads - The list of bad channels.
        """
        self.ui.listWidgetBads.clear()
        self.caller.raw.info['bads'] = bads
        self.ui.listWidgetBads.addItems(self.caller.raw.info['bads'])

    @QtCore.pyqtSlot(int)
    def on_EventsChanged(self, index):
        """
        Slot removing an event from the table.
        Parameters:
        index - Index of the item on the table.
        """
        self.ui.tableWidgetEvents.removeRow(index)

    def on_pushButtonDelete_clicked(self, checked=None):
        """
        Called when delete button of eventlist is clicked.
        """
        if checked is None: return
        index = self.ui.tableWidgetEvents.currentRow()
        self.ui.tableWidgetEvents.removeRow(index)

    def on_pushButtonCalculateSSP_clicked(self, checked=None):
        """
        Called when calculate SSP projections -button is clicked.
        """
        if checked is None or not self.caller.raw: return
        events = []
        rowCount = self.ui.tableWidgetEvents.rowCount()
        for i in xrange(0, rowCount):
            time, _ = self.ui.tableWidgetEvents.item(i, 1).text().toFloat()
            prev, _ = self.ui.tableWidgetEvents.item(i, 2).text().toFloat()
            curr, _ = self.ui.tableWidgetEvents.item(i, 3).text().toFloat()
            events.append([time, prev, curr])
        if events == []:
            print "Cannot remove blinks without events!"
            return
        projectionDialog = ProjectionDialog(np.array(events), curr, self)
        projectionDialog.badsChanged.connect(self.on_BadsChanged)
        projectionDialog.eventsChanged.connect(self.on_EventsChanged)
        projectionDialog.exec_()

    def on_pushButtonSave_clicked(self, checked=None):
        """
        Called when save button is clicked.
        """
        if checked is None or not self.caller.raw: return
        saveDialog = SaveDialog(self)
        saveDialog.exec_()
        self.ui.labelRaw.setText(self.caller.raw.info.get('filename'))

    def on_pushButtonSeriesFromTriggers_clicked(self, checked=None):
        """
        Opens a dialog for constructing a set of time series for PSDs
        from triggers.
        """
        if checked is None or self.caller.raw is None: return
        dialog = TimeSeriesDialog()
        dialog.timeSeriesChanged.connect(self.on_TimeSeriesChanged)
        dialog.exec_()

    @QtCore.pyqtSlot(list)
    def on_TimeSeriesChanged(self, conditions):
        """
        Slot for adding a set of time series for PSDs.
        Parameters:
        conditions - A list of PowerSpectrumWidgets.
        """
        if conditions == []: return
        for widget in self.conditions:
            self.on_RemoveWidget_clicked(widget.index)
        i = 0
        tmax = np.floor(self.caller.raw.index_as_time(self.caller.raw.n_times))
        for condition in conditions:
            widget = PowerSpectrumWidget(tmax, self)
            widget.setStartTime(condition.getStartTime())
            widget.setEndTime(condition.getEndTime())
            widget.setColor(condition.getColor())
            widget.setChannelColor(condition.getChannelColor())
            widget.on_ChannelsChanged(condition.getChannels())
            self.conditions.append(widget)
            widget.index = i
            widget.removeWidget.connect(self.on_RemoveWidget_clicked)
            widget.channelCopy.connect(self.copyChannels)
            self.ui.verticalLayoutConditions.addWidget(widget)
            i += 1
        self.ui.scrollAreaConditions.updateGeometry()

    def on_pushButtonAddTimeSeries_clicked(self, checked=None):
        """
        Called when condition add button is clicked.
        """
        if checked is None or not self.caller.raw: return
        tmax = np.floor(self.caller.raw.index_as_time(
            self.caller.raw.n_times))  # ms to s
        index = len(self.conditions)
        channels = self.conditions[0].getChannels()
        widget = PowerSpectrumWidget(tmax, self)
        widget.index = index
        widget.on_ChannelsChanged(channels)
        self.conditions.append(widget)
        self.ui.verticalLayoutConditions.addWidget(widget)
        widget.removeWidget.connect(self.on_RemoveWidget_clicked)
        widget.channelCopy.connect(self.copyChannels)

    def on_pushButtonFileInfo_clicked(self, checked=None):
        """
        Opens the info dialog.
        """
        if checked is None or not self.caller.raw: return
        info = Ui_infoDialog()
        infoDialog = InfoDialog(self.caller.raw, info, True)
        infoDialog.exec_()

    @QtCore.pyqtSlot(int)
    def on_RemoveWidget_clicked(self, index):
        """
        Called when a condition widget sends a remove signal.
        Removes a condition from the list.
        Parameters:
        index - The index of the widget.
        """
        widget = self.conditions.pop(index)
        self.ui.verticalLayoutConditions.removeWidget(widget)
        widget.deleteLater()
        widget = None
        # Restore order of indices:
        for i in xrange(len(self.conditions)):
            self.conditions[i].index = i

    @QtCore.pyqtSlot(int)
    def copyChannels(self, index):
        """
        """
        channels = self.conditions[index].getChannels()
        for widget in self.conditions:
            widget.on_ChannelsChanged(channels)

    def on_pushButtonPlot_clicked(self, checked=None):
        """
        Called when plot spectrum button is clicked.
        """
        if checked is None or not self.caller.raw: return
        QtGui.QApplication.setOverrideCursor(QtGui.\
                                             QCursor(QtCore.Qt.WaitCursor))

        colors = []
        times = []  # Array for start and end times.
        channelColors = dict()
        i = 0
        for condition in self.conditions:
            start = condition.getStartTime()
            end = condition.getEndTime()
            if end < start:
                messageBox = QtGui.QMessageBox()
                messageBox.setText("End time must be higher than the " + \
                                   "start time.")
                QtGui.QApplication.restoreOverrideCursor()
                messageBox.exec_()
                return
            times.append((start, end))

            colors.append(condition.getColor())
            channels = condition.getChannels()
            channelColors[i] = (condition.getChannelColor(), channels)
            i += 1
        if len(times) == 0:
            messageBox = QtGui.QMessageBox()
            messageBox.setText("Could not find data. Check parameters!")
            QtGui.QApplication.restoreOverrideCursor()
            messageBox.exec_()
            return
        fmin = self.ui.spinBoxFmin.value()
        fmax = self.ui.spinBoxFmax.value()
        if fmin >= fmax:
            messageBox = QtGui.QMessageBox()
            messageBox.setText("End frequency must be higher than the " + \
                               "starting frequency.")
            QtGui.QApplication.restoreOverrideCursor()
            messageBox.exec_()
        params = dict()
        params['times'] = times
        params['fmin'] = fmin
        params['fmax'] = fmax
        params['nfft'] = self.ui.spinBoxNfft.value()
        params['log'] = self.ui.checkBoxLogarithm.isChecked()
        params['lout'] = str(self.ui.lineEditLayout.text())
        try:
            self.caller.plotSpectrum(self, params, colors, channelColors)
        except Exception as e:
            messageBox = QtGui.QMessageBox()
            messageBox.setText(str(e))
            QtGui.QApplication.restoreOverrideCursor()
            messageBox.exec_()
            return

        QtGui.QApplication.restoreOverrideCursor()

    def on_pushButtonBrowseLayout_clicked(self, checked=None):
        """
        Opens a dialog for selecting a layout file.
        """
        if checked is None: return
        fname = str(
            QtGui.QFileDialog.getOpenFileName(
                self, 'Open file', '/home/',
                "Layout-files (*.lout *.lay);;All files (*.*)"))
        self.ui.lineEditLayout.setText(fname)
        self.settings.setValue("Layout", fname)

    def on_pushButtonGroupPlot_clicked(self, checked=None):
        """
        Opens a dialog for plotting power spectrums as a group.
        """
        if checked is None: return
        fmin = self.ui.spinBoxFmin.value()
        fmax = self.ui.spinBoxFmax.value()
        nfft = self.ui.spinBoxNfft.value()
        logarithm = self.ui.checkBoxLogarithm.isChecked()
        lout = self.ui.lineEditLayout.text()
        tmax = 10000
        if self.caller.raw:
            tmax = np.floor(
                self.caller.raw.index_as_time(self.caller.raw.n_times))
        groupSpectrumDialog = GroupSpectrumDialog(self, self.conditions, fmin,
                                                  fmax, nfft, logarithm, lout,
                                                  tmax)
        groupSpectrumDialog.fileChanged.connect(self.on_FileChanged)
        groupSpectrumDialog.exec_()

    def keyPressEvent(self, event):
        key = event.key()
        if key == QtCore.Qt.Key_Delete:
            if self.ui.tabWidget.currentIndex() == 0:
                self.on_pushButtonDelete_clicked(1)

    def installEventFilters(self):
        """
        Helper method for disabling wheel events on all widgets.
        """
        #Preprocess tab:
        self.ui.doubleSpinBoxLowCutOff.installEventFilter(self)
        self.ui.doubleSpinBoxHighCutOff.installEventFilter(self)
        self.ui.doubleSpinBoxNotchFilter.installEventFilter(self)
        self.ui.comboBoxChannelSelect.installEventFilter(self)
        self.ui.doubleSpinBoxLowPass.installEventFilter(self)
        self.ui.doubleSpinBoxHighPass.installEventFilter(self)
        self.ui.spinBoxFilterLength.installEventFilter(self)
        self.ui.doubleSpinBoxStart.installEventFilter(self)
        #Power spectrum tab:
        self.ui.spinBoxFmin.installEventFilter(self)
        self.ui.spinBoxFmax.installEventFilter(self)
        self.ui.spinBoxNfft.installEventFilter(self)

    def eventFilter(self, source, event):
        """
        Event filter for disabling wheel events on spin boxes and such.
        """
        if (event.type() == QtCore.QEvent.Wheel):
            return True
        return QtGui.QWidget.eventFilter(self, source, event)

    @QtCore.pyqtSlot()
    def updateUi(self):
        """
        Method for updating the UI.
        """
        QApplication.processEvents()

    def __del__(self):
        """
        Restores stdout at the end.
        """
        sys.stdout = sys.__stdout__
        sys.stderr = sys.__stderr__

    def normalOutputWritten(self, text):
        """
        Appends text to 'console' at the bottom of the dialog.
        Used for redirecting stdout.
        Parameters:
        text - Text to write to the console.
        """
        cursor = self.ui.textEdit.textCursor()
        cursor.movePosition(QtGui.QTextCursor.End)
        cursor.insertText(text)
        self.ui.textEdit.setTextCursor(cursor)
        self.ui.textEdit.ensureCursorVisible()

    def errorOutputWritten(self, text):
        """
        Appends text to 'console' at the bottom of the dialog.
        Used for redirecting stderr.
        Parameters:
        text - Text to write to the console.
        """
        cursor = self.ui.textEdit.textCursor()
        cursor.movePosition(QtGui.QTextCursor.End)
        cursor.insertText(text)
        self.ui.textEdit.setTextCursor(cursor)
        self.ui.textEdit.ensureCursorVisible()
Пример #23
0
class GroupSpectrumDialog(QtGui.QDialog):
    fileChanged = QtCore.pyqtSignal()
    caller = Caller.Instance()
    conditions = []
    tmax = 1000
    settings = QSettings("CIBR", "Eggie")
    
    def __init__(self, parent, conditions, fmin, fmax, nfft, logarithm, lout, 
                 tmax):
        """
        Init method for the dialog.
        Constructs a set of time series from the given parameters.
        Parameters:
        parent     - The parent window for this dialog.
        conditions - A list of PowerSpectrumWidgets. The data from these 
                     widgets are copied to this dialog.
        fmin       - Starting frequency of interest.
        fmax       - Ending frequency of interest.
        nfft       - The length of the tapers ie. the windows. 
                     The smaller it is the smoother are the PSDs.
        logarithm  - A boolean that determines if a logarithmic scale is used.
        lout       - A layout file name.
        """
        QtGui.QDialog.__init__(self)
        
        self.conditions = []
        self.ui = Ui_GroupSpectrumDialog()
        self.ui.setupUi(self)
        self.installEventFilters()
        self.parent = parent
        self.tmax = tmax
        if conditions == []:
            widget = PowerSpectrumWidget(tmax, self)
            widget.setStartTime(5)
            widget.setEndTime(tmax)
            self.conditions.append(widget)
            widget.index = 0
            widget.removeWidget.connect(self.on_RemoveWidget_clicked)
            widget.channelCopy.connect(self.copyChannels)
            self.ui.verticalLayoutConditions.addWidget(widget)
        else:
            i = 0
            for condition in conditions:
                widget = PowerSpectrumWidget(tmax, self)
                widget.setStartTime(condition.getStartTime())
                widget.setEndTime(condition.getEndTime())
                widget.setColor(condition.getColor())
                widget.setChannelColor(condition.getChannelColor())
                widget.on_ChannelsChanged(condition.getChannels())
                self.conditions.append(widget)
                widget.index = i
                widget.removeWidget.connect(self.on_RemoveWidget_clicked)
                widget.channelCopy.connect(self.copyChannels)
                self.ui.verticalLayoutConditions.addWidget(widget)
                i+=1
        
        self.ui.spinBoxFmin.setValue(fmin)
        self.ui.spinBoxFmax.setValue(fmax)
        self.ui.spinBoxNfft.setValue(nfft)
        self.ui.checkBoxLogarithm.setChecked(logarithm)
        self.ui.lineEditLayout.setText(lout)
        self.ui.buttonBox.addButton("Start", QtGui.QDialogButtonBox.AcceptRole)
        self.ui.buttonBox.addButton(QtGui.QDialogButtonBox.Close)
        self.ui.lineEditPath.editingFinished.connect(self.on_PathChanged)
        
    @QtCore.pyqtSlot(int)
    def on_RemoveWidget_clicked(self, index):
        """
        Called when a condition widget sends a remove signal.
        Removes a condition from the list.
        """
        widget = self.conditions.pop(index)
        self.ui.verticalLayoutConditions.removeWidget(widget)
        widget.deleteLater()
        widget = None
        # Restore order of indices:
        for i in xrange(len(self.conditions)):
            self.conditions[i].index = i
            
    @QtCore.pyqtSlot(int)
    def copyChannels(self, index):
        """
        """
        channels = self.conditions[index].getChannels()
        for widget in self.conditions:
            widget.on_ChannelsChanged(channels)
            
    @QtCore.pyqtSlot()
    def on_PathChanged(self):
        """
        Called when source path field loses focus. Loads the first fif file
        in the folder and uses it as a template for configuring the parameters.
        """
        QtGui.QApplication.setOverrideCursor(QtGui.\
                                             QCursor(QtCore.Qt.WaitCursor))
        data_path = str(self.ui.lineEditPath.text())
        try:
            fifFiles = [ f for f in listdir(data_path)\
                      if isfile(join(data_path,f)) and f.endswith('.fif') ]
        except Exception as e:
            messageBox = QtGui.QMessageBox()
            messageBox.setText("Cannot open folder.")
            messageBox.setInformativeText(str(e))
            messageBox.exec_()
            QtGui.QApplication.restoreOverrideCursor()
            return
        if len(fifFiles) == 0:
            QtGui.QApplication.restoreOverrideCursor()
            return
        else:
            fName = data_path + '/' + fifFiles[0]   
            try:
                #raw = mne.io.Raw(fName, preload=True)
                self.caller.setRaw(fName, self, False)
            except Exception as e:
                messageBox = QtGui.QMessageBox()
                messageBox.setText("Cannot open file " + fName)
                messageBox.setInformativeText(str(e))
                messageBox.exec_()
                QtGui.QApplication.restoreOverrideCursor()
                return
        self.tmax = np.floor(self.caller.raw.index_as_time\
                             (self.caller.raw.n_times))
        for condition in self.conditions:
            condition.setMaxTime(self.tmax)
        triggers = []
        try:
            triggers = find_events(self.caller.raw, stim_channel='STI 014')
            for trigger in triggers:
                self.ui.comboBoxStart.addItem(str(trigger[2]))
                self.ui.comboBoxEnd.addItem(str(trigger[2]))
        except Exception as e:
            print 'Could not find triggers from STI 014.'
            print str(e)
        self.fileChanged.emit()
        messageBox = QtGui.QMessageBox()
        messageBox.setText("Working file changed to " + fName)
        QtGui.QApplication.restoreOverrideCursor()
        messageBox.exec_()
            
    def on_pushButtonBrowseLayout_clicked(self, checked=None):
        """
        Called when browse layout button is clicked.
        Opens a file dialog for selecting a file.
        """
        if checked is None: return
        fname = str(QtGui.QFileDialog.getOpenFileName(self, 'Open file',
                            '/home/', 
                            "Layout-files (*.lout *.lay);;All files (*.*)"))
        self.ui.lineEditLayout.setText(fname)
        self.settings.setValue("Layout", fname)
    
    def on_pushButtonBrowseDest_clicked(self, checked=None):
        """
        Called when browse destination path button is clicked.
        Opens a file dialog for selecting a directory.
        """
        if checked is None: return
        dest = str(QtGui.QFileDialog.getExistingDirectory(self,
                                                        'Set destination path',
                                                        '/home/'))
        self.ui.lineEditDestPath.setText(dest)
        
    def on_pushButtonBrowsePath_clicked(self, checked=None):
        """
        Called when browse path button is clicked.
        Opens a file dialog for selecting a directory.
        """
        if checked is None: return
        path = str(QtGui.QFileDialog.getExistingDirectory(self,
                                                        'Set source path',
                                                        '/home/'))
        self.ui.lineEditPath.setText(path)
        self.on_PathChanged()
        
    def on_pushButtonAddTimeSeries_clicked(self, checked=None):
        """
        Called when the add condition button is clicked.
        Adds a new condition to the list.
        """
        if checked is None: return
        index = len(self.conditions)
        channels = self.conditions[0].getChannels()
        widget = PowerSpectrumWidget(self.tmax, self)
        widget.index = index
        widget.on_ChannelsChanged(channels)
        self.conditions.append(widget)
        self.ui.verticalLayoutConditions.addWidget(widget)
        widget.removeWidget.connect(self.on_RemoveWidget_clicked)
        widget.channelCopy.connect(self.copyChannels)
    
    def accept(self, *args, **kwargs):
        """
        Begins the plotting of power spectral densities to files.
        """
        self.caller.clearGroups()
        destPath = str(self.ui.lineEditDestPath.text())
        if destPath == "":
            messageBox = QtGui.QMessageBox()
            messageBox.setText("You must set a destination "\
                                + "path for the images.")
            messageBox.exec_()
            return
            
        QtGui.QApplication.setOverrideCursor(QtGui.\
                                             QCursor(QtCore.Qt.WaitCursor))
        colors = []
        times = [] # Array for start and end times.
        channelColors = dict()
        i = 0
        for condition in self.conditions:
            start = condition.getStartTime()
            end = condition.getEndTime()
            if end < start:
                messageBox = QtGui.QMessageBox()
                messageBox.setText\
                            ("End time must be higher than the start time.")
                messageBox.exec_()
                QtGui.QApplication.restoreOverrideCursor()
                return 
            times.append((start, end))
            
            colors.append(condition.getColor())
            channels = condition.getChannels()
            channelColors[i] = (condition.getChannelColor(), channels)
            i += 1
        if len(times) == 0:
            messageBox = QtGui.QMessageBox()
            messageBox.setText("Could not find data. Check parameters!")
            messageBox.exec_()
            QtGui.QApplication.restoreOverrideCursor()
            return 
        params = dict()
        params['times'] = times
        params['fmin'] = self.ui.spinBoxFmin.value()
        params['fmax'] = self.ui.spinBoxFmax.value()
        params['nfft'] = self.ui.spinBoxNfft.value()
        params['log']  = self.ui.checkBoxLogarithm.isChecked()
        params['lout'] = str(self.ui.lineEditLayout.text())
        params['dpi']  = self.ui.spinBoxResolution.value()
        params['format'] = str(self.ui.comboBoxFormat.currentText())
        params['groupAverage'] = self.ui.checkBoxGroupAverage.isChecked()
        params['plotChannels'] = self.ui.checkBoxPlotChannels.isChecked()
        
        origRaw = self.caller.raw.info['filename']
        data_path = str(self.ui.lineEditPath.text())
        try:
            fifFiles = [ f for f in listdir(data_path)\
                      if isfile(join(data_path,f)) and f.endswith('.fif') ]
        except OSError as e:
            messageBox = QtGui.QMessageBox()
            messageBox.setText("Error reading files.")
            messageBox.setInformativeText(str(e))
            messageBox.exec_()
            QtGui.QApplication.restoreOverrideCursor()
            return
        print "Found {!s} fif-files.\n".format(len(fifFiles))
        self.parent.ui.progressBar.setVisible(True)
        if params['groupAverage']:
            self.parent.ui.progressBar.setRange(0, len(fifFiles) + 1)
        else:
            self.parent.ui.progressBar.setRange(0, len(fifFiles))
        self.parent.ui.progressBar.setValue(0)
        counter = 0
        for fName in fifFiles:
            print "Working on {!s}...\n".format(fName)
            raw = data_path + '/' + fName
            try:
                self.caller.setRaw(raw, self)
            except Exception as e:
                messageBox = QtGui.QMessageBox()
                messageBox.setText("Cannot open file " + raw)
                messageBox.setInformativeText(str(e))
                messageBox.exec_()
                break
            self.parent.updateUi()
            if self.ui.checkBoxTriggers.isChecked():
                times = []
                try:
                    events = find_events(self.caller.raw, 'STI 014')
                except Exception as e:
                    print "Could not find events from STI 014. Aborting..."
                    print str(e)
                    continue
                triggerStart, _ = self.ui.comboBoxStart.currentText().toInt()
                #triggerStart = int(triggerStart)
                triggerEnd, _ = self.ui.comboBoxEnd.currentText().toInt()
                #triggerEnd = int(triggerEnd))
                tmin = np.where(events[:,2]==triggerStart)[0][0]
                tmax = np.where(events[:,2]==triggerEnd)[0][0]
                tmin = self.caller.raw.index_as_time(events[tmin][0])
                tmax = self.caller.raw.index_as_time(events[tmax][0])
                times.append((int(tmin[0]), int(tmax[0])))
                print times
                params['times'] = times
            try:
                self.caller.plotSpectrum(self, params, colors, channelColors,
                                         destPath)
            except IOError as e:
                messageBox = QtGui.QMessageBox()
                messageBox.setText("IO error occurred:")
                messageBox.setInformativeText(str(e))
                messageBox.exec_()
                break
            except RuntimeError as e:
                messageBox = QtGui.QMessageBox()
                messageBox.setText("Runtime error occurred:")
                messageBox.setInformativeText(str(e))
                messageBox.exec_()
                break
            except Exception as e:
                messageBox = QtGui.QMessageBox()
                messageBox.setText("Error occurred:")
                messageBox.setInformativeText(str(e))
                messageBox.exec_()
                break
            counter = counter + 1
            self.parent.ui.progressBar.setValue(counter)
        
        if params['groupAverage']:
            print "Calculating group averages..."
            self.updateUi()
            self.caller.createGroupAverage(destPath, colors, channelColors, params['format'], 
                                           params['dpi'], params['log'], params['lout'])
            counter = counter + 1
            
        self.parent.ui.progressBar.setValue(counter)
        self.updateUi()
        self.caller.setRaw(origRaw, self)
        self.parent.ui.progressBar.setVisible(False)
        QtGui.QApplication.restoreOverrideCursor()
    
    @QtCore.pyqtSlot(int)   
    def on_comboBoxStart_currentIndexChanged(self, index):
        """
        Method for setting time on the start time spinbox after trigger 
        selection has changed.
        Parameters:
        index - Index of the selection in combobox.
        """
        if not self.ui.checkBoxTriggers.isChecked(): return
        triggers = find_events(self.caller.raw, stim_channel='STI 014')
        triggerStart, _ = self.ui.comboBoxStart.currentText().toInt()
        tmin = np.where(triggers[:,2]==triggerStart)[0][0]
        tmin = self.caller.raw.index_as_time(triggers[tmin][0])
        tmin = int(tmin[0])
        self.conditions[0].setStartTime(tmin)
        
    @QtCore.pyqtSlot(int)   
    def on_comboBoxEnd_currentIndexChanged(self, index):
        """
        Method for setting time on the end time spinbox after trigger selection
        has changed.
        Parameters:
        index - Index of the selection in combobox.
        """
        if not self.ui.checkBoxTriggers.isChecked(): return
        triggers = find_events(self.caller.raw, stim_channel='STI 014')
        triggerEnd, _ = self.ui.comboBoxEnd.currentText().toInt()
        tmax = np.where(triggers[:,2]==triggerEnd)[0][0]
        tmax = self.caller.raw.index_as_time(triggers[tmax][0])
        tmax = int(tmax[0])
        self.conditions[0].setEndTime(tmax)
        
    @QtCore.pyqtSlot(bool)
    def on_checkBoxTriggers_toggled(self, toggled):
        """
        A slot for setting the powerspectrumwidgets according to trigger 
        settings. Called when trigger check box is toggled.
        Parameters:
        toggled - A boolean that determines if check box is ticked.
        """
        if toggled:
            for condition in reversed(self.conditions):
                index = condition.index
                if index != 0:
                    self.on_RemoveWidget_clicked(index)
                else:
                    condition.disableSpinBoxes(toggled)
            self.ui.pushButtonAddTimeSeries.setEnabled(False)
            index = self.ui.comboBoxStart.currentIndex()
            self.on_comboBoxStart_currentIndexChanged(index)
            index = self.ui.comboBoxEnd.currentIndex()
            self.on_comboBoxEnd_currentIndexChanged(index)
        else:
            self.conditions[0].disableSpinBoxes(False)
            self.ui.pushButtonAddTimeSeries.setEnabled(True)
                        
    def on_pushButtonSeriesFromTriggers_clicked(self, checked=None):
        """
        Opens a TimeSeriesDialog.
        Called when construct time series from triggers -button is clicked.
        """
        if checked is None or self.caller.raw is None: return
        dialog = TimeSeriesDialog()
        dialog.timeSeriesChanged.connect(self.on_TimeSeriesChanged)
        dialog.exec_()
        
    @QtCore.pyqtSlot(list)    
    def on_TimeSeriesChanged(self, conditions):
        """
        Slot for adding a set of PowerSpectrumWidgets to this dialog.
        Called from TimeSeriesDialog.
        Parameters:
        conditions - A list of PowerSpectrumWidgets.
        """
        if conditions == []: return
        for widget in self.conditions:
            self.on_RemoveWidget_clicked(widget.index)
        i = 0
        tmax = np.floor(self.caller.raw.index_as_time(self.caller.raw.n_times))
        for condition in conditions:
            widget = PowerSpectrumWidget(tmax, self)
            widget.setStartTime(condition.getStartTime())
            widget.setEndTime(condition.getEndTime())
            widget.setColor(condition.getColor())
            widget.setChannelColor(condition.getChannelColor())
            widget.on_ChannelsChanged(condition.getChannels())
            self.conditions.append(widget)
            widget.index = i
            widget.removeWidget.connect(self.on_RemoveWidget_clicked)
            widget.channelCopy.connect(self.copyChannels)
            self.ui.verticalLayoutConditions.addWidget(widget)
            i+=1
        self.ui.scrollAreaConditions.updateGeometry()
        
    def updateUi(self):
        self.parent.updateUi()
        
    def keyPressEvent(self, qKeyEvent):
        """
        Overrided method to prevent enter or return from starting the plotting.
        Parameters:
        qKeyEvent - Qt key event.
        """
        key = qKeyEvent.key()
        if key == QtCore.Qt.Key_Return or key == QtCore.Qt.Key_Enter:
            return
        return QtGui.QDialog.keyPressEvent(self, qKeyEvent)
    
    def installEventFilters(self):
        """
        Helper method for disabling wheel events on all widgets.
        """
        self.ui.spinBoxFmin.installEventFilter(self)
        self.ui.spinBoxFmax.installEventFilter(self)
        self.ui.comboBoxFormat.installEventFilter(self)
        self.ui.spinBoxNfft.installEventFilter(self)
        self.ui.spinBoxResolution.installEventFilter(self)
    
    def eventFilter(self, source, event):
        """
        Event filter for disabling wheel events on spin boxes and such.
        """
        if (event.type() == QtCore.QEvent.Wheel):
            return True
        return QtGui.QWidget.eventFilter(self, source, event)
Пример #24
0
class SaveDialog(QtGui.QDialog):
    caller = Caller.Instance()
    e = Event()
    error = False  # Boolean to notify error in worker thread.
    settings = QSettings("CIBR", "Eggie")

    def __init__(self, parent):
        """
        """
        QtGui.QDialog.__init__(self)

        self.ui = Ui_SaveDialog()
        self.ui.setupUi(self)
        self.parent = parent
        #self.ui.buttonBox.button(QtGui.QDialogButtonBox.Save).clicked.\
        #    connect(self.on_SaveClicked)

        #fName = self.caller.raw.info['filename']
        # Remove file-extension and add -pre.fif
        self.ui.lineEditPath.setText(self.settings.value("SaveFolder", "").\
                                     toString())
        fullPath = self.caller.raw.info['filename'].\
            rsplit('.', 1)[0] + '-pre.fif'
        fName = fullPath.rsplit('/', 1)
        if len(fName) == 2:
            self.ui.lineEditFileName.setText(fName[1])
            if self.ui.lineEditPath.text() == "":
                self.ui.lineEditPath.setText(fName[0])

        #self.caller.raw.save(fName, preload=True)

    def on_pushButtonBrowse_clicked(self, checked=None):
        """
        Called when browse button is clicked.
        Opens a dialog for choosing a directory.
        """
        if checked is None: return
        path = str(
            QtGui.QFileDialog.getExistingDirectory(
                self, 'Select path', self.ui.lineEditPath.text()))
        if path != '':
            self.ui.lineEditPath.setText(path)

    def saveFile(self):
        """
        Method for saving the file.
        """
        fName = str(self.ui.lineEditPath.text()) + '/' + \
                str(self.ui.lineEditFileName.text())
        try:
            self.caller.raw.save(fName)
            self.caller.setRaw(fName, self.parent)
        except IOError as e:
            self.error = True
            sys.stderr.write("Could not save!\n")
            sys.stderr.write(str(e))
        finally:
            self.e.set()

    def accept(self, *args, **kwargs):
        """
        Saves the raw object to a file.
        """
        QtGui.QApplication.setOverrideCursor(QtGui.\
                                             QCursor(QtCore.Qt.WaitCursor))

        self.thread = Thread(target=self.saveFile)
        self.thread.start()
        while not (self.e.is_set()):
            sleep(0.5)
            self.parent.updateUi()
            if self.e.is_set(): break

        QtGui.QApplication.restoreOverrideCursor()
        self.e.clear()
        if self.error:
            messageBox = QtGui.QMessageBox()
            messageBox.setText("Error while saving data.")
            messageBox.exec_()
            self.error = False
        self.settings.setValue("SaveFolder", self.ui.lineEditPath.text())
        return QtGui.QDialog.accept(self, *args, **kwargs)
Пример #25
0
class Filterer:

    def __init__(self, app):
        if not hasattr(app, 'db'):
            print("filters: need 'db' from app.")
            exit(1)
        if not hasattr(app, 'preferences'):
            print("filters: need 'preferences' from app.")
            exit(1)
        self.app = app
        self._filters = {}
        self._keys = []
        self._instances = ([], [])
        self.settings = QSettings("blain", "filters")


    def connect(self):
        ui = self.app.preferences.ui
        ui.filtersComboBox.currentIndexChanged.connect(self.changeDescription)
        ui.filtersComboBox_new.currentIndexChanged.connect(self.changeNew)
        ui.addfilterButton.clicked.connect(self.install)
        ui.updatefilterButton.clicked.connect(lambda: self.update())
        ui.removefilterButton.clicked.connect(self.remove)
        # init filter ui stuff in preferences
        self.changeNew(0)
        self.changeDescription(0)


    def setup(self):
        app, st, pref = self.app, self.settings, self.app.preferences.ui
        settingspath = dirname(str(self.settings.fileName()))
        filterpath = pathjoin(settingspath, "filter")
        # copy default filters into user config
        if not exists(filterpath) or not isdir(filterpath):
            mkdir(filterpath)
        localfilterpath = pathjoin(app.cwd, "filter")
        for filename in listdir(localfilterpath):
            if isfile(pathjoin(localfilterpath, filename)) and \
                filename.endswith(".py") and \
                not exists(pathjoin(filterpath, filename)):
                copyfile(pathjoin(localfilterpath, filename),
                         pathjoin(     filterpath, filename))
        # read filters from directory
        for filename in listdir(filterpath):
            if isfile(pathjoin(filterpath, filename)) and filename.endswith(".py"):
                mname = filename[:-3]
                fp, pathname, desc = find_module(mname,[filterpath])
                try:
                    filter = load_module(mname, fp, pathname, desc)
                    filterinfo = fi = filter.info()
                    if not isinstance(filterinfo, dict) or  \
                    not ('id' in fi and 'name' in fi and \
                            'filter' in fi and 'install' in \
                            fi and 'config' in fi and       \
                            'filter_description' in fi and  \
                            'instance_description' in fi and\
                            isinstance(fi['config'], dict)):
                        print "[ERROR] filter '%s' not valid." % filename
                    else:
                        filterinfo = drug(**filterinfo)
                        self._keys.append(filterinfo.id)
                        self._filters[filterinfo.id] = filterinfo
                        item = filterinfo.name, filterinfo.id
                        pref.filtersComboBox.addItem(*item)
                        pref.filtersComboBox_new.addItem(*item)
                finally:
                    if fp: fp.close()
        # add filters to list
        for n in range(st.value('count', 0).toInt()[0]):
            fid = str(st.value("id" + str(n)).toString())
            fhash = str(st.value("hash" + str(n)).toString())
            if fid in self._filters:
                self.show_filter_instance(self._filters[fid], fhash)
            else:
                print "[WARNING] doens't found filter", fid


    def filter_settings(self, id, hash):
        return QSettings("blain", "filter-{0}-{1}".format(id, hash))


    def apply(self, posts):
        for i in range(len(self._instances[0])):
            hs = self._instances[0][i]
            id = self._instances[1][i]
            st = self.filter_settings(id, hs)
            posts = self._filters[id].filter(st, posts)
        return posts


    def changeDescription(self, index):
        self.app.preferences.ui.descriptionText.setText(
            self._filters[self._keys[int(index)]].filter_description)


    def changeNew(self, index):
        filter = self._filters[self._keys[int(index)]]
        ct = self.app.preferences.ui.configTable
        ct.clear()
        n = 0
        ct.setRowCount(len(filter.config))
        for key, value in filter.config.items():
            twi = QTableWidgetItem(key)
            twi.setFlags(Qt.ItemIsSelectable)
            ct.setItem(n, 0, twi)
            ct.setItem(n, 1, QTableWidgetItem(value))
            n += 1


    def show_filter_instance(self, filter, hash):
        if hash not in self._instances[0]:
            self._instances[0].append(hash)
            self._instances[1].append(filter.id)
            desc = str(filter.instance_description(
                self.filter_settings(filter.id, hash)))
            text = filter.name
            if desc:
                text = "{0}: {1}".format(text, desc)
            self.app.preferences.ui.filterList.addItem(text)


    def add_filter_instance(self, filter, hash):
        st = self.settings
        c = st.value('count',0).toInt()[0]
        st.setValue("id" + str(c), filter.id)
        st.setValue("hash" + str(c), hash)
        st.setValue('count', c + 1)
        self.show_filter_instance(filter, hash)


    def install(self):
        pref = self.app.preferences.ui
        ct = pref.configTable
        curi = int(pref.filtersComboBox_new.currentIndex())
        filter = self._filters[self._keys[curi]]
        config, hash = {}, gen_hash()
        settings = self.filter_settings(filter.id, hash)
        for i in range(ct.rowCount()):
            config[unicode(ct.item(i,0).text())] = unicode(ct.item(i,1).text())
        try:
            filter.install(settings, config)
        except Exception as e:
            msg = QMessageBox(pref)
            msg.setIcon(QMessageBox.Critical)
            msg.setWindowTitle("Installation Error ...")
            msg.setText("An Error occured during installation.")
            msg.setInformativeText("Could install filter '%s'." % filter.name)
            msg.setStandardButtons(QMessageBox.Ok)
            msg.setDetailedText(format_exc())
            msg.exec_()
            return
        # success
        self.add_filter_instance(filter, hash)
        pref.filtersComboBox_new.currentIndexChanged.emit(curi)
        pref.filtertabWidget.setCurrentIndex(0)


    def update(self, doupdate = True):
        self.app.db.update_cache()
        if doupdate: self.app.updateMessageView()
        #print "done."


    def remove(self):
        st = self.settings
        pref = self.app.preferences.ui
        n = pref.filterList.currentRow()
        filter = self._filters[self._instances[1][n]]
        fst = self.filter_settings(filter.id, self._instances[0][n])
        if 1 == QMessageBox.question(pref,
          "Removing %s ..." % filter.name,
          "Are you sure you want remove filter '%s' (%s)?" % \
          (filter.name, filter.instance_description(fst)), 0, 1, 2):
            pref.filterList.takeItem(n)
            c = st.value('count', 0).toInt()[0] - 1
            if n == c:
                for i in range(2):
                    self._instances[i].pop()
            for i in range(n, c):
                self._instances[0][i] = hs = self._instances[0][i+1]
                self._instances[1][i] = id = self._instances[1][i+1]
                st.setValue("id"   + str(i), id)
                st.setValue("hash" + str(i), hs)
            st.remove("id"   + str(c))
            st.remove("hash" + str(c))
            st.setValue('count', c)
            if exists(fst.fileName()):
                fileremove(fst.fileName())


    def move(self, from_row, to_row):
        st = self.settings
        for i in range(2):
            self._instances[i].insert(to_row, self._instances[i].pop(from_row))
        for i in range(min(from_row, to_row), max(from_row, to_row) + 1):
            st.setValue("id"   + str(i), self._instances[1][i])
            st.setValue("hash" + str(i), self._instances[0][i])
Пример #26
0
 def __init__(self, app, user, updategroups = True):
     QThread.__init__(self, app)
     self.app = app
     self.user = user
     self.updategroups = updategroups
     self.groups = QSettings("blain", "%s-groups" % user)
Пример #27
0
              help=_('Disable UI animations'))

    # This option is no longer used. It remains for compatibility with upgrades
    # so the value can be migrated
    c.add_opt('tag_browser_hidden_categories',
              default=set(),
              help=_('tag browser categories not to display'))

    c.add_opt
    return ConfigProxy(c)


config = _config()
# }}}

QSettings.setPath(QSettings.IniFormat, QSettings.UserScope, config_dir)
QSettings.setPath(QSettings.IniFormat, QSettings.SystemScope, config_dir)
QSettings.setDefaultFormat(QSettings.IniFormat)

# Turn off DeprecationWarnings in windows GUI
if iswindows:
    import warnings
    warnings.simplefilter('ignore', DeprecationWarning)


def available_heights():
    desktop = QCoreApplication.instance().desktop()
    return map(lambda x: x.height(),
               map(desktop.availableGeometry, range(desktop.numScreens())))

Пример #28
0
class Updater:

    def __init__(self, app):
        if not hasattr(app, 'preferences'):
            print("update: need 'preferences' from app.")
            exit(1)
        if not hasattr(app, 'accounts'):
            print("update: need 'accounts' from app.")
            exit(1)
        self.app = app
        self.update = {}
        self.timers = []
        self.updates = drug()
        self.timer = QTimer(app)
        self.settings = QSettings("blain", "timers")


    def connect(self):
        win = self.app.window.ui
        win.actionDoUpdates.triggered.connect(self.do)
        win.actionUpdate_now.triggered.connect(self.all)
        self.timer.timeout.connect(self.timer_step)
        self.app.window.ui.actionDoUpdates.setChecked(
            self.app.preferences.settings.value("timer/active",False).toBool())


    def setup(self):
        app, st, pref = self.app, self.settings, self.app.preferences.settings
        account_id = {}
        # thread starting functions
        self.update['user'] = app.updateUser.emit
        self.update['group'] = app.updateGroup.emit
        self.update['groups'] = lambda *args: \
            app.updateGroups.emit(*(args[:2]+(False,)+args[3:]))
        self.update['friends'] = lambda *args: \
            app.updateFriends.emit(*(args[:2]+(False,)+args[3:]))
        # read existing friends and groups
        friends, friends_list, groups, groups_list = {}, {}, {}, {}
        for account in self.app.accounts.get():
            if account.service not in friends:
                friends[account.service] = {}
            if account.service not in friends_list:
                friends_list[account.service] = []
            friends_list[account.service].append(account.name)
            friends[account.service][account.name] = \
                list(map(unicode, account.friends.allKeys())) + [account.name]
            if account.groups is not None:
                if account.service not in groups:
                    groups[account.service] = {}
                if account.service not in groups_list:
                    groups_list[account.service] = []
                groups_list[account.service].append(account.name)
                groups[account.service][account.name] = \
                    list(map(unicode, account.groups.allKeys()))
        # read existing timer events

        # format: (timestamp, func, service, account, user, *args)
        timers = [ unicode(st.value(str(i)).toString())
                for i in range(st.value("count",0).toInt()[0]) ]

        #find new timer events
        user_leveled = {'user': friends, 'group': groups}
        account_leveled = {'friends': friends_list, 'groups': groups_list}
        for timer in map(lambda t: unicode(t).split(","), timers):
            if timer[1] == 'user' or timer[1] == 'group':
                # choose current data
                service_level = user_leveled[timer[1]]
                # dive data levels
                if timer[2] in service_level:
                    account_level = service_level[timer[2]]
                    if timer[3] in account_level:
                        user_level = account_level[timer[3]]
                        if timer[4] in user_level:
                            # event found, remove it
                            user_level.remove(timer[4])
            elif timer[1] == 'friends' or timer[1] == 'groups':
                # choose current data
                service_level = account_leveled[timer[1]]
                # dive data levels
                if timer[2] in service_level:
                    account_level = service_level[timer[2]]
                    if timer[3] in account_level:
                        # event found, remove it
                        account_level.remove(timer[3])
        # save left overs
        t = time()
        # add new group lists
        timers.extend([ u"{0},groups,{1},{2},".format(t, service, account)
                        for service in groups_list
                        for account in groups_list[service] ])
        # add new friend lists
        timers.extend([ u"{0},friends,{1},{2},".format(t, service, account)
                        for service in friends_list
                        for account in friends_list[service] ])
        # add new groups
        timers.extend([ u"{0},group,{1},{2},{3}".format(t,service,account,group)
                        for service in groups
                        for account in groups[service]
                        for group   in groups[service][account] ])
        # add new friends
        timers.extend([ u"{0},user,{1},{2},{3}".format(t,service,account,user)
                        for service in friends
                        for account in friends[service]
                        for user    in friends[service][account] ])
        # add some random to the order so twitter
        #   wont get called to often in a row hopfully
        if len(timers) != st.value("count", 0).toInt()[0]:
            shuffle(timers) # inplace
        # save new timers
        st.setValue('count',len(timers))
        for i, timer in enumerate(timers):
            st.setValue(str(i), timer)
        # more python readable format
        timers = [ unicode(t).split(",") for t in timers ]
        timers = [ [float(t[0])] + t[1:] for t in timers ]
        self.timers = timers
        # start timers
        self.updates.user = self.user
        self.updates.group = self.group
        self.updates.groups = self.groups
        self.updates.friends = self.friends
        self.timer.setInterval(
            pref.value("timer/interval",1e4).toInt()[0]) # 10 sec
        if pref.value("timer/active", True).toBool():
            self.timer.start()


    def add_timer(self, func, service, account, user, *args):
        timer = ",".join(map(unicode, [time(), func, service, account, user]))
        if args:
            timer += "," + ",".join(map(unicode, args))
        self.settings.setValue(str(len(self.timers)), timer)
        timer = timer.split(",")
        self.timers.append([float(timer[0])] + timer[1:])
        self.settings.setValue("count", len(self.timers))


    def remove_timer(self, func, service, account, user):
        found, cur = [], ",".join(map(unicode, [func, service, account, user]))
        for i, timer in enumerate(self.timers):
            if cur in ",".join(map(unicode, timer)):
                found.append(i)
        if not found: return
        for i in reversed(found):
            self.timers.pop(i)
        self.settings.setValue('count',len(self.timers))
        for i, timer in enumerate(self.timers[found[0]:]):
            self.settings.setValue(str(i+found[0]),",".join(map(unicode,timer)))


    def new_updates(self, account, new_time, break_): # new_updates count
        cur, n, service, accid = None, -1, account.service, account.name
        for i, timer in enumerate(self.timers):
            if service == timer[2] and accid == timer[3] and break_(timer):
                n, cur = i, timer
                break
        if cur is None: return
        cur[0] = new_time
        self.settings.setValue(str(n), ",".join(map(unicode, cur)))


    def user(self, account, user, count, ok): # new_updates count
        if count:
            self.app.notifier.notify_by_mode(
                amount = count, user = user)
        self.new_updates(account,
            time() - (not ok) * 5 - count / len(self.timers),
            lambda t: t[1] == "user" and t[4] == user)


    def group(self, account, group, count, ok): # new_updates count
        if count:
            self.app.notifier.notify_by_mode(
                amount = count, user = "******" + group)
        self.new_updates(account,
            time() - (not ok) * 5 - count / len(self.timers),
            lambda t: t[1] == "group" and t[4] == group)


    def groups(self, account): # new_updates count
        self.new_updates(account, time(), lambda t: t[1] == "groups")


    def friends(self, account): # new_updates count
        self.new_updates(account, time(), lambda t: t[1] == "friends")


    def timer_step(self):
        cur = self.timers[0]
        for timer in self.timers:
            if timer[0] < cur[0]:
                cur = timer
        print "* timer update", cur
        self.update[cur[1]](*cur[2:])


    def account(self, account, start = True):
        acc = account.service, account.name
        ids = [u"{0}{1}friends".format(*acc)]
        self.app.threads.updateFriends(*acc)
        if account.groups is not None:
            ids.append(u"{0}{1}groups".format(*acc))
            self.app.threads.updateGroups(*acc)
        if start:
            self.app.threads.start(*ids)
            return []
        return ids


    def do(self, checked):
        if checked: self.timer.start()
        else:       self.timer.stop()
        self.app.preferences.settings.setValue("timer/active", checked)


    def all(self):
        self.app.threads.start(
            *sum([ self.account(account,False)
            for account in self.app.accounts.get() ],[]))
Пример #29
0
class Updater:

    def __init__(self, app):
        if not hasattr(app, 'preferences'):
            print("update: need 'preferences' from app.")
            exit(1)
        self.app = app
        self.update = {}
        self.timers = []
        self.updates = drug()
        self.timer = QTimer(app)
        self.settings = QSettings("blain", "timers")


    def connect(self):
        win = self.app.window.ui
        win.actionDoUpdates.triggered.connect(self.do)
        win.actionUpdate_now.triggered.connect(self.all)
        self.timer.timeout.connect(self.timer_step)
        self.app.window.ui.actionDoUpdates.setChecked(
            self.app.preferences.settings.value("timer/active",True).toBool())


    def setup(self):
        app, st, pref = self.app, self.settings, self.app.preferences.settings
        self.update['user'] = app.updateUser.emit
        self.update['friends'] = lambda *args: \
            app.updateMicroblogging.emit(args[0],
            app.preferences.settings.value(\
            "account/"+args[0]+"/id").toString(),\
            False, *args[2:])
        friends = drug(twitter = [], identica = [])
        if pref.contains("account/twitter/id"):
            friends.twitter  = map(unicode, QSettings("blain",
                "%s-twitter-friends" % pref.value("account/twitter/id").\
                toString()).allKeys())
        if pref.contains("account/identica/id"):
            friends.identica = map(unicode, QSettings("blain",
                "%s-identica-friends" % pref.value("account/identica/id").\
                toString()).allKeys())
        # format: (timestamp, func, service, user, *args)
        self.timers = timers = [ unicode(st.value(str(i)).toString())
                for i in range(st.value("count",0).toInt()[0]) ]

        # add timer entries
        new_friends = ['twitter', 'identica']
        new_friend = {'twitter':friends.twitter , 'identica':friends.identica}
        for timer in map(lambda t: unicode(t).split(","), timers):
            if timer[1] == 'user':
                if timer[3] in new_friend[timer[2]]:
                    new_friend[timer[2]].remove(timer[3])
            elif timer[1] == 'friends':
                if timer[2] in new_friends:
                    new_friends.remove(timer[2])
        for service in new_friends:
            timers.append("{0},friends,{1},".format(time(),service))

        for service in new_friend:
            for i, user in enumerate(new_friend[service]):
                new_friend[service][i] = "{0},user,{1},{2}".\
                    format(time(),service,user)
        if new_friend['twitter'] or new_friend['identica']:
            timers.extend(list(sum(zip(new_friend['identica'],
                                            new_friend['twitter']), ())))
            if len(new_friend['twitter']) > len(new_friend['identica']):
                timers.extend(new_friend['twitter'][len(new_friend['identica']):])
            else:
                timers.extend(new_friend['identica'][len(new_friend['twitter']):])
        st.setValue('count',len(timers))
        for i in range(len(timers)):
            st.setValue(str(i), timers[i])
        self.timers = list(map(lambda t: [float(t[0])] + t[1:],
                        map(lambda t: unicode(t).split(","), timers)))

        self.updates.user = self.user
        self.updates.friends = self.friends
        self.timer.setInterval(
            pref.value("timer/interval",1e4).toInt()[0]) # 10 sec
        if pref.value("timer/active", True).toBool():
            self.timer.start()


    def user(self, service, user, count , ok): # new_updates count
        service, user = unicode(service), unicode(user)
        cur, n = None, -1
        for i, timer in enumerate(self.timers):
            if timer[1] == "user" and timer[2] == service and timer[3] == user:
                n, cur = i, timer
                break
        if cur is None: return
        cur[0] = time() - (not ok) * 5 - count / len(self.timers)
        self.settings.setValue(str(n), ",".join(map(unicode, cur)))


    def friends(self, service, user): # new_updates count
        service, user = unicode(service), unicode(user)
        cur, n = None, -1
        for i, timer in enumerate(self.timers):
            if timer[1] == "friends" and timer[2] == service:
                n, cur = i, timer
                break
        if cur is None: return
        cur[0] = time()
        self.settings.setValue(str(n), ",".join(map(unicode, cur)))


    def timer_step(self):
        print "* timer update"
        cur = self.timers[0]
        for timer in self.timers:
            if timer[0] < cur[0]:
                cur = timer
        print cur
        self.update[cur[1]](*cur[2:])


    def twitter(self, start = True):
        self.app.threads.updateMicroblogging('twitter',
            self.app.preferences.ui.twitteridEdit.text())
        if start:
            self.app.threads.start('twitter')


    def identica(self, start = True):
        self.app.threads.updateMicroblogging('identica',
            self.app.preferences.ui.identicaidEdit.text())
        if start:
            self.app.threads.start('identica')


    def do(self, checked):
        if checked: self.timer.start()
        else:       self.timer.stop()
        self.app.preferences.settings.setValue("timer/active", checked)


    def all(self):
        self.identica(False)
        self.twitter(False)
        self.app.threads.start('identica', 'twitter')
Пример #30
0
class FileSelectionDialog(QtGui.QDialog):
    """
    """
    fileChanged = pyqtSignal()
    settings = QSettings("CIBR", "Eggie")

    def __init__(self, parent):
        """
        Dialog for setting the raw file and environment variables.
        """
        QtGui.QDialog.__init__(self, parent)
        self.parent = parent
        self.ui = Ui_FileSelectDialog()
        self.ui.setupUi(self)
        mneRoot = os.environ.get('MNE_ROOT', '')
        if mneRoot == "":
            mneRoot = self.settings.value("MNE_ROOT", "").toString()
        self.ui.lineEditMneRoot.setText(mneRoot)
        self.show()

    def on_pushButtonConvertEdf_clicked(self, checked=None):
        """
        Opens a dialog for converting files to fif.
        """
        if checked is None: return
        self.mneRoot = self.ui.lineEditMneRoot.text()
        if str(self.mneRoot) is '':
            QtGui.QMessageBox.critical(
                self, "Cannot convert",
                "MNE_ROOT must be set before conversion", "Ok")
            return
        self.edfToFifDialog = EdfToFifDialog(self.mneRoot)
        self.edfToFifDialog.edfConverted.connect(self.edfConverted)
        self.edfToFifDialog.updateUi.connect(self.parent.updateUi)
        self.edfToFifDialog.show()

    def on_pushButtonBrowse_clicked(self, checked=None):
        """
        Opens a dialog for selecting a raw file.
        """
        if checked is None: return
        self.fname = str(
            QtGui.QFileDialog.getOpenFileName(
                self, 'Open file', '/home/',
                "Fif-files (*.fif);;All files (*.*)"))

        if self.fname != '':
            self.ui.lineEditRawFile.setText(self.fname)

    def on_pushButtonShowInfo_clicked(self, checked=None):
        """
        Opens a dialog for showing file info.
        Called when show info button is clicked.
        """
        if checked is None: return
        QtGui.QApplication.setOverrideCursor(QtGui.QCursor(Qt.WaitCursor))
        print str(self.ui.lineEditRawFile.text())
        try:
            raw = mne.io.Raw(str(self.ui.lineEditRawFile.text()))
        except Exception as e:
            messageBox = QtGui.QMessageBox()
            messageBox.setText(str(e))
            QtGui.QApplication.restoreOverrideCursor()
            messageBox.exec_()
        info = Ui_infoDialog()
        infoDialog = InfoDialog(raw, info, True)
        QtGui.QApplication.restoreOverrideCursor()
        infoDialog.exec_()

    @pyqtSlot(str)
    def edfConverted(self, fifName):
        """
        Slot for setting the file name to the line edit.
        Parameters:
        fifName - The name of the file.
        """
        self.ui.lineEditRawFile.setText(fifName)

    def accept(self, *args, **kwargs):
        """
        Called when ok button is clicked.
        If raw file is successfully loaded, a fileChanged -signal is emitted.
        """
        QtGui.QApplication.setOverrideCursor(QtGui.QCursor(Qt.WaitCursor))

        mneRoot = self.ui.lineEditMneRoot.text()
        if str(mneRoot) is '':
            messageBox = QtGui.QMessageBox()
            messageBox.setText("Environment variables MNE_ROOT " +
                               "must be set!")
            messageBox.exec_()
            QtGui.QApplication.restoreOverrideCursor()
            return
        else:
            self.settings.setValue("MNE_ROOT", mneRoot)
        caller = Caller.Instance()
        preload = self.ui.checkBoxPreload.isChecked()
        try:
            caller.setRaw(str(self.ui.lineEditRawFile.text()), self.parent,
                          preload)
            self.fileChanged.emit()
        except Exception as e:
            messageBox = QtGui.QMessageBox()
            messageBox.setText("Cannot open file. ")
            messageBox.setInformativeText(str(e))
            messageBox.exec_()
            QtGui.QApplication.restoreOverrideCursor()

        QtGui.QDialog.accept(self, *args, **kwargs)
        QtGui.QApplication.restoreOverrideCursor()
Пример #31
0
 def __init__(self, organization, product):
     self.config = QSettings(organization, product)
Пример #32
0
class Accounter:

    def __init__(self, app):
        if not hasattr(app, 'preferences'):
            print("accounts: need 'preferences' from app.")
            exit(1)
        if not hasattr(app, 'icons'):
            print("accounts: need 'icons' from app.")
            exit(1)
        self.app = app
        self.urls = {}
        self.services = {}
        self.accounts = {}
        self._accounts = []
        self.settings = QSettings("blain", "accounts")


    def connect(self):
        ui = self.app.preferences.ui
        ui.addaccountButton.clicked.connect(self.addAccount)
        ui.removeaccountButton.clicked.connect(self.removeAccount)
        cb = ui.accountserviceComboBox
        cb.currentIndexChanged.connect(self.changeAccountservice)
        for service in services:
            cb.addItem(service.title)
        cb.setCurrentIndex(1)


    def setup(self):
        st = self.settings
        st.beginGroup("url")
        for service in map(unicode, st.allKeys()):
            self.urls[service] = unicode(st.value(service).toString())
        st.endGroup()
        st.beginGroup("service")
        for service in map(unicode, st.allKeys()):
            self.services[service] = unicode(st.value(service).toString())
        st.endGroup()
        st.beginGroup("account")
        for key in map(unicode, st.allKeys()):
            service = unicode(st.value(key).toString())
            self.accounts[key] = drug(
                service = service,
                name = key.partition("/")[2],
                type = self.services[service],
                url = self.urls[service])
        st.endGroup()
        for key, account in self.accounts.items():
            self._accounts.append(key)
            self.add_account_to_list(account)
            self.accounts[key] = account = Account(account)
            add_service(account.service,
                {'api':account.api, 'search':account.search})


    def add_account_to_list(self, account):
        at = self.app.preferences.ui.accountList
        n = at.count()
        icon = self.app.icons.get_service_icon(account.service, account.url)
        li = QListWidgetItem( u"{0}   ({1})".format(
            account.name, account.service))
        if icon is not None:
            li.setIcon(icon)
        at.insertItem(n, li)
        at.setCurrentRow(n)


    def addAccount(self):
        pref = self.app.preferences.ui
        if pref.addaccountButton.text() == "wait":
            return # already adding an account
        if pref.accountidEdit.text() == "":
            return # is empty
        index = pref.accountserviceComboBox.currentIndex()
        if index == 0 and pref.accounturlEdit.text() == "":
            return # is empty too
        account = drug(service = services[index].name,
                       name = unicode(pref.accountidEdit.text()),
                       type = services[index].type,
                       url = services[index].url)
        if account.url is None:
            url = unicode(pref.accounturlEdit.text())
            if url.endswith("/"):
                url = url[:-1]
            if not "://" in url:
                url = u"http://" + url
            account.url = url
        if account.service is None:
            s = account.url.partition("//")[2].partition("/")[0].split(".")
            account.service = s[-2] + s[-1]
        # save new account
        pref.addaccountButton.setText("wait")
        st = self.settings
        key = u"account/{0}/{1}".format(account.service, account.name)
        if st.contains(key):
            return # allready existing -> skip
        st.setValue(key, account.service)
        key = u"service/" + account.service
        if not st.contains(key):
            st.setValue(key, account.type)
            st.setValue(u"url/" + account.service, account.url)
            self.urls[account.service] = account.url
        pref.accountsTabWidget.setCurrentIndex(0)
        self.add_account_to_list(account)
        key = u"{0}/{1}".format(account.service, account.name)
        self._accounts.append(key)
        self.accounts[key] = account = Account(account)
        # create timer events for new account
        self.app.updates.add_timer("friends", account.service, account.name, "")
        self.app.updates.add_timer(
            "user", account.service, account.name, account.name)
        if account.groups is not None:
            self.app.updates.add_timer("groups",account.service,account.name,"")
        # install service
        if account.service not in self.services:
            self.services[account.service] = account.type
            add_service(account.service,
                {'api':account.api, 'search':account.search})
        pref.addaccountButton.setText("add")


    def removeAccount(self):
        at = self.app.preferences.ui.accountList
        n = at.currentRow()
        if n == -1:
            return # no items
        acc = self._accounts.pop(n)
        self.settings.remove(u"account/" + acc)
        account = self.accounts[acc]
        self.app.updates.remove_timer("friends",account.service,account.name,"")
        self.app.updates.remove_timer("user"   ,account.service,account.name,"")
        self.app.updates.remove_timer("groups" ,account.service,account.name,"")
        self.app.updates.remove_timer("group"  ,account.service,account.name,"")
        del self.accounts[acc]
        at.takeItem(n)


    def changeAccountservice(self, index):
        ui = self.app.preferences.ui
        if index in range(len(services)):
            visible = services[index].url is None
            ui.accounturlLabel.setVisible(visible)
            ui.accounturlEdit.setVisible(visible)


    def get_services(self, services): # returning merged services as list
        active,merged,services = self.get_active_services(),unicode(services),[]
        while merged:
            matched = []
            for service in active:
                if service in merged:
                    i = merged.index(service)
                    matched.append((i, service))
            if not matched: break
            matched.sort(key=lambda x:x[0])
            service = matched[0][1]
            services.append(service)
            merged = merged[len(service):]
        # prefer statusnet
        services.sort(key=lambda s:(self.services[s] == "twitter") * 1)
        return services


    def get_active_services(self):
        return list(set(account.service for account in self.accounts.values()))


    def get(self, service = None, user = None):
        if service is None and user is None:
            return self.accounts.values()
        return self.accounts[u"{0}/{1}".format(service, user)]
Пример #33
0
 def setSettingsValue( key, val):
     syslog.syslog( syslog.LOG_DEBUG,
                    "DEBUG  setSettingsValue %s, value: %s" %
                    (key, str(val)))
     s = QSettings()
     s.setValue( key, val)
Пример #34
0
class Updater:

    def __init__(self, app):
        if not hasattr(app, 'preferences'):
            print("update: need 'preferences' from app.")
            exit(1)
        self.app = app
        self.update = {}
        self.timers = []
        self.updates = drug()
        self.timer = QTimer(app)
        self.settings = QSettings("blain", "timers")


    def connect(self):
        win = self.app.window.ui
        win.actionDoUpdates.triggered.connect(self.do)
        win.actionUpdate_now.triggered.connect(self.all)
        self.timer.timeout.connect(self.timer_step)
        self.app.window.ui.actionDoUpdates.setChecked(
            self.app.preferences.settings.value("timer/active",True).toBool())


    def setup(self):
        app, st, pref = self.app, self.settings, self.app.preferences.settings
        account_id = {}
        # thread starting functions
        self.update['user'] = app.updateUser.emit
        self.update['group'] = lambda *args: app.updateGroup.emit(*args[1:])
        self.update['groups'] = lambda *args: \
            app.updateGroups.emit(args[1], False, *args[2:])
        self.update['friends'] = lambda *args: \
            app.updateMicroblogging.emit(args[0],
            account_id[service], False, *args[2:])
        # read existing friends
        friends = {}
        for service in ["twitter", "identica"]:
            friends[service] = []
            if pref.contains("account/%s/id" % service):
                account_id[service] = pref.value(
                    "account/%s/id" % service).toString()
                friends[service] = map(unicode, QSettings("blain",
                    "%s-%s-friends" % (account_id[service], service)).allKeys())
        friends = drug(**friends)
        # read existing groups
        groups = []
        if pref.contains("account/identica/id"):
            groups = map(unicode, QSettings("blain",
                "%s-groups" % account_id['identica']).allKeys())

        # format: (timestamp, func, service, user, *args)
        timers = [ unicode(st.value(str(i)).toString())
                for i in range(st.value("count",0).toInt()[0]) ]

        # find new timer entries
        new_friend = {'twitter':friends.twitter , 'identica':friends.identica}
        new_friends = new_friend.keys()
        new_group = groups
        new_groups = True
        for timer in map(lambda t: unicode(t).split(","), timers):
            if timer[1] == 'user':
                if timer[3] in new_friend[timer[2]]:
                    new_friend[timer[2]].remove(timer[3])
            elif timer[1] == 'friends':
                if timer[2] in new_friends:
                    new_friends.remove(timer[2])
            elif timer[1] == 'groups':
                new_groups = False
            elif timer[1] == 'group':
                if timer[3] in new_group:
                    new_group.remove(timer[3])
        # add new friend lists
        for service in new_friends:
            timers.append("{0},friends,{1},".format(time(), service))
        # add groups update timer
        if new_groups and 'identica' in account_id:
            timers.append("{0},groups,,{1}".\
                format(time(), account_id['identica']))
        # add new groups
        for group in new_group:
            timers.append("{0},group,,{1}".format(time(), group))
        # add new friends
        for service in new_friend:
            for i, user in enumerate(new_friend[service]):
                new_friend[service][i] = "{0},user,{1},{2}".\
                    format(time(),service,user)
        # zip list(friends) of both services together
        if new_friend['twitter'] or new_friend['identica']:
            timers.extend(list(sum(zip(new_friend['identica'],
                                            new_friend['twitter']), ())))
            if len(new_friend['twitter']) > len(new_friend['identica']):
                timers.extend(new_friend['twitter'][len(new_friend['identica']):])
            else:
                timers.extend(new_friend['identica'][len(new_friend['twitter']):])
        # save new timers
        st.setValue('count',len(timers))
        for i in range(len(timers)):
            st.setValue(str(i), timers[i])
        # more python readable format
        timers = [ unicode(t).split(",") for t in timers ]
        timers = [ [float(t[0])] + t[1:] for t in timers ]
        self.timers = timers
        # start timers
        self.updates.user = self.user
        self.updates.group = self.group
        self.updates.groups = self.groups
        self.updates.friends = self.friends
        self.timer.setInterval(
            pref.value("timer/interval",1e4).toInt()[0]) # 10 sec
        if pref.value("timer/active", True).toBool():
            self.timer.start()


    def new_updates(self, service, user, new_time, break_): # new_updates count
        cur, n = None, -1
        for i, timer in enumerate(self.timers):
            if break_(timer):
                n, cur = i, timer
                break
        if cur is None: return
        cur[0] = new_time
        self.settings.setValue(str(n), ",".join(map(unicode, cur)))


    def user(self, service, user, count , ok): # new_updates count
        if count:
            self.app.notifier.notify_by_mode(
                amount = count, user = user)
        service, user = unicode(service), unicode(user)
        self.new_updates(service, user,
            time() - (not ok) * 5 - count / len(self.timers),
            lambda t: t[1] == "user" and t[2] == service and t[3] == user)


    def group(self, _, group, count , ok): # new_updates count
        if count:
            self.app.notifier.notify_by_mode(
                amount = count, user = "******" + group)
        user = unicode(group)
        self.new_updates("identica", group,
            time() - (not ok) * 5 - count / len(self.timers),
            lambda t: t[1] == "group" and t[3] == group)


    def groups(self, user): # new_updates count
        user = unicode(user)
        self.new_updates('identica', user, time(),
            lambda t: t[1] == "groups")


    def friends(self, service, user): # new_updates count
        service, user = unicode(service), unicode(user)
        self.new_updates(service, user, time(),
            lambda t: t[1] == "friends" and t[2] == service)


    def timer_step(self):
        print "* timer update"
        cur = self.timers[0]
        for timer in self.timers:
            if timer[0] < cur[0]:
                cur = timer
        print cur
        self.update[cur[1]](*cur[2:])


    def twitter(self, start = True):
        self.app.threads.updateMicroblogging('twitter',
            self.app.preferences.ui.twitteridEdit.text())
        ids = ['__twitter__']
        if start:
            self.app.threads.start(*ids)
            return []
        return ids


    def identica(self, start = True):
        user = self.app.preferences.ui.identicaidEdit.text()
        self.app.threads.updateMicroblogging('identica', user)
        self.app.threads.updateGroups(user)
        ids = ['__identica__', '%s groups' % user]
        if start:
            self.app.threads.start(*ids)
            return []
        return ids


    def do(self, checked):
        if checked: self.timer.start()
        else:       self.timer.stop()
        self.app.preferences.settings.setValue("timer/active", checked)


    def all(self):
        self.app.threads.start(*(self.identica(False) + self.twitter(False)))