def _process_cache(self): """ Actually does the work. """ log.debug('_processCache') image = self._conversion_queue.get()[2] # Generate the QImage for the image. if image.image is None: # Let's see if the image was requested with specific dimensions width = self.width if image.width == -1 else image.width height = self.height if image.height == -1 else image.height image.image = resize_image( image.path, width, height, image.background, Settings().value('advanced/ignore aspect ratio')) # Set the priority to Lowest and stop here as we need to process more important images first. if image.priority == Priority.Normal: self._conversion_queue.modify_priority(image, Priority.Lowest) return # For image with high priority we set the priority to Low, as the byte stream might be needed earlier the # byte stream of image with Normal priority. We stop here as we need to process more important images first. elif image.priority == Priority.High: self._conversion_queue.modify_priority(image, Priority.Low) return # Generate the byte stream for the image. if image.image_bytes is None: image.image_bytes = image_to_byte(image.image)
def udp_start(self): """ Start listening on UDP port """ log.debug('(UDP:{port}) Start called'.format(port=self.port)) self.readyRead.connect(self.get_datagram) self.check_settings(checked=Settings().value('projector/udp broadcast listen'))
def set_search_types(self, items): """ A list of tuples to be used in the search type menu. The first item in the list will be preselected as the default. :param items: The list of tuples to use. The tuples should contain an integer identifier, an icon (QIcon instance or string) and a title for the item in the menu. In short, they should look like this:: (<identifier>, <icon>, <title>, <place holder text>) For instance:: (1, <QIcon instance>, "Titles", "Search Song Titles...") Or:: (2, ":/songs/authors.png", "Authors", "Search Authors...") """ menu = QtWidgets.QMenu(self) for identifier, icon, title, placeholder in items: action = create_widget_action( menu, text=title, icon=icon, data=identifier, triggers=self._on_menu_action_triggered) action.placeholder_text = placeholder if not hasattr(self, 'menu_button'): self.menu_button = QtWidgets.QToolButton(self) self.menu_button.setIcon(UiIcons().shortcuts) self.menu_button.setCursor(QtCore.Qt.ArrowCursor) self.menu_button.setPopupMode(QtWidgets.QToolButton.InstantPopup) self.menu_button.setStyleSheet('QToolButton { border: none; padding: 0px 10px 0px 0px; }') self.menu_button.resize(QtCore.QSize(28, 18)) self.menu_button.setMenu(menu) self.set_current_search_type( Settings().value('{section}/last used search type'.format(section=self.settings_section))) self.menu_button.show() self._update_style_sheet()
def _set_plugin_status(self, field, tag): """ Set the status of a plugin. """ status = PluginStatus.Active if field.checkState( ) == QtCore.Qt.Checked else PluginStatus.Inactive Settings().setValue(tag, status)
def is_data_path_missing(): """ Check if the data folder path exists. """ data_folder_path = AppLocation.get_data_path() if not data_folder_path.exists(): log.critical('Database was not found in: %s', data_folder_path) status = QtWidgets.QMessageBox.critical( None, translate('OpenLP', 'Data Directory Error'), translate( 'OpenLP', 'OpenLP data folder was not found in:\n\n{path}\n\nThe location of the data folder ' 'was previously changed from the OpenLP\'s default location. If the data was ' 'stored on removable device, that device needs to be made available.\n\nYou may ' 'reset the data location back to the default location, or you can try to make the ' 'current location available.\n\nDo you want to reset to the default data location? ' 'If not, OpenLP will be closed so you can try to fix the the problem.' ).format(path=data_folder_path), QtWidgets.QMessageBox.StandardButtons( QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No), QtWidgets.QMessageBox.No) if status == QtWidgets.QMessageBox.No: # If answer was "No", return "True", it will shutdown OpenLP in def main log.info('User requested termination') return True # If answer was "Yes", remove the custom data path thus resetting the default location. Settings().remove('advanced/data path') log.info( 'Database location has been reset to the default settings.') return False
def on_search_button_clicked(self): """ Run a search on SongSelect. """ # Set up UI components self.view_button.setEnabled(False) self.search_button.setEnabled(False) self.search_combobox.setEnabled(False) self.search_progress_bar.setMinimum(0) self.search_progress_bar.setMaximum(0) self.search_progress_bar.setValue(0) self.set_progress_visible(True) self.search_results_widget.clear() self.result_count_label.setText( translate('SongsPlugin.SongSelectForm', 'Found {count:d} song(s)').format(count=self.song_count)) self.application.process_events() self.song_count = 0 search_history = self.search_combobox.getItems() Settings().setValue( self.plugin.settings_section + '/songselect searches', '|'.join(search_history)) # Create thread and run search worker = SearchWorker(self.song_select_importer, self.search_combobox.currentText()) worker.show_info.connect(self.on_search_show_info) worker.found_song.connect(self.on_search_found_song) worker.finished.connect(self.on_search_finished) run_thread(worker, 'songselect')
def set_global_theme(self): """ Set the global-level theme name. """ global_theme_name = Settings().value('themes/global theme') self._set_theme(global_theme_name) self.global_theme_name = global_theme_name
def test_requires_auth_missing_credentials(self): """ Test the requires_auth wrapper with enabled security and authorization taken place and and error :return: """ # GIVEN: An enabled security and a known user Settings().setValue('api/authentication enabled', True) Settings().setValue('api/user id', 'superfly') Settings().setValue('api/password', 'lamas') # WHEN: I call the function with no password wrapped_function = requires_auth(func) value = wrapped_function(0) # THEN: the result will be as expected (unauthorized) assert str(value) == str(authenticate())
def setUp(self): """ Set up the components need for all tests. """ Registry.create() Registry().register('service_list', MagicMock()) Registry().register('main_window', MagicMock()) self.mocked_plugin = MagicMock() with patch('openlp.core.lib.mediamanageritem.MediaManagerItem._setup'), \ patch('openlp.plugins.songs.forms.editsongform.EditSongForm.__init__'): self.media_item = SongMediaItem(None, self.mocked_plugin) self.media_item.save_auto_select_id = MagicMock() self.media_item.list_view = MagicMock() self.media_item.list_view.save_auto_select_id = MagicMock() self.media_item.list_view.clear = MagicMock() self.media_item.list_view.addItem = MagicMock() self.media_item.list_view.setCurrentItem = MagicMock() self.media_item.auto_select_id = -1 self.media_item.display_songbook = False self.media_item.display_copyright_symbol = False self.setup_application() self.build_settings() Settings().extend_default_settings(__default_settings__) self.settings = self.setting Registry().register('settings', self.settings) QtCore.QLocale.setDefault(QtCore.QLocale('en_GB'))
def validateCurrentPage(self): """ Re-implement the validateCurrentPage() method. Validate the current page before moving on to the next page. Provide each song format class with a chance to validate its input by overriding is_valid_source(). """ if self.currentPage() == self.welcome_page: return True elif self.currentPage() == self.source_page: this_format = self.current_format Settings().setValue('songs/last import type', this_format) select_mode, class_, error_msg = SongFormat.get(this_format, 'selectMode', 'class', 'invalidSourceMsg') if select_mode == SongFormatSelect.MultipleFiles: import_source = self.get_list_of_paths(self.format_widgets[this_format]['file_list_widget']) error_title = UiStrings().IFSp focus_button = self.format_widgets[this_format]['addButton'] else: import_source = self.format_widgets[this_format]['path_edit'].path error_title = (UiStrings().IFSs if select_mode == SongFormatSelect.SingleFile else UiStrings().IFdSs) focus_button = self.format_widgets[this_format]['path_edit'] if not class_.is_valid_source(import_source): critical_error_message_box(error_title, error_msg) focus_button.setFocus() return False return True elif self.currentPage() == self.progress_page: return True
def setUp(self): """ Set up the environment for testing bible queries with 1 Timothy 3 """ self.setup_application() self.build_settings() Registry.create() Registry().register('service_list', MagicMock()) Registry().register('application', MagicMock()) bible_settings = { 'bibles/proxy name': '', 'bibles/db type': 'sqlite', 'bibles/book name language': LanguageSelection.Bible, 'bibles/verse separator': '', 'bibles/range separator': '', 'bibles/list separator': '', 'bibles/end separator': '', } Settings().extend_default_settings(bible_settings) with patch('openlp.core.common.applocation.Settings') as mocked_class, \ patch('openlp.core.common.applocation.AppLocation.get_section_data_path') as mocked_get_data_path, \ patch('openlp.core.common.applocation.AppLocation.get_files') as mocked_get_files: # GIVEN: A mocked out Settings class and a mocked out AppLocation.get_files() mocked_settings = mocked_class.return_value mocked_settings.contains.return_value = False mocked_get_files.return_value = ["tests.sqlite"] mocked_get_data_path.return_value = TEST_RESOURCES_PATH + "/bibles" self.manager = BibleManager(MagicMock())
def __recalculate_layout(self): """ Recalculates the layout of the table widget. It will set height and width of the table cells. QTableWidget does not adapt the cells to the widget size on its own. """ self.setColumnWidth(0, self.viewport().width()) if self.service_item: # Sort out songs, bibles, etc. if self.service_item.is_text(): self.resizeRowsToContents() # Sort out image heights. else: height = self.viewport().width() // self.screen_ratio max_img_row_height = Settings().value('advanced/slide max height') # Adjust for row height cap if in use. if isinstance(max_img_row_height, int): if max_img_row_height > 0 and height > max_img_row_height: height = max_img_row_height elif max_img_row_height < 0: # If auto setting, show that number of slides, or if the resulting slides too small, 100px. # E.g. If setting is -4, 4 slides will be visible, unless those slides are < 100px high. self.auto_row_height = max(self.viewport().height() / (-1 * max_img_row_height), 100) height = min(height, self.auto_row_height) # Apply new height to slides for frame_number in range(len(self.service_item.get_frames())): self.setRowHeight(frame_number, height)
def set_language(action, message=True): """ Set the language to translate OpenLP into :param action: The language menu option :param message: Display the message option """ language = 'en' if action: action_name = str(action.objectName()) if action_name == 'autoLanguageItem': LanguageManager.auto_language = True else: LanguageManager.auto_language = False qm_list = LanguageManager.get_qm_list() language = str(qm_list[action_name]) if LanguageManager.auto_language: language = '[{language}]'.format(language=language) Settings().setValue('core/language', language) log.info("Language file: '{language}' written to conf file".format( language=language)) if message: QtWidgets.QMessageBox.information( None, translate('OpenLP.LanguageManager', 'Language'), translate( 'OpenLP.LanguageManager', 'Please restart OpenLP to use your new language setting.'))
def destroy_settings(self): """ Destroy the Settings Object """ del self.setting os.close(self.fd) os.unlink(Settings().fileName())
def test_convert_value_setting_none_list(self): """Test the Settings._convert_value() method when a setting is None and the default value is a list""" # GIVEN: A settings object # WHEN: _convert_value() is run result = Settings()._convert_value(None, [None]) # THEN: The result should be an empty list assert result == [], 'The result should be an empty list'
def test_convert_value_setting_none_str(self): """Test the Settings._convert_value() method when a setting is None and the default value is a string""" # GIVEN: A settings object # WHEN: _convert_value() is run result = Settings()._convert_value(None, 'string') # THEN: The result should be an empty string assert result == '', 'The result should be an empty string'
def setUp(self): """ Create the UI """ self.build_settings() Settings().extend_default_settings(__default_settings__) Registry().create() self.poll = Poller()
def get_media_display_css(self): """ Add css style sheets to htmlbuilder """ background = QtGui.QColor( Settings().value('players/background color')).name() css = VIDEO_CSS % {'bgcolor': background} return css
def test_convert_value_setting_bool_str(self): """Test the Settings._convert_value() method when a setting is supposed to be a boolean""" # GIVEN: A settings object # WHEN: _convert_value() is run result = Settings()._convert_value('false', True) # THEN: The result should be False assert result is False, 'The result should be False'
def on_login_button_clicked(self): """ Log the user in to SongSelect. """ self.username_edit.setEnabled(False) self.password_edit.setEnabled(False) self.save_password_checkbox.setEnabled(False) self.login_button.setEnabled(False) self.login_spacer.setVisible(False) self.login_progress_bar.setValue(0) self.login_progress_bar.setVisible(True) self.application.process_events() # Log the user in if not self.song_select_importer.login(self.username_edit.text(), self.password_edit.text(), self._update_login_progress): QtWidgets.QMessageBox.critical( self, translate('SongsPlugin.SongSelectForm', 'Error Logging In'), translate( 'SongsPlugin.SongSelectForm', 'There was a problem logging in, perhaps your username or password is incorrect?' )) else: if self.save_password_checkbox.isChecked(): Settings().setValue( self.plugin.settings_section + '/songselect username', self.username_edit.text()) Settings().setValue( self.plugin.settings_section + '/songselect password', self.password_edit.text()) else: Settings().remove(self.plugin.settings_section + '/songselect username') Settings().remove(self.plugin.settings_section + '/songselect password') self.stacked_widget.setCurrentIndex(1) self.login_progress_bar.setVisible(False) self.login_progress_bar.setValue(0) self.login_spacer.setVisible(True) self.login_button.setEnabled(True) self.username_edit.setEnabled(True) self.password_edit.setEnabled(True) self.save_password_checkbox.setEnabled(True) self.search_combobox.setFocus() self.application.process_events()
def tearDown(self): Settings().remove('advanced/data path') self.destroy_settings() del self.main_window # On windows we need to manually garbage collect to close sqlalchemy files # to avoid errors when temporary files are deleted. gc.collect() self.temp_dir_path.rmtree()
def test_convert_value_setting_json_Path(self): """Test the Settings._convert_value() method when a setting is JSON and represents a Path object""" # GIVEN: A settings object # WHEN: _convert_value() is run result = Settings()._convert_value('{"__Path__": ["openlp", "core"]}', None) # THEN: The result should be a Path object assert isinstance(result, Path), 'The result should be a Path object'
def bootstrap_initialise(self): """ process the bootstrap initialise setup request """ self.setup_ui(self) self.global_theme = Settings().value(self.settings_section + '/global theme') self.build_theme_path()
def test_manual_proxy_mode_no_servers(self): """ Test that the system proxies are overidden when the MANUAL_PROXY mode is specified, but no server addresses are supplied """ # GIVEN: A `proxy mode` setting of MANUAL_PROXY with no servers specified Settings().setValue('advanced/proxy mode', ProxyMode.MANUAL_PROXY) Settings().setValue('advanced/proxy http', '') Settings().setValue('advanced/proxy https', '') Settings().setValue('advanced/proxy username', 'user') Settings().setValue('advanced/proxy password', 'pass') # WHEN: Calling `get_proxy_settings` result = get_proxy_settings() # THEN: The returned value should be the proxy servers set to None assert result == {'http': None, 'https': None}
def setUp(self): """ Create the UI """ self.setup_application() Registry.create() State().load_settings() Registry().register('settings', Settings()) self.plugin = PlanningCenterPlugin() Settings().setValue('planningcenter/application_id', 'abc') Settings().setValue('planningcenter/secret', '123') self.dialog = QtWidgets.QDialog() self.tab = PlanningCenterTab(self.dialog, 'PlanningCenter') self.tab.setup_ui() self.tab.retranslate_ui() self.tab.load() self.tab.resizeEvent()
def test_manual_proxy_mode_auth(self): """ Test that the correct proxy addresses are returned when basic authentication is used """ # GIVEN: A `proxy mode` setting of MANUAL_PROXY with proxy servers and auth credentials supplied Settings().setValue('advanced/proxy mode', ProxyMode.MANUAL_PROXY) Settings().setValue('advanced/proxy http', 'testhttp.server:port') Settings().setValue('advanced/proxy https', 'testhttps.server:port') Settings().setValue('advanced/proxy username', 'user') Settings().setValue('advanced/proxy password', 'pass') # WHEN: Calling `get_proxy_settings` result = get_proxy_settings() # THEN: The returned value should be the proxy servers with the authentication credentials assert result == {'http': 'http://*****:*****@testhttp.server:port', 'https': 'https://*****:*****@testhttps.server:port'}
def get_media_players(): """ This method extracts the configured media players and overridden player from the settings. """ log.debug('get_media_players') saved_players = Settings().value('media/players') reg_ex = QtCore.QRegExp(r'.*\[(.*)\].*') if Settings().value('media/override player') == QtCore.Qt.Checked: if reg_ex.exactMatch(saved_players): overridden_player = '{text}'.format(text=reg_ex.cap(1)) else: overridden_player = 'auto' else: overridden_player = '' saved_players_list = saved_players.replace('[', '').replace(']', '').split(',') if saved_players else [] return saved_players_list, overridden_player
def save_screen_settings(self): """ Saves the screen size and screen settings """ Settings().setValue( 'core/screens', {screen.number: screen.to_dict() for screen in self.screens})
def setupUi(self, edit_verse_dialog): edit_verse_dialog.setObjectName('edit_verse_dialog') edit_verse_dialog.setWindowIcon(UiIcons().main_icon) edit_verse_dialog.resize(400, 400) edit_verse_dialog.setModal(True) self.dialog_layout = QtWidgets.QVBoxLayout(edit_verse_dialog) self.dialog_layout.setObjectName('dialog_layout') self.verse_text_edit = SpellTextEdit(edit_verse_dialog) self.verse_text_edit.setObjectName('verse_text_edit') self.dialog_layout.addWidget(self.verse_text_edit) self.verse_type_layout = QtWidgets.QHBoxLayout() self.verse_type_layout.setObjectName('verse_type_layout') self.forced_split_button = QtWidgets.QPushButton(edit_verse_dialog) self.forced_split_button.setIcon(UiIcons().add) self.forced_split_button.setObjectName('forced_split_button') self.verse_type_layout.addWidget(self.forced_split_button) self.overflow_split_button = QtWidgets.QPushButton(edit_verse_dialog) self.overflow_split_button.setIcon(UiIcons().add) self.overflow_split_button.setObjectName('overflow_split_button') self.verse_type_layout.addWidget(self.overflow_split_button) self.verse_type_label = QtWidgets.QLabel(edit_verse_dialog) self.verse_type_label.setObjectName('verse_type_label') self.verse_type_layout.addWidget(self.verse_type_label) self.verse_type_combo_box = QtWidgets.QComboBox(edit_verse_dialog) self.verse_type_combo_box.addItems(['', '', '', '', '', '', '']) self.verse_type_combo_box.setObjectName('verse_type_combo_box') self.verse_type_label.setBuddy(self.verse_type_combo_box) self.verse_type_layout.addWidget(self.verse_type_combo_box) self.verse_number_box = QtWidgets.QSpinBox(edit_verse_dialog) self.verse_number_box.setMinimum(1) self.verse_number_box.setObjectName('verse_number_box') self.verse_type_layout.addWidget(self.verse_number_box) self.insert_button = QtWidgets.QPushButton(edit_verse_dialog) self.insert_button.setIcon(UiIcons().add) self.insert_button.setObjectName('insert_button') self.verse_type_layout.addWidget(self.insert_button) self.verse_type_layout.addStretch() self.dialog_layout.addLayout(self.verse_type_layout) if Settings().value('songs/enable chords'): self.transpose_layout = QtWidgets.QHBoxLayout() self.transpose_layout.setObjectName('transpose_layout') self.transpose_label = QtWidgets.QLabel(edit_verse_dialog) self.transpose_label.setObjectName('transpose_label') self.transpose_layout.addWidget(self.transpose_label) self.transpose_up_button = QtWidgets.QPushButton(edit_verse_dialog) self.transpose_up_button.setIcon(UiIcons().arrow_up) self.transpose_up_button.setObjectName('transpose_up') self.transpose_layout.addWidget(self.transpose_up_button) self.transpose_down_button = QtWidgets.QPushButton( edit_verse_dialog) self.transpose_down_button.setIcon(UiIcons().arrow_down) self.transpose_down_button.setObjectName('transpose_down') self.transpose_layout.addWidget(self.transpose_down_button) self.dialog_layout.addLayout(self.transpose_layout) self.button_box = create_button_box(edit_verse_dialog, 'button_box', ['cancel', 'ok']) self.dialog_layout.addWidget(self.button_box) self.retranslateUi(edit_verse_dialog)
def load(self): settings = Settings() settings.beginGroup(self.settings_section) self.background_color = settings.value('background color') self.initial_color = self.background_color settings.endGroup() self.background_color_button.color = self.background_color