<commit_before>/*
 * Copyright 2012 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 annis.visualizers.component.grid;

import annis.CommonHelper;
import annis.libgui.VisualizationToggle;
import annis.libgui.media.MediaController;
import annis.libgui.media.TimeHelper;
import annis.libgui.visualizers.AbstractVisualizer;
import annis.libgui.visualizers.VisualizerInput;
import annis.gui.widgets.grid.AnnotationGrid;
import annis.gui.widgets.grid.GridEvent;
import annis.gui.widgets.grid.Row;
import static annis.model.AnnisConstants.*;
import com.vaadin.server.VaadinSession;
import com.vaadin.ui.Panel;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.themes.ChameleonTheme;
import de.hu_berlin.german.korpling.saltnpepper.salt.graph.Edge;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sDocumentStructure.SDocumentGraph;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sDocumentStructure.SSpan;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sDocumentStructure.SSpanningRelation;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sDocumentStructure.STextualRelation;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sDocumentStructure.SToken;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCore.SAnnotation;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCore.SFeature;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCore.SLayer;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCore.SNode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import net.xeoh.plugins.base.annotations.PluginImplementation;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.emf.common.util.EList;
import org.slf4j.LoggerFactory;

/**
 * Visualizes annotations of a spans.
 * 
 * 
 * Mappings: <br/>
 * It is possible to specify the order of annotation layers in each grid. 
 * Use <b>annos: anno_name1, anno_name2, anno_name3</b> to specify the order or
 * annotation layers. If <b>anno:</b> is used, additional annotation layers not present
 * in the list will not be visualized. If mappings is left empty, layers will be
 * ordered alphabetically
 * @author <NAME> <<EMAIL>>
 */
@PluginImplementation
public class GridVisualizer extends AbstractVisualizer<GridVisualizer.GridVisualizerComponent>
{
  
  @Override
  public String getShortName()
  {
    return "grid";
  }

  @Override
  public GridVisualizerComponent createComponent(VisualizerInput visInput, VisualizationToggle visToggle)
  {
    MediaController mediaController = VaadinSession.getCurrent().getAttribute(MediaController.class);
    GridVisualizerComponent component = new GridVisualizerComponent(visInput, mediaController);
    return component;
  }

  public static class GridVisualizerComponent extends Panel
  {

    private static final org.slf4j.Logger log = LoggerFactory.getLogger(GridVisualizerComponent.class);
    
    public static final String MAPPING_ANNOS_KEY = "annos";
    public static final String MAPPING_ANNO_REGEX_KEY = "anno_regex";
    public static final String MAPPING_HIDE_TOK_KEY = "hide_tok";
    
    private AnnotationGrid grid;
    private transient VisualizerInput input;
    private VerticalLayout layout;

    public enum ElementType
    {

      begin,
      end,
      middle,
      single,
      noEvent
    }

    public GridVisualizerComponent(VisualizerInput input, MediaController mediaController)
    {
      this.input = input;
      
      setWidth("100%");
      setHeight("-1");
      
      layout = new VerticalLayout();
      setContent(layout);
      layout.setSizeUndefined();
      addStyleName(ChameleonTheme.PANEL_BORDERLESS);
      
      if(input != null)
      {
        String resultID = input.getId();
      
        grid = new AnnotationGrid(mediaController, resultID);
        grid.addStyleName("partitur_table");
        grid.addStyleName("corpus-font");
        layout.addComponent(grid);

        SDocumentGraph graph = input.getDocument().getSDocumentGraph();

        List<String> annos = computeDisplayAnnotations(graph);

        EList<SToken> token = graph.getSortedSTokenByText();
        long startIndex = token.get(0).getSFeature(ANNIS_NS, FEAT_TOKENINDEX).getSValueSNUMERIC();
        long endIndex = token.get(token.size()-1).getSFeature(ANNIS_NS, FEAT_TOKENINDEX).getSValueSNUMERIC();
        
        LinkedHashMap<String, ArrayList<Row>> rowsByAnnotation = 
          parseSalt(input.getDocument().getSDocumentGraph(), annos, 
            (int) startIndex, (int) endIndex);

        
        // we will only add tokens of one texts which is mentioned by any 
        // included annotation.
        Set<String> validTextIDs = new HashSet<String>();
        Iterator<ArrayList<Row>> itAllRows = rowsByAnnotation.values().iterator();
        while(itAllRows.hasNext())
        {
          ArrayList<Row> rowsForAnnotation = itAllRows.next();
          for(Row r : rowsForAnnotation)
          {
            validTextIDs.addAll(r.getTextIDs());
          }
        }
        
        int tokenOffsetForText = -1;
        
        // add tokens as row
        Row tokenRow = new Row();<commit_msg>for results with only one text: show old behavior (show all tokens) when no annotation was found<commit_after>/*
 * Copyright 2012 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 annis.visualizers.component.grid;

import annis.CommonHelper;
import annis.libgui.VisualizationToggle;
import annis.libgui.media.MediaController;
import annis.libgui.media.TimeHelper;
import annis.libgui.visualizers.AbstractVisualizer;
import annis.libgui.visualizers.VisualizerInput;
import annis.gui.widgets.grid.AnnotationGrid;
import annis.gui.widgets.grid.GridEvent;
import annis.gui.widgets.grid.Row;
import static annis.model.AnnisConstants.*;
import com.vaadin.server.VaadinSession;
import com.vaadin.ui.Panel;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.themes.ChameleonTheme;
import de.hu_berlin.german.korpling.saltnpepper.salt.graph.Edge;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sDocumentStructure.SDocumentGraph;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sDocumentStructure.SSpan;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sDocumentStructure.SSpanningRelation;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sDocumentStructure.STextualDS;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sDocumentStructure.STextualRelation;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sDocumentStructure.SToken;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCore.SAnnotation;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCore.SFeature;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCore.SLayer;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCore.SNode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import net.xeoh.plugins.base.annotations.PluginImplementation;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.emf.common.util.EList;
import org.slf4j.LoggerFactory;

/**
 * Visualizes annotations of a spans.
 * 
 * 
 * Mappings: <br/>
 * It is possible to specify the order of annotation layers in each grid. 
 * Use <b>annos: anno_name1, anno_name2, anno_name3</b> to specify the order or
 * annotation layers. If <b>anno:</b> is used, additional annotation layers not present
 * in the list will not be visualized. If mappings is left empty, layers will be
 * ordered alphabetically
 * @author <NAME> <<EMAIL>>
 */
@PluginImplementation
public class GridVisualizer extends AbstractVisualizer<GridVisualizer.GridVisualizerComponent>
{
  
  @Override
  public String getShortName()
  {
    return "grid";
  }

  @Override
  public GridVisualizerComponent createComponent(VisualizerInput visInput, VisualizationToggle visToggle)
  {
    MediaController mediaController = VaadinSession.getCurrent().getAttribute(MediaController.class);
    GridVisualizerComponent component = new GridVisualizerComponent(visInput, mediaController);
    return component;
  }

  public static class GridVisualizerComponent extends Panel
  {

    private static final org.slf4j.Logger log = LoggerFactory.getLogger(GridVisualizerComponent.class);
    
    public static final String MAPPING_ANNOS_KEY = "annos";
    public static final String MAPPING_ANNO_REGEX_KEY = "anno_regex";
    public static final String MAPPING_HIDE_TOK_KEY = "hide_tok";
    
    private AnnotationGrid grid;
    private transient VisualizerInput input;
    private VerticalLayout layout;

    public enum ElementType
    {

      begin,
      end,
      middle,
      single,
      noEvent
    }

    public GridVisualizerComponent(VisualizerInput input, MediaController mediaController)
    {
      this.input = input;
      
      setWidth("100%");
      setHeight("-1");
      
      layout = new VerticalLayout();
      setContent(layout);
      layout.setSizeUndefined();
      addStyleName(ChameleonTheme.PANEL_BORDERLESS);
      
      if(input != null)
      {
        String resultID = input.getId();
      
        grid = new AnnotationGrid(mediaController, resultID);
        grid.addStyleName("partitur_table");
        grid.addStyleName("corpus-font");
        layout.addComponent(grid);

        SDocumentGraph graph = input.getDocument().getSDocumentGraph();

        List<String> annos = computeDisplayAnnotations(graph);

        EList<SToken> token = graph.getSortedSTokenByText();
        long startIndex = token.get(0).getSFeature(ANNIS_NS, FEAT_TOKENINDEX).getSValueSNUMERIC();
        long endIndex = token.get(token.size()-1).getSFeature(ANNIS_NS, FEAT_TOKENINDEX).getSValueSNUMERIC();
        
        LinkedHashMap<String, ArrayList<Row>> rowsByAnnotation = 
          parseSalt(input.getDocument().getSDocumentGraph(), annos, 
            (int) startIndex, (int) endIndex);

        
        // we will only add tokens of one texts which is mentioned by any 
        // included annotation.
        Set<String> validTextIDs = new HashSet<String>();
        Iterator<ArrayList<Row>> itAllRows = rowsByAnnotation.values().iterator();
        while(itAllRows.hasNext())
        {
          ArrayList<Row> rowsForAnnotation = itAllRows.next();
          for(Row r : rowsForAnnotation)
          {
            validTextIDs.addAll(r.getTextIDs());
          }
        }
        // we want to show all token if no valid text was found and we have only one text
        EList<STextualDS> allTexts = graph.getSTextualDSs();
        if(validTextIDs.isEmpty() && allTexts != null && allTexts.size() == 1)
        {
          validTextIDs.add(allTexts.get(0).getSId());
        }
        
        int tokenOffsetForText = -1;
        
        // add tokens as row
        Row tokenRow = new Row();
{'fraction_non_alphanumeric': 0.0928021373565928, 'fraction_numerical': 0.0034574886060034574, 'mean_word_length': 3.8762452107279692, 'pattern_counts': {'":': 0, '<': 40, '<?xml version=': 0, '>': 40, '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': '3440431', 'n_tokens_mistral': 3902, 'n_tokens_neox': 3744, 'n_words': 860}