<commit_before>/*
 * Copyright 2011 Corpuslinguistic working group Humboldt University Berlin.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package org.corpus_tools.annis.gui;

import com.google.common.collect.ComparisonChain;
import com.google.common.util.concurrent.FutureCallback;
import com.vaadin.data.ValueProvider;
import com.vaadin.data.provider.ListDataProvider;
import com.vaadin.shared.data.sort.SortDirection;
import com.vaadin.shared.ui.ContentMode;
import com.vaadin.ui.Accordion;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Grid;
import com.vaadin.ui.Grid.Column;
import com.vaadin.ui.Label;
import com.vaadin.ui.Panel;
import com.vaadin.ui.ProgressBar;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.corpus_tools.annis.api.model.AnnoKey;
import org.corpus_tools.annis.api.model.Annotation;
import org.corpus_tools.annis.api.model.CorpusConfiguration;
import org.corpus_tools.annis.gui.components.ExceptionDialog;
import org.corpus_tools.salt.common.SCorpus;
import org.corpus_tools.salt.common.SCorpusGraph;
import org.corpus_tools.salt.common.SDocument;
import org.corpus_tools.salt.core.SMetaAnnotation;
import org.eclipse.emf.common.util.URI;

/**
 * Provides all corpus annotations for a corpus or for a specific search result.
 *
 * // TODO cleanup the toplevelCorpus side effects.
 *
 * @author <NAME> {@literal <<EMAIL>>}
 * @author <NAME> {@literal <<EMAIL>>}
 */
public class MetaDataPanel extends Panel {

  private static class CorpusMetadataCallResult {
    SCorpusGraph metadata;
    CorpusConfiguration config;
  }

  private final class MetadataAvailableCallback
      implements FutureCallback<CorpusMetadataCallResult> {
    @Override
    public void onFailure(Throwable t) {
      layout.removeComponent(progress);
      ExceptionDialog.show(t, "Could not get meta data", getUI());
    }

    @Override
    public void onSuccess(CorpusMetadataCallResult result) {
      layout.removeComponent(progress);
      Accordion accordion = new Accordion();
      accordion.setSizeFull();


      boolean hasDocument = addDocumentMetadata(result.metadata, accordion);
      boolean hasCorpus = addCorpusMetadata(result.metadata, accordion);

      // set output to none if no metadata are available
      if (hasDocument || hasCorpus) {
        layout.addComponent(accordion);
      } else {
        addEmptyLabel();
      }
    }

    private boolean addCorpusMetadata(SCorpusGraph result, Accordion accordion) {
      boolean hasResult = false;

      // Sort the (sub-) corpora so sub-corpora come first
      List<SCorpus> corpora = new ArrayList<>(result.getCorpora());
      corpora.sort((c1, c2) -> {
        URI u1 = c1.getPath();
        URI u2 = c2.getPath();
        return ComparisonChain.start().compare(u1.segmentCount(), u2.segmentCount())
            .compare(u1.toString(), u2.toString()).result();
      });

      for (SCorpus c : corpora) {
        List<Annotation> corpusAnnos = new ArrayList<>();
        for (SMetaAnnotation metaAnno : c.getMetaAnnotations()) {
          Annotation anno = new Annotation();
          AnnoKey key = new AnnoKey();
          key.setNs(metaAnno.getNamespace());
          key.setName(metaAnno.getName());
          anno.setKey(key);
          anno.setVal(metaAnno.getValue_STEXT());
          corpusAnnos.add(anno);
        }

        if (!corpusAnnos.isEmpty()) {
          String path = c.getPath().toString();
          if (path.startsWith("salt:/")) {
            path = path.substring("salt:/".length());
          }
          path = path + " (corpus)";
          accordion.addTab(setupTable(new ListDataProvider<>(corpusAnnos)), path);
          hasResult = true;
        }
      }
      return hasResult;
    }

    private boolean addDocumentMetadata(SCorpusGraph result, Accordion accordion) {
      boolean hasResult = false;

      // Add all document metadata first, then the corpus metadata
      List<SDocument> documents = result.getDocuments();
      if (documents != null) {
        // There should only be one document in the corpus graph, but keeping the code generic
        // should not hurt
        for (SDocument d : documents) {
          List<Annotation> docAnnos = new ArrayList<>();
          for (SMetaAnnotation metaAnno : d.getMetaAnnotations()) {
            Annotation anno = new Annotation();
            AnnoKey key = new AnnoKey();
            key.setNs(metaAnno.getNamespace());
            key.setName(metaAnno.getName());
            anno.setKey(key);
            anno.setVal(metaAnno.getValue_STEXT());
            docAnnos.add(anno);
          }<commit_msg>Attempt to sort the displayed metadata according to the configuration.<commit_after>/*
 * Copyright 2011 Corpuslinguistic working group Humboldt University Berlin.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package org.corpus_tools.annis.gui;

import com.google.common.collect.ComparisonChain;
import com.google.common.util.concurrent.FutureCallback;
import com.vaadin.data.ValueProvider;
import com.vaadin.data.provider.ListDataProvider;
import com.vaadin.shared.data.sort.SortDirection;
import com.vaadin.shared.ui.ContentMode;
import com.vaadin.ui.Accordion;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Grid;
import com.vaadin.ui.Grid.Column;
import com.vaadin.ui.Label;
import com.vaadin.ui.Panel;
import com.vaadin.ui.ProgressBar;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import org.corpus_tools.annis.api.model.AnnoKey;
import org.corpus_tools.annis.api.model.Annotation;
import org.corpus_tools.annis.api.model.CorpusConfiguration;
import org.corpus_tools.annis.gui.components.ExceptionDialog;
import org.corpus_tools.salt.common.SCorpus;
import org.corpus_tools.salt.common.SCorpusGraph;
import org.corpus_tools.salt.common.SDocument;
import org.corpus_tools.salt.core.SMetaAnnotation;
import org.eclipse.emf.common.util.URI;

/**
 * Provides all corpus annotations for a corpus or for a specific search result.
 *
 * // TODO cleanup the toplevelCorpus side effects.
 *
 * @author <NAME> {@literal <<EMAIL>>}
 * @author <NAME> {@literal <<EMAIL>>}
 */
public class MetaDataPanel extends Panel {

  private static class CorpusMetadataCallResult {
    SCorpusGraph metadata;
    CorpusConfiguration config;
  }

  private static class ConfiguredSortOrderComparator implements Comparator<Annotation> {
    private ArrayList<String> corpusAnnotationOrder;

    public ConfiguredSortOrderComparator(Collection<String> corpusAnnotationOrder) {
      this.corpusAnnotationOrder = new ArrayList<String>(corpusAnnotationOrder);
    }

    @Override
    public int compare(Annotation o1, Annotation o2) {
      // TODO: this must be the qualified name
      int pos1 = Collections.binarySearch(this.corpusAnnotationOrder, o1.getKey().getName());
      int pos2 = Collections.binarySearch(this.corpusAnnotationOrder, o2.getKey().getName());
      return ComparisonChain.start().compare(pos1, pos2)
          .compare(o1.getKey().getNs(), o2.getKey().getNs())
          .compare(o1.getKey().getName(), o2.getKey().getName()).result();
    }
  }

  private final class MetadataAvailableCallback
      implements FutureCallback<CorpusMetadataCallResult> {
    @Override
    public void onFailure(Throwable t) {
      layout.removeComponent(progress);
      ExceptionDialog.show(t, "Could not get meta data", getUI());
    }

    @Override
    public void onSuccess(CorpusMetadataCallResult result) {
      layout.removeComponent(progress);
      Accordion accordion = new Accordion();
      accordion.setSizeFull();


      boolean hasDocument = addDocumentMetadata(result.metadata, accordion);
      boolean hasCorpus = addCorpusMetadata(result, accordion);

      // set output to none if no metadata are available
      if (hasDocument || hasCorpus) {
        layout.addComponent(accordion);
      } else {
        addEmptyLabel();
      }
    }

    private boolean addCorpusMetadata(CorpusMetadataCallResult result, Accordion accordion) {
      boolean hasResult = false;

      // Sort the (sub-) corpora so sub-corpora come first
      List<SCorpus> corpora = new ArrayList<>(result.metadata.getCorpora());
      corpora.sort((c1, c2) -> {
        URI u1 = c1.getPath();
        URI u2 = c2.getPath();
        return ComparisonChain.start().compare(u1.segmentCount(), u2.segmentCount())
            .compare(u1.toString(), u2.toString()).result();
      });

      for (SCorpus c : corpora) {
        List<Annotation> corpusAnnos = new ArrayList<>();
        for (SMetaAnnotation metaAnno : c.getMetaAnnotations()) {
          Annotation anno = new Annotation();
          AnnoKey key = new AnnoKey();
          key.setNs(metaAnno.getNamespace());
          key.setName(metaAnno.getName());
          anno.setKey(key);
          anno.setVal(metaAnno.getValue_STEXT());
          corpusAnnos.add(anno);
        }


        if (!corpusAnnos.isEmpty()) {
          // Sort the meta annotations by their name if configured
          if (result.config != null) {
            corpusAnnos.sort(new ConfiguredSortOrderComparator(
                result.config.getView().getCorpusAnnotationOrder()));
          }

          String path = c.getPath().toString();
          if (path.startsWith("salt:/")) {
            path = path.substring("salt:/".length());
          }
          path = path + " (corpus)";
          accordion.addTab(setupTable(new ListDataProvider<>(corpusAnnos)), path);
          hasResult = true;
        }
      }
      return hasResult;
    }

    private boolean addDocumentMetadata(SCorpusGraph result, Accordion accordion) {
      boolean hasResult = false;

      // Add all document metadata first, then the corpus metadata
      List<SDocument> documents = result.getDocuments();
      if (documents != null) {
        // There should only be one document in the corpus graph, but keeping the code generic
        // should not hurt
        for (SDocument d : documents) {
          List<Annotation> docAnnos = new ArrayList<>();
          for (SMetaAnnotation metaAnno : d.getMetaAnnotations()) {
            Annotation anno = new Annotation();
            AnnoKey key = new AnnoKey();
            key.setNs(metaAnno.getNamespace());
            key.setName(metaAnno.getName());
            anno.setKey(key);
            anno.setVal(metaAnno.getValue_STEXT());
            docAnnos.add(anno);
          }
{'fraction_non_alphanumeric': 0.10662997678218247, 'fraction_numerical': 0.0041276120044715795, 'mean_word_length': 3.213768115942029, 'pattern_counts': {'":': 0, '<': 37, '<?xml version=': 0, '>': 39, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4890690', 'n_tokens_mistral': 3362, 'n_tokens_neox': 3255, 'n_words': 836}