def show_splash(version=''): splash_fname = utils.get_resource_path('icons/splash.jpg') splash_pix = QPixmap(splash_fname) size = splash_pix.size()*.35 splash_pix = splash_pix.scaled(size, Qt.KeepAspectRatio, transformMode=Qt.SmoothTransformation) numbers = {} for number in list(range(10)) + ['point']: fname = utils.get_resource_path('icons/{}.png'.format(number)) pix = QPixmap(fname) size = pix.size() * .65 numbers[str(number)] = pix.scaled(size, Qt.KeepAspectRatio, transformMode=Qt.SmoothTransformation) numbers['.'] = numbers['point'] painter = QPainter(splash_pix) painter.begin(splash_pix) x, y = 470, 70 for digit in version: painter.drawPixmap(x, y, numbers[digit]) x += numbers[digit].rect().width()/3 painter.end() splash = QSplashScreen(splash_pix, Qt.WindowStaysOnBottomHint) splash.show() return splash
def validate_xml(xml, xsl_fname='fgdc', as_dataframe=False): """ Parameters ---------- xml : lxml document or filename or string containing xml representation xsl_fname : str (optional) can be one of: 'fgdc' - uses the standard fgdc schema ../resources/FGDC/fgdc-std-001-1998-annotated.xsd 'bdp' = use the Biological Data profile schema, ../resources/FGDC/BDPfgdc-std-001-1998-annotated.xsd full file path to another local schema. if not specified defaults to 'fgdc' Returns ------- list of tuples ( """ if xsl_fname.lower() == 'fgdc': xsl_fname = utils.get_resource_path('fgdc/fgdc-std-001-1998-annotated.xsd') elif xsl_fname.lower() == 'bdp': xsl_fname = utils.get_resource_path('fgdc/BDPfgdc-std-001-1998-annotated.xsd') else: xsl_fname = xsl_fname xmlschema_doc = etree.parse(xsl_fname) xmlschema = etree.XMLSchema(xmlschema_doc) xml_str = xml_utils.node_to_string(xml_utils.xml_document_loader(xml)) tree = etree.ElementTree(etree.fromstring(xml_str)) if xmlschema.validate(tree): return [] # tree = etree.ElementTree(xml) line_lookup = dict([(e.sourceline, tree.getpath(e)) for e in tree.xpath('.//*')]) line_lookup[tree.getroot().sourceline] = tree.getpath(tree.getroot()) errors = [] for error in xmlschema.error_log: try: errors.append((line_lookup[error.line][1:], clean_error_message(error.message), error.line)) except KeyError: errors.append(('Unknown', clean_error_message(error.message), error.line)) if as_dataframe: cols = ['xpath', 'message', 'line number'] return pd.DataFrame.from_records(errors, columns=cols) else: return errors
def format_errors(xml_document, which="bdp"): if which == "bdp": xsl_fname = utils.get_resource_path("FGDC/BDPfgdc-std-001-1998-annotated.xsd") else: xsl_fname = utils.get_resource_path("FGDC/fgdc-std-001-1998-annotated.xsd") return fgdc_utils.validate_xml(xml_document.record, xsl_fname)
def validate(self): """ Check the current record against the schema and highlight any error widgets Returns ------- None """ if self.metadata_root.schema == 'bdp': xsl_fname = utils.get_resource_path('FGDC/BDPfgdc-std-001-1998-annotated.xsd') else: xsl_fname = utils.get_resource_path('FGDC/fgdc-std-001-1998-annotated.xsd') from pymdwizard.core import fgdc_utils errors = fgdc_utils.validate_xml(self.metadata_root._to_xml(), xsl_fname) self.clear_validation() marked_errors = [] self.widget_lookup = self.metadata_root.make_tree(widget=self.metadata_root) error_count = 0 for error in errors: xpath, error_msg, line_num = error if xpath not in marked_errors: action = QAction(self, visible=True) action.setText(error_msg) action.setData(xpath) action.triggered.connect(self.goto_error) self.ui.menuErrors.addAction(action) marked_errors.append(xpath) # widget = self.metadata_root.get_widget(xpath) widgets = self.widget_lookup.xpath_march(xpath, as_list=True) for widget in widgets: if isinstance(widget, list): for w in widget: print('problem highlighting error', xpath, widget) else: self.highlight_error(widget.widget, error_msg) self.error_widgets.append(widget.widget) error_count += 1 if errors: msg = "There are {} errors in this record".format(error_count) self.statusBar().showMessage(msg, 20000) msg += "\n\n These errors are highlighted in red in the form below." msg += "\n\n These errors are also listed in the Validation Menu's Errors submenu item above." msg += "\n Clicking each error will take you to the section it is contained in." msg += "\n Note that some highlighed errors can be in collapsed items, scrolled out of view, or in non-selected tabs" QMessageBox.warning(self, "Validation", msg) else: msg = "Congratulations there were No FGDC Errors!" self.statusBar().showMessage(msg, 20000) QMessageBox.information(self, "Validation", msg)
def validate(self): if self.metadata_root.schema == 'bdp': xsl_fname = utils.get_resource_path('FGDC/BDPfgdc-std-001-1998-annotated.xsd') else: xsl_fname = utils.get_resource_path('FGDC/fgdc-std-001-1998-annotated.xsd') from pymdwizard.core import fgdc_utils errors = fgdc_utils.validate_xml(self.metadata_root._to_xml(), xsl_fname) self.clear_validation() for error in errors: xpath, error_msg, line_num = error widget = self.metadata_root.get_widget(xpath) self.error_widgets.append(widget) if widget.objectName() not in ['metadata_root', 'fgdc_metadata']: widget.setToolTip(error_msg) widget.setStyleSheet( """ QGroupBox#{widgetname}{{ background-color: rgb(255,76,77); border: 2px solid red; subcontrol-position: top left; /* position at the top left*/ padding-top: 20px; font: bold 14px; color: rgb(90, 90, 90); }} QGroupBox#{widgetname}::title {{ text-align: left; subcontrol-origin: padding; subcontrol-position: top left; /* position at the top center */padding: 3 3px; }} QLabel{{ font: 9pt "Arial"; color: rgb(90, 90, 90); }} QLineEdit#{widgetname}, QPlainTextEdit#{widgetname}, QComboBox#{widgetname} {{ font: 9pt "Arial"; color: rgb(50, 50, 50); background-color: rgb(255,76,77); opacity: 25; }} QToolTip {{ background-color: rgb(255,76,77); border-color: red; opacity: 255; }} """.format(widgetname=widget.objectName()))
def build_ui(self): """ Build and modify this widget's GUI Returns ------- None """ self.ui = self.ui_class() self.ui.setupUi(self) self.ui.map_viewer.hide() self.view = self.view = QWebView() self.view.page().mainFrame().addToJavaScriptWindowObject("Spdom", self) map_fname = utils.get_resource_path('leaflet/map.html') self.view.setUrl(QUrl.fromLocalFile(map_fname)) self.ui.verticalLayout_3.addWidget(self.view) # this is where more complex build information would go such as # instantiating child widgets, inserting them into the layout, # tweaking the layout or individual widget properties, etc. # If you are using this base class as intended this should not # include extensive widget building from scratch. # setup drag-drop functionality for this widget and all it's children. self.setup_dragdrop(self) self.in_update = False self.raise_()
def populate_tooltips(self): import json annotation_lookup_fname = utils.get_resource_path('FGDC/bdp_lookup') try: with open(annotation_lookup_fname, encoding='utf-8') as data_file: annotation_lookup = json.loads(data_file.read()) except TypeError: with open(annotation_lookup_fname) as data_file: annotation_lookup = json.loads(data_file.read()) if self.objectName().startswith('fgdc_'): shortname = self.objectName().replace('fgdc_', '') if shortname[-1].isdigit(): shortname = shortname[:-1] self.help_text = annotation_lookup[shortname]['annotation'] widgets = self.findChildren(QObject, QRegExp(r'.*')) for widget in widgets: if widget.objectName().startswith('fgdc_'): shortname = widget.objectName().replace('fgdc_', '') if shortname[-1].isdigit(): shortname = shortname[:-1] widget.help_text = annotation_lookup[shortname]['annotation'] if not self.help_text: self.help_text = annotation_lookup[shortname]['annotation']
def load_settings(self): self.settings = QSettings('USGS', 'pymdwizard') template_fname = self.settings.value('template_fname') if template_fname is None: template_fname = utils.get_resource_path('CSDGM_Template.xml') self.ui.template_fname.setText(template_fname) use_spelling = self.settings.value('use_spelling', True) if use_spelling == 'true': self.ui.spelling_on.setChecked(True) else: self.ui.spelling_off.setChecked(True) max_rows = self.settings.value('maxrows', 1000000) self.ui.maxrows.setText(str(max_rows)) defsource = self.settings.value('defsource', 'Producer defined') self.ui.defsource.setText(defsource) fontfamily = self.settings.value('fontfamily', 'Arial') self.ui.font.setFont(QFont(fontfamily)) self.ui.font.setCurrentFont(QFont(fontfamily)) fontsize = self.settings.value('fontsize', 9) self.ui.font_size.setValue(fontsize)
def preview(self): """ Shows a preview window with the xml content rendered using stylesheet Returns ------- None """ xsl_fname = utils.get_resource_path("FGDC/FGDC_Stylesheet.xsl") transform = xml_utils.load_xslt(xsl_fname) result = transform(self.metadata_root.to_xml()) tmp = tempfile.NamedTemporaryFile(suffix=".html") tmp.close() result.write(tmp.name) self.preview = Preview(url=tmp.name) self.preview_dialog = QDialog(self) self.preview_dialog.setWindowTitle("Metadata Preview") self.preview_dialog.setLayout(self.preview.layout()) self.preview_dialog.resize(600, 600) self.preview_dialog.exec_()
def __init__(self, root_widget=None): self.east = 180 self.west = -180 self.north = 90 self.south = -90 self.valid = True super(self.__class__, self).__init__() self.schema = "bdp" self.root_widget = root_widget self.after_load = False self.in_xml_load = False self.has_rect = True self.completer = QCompleter() self.ui.fgdc_descgeog.setCompleter(self.completer) self.model = QStringListModel() self.completer.setModel(self.model) self.completer.setCaseSensitivity(0) fname = utils.get_resource_path("spatial/BNDCoords.csv") self.bnds_df = pd.read_csv(fname) self.model.setStringList(self.bnds_df["Name"]) self.completer.popup().clicked.connect(self.on_completer_activated) self.completer.popup().selectionModel().selectionChanged.connect( self.on_completer_activated)
def __init__(self, root_widget=None): self.east = 180 self.west = -180 self.north = 90 self.south = -90 self.valid = True super(self.__class__, self).__init__() self.schema = 'bdp' self.root_widget = root_widget self.after_load = False self.in_xml_load = False self.has_rect = True completer = QCompleter() self.ui.fgdc_descgeog.setCompleter(completer) model = QStringListModel() completer.setModel(model) completer.setCaseSensitivity(0) fname = utils.get_resource_path("spatial/BNDCoords.csv") self.bnds_df = pd.read_csv(fname) model.setStringList(self.bnds_df['Name'])
def launch_main(xml_fname=None, introspect_fname=None): app = QApplication(sys.argv) import time start = time.time() splash_fname = utils.get_resource_path('icons/splash.jpg') splash_pix = QPixmap(splash_fname) size = splash_pix.size()*.35 splash_pix = splash_pix.scaled(size, Qt.KeepAspectRatio, transformMode=Qt.SmoothTransformation) # # below makes the pixmap half transparent painter = QPainter(splash_pix) painter.setCompositionMode(painter.CompositionMode_DestinationAtop) painter.end() splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.show() app.processEvents() time.sleep(2) app.processEvents() mdwiz = PyMdWizardMainForm() mdwiz.show() splash.finish(mdwiz) if xml_fname is not None and os.path.exists(xml_fname): mdwiz.open_file(xml_fname) if introspect_fname is not None and os.path.exists(introspect_fname): mdwiz.metadata_root.eainfo.detaileds[0].populate_from_fname(introspect_fname) mdwiz.metadata_root.eainfo.ui.fgdc_eainfo.setCurrentIndex(1) app.exec_()
def new_record(self): """ Create a new record. Starts by making a copy of the template file 'CSDGM_Template.xml'. in the resources folder to a name selected in a save as dialog. Then updates the MD date to today. Returns ------- None """ self.load_default() save_as_fname = self.get_save_name() if save_as_fname: template_fname = self.settings.value("template_fname") if template_fname is None or not os.path.exists(template_fname): template_fname = utils.get_resource_path("CSDGM_Template.xml") shutil.copyfile(template_fname, save_as_fname) self.load_file(save_as_fname) self.set_current_file(save_as_fname) self.update_recent_file_actions() today = fgdc_utils.format_date(datetime.datetime.now()) self.metadata_root.metainfo.metd.set_date(today) this_year = today[:4] self.metadata_root.idinfo.citation.ui.pubdate_widget.set_date(this_year)
def load_settings(self): self.settings = QSettings("USGS_2.0.7", "pymdwizard_2.0.7") template_fname = self.settings.value("template_fname") if template_fname is None: template_fname = utils.get_resource_path("CSDGM_Template.xml") self.ui.template_fname.setText(template_fname) use_spelling = self.settings.value("use_spelling", True) if use_spelling == "true": self.ui.spelling_on.setChecked(True) else: self.ui.spelling_off.setChecked(True) max_rows = self.settings.value("maxrows", 1000000) self.ui.maxrows.setText(str(max_rows)) defsource = self.settings.value("defsource", "Producer defined") self.ui.defsource.setText(defsource) fontfamily = self.settings.value("fontfamily", "Arial") self.ui.font.setFont(QFont(fontfamily)) self.ui.font.setCurrentFont(QFont(fontfamily)) fontsize = self.settings.value("fontsize", 9) self.ui.font_size.setValue(fontsize)
def clear_validation(self): """ Remove the error highlighting from all the error widgets Returns ------- None """ self.ui.menuErrors.clear() annotation_lookup_fname = utils.get_resource_path("FGDC/bdp_lookup") with open(annotation_lookup_fname, encoding='utf-8') as data_file: annotation_lookup = json.loads(data_file.read()) for widget in self.error_widgets: if not sip.isdeleted(widget) and \ widget.objectName() not in ['metadata_root', 'fgdc_metadata']: widget.setStyleSheet("""""") shortname = widget.objectName().replace('fgdc_', '') if shortname[-1].isdigit(): shortname = shortname[:-1] widget.setToolTip(annotation_lookup[shortname]['annotation']) self.error_widgets = []
def build_ui(self): """ Build and modify this widget's GUI Returns ------- None """ self.ui = self.ui_class() self.ui.setupUi(self) if platform.system() == "Darwin": map_fname = utils.get_resource_path("leaflet/map_mac.html") else: map_fname = utils.get_resource_path("leaflet/map.html") try: self.view = QWebView() self.view.page().mainFrame().addToJavaScriptWindowObject( "Spdom", self) self.view.setUrl(QUrl.fromLocalFile(map_fname)) self.frame = self.view.page().mainFrame() self.view.load( QUrl.fromLocalFile(QtCore.QDir.current().filePath(map_fname))) except AttributeError: self.view = QWebView() self.view.load( QUrl.fromLocalFile(QtCore.QDir.current().filePath(map_fname))) channel = QWebChannel(self.view.page()) jstr = """ var spdom; new QWebChannel(qt.webChannelTransport, function (channel) { spdom = channel.objects.spdom; });""" self.view.page().setWebChannel(channel) self.evaluate_js(jstr) channel.registerObject("spdom", self) self.ui.verticalLayout_3.addWidget(self.view) # setup drag-drop functionality for this widget and all it's children. self.setup_dragdrop(self) self.add_rect() self.raise_()
def load_default(self): template_fname = self.settings.value("template_fname") if template_fname is None: template_fname = utils.get_resource_path("CSDGM_Template.xml") elif not os.path.exists(template_fname): msg = ("The previous template file specified, {}, could not be " "found.".format(template_fname)) msg += "\nCheck that the file has not beed deleted, renamed " "or moved." msg += "Defaulting to the built in template.".format( template_fname) QMessageBox.warning(self, "Template file missing", msg) template_fname = utils.get_resource_path("CSDGM_Template.xml") self.load_file_content(template_fname) self.cur_fname = "" today = fgdc_utils.format_date(datetime.datetime.now()) self.metadata_root.metainfo.metd.set_date(today)
def show_splash(version="2.x.x"): """ Show the applications splash screen Parameters ---------- version : str Version number as a string (only numerals, period or x supported) Returns ------- None """ splash_fname = utils.get_resource_path("icons/splash.jpg") splash_pix = QPixmap(splash_fname) size = splash_pix.size() * 0.35 splash_pix = splash_pix.scaled( size, Qt.KeepAspectRatio, transformMode=Qt.SmoothTransformation ) numbers = {} for number in list(range(10)) + ["point", "x"]: fname = utils.get_resource_path("icons/{}.png".format(number)) pix = QPixmap(fname) size = pix.size() * 0.65 numbers[str(number)] = pix.scaled( size, Qt.KeepAspectRatio, transformMode=Qt.SmoothTransformation ) numbers["."] = numbers["point"] painter = QPainter(splash_pix) painter.begin(splash_pix) x, y = 470, 70 for digit in version: painter.drawPixmap(x, y, numbers[digit]) x += numbers[digit].rect().width() / 3 painter.end() splash = QSplashScreen(splash_pix, Qt.WindowStaysOnBottomHint) splash.show() return splash
def draw_js_map(self): js_fname = utils.get_resource_path('leaflet/map.js') with open(js_fname, 'r') as f: js_str = f.read() js_str = js_str.replace('east_var', str(self.east)) js_str = js_str.replace('west_var', str(self.west)) js_str = js_str.replace('north_var', str(self.north)) js_str = js_str.replace('south_var', str(self.south)) frame = self.view.page().mainFrame() frame.evaluateJavaScript(js_str)
def load_words(): fname = utils.get_resource_path("spelling/words.txt") global word_set try: word_set = set(line.strip() for line in open(fname, 'r')) except UnicodeDecodeError: word_set = set(line.strip() for line in open(fname, 'r', encoding='latin-1')) return word_set
def load_default(self): settings = QSettings('USGS', 'pymdwizard') template_fname = settings.value('template_fname') if template_fname is None: template_fname = utils.get_resource_path('CSDGM_Template.xml') self.load_file_content(template_fname) self.cur_fname = '' today = fgdc_utils.format_date(datetime.datetime.now()) self.metadata_root.metainfo.metd.set_date(today)
def main(): app = QApplication(sys.argv) import time start = time.time() splash_fname = utils.get_resource_path('icons/splash_ducks.jpg') splash_pix = QPixmap(splash_fname) size = splash_pix.size()*.55 splash_pix = splash_pix.scaled(size, Qt.KeepAspectRatio, transformMode=Qt.SmoothTransformation) # below makes the pixmap half transparent painter = QPainter(splash_pix) painter.setCompositionMode(painter.CompositionMode_DestinationAtop) painter.fillRect(splash_pix.rect(), QColor(0, 0, 0, 100)) font = QFont() font.setFamily('Arial') font.setPointSize(40) font.setBold(True) painter.setFont(font) painter.setPen(QColor(250, 250, 250)) painter.drawText(splash_pix.rect(), Qt.AlignCenter, "Metadata Wizard") font = QFont() font.setFamily('Arial') font.setPointSize(19) font.setBold(True) painter.setFont(font) painter.setPen(QColor(150, 150, 150, 200)) painter.drawText(splash_pix.rect().adjusted(20, -20, -20, -20), Qt.AlignBottom, "version 0.0.0 pre-pre Alpha") painter.end() splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.show() app.processEvents() time.sleep(2) app.processEvents() mdwiz = PyMdWizardMainForm() mdwiz.show() splash.finish(mdwiz) app.exec_()
def get_fgdc_lookup(): """ Loads the local resource, 'bdp_lookup' into a json object Returns ------- json fgdc item lookup """ annotation_lookup_fname = utils.get_resource_path("FGDC/bdp_lookup") try: with open(annotation_lookup_fname, encoding="utf-8") as data_file: annotation_lookup = json.loads(data_file.read()) except TypeError: with open(annotation_lookup_fname) as data_file: annotation_lookup = json.loads(data_file.read()) return annotation_lookup
def load_projection(self): projection_name = self.ui.fgdc_mapprojn.currentText() projection = spatial_utils.PROJECTION_LOOKUP[projection_name] annotation_lookup_fname = utils.get_resource_path('fgdc/bdp_lookup') try: with open(annotation_lookup_fname, encoding='utf-8') as data_file: annotation_lookup = json.loads(data_file.read()) except TypeError: with open(annotation_lookup_fname) as data_file: annotation_lookup = json.loads(data_file.read()) annotation_lookup['stdparl_2'] = {'long_name':'Standard Parallel', 'annotation':annotation_lookup['stdparll']['annotation']} # widgets = self.findChildren(QObject, QRegExp(r'.*')) # for widget in widgets: # if widget.objectName().startswith('fgdc_'): # shortname = widget.objectName().replace('fgdc_', '') # if shortname[-1].isdigit(): # shortname = shortname[:-1] # widget.setToolTip(annotation_lookup[shortname]['annotation']) layout = self.ui.scrollAreaWidgetContents.layout() while layout.count(): child = layout.takeAt(0) if child.widget(): child.widget().deleteLater() for param in projection['elements']: try: long_name = annotation_lookup[param]['long_name'] annotation = annotation_lookup[param]['annotation'] except: long_name = param annotation = 'Unknown' label = QLabel(long_name) label.setToolTip(annotation) lineedit = QLineEdit('...') lineedit.setObjectName('fgdc_' + param) lineedit.setToolTip(annotation) layout.addRow(label, lineedit)
def new_record(self): """ Create a new record. Starts by making a copy of the template file 'CSDGM_Template.xml'. in the resources folder to a name selected in a save as dialog. Then updates the MD date to today. Returns ------- None """ self.load_default() save_as_fname = self.get_save_name() if save_as_fname: template_fname = utils.get_resource_path('CSDGM_Template.xml') shutil.copyfile(template_fname, save_as_fname) self.load_file(save_as_fname) self.set_current_file(save_as_fname) self.update_recent_file_actions() today = fgdc_utils.format_date(datetime.datetime.now()) self.metadata_root.metainfo.metd.set_date(today)
def load_gridsys(self): gridsys_name = self.ui.fgdc_gridsysn.currentText() projection = spatial_utils.GRIDSYS_LOOKUP[gridsys_name] annotation_lookup_fname = utils.get_resource_path('fgdc/bdp_lookup') try: with open(annotation_lookup_fname, encoding='utf-8') as data_file: annotation_lookup = json.loads(data_file.read()) except TypeError: with open(annotation_lookup_fname) as data_file: annotation_lookup = json.loads(data_file.read()) layout = self.ui.gridsys_contents.layout() while layout.count(): child = layout.takeAt(0) if child.widget(): child.widget().deleteLater() for param in projection['elements']: try: long_name = annotation_lookup[param]['long_name'] annotation = annotation_lookup[param]['annotation'] except: long_name = param annotation = 'Unknown' label = QLabel(long_name) label.setToolTip(annotation) label.help_text = annotation lineedit = QLineEdit('...') lineedit.setObjectName('fgdc_' + param) lineedit.setToolTip(annotation) layout.addRow(label, lineedit) gridsys_proj = spatial_utils.PROJECTION_LOOKUP[ projection['projection']] self.grid_mapproj.load_projection(gridsys_proj['shortname'])
def build_ui(self): """ Build and modify this widget's GUI Returns ------- None """ self.ui = UI_MainWindow.Ui_MainWindow() self.ui.setupUi(self) self.icon = QIcon(utils.get_resource_path('icons/Ducky.ico')) self.setWindowIcon(self.icon) self.metadata_root = MetadataRoot() self.ui.centralwidget.layout().addWidget(self.metadata_root) for i in range(PyMdWizardMainForm.max_recent_files): self.recent_file_actions.append( QAction(self, visible=False, triggered=self.open_recent_file)) self.ui.menuRecent_Files.addAction(self.recent_file_actions[i]) self.update_recent_file_actions()
def load_projection(self, shortname): self.clear_widget() self.shortname = shortname self.projection = spatial_utils.lookup_shortname(shortname) annotation_lookup_fname = utils.get_resource_path('fgdc/bdp_lookup') try: with open(annotation_lookup_fname, encoding='utf-8') as data_file: annotation_lookup = json.loads(data_file.read()) except TypeError: with open(annotation_lookup_fname) as data_file: annotation_lookup = json.loads(data_file.read()) annotation_lookup['stdparll_2'] = { 'long_name': 'Standard Parallel', 'annotation': annotation_lookup['stdparll']['annotation'] } self.clear_widget() layout = self.ui.mapproj_contents.layout() for param in self.projection['elements']: try: long_name = annotation_lookup[param]['long_name'] annotation = annotation_lookup[param]['annotation'] except: long_name = param annotation = 'Unknown' label = QLabel(long_name) label.setToolTip(annotation) label.help_text = annotation lineedit = QLineEdit('...') lineedit.setObjectName('fgdc_' + param) lineedit.setToolTip(annotation) layout.addRow(label, lineedit)
def preview(self): """ Shows a preview window with the xml content rendered using stylesheet Returns ------- None """ xsl_fname = utils.get_resource_path("FGDC/FGDC_Stylesheet.xsl") transform = etree.XSLT(etree.parse(xsl_fname)) result = transform(self.metadata_root._to_xml()) tmp = tempfile.NamedTemporaryFile(suffix='.html') tmp.close() result.write(tmp.name) self.preview = Preview(url=tmp.name) self.preview_dialog = QDialog(self) self.preview_dialog.setWindowTitle('Metadata Preview') self.preview_dialog.setLayout(self.preview.layout()) self.preview_dialog.exec_()
def validate(self): """ Check the current record against the schema and highlight any error widgets Returns ------- None """ self.error_list_dialog.show() if self.metadata_root.schema == "bdp": xsl_fname = utils.get_resource_path( "FGDC/BDPfgdc-std-001-1998-annotated.xsd" ) else: xsl_fname = utils.get_resource_path("FGDC/fgdc-std-001-1998-annotated.xsd") from pymdwizard.core import fgdc_utils errors = fgdc_utils.validate_xml(self.metadata_root.to_xml(), xsl_fname) self.clear_validation() marked_errors = [] # We need to expand / populate all attributes that have an error for error in errors: try: xpath, error_msg, line_num = error if "attr" in xpath: try: detailed_index = xpath.split("/detailed[")[1].split("/")[0][:-1] detailed_index = int(detailed_index) - 1 except IndexError: detailed_index = 0 try: attr_index = xpath.split("/attr[")[1].split("/")[0][:-1] attr_index = int(attr_index) - 1 except IndexError: attr_index = 0 self.metadata_root.eainfo.detaileds[ detailed_index ].attributes.attrs[attr_index].regular_me() self.metadata_root.eainfo.detaileds[ detailed_index ].attributes.attrs[attr_index].supersize_me() except: pass widget_lookup = self.metadata_root.make_tree(widget=self.metadata_root) self.metadata_root.add_children( self.metadata_root.spatial_tab, widget_lookup.metadata.idinfo ) self.metadata_root.add_children( self.metadata_root.dataqual.sourceinput, widget_lookup.metadata.dataqual.lineage, ) error_count = 0 for error in errors: try: xpath, error_msg, line_num = error if xpath not in marked_errors: self.error_list.add_error(error_msg, xpath) marked_errors.append(xpath) # widget = self.metadata_root.get_widget(xpath) widgets = widget_lookup.xpath_march(xpath, as_list=True) for widget in widgets: if isinstance(widget, list): for w in widget: print("problem highlighting error", xpath, widget) else: self.highlight_error(widget.widget, error_msg) self.error_widgets.append(widget.widget) error_count += 1 except BaseException as e: import traceback msg = "Error encountered highlighting error:" msg += "\t" + xpath msg += "\n\n" + traceback.format_exc() QMessageBox.warning(self, "Bug encountered", msg) widget_lookup = self.metadata_root.make_tree(widget=self.metadata_root) if errors: msg = "There are {} errors in this record".format(error_count) self.statusBar().showMessage(msg, 20000) msg += "\n\n These errors are highlighted in red in the form below." msg += "\n\n These errors are also listed in the Validation Errors Form that just popped up." msg += "\n Clicking each error will take you to the section it is contained in." msg += "\n Note that some highlighed errors can be in collapsed items, scrolled out of view, or in non-selected tabs" QMessageBox.warning(self, "Validation", msg) self.error_list_dialog.show() else: msg = "Congratulations there were No FGDC Errors!" self.statusBar().showMessage(msg, 20000) QMessageBox.information(self, "Validation", msg)