from PyQt5.QtWidgets import QApplication, QFileDialog from PyQt5.QtCore import QSettings from qgis.core import QgsProject from .uri import Uri from os.path import relpath from os import sep from pathlib import Path def copy_path(view, reference_type, text_=None, settings=None): layer = view.currentLayer() if layer is None: return uri = Uri(layer) uri.strip_filter() path = None if reference_type == 'full path': path = uri.uri() if settings is not None and settings.dont_copy_layer_name_if_same and uri.database_layer_name_same(): path = uri.database() elif reference_type == 'database path': path = uri.database() elif reference_type == 'file name': path = uri.layer_name() if not uri.is_memory_layer(): path = f'{path}{uri.ext()}' elif reference_type == 'relative path workspace': wor = QgsProject.instance().absolutePath() if not wor: path = uri.uri() if settings is not None and settings.dont_copy_layer_name_if_same and uri.database_layer_name_same(): path = uri.database() elif Path(uri.database()).anchor != Path(wor).anchor: path = uri.uri() if settings is not None and settings.dont_copy_layer_name_if_same and uri.database_layer_name_same(): path = uri.database() else: db = relpath(uri.database(), wor) uri_ = Uri() uri_.set_database(db) if uri.is_database(): uri_.set_layer_name(uri.layer_name()) uri_.build(uri) path = uri_.uri() if settings is not None and settings.dont_copy_layer_name_if_same and uri_.database_layer_name_same(): path = uri_.database() elif reference_type == 'relative path': if not text_: wor = QFileDialog.getExistingDirectory(view, 'Relative to Directory', uri.database()) if wor is None: return else: recent_paths = QSettings().value('file_management/recent_rel_paths', []) if wor not in recent_paths: recent_paths.insert(0, wor) else: recent_paths.remove(wor) recent_paths.insert(0, wor) if len(recent_paths) > 5: recent_paths = recent_paths[:5] QSettings().setValue('file_management/recent_rel_paths', recent_paths) else: wor = text_ if not wor: path = uri.uri() if settings is not None and settings.dont_copy_layer_name_if_same and uri.database_layer_name_same(): path = uri.database() elif Path(uri.database()).anchor != Path(wor).anchor: path = uri.uri() if settings is not None and settings.dont_copy_layer_name_if_same and uri.database_layer_name_same(): path = uri.database() else: db = relpath(uri.database(), wor) uri_ = Uri() uri_.set_database(db) if uri.is_database(): uri_.set_layer_name(uri.layer_name()) uri_.build(uri) path = uri_.uri() if settings is not None and settings.dont_copy_layer_name_if_same and uri_.database_layer_name_same(): path = uri_.database() if path is not None: path = path.replace('\\', sep).replace('/', sep) if settings is not None and not settings.use_default_delimiter and '|layername=' in path: path = path.replace('|layername=', settings.custom_delimiter) clipboard = QApplication.clipboard() clipboard.setText(path)