Dataset Viewer (First 5GB)
Auto-converted to Parquet
answer
stringlengths
17
10.2M
package org.csstudio.display.builder.editor.util; import static org.csstudio.display.builder.editor.Plugin.logger; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.Stroke; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.File; import java.io.InputStream; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.function.Consumer; import java.util.logging.Level; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.imageio.ImageIO; import javax.swing.text.Document; import javax.swing.text.html.HTMLEditorKit; import javax.swing.text.rtf.RTFEditorKit; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.StringUtils; import org.csstudio.display.builder.editor.DisplayEditor; import org.csstudio.display.builder.editor.EditorUtil; import org.csstudio.display.builder.editor.Messages; import org.csstudio.display.builder.editor.palette.Palette; import org.csstudio.display.builder.editor.tracker.SelectedWidgetUITracker; import org.csstudio.display.builder.model.DisplayModel; import org.csstudio.display.builder.model.Widget; import org.csstudio.display.builder.model.WidgetDescriptor; import org.csstudio.display.builder.model.WidgetFactory; import org.csstudio.display.builder.model.persist.ModelReader; import org.csstudio.display.builder.model.persist.ModelWriter; import org.csstudio.display.builder.model.persist.WidgetClassesService; import org.csstudio.display.builder.model.util.ModelResourceUtil; import org.csstudio.display.builder.model.widgets.EmbeddedDisplayWidget; import org.csstudio.display.builder.model.widgets.LabelWidget; import org.csstudio.display.builder.model.widgets.PVWidget; import org.csstudio.display.builder.model.widgets.PictureWidget; import org.csstudio.display.builder.model.widgets.WebBrowserWidget; import org.csstudio.display.builder.representation.ToolkitRepresentation; import org.eclipse.osgi.util.NLS; import javafx.embed.swing.SwingFXUtils; import javafx.geometry.Point2D; import javafx.scene.Node; import javafx.scene.control.ChoiceDialog; import javafx.scene.image.Image; import javafx.scene.image.WritableImage; import javafx.scene.input.ClipboardContent; import javafx.scene.input.DragEvent; import javafx.scene.input.Dragboard; import javafx.scene.input.MouseEvent; import javafx.scene.input.TransferMode; /** Helper for widget drag/drop * * <h3>Handling New File/URL Extensions</h3> * To add the support for a new set of file/URL extensions do the following: * <ul> * <li>Create a new static list of extensions (see {@link #IMAGE_FILE_EXTENSIONS});</li> * <li>Update {@link #SUPPORTED_EXTENSIONS} to include the new list;</li> * <li>Update {@link #installWidgetsFromFiles(List,SelectedWidgetUITracker,List) * to handle files having the new extensions;</li> * <li>Update {@link #installWidgetsFromURL(DragEvent,List) * to handle URLs having the new extensions.</li> * </ul> * * @author Kay Kasemir * @author Claudio Rosati */ @SuppressWarnings("nls") public class WidgetTransfer { private static Color TRANSPARENT = new Color(0, 0, 0, 24); private static Stroke OUTLINE_STROKE = new BasicStroke(2.2F); // The extensions listed here MUST BE ALL UPPERCASE. private static List<String> IMAGE_FILE_EXTENSIONS = Arrays.asList("BMP", "GIF", "JPEG", "JPG", "PNG", "SVG"); private static List<String> EMBEDDED_FILE_EXTENSIONS = Arrays.asList("BOB", "OPI"); private static List<String> SUPPORTED_EXTENSIONS = Stream.concat(IMAGE_FILE_EXTENSIONS.stream(), EMBEDDED_FILE_EXTENSIONS.stream()).collect(Collectors.toList()); // Lazily initialized list of widgets that have a PV private static List<WidgetDescriptor> pvWidgetDescriptors = null; // Could create custom data format, or use "application/xml". // Transferring as DataFormat("text/plain"), however, allows exchange // with basic text editor, which can be very convenient. /** Add support for 'dragging' a widget out of a node * * @param source Source {@link Node} * @param selection * @param desc Description of widget type to drag * @param image Image to represent the widget, or <code>null</code> */ public static void addDragSupport(final Node source, final DisplayEditor editor, final Palette palette, final WidgetDescriptor descriptor, final Image image) { source.setOnDragDetected( ( MouseEvent event ) -> { logger.log(Level.FINE, "Starting drag for {0}", descriptor); editor.getWidgetSelectionHandler().clear(); final Widget widget = descriptor.createWidget(); // In class editor mode, create widget with some class name. // In display editor mode, apply the class settings. final DisplayModel model = editor.getModel(); if (model != null && model.isClassModel()) widget.propName().setValue("MY_CLASS"); else WidgetClassesService.getWidgetClasses().apply(widget); final String xml; try { xml = ModelWriter.getXML(Arrays.asList(widget)); } catch (Exception ex) { logger.log(Level.WARNING, "Cannot drag-serialize", ex); return; } final Dragboard db = source.startDragAndDrop(TransferMode.COPY); final ClipboardContent content = new ClipboardContent(); content.putString(xml); db.setContent(content); final int width = widget.propWidth().getValue(); final int height = widget.propHeight().getValue(); db.setDragView(createDragImage(widget, image, width, height), width / 2, -height / 2); event.consume(); }); source.setOnDragDone(event -> { // Widget was dropped // -> Stop scrolling, clear the selected palette entry editor.getAutoScrollHandler().canceTimeline(); palette.clearSelectedWidgetType(); }); } /** Add support for dropping widgets * * @param node Node that will receive the widgets * @param group_handler Group handler * @param selection_tracker The selection tracker. * @param handleDroppedModel Callback for handling the dropped widgets */ public static void addDropSupport( final Node node, final ParentHandler group_handler, final SelectedWidgetUITracker selection_tracker, final Consumer<List<Widget>> handleDroppedModel) { node.setOnDragOver( ( DragEvent event ) -> { final Dragboard db = event.getDragboard(); if (db.hasString() || db.hasUrl() || db.hasRtf() || db.hasHtml() || db.hasImage() || db.hasFiles()) event.acceptTransferModes(TransferMode.COPY_OR_MOVE); group_handler.locateParent(event.getX(), event.getY(), 10, 10); event.consume(); }); node.setOnDragDropped( (DragEvent event) -> { final Dragboard db = event.getDragboard(); final Point2D location = selection_tracker.gridConstrain(event.getX(), event.getY()); final List<Widget> widgets = new ArrayList<>(); final List<Runnable> updates = new ArrayList<>(); if (db.hasFiles() && canAcceptFiles(db.getFiles())) installWidgetsFromFiles(db, selection_tracker, widgets, updates); else if (db.hasImage() && db.getImage() != null) installWidgetsFromImage(db, selection_tracker, widgets); else if (db.hasUrl() && db.getUrl() != null) installWidgetsFromURL(event, widgets, updates); else if (db.hasHtml() && db.getHtml() != null) installWidgetsFromHTML(event, selection_tracker, widgets); else if (db.hasRtf() && db.getRtf() != null) installWidgetsFromRTF(event, selection_tracker, widgets); else if (db.hasString() && db.getString() != null) installWidgetsFromString(event, selection_tracker, widgets); if (widgets.isEmpty()) event.setDropCompleted(false); else { logger.log(Level.FINE, "Dropped {0} widgets.", widgets.size()); GeometryTools.moveWidgets((int) location.getX(), (int) location.getY(), widgets); handleDroppedModel.accept(widgets); // Now that model holds the widgets, perform updates that for example check an image size for (Runnable update : updates) EditorUtil.getExecutor().execute(update); event.setDropCompleted(true); } event.consume(); }); } /** Return {@code true} if there is a {@link File} in {@code files} * whose extension is one of the {@link #SUPPORTED_EXTENSIONS}. * * <P> * <B>Note:<B> only one file will be accepted: the first one * matching the above condition. * * @param files The {@link List} of {@link File}s to be checked. * Can be {@code null} or empty. * @return {@code true} if a file existing whose extension is * contained in {@link #SUPPORTED_EXTENSIONS}. */ private static boolean canAcceptFiles(final List<File> files) { if (files != null && !files.isEmpty()) return files.stream().anyMatch(f -> SUPPORTED_EXTENSIONS.contains(FilenameUtils.getExtension(f.toString()).toUpperCase())); return false; } /** Create a image representing the dragged widget. * * @param widget The {@link Widget} being dragged. * @param image The widget's type image. Can be {@code null}. * @return An {@link Image} instance. */ private static Image createDragImage (final Widget widget, final Image image, final int width, final int height) { final BufferedImage bImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); final Graphics2D g2d = bImage.createGraphics(); g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); g2d.setBackground(TRANSPARENT); g2d.clearRect(0, 0, width, height); g2d.setColor(Color.ORANGE); g2d.setStroke(OUTLINE_STROKE); g2d.drawRect(0, 0, width, height); if ( image != null ) { int w = (int) image.getWidth(); int h = (int) image.getHeight(); BufferedImage bbImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); SwingFXUtils.fromFXImage(image, bbImage); g2d.drawImage(bbImage, (int) ( ( width - w ) / 2.0 ), (int) ( ( height - h ) / 2.0 ), null); } final WritableImage dImage = new WritableImage(width, height); SwingFXUtils.toFXImage(bImage, dImage); return dImage; } /** @param image_file The image file used to create and preset a {@link PictureWidget}. * @param selection_tracker Used to get the grid steps from its model to be used * in offsetting multiple widgets. * @param widgets The container of the created widgets. * @param updates Updates to perform on widgets */ private static void imageFileAcceptor(final String image_file, final SelectedWidgetUITracker selection_tracker, final List<Widget> widgets, final List<Runnable> updates) { logger.log(Level.FINE, "Creating PictureWidget for dropped image {0}", image_file); final DisplayModel model = selection_tracker.getModel(); final PictureWidget widget = (PictureWidget) PictureWidget.WIDGET_DESCRIPTOR.createWidget(); widget.propFile().setValue(image_file); final int index = widgets.size(); widget.propX().setValue(model.propGridStepX().getValue() * index); widget.propY().setValue(model.propGridStepY().getValue() * index); widgets.add(widget); updates.add(() -> updatePictureWidget(widget)); } /** Update a picture widget's size from image file * @param widget {@link PictureWidget} */ private static void updatePictureWidget(final PictureWidget widget) { final String image_file = widget.propFile().getValue(); try { final String filename = ModelResourceUtil.resolveResource(widget.getTopDisplayModel(), image_file); final BufferedImage image = ImageIO.read(ModelResourceUtil.openResourceStream(filename)); widget.propWidth().setValue(image.getWidth()); widget.propHeight().setValue(image.getHeight()); } catch (Exception ex) { logger.log(Level.WARNING, "Cannot obtain image size for " + image_file, ex); } } /** @param db The {@link Dragboard} containing the dragged data. * @param selection_tracker Used to get the grid steps from its model to be used * in offsetting multiple widgets. * @param widgets The container of the created widgets. * @param updates Updates to perform on widgets */ private static void installWidgetsFromFiles(final Dragboard db, final SelectedWidgetUITracker selection_tracker, final List<Widget> widgets, final List<Runnable> updates) { final List<File> files = db.getFiles(); for (int i = 0; i < files.size(); i++) { String filename = files.get(i).toString(); // If running under RCP, try to convert dropped files which are always // absolute file system locations into workspace resource final String workspace_file = ModelResourceUtil.getWorkspacePath(filename); if (workspace_file != null) filename = workspace_file; // Attempt to turn into relative path final DisplayModel model = selection_tracker.getModel(); filename = ModelResourceUtil.getRelativePath(model.getUserData(DisplayModel.USER_DATA_INPUT_FILE), filename); final String extension = FilenameUtils.getExtension(filename).toUpperCase(); if (IMAGE_FILE_EXTENSIONS.contains(extension)) imageFileAcceptor(filename, selection_tracker, widgets, updates); else if (EMBEDDED_FILE_EXTENSIONS.contains(extension) ) displayFileAcceptor(filename, selection_tracker, widgets, updates); } } /** @param event The {@link DragEvent} containing the dragged data. * @param selection_tracker Used to get the grid steps from its model to be used * in offsetting multiple widgets. * @param widgets The container of the created widgets. */ private static void installWidgetsFromHTML(final DragEvent event, final SelectedWidgetUITracker selection_tracker, final List<Widget> widgets) { final Dragboard db = event.getDragboard(); String html = db.getHtml(); HTMLEditorKit htmlParser = new HTMLEditorKit(); Document document = htmlParser.createDefaultDocument(); try { htmlParser.read(new ByteArrayInputStream(html.getBytes()), document, 0); installWidgetsFromString(event, document.getText(0, document.getLength()), selection_tracker, widgets); } catch (Exception ex) { logger.log(Level.WARNING, "Invalid HTML string", ex); } } /** @param db The {@link Dragboard} containing the dragged data. * @param selection_tracker Used to get the display model. * @param widgets The container of the created widgets. */ private static void installWidgetsFromImage(final Dragboard db, final SelectedWidgetUITracker selection_tracker, final List<Widget> widgets) { logger.log(Level.FINE, "Dropped image: creating PictureWidget"); final DisplayModel model = selection_tracker.getModel(); final ToolkitRepresentation<?, ?> toolkit = ToolkitRepresentation.getToolkit(selection_tracker.getModel()); final String filename = toolkit.showSaveAsDialog(model, null); if (filename == null) return; final Image image = db.getImage(); if (image == null) return; final PictureWidget widget = (PictureWidget) PictureWidget.WIDGET_DESCRIPTOR.createWidget(); widget.propWidth().setValue((int) image.getWidth()); widget.propHeight().setValue((int) image.getHeight()); widgets.add(widget); // File access should not be on UI thread, // but we need to return the widget right away. // -> Return the widget now, // create the image file later, // and then update the widget's file property EditorUtil.getExecutor().execute(() -> { try { BufferedImage bImage = SwingFXUtils.fromFXImage(image, null); ImageIO.write(bImage, "png", new File(filename)); widget.propFile().setValue(ModelResourceUtil.getRelativePath(model.getUserData(DisplayModel.USER_DATA_INPUT_FILE), filename)); } catch (Exception ex) { logger.log(Level.WARNING, "Cannot save image as " + filename, ex); } }); } /** @param db The {@link Dragboard} containing the dragged data. * @param selection_tracker Used to get the grid steps from its model to be used * in offsetting multiple widgets. * @param widgets The container of the created widgets. */ private static void installWidgetsFromRTF(final DragEvent event, final SelectedWidgetUITracker selection_tracker, final List<Widget> widgets) { final Dragboard db = event.getDragboard(); final String rtf = db.getRtf(); final RTFEditorKit rtfParser = new RTFEditorKit(); final Document document = rtfParser.createDefaultDocument(); try { rtfParser.read(new ByteArrayInputStream(rtf.getBytes()), document, 0); installWidgetsFromString(event, document.getText(0, document.getLength()), selection_tracker, widgets); } catch (Exception ex) { logger.log(Level.WARNING, "Invalid RTF string", ex); } } /** @param event The {@link DragEvent} containing the dragged data. * @param selection_tracker Used to get the grid steps from its model to be used * in offsetting multiple widgets. * @param widgets The container of the created widgets. */ private static void installWidgetsFromString(final DragEvent event, final SelectedWidgetUITracker selection_tracker, final List<Widget> widgets) { final Dragboard db = event.getDragboard(); final String xmlOrText = db.getString(); try { final DisplayModel model = ModelReader.parseXML(xmlOrText); widgets.addAll(model.getChildren()); } catch (Exception ex) { installWidgetsFromString(event, xmlOrText, selection_tracker, widgets); } } private static void installWidgetsFromString(final DragEvent event, final String text, final SelectedWidgetUITracker selection_tracker, final List<Widget> widgets) { // Consider each word a separate PV final String[] words = text.split("[ \n]+"); final boolean multiple = words.length > 1; final List<WidgetDescriptor> descriptors = getPVWidgetDescriptors(); final List<String> choices = new ArrayList<>(descriptors.size() + ( multiple ? 1 : 0 )); final String format = multiple ? Messages.WT_FromString_multipleFMT : Messages.WT_FromString_singleFMT; // Always offer a single LabelWidget for the complete text final String defaultChoice = NLS.bind(Messages.WT_FromString_singleFMT, LabelWidget.WIDGET_DESCRIPTOR.getName()); choices.add(defaultChoice); // When multiple words were dropped, offer multiple label widgets if (multiple) choices.add(NLS.bind(Messages.WT_FromString_multipleFMT, LabelWidget.WIDGET_DESCRIPTOR.getName())); choices.addAll(descriptors.stream().map(d -> NLS.bind(format, d.getName())).collect(Collectors.toList())); Collections.sort(choices); final ChoiceDialog<String> dialog = new ChoiceDialog<>(defaultChoice, choices); dialog.setX(event.getScreenX()-100); dialog.setY(event.getScreenY()-200); dialog.setTitle(Messages.WT_FromString_dialog_title); dialog.setHeaderText(NLS.bind(Messages.WT_FromString_dialog_headerFMT, reduceStrings(words))); dialog.setContentText(Messages.WT_FromString_dialog_content); final Optional<String> result = dialog.showAndWait(); if (! result.isPresent()) return; final String choice = result.get(); if (defaultChoice.equals(choice)) { logger.log(Level.FINE, "Dropped text: created LabelWidget [{0}].", text); // Not a valid XML. Instantiate a Label object. final LabelWidget widget = (LabelWidget) LabelWidget.WIDGET_DESCRIPTOR.createWidget(); widget.propText().setValue(text); widgets.add(widget); } else { // Parse choice back into widget descriptor final MessageFormat msgf = new MessageFormat(format); final String descriptorName; try { descriptorName = msgf.parse(choice)[0].toString(); } catch (Exception ex) { logger.log(Level.SEVERE, "Cannot parse selected widget type " + choice, ex); return; } WidgetDescriptor descriptor = null; if (LabelWidget.WIDGET_DESCRIPTOR.getName().equals(descriptorName)) descriptor = LabelWidget.WIDGET_DESCRIPTOR; else descriptor = descriptors.stream().filter(d -> descriptorName.equals(d.getName())).findFirst().orElse(null); if (descriptor == null) { logger.log(Level.SEVERE, "Cannot obtain widget for " + descriptorName); return; } for (String word : words) { final Widget widget = descriptor.createWidget(); logger.log(Level.FINE, "Dropped text: created {0} [{1}].", new Object[] { widget.getClass().getSimpleName(), word }); if (widget instanceof PVWidget) ((PVWidget) widget).propPVName().setValue(word); else if (widget instanceof LabelWidget) ((LabelWidget) widget).propText().setValue(word); else logger.log(Level.WARNING, "Unexpected widget type [{0}].", widget.getClass().getSimpleName()); final int index = widgets.size(); if (index > 0) { // Place widgets below each other final Widget previous = widgets.get(index - 1); int x = previous.propX().getValue(); int y = previous.propY().getValue() + previous.propHeight().getValue(); // Align (if enabled) final Point2D pos = selection_tracker.gridConstrain(x, y); widget.propX().setValue((int)pos.getX()); widget.propY().setValue((int)pos.getY()); } widgets.add(widget); } } } /** @return Widgets that have a PV */ private static List<WidgetDescriptor> getPVWidgetDescriptors() { if (pvWidgetDescriptors == null) pvWidgetDescriptors = WidgetFactory.getInstance().getWidgetDescriptions() .stream() .filter(d -> d.createWidget() instanceof PVWidget) .collect(Collectors.toList()); return pvWidgetDescriptors; } private static void installWidgetsFromURL(final DragEvent event, final List<Widget> widgets, final List<Runnable> updates) { final String choice; final Dragboard db = event.getDragboard(); String url = db.getUrl(); // Fix URL, which on linux can contain the file name twice: int sep = url.indexOf('\n'); if (sep > 0) url = url.substring(0, sep); // Check URL's extension sep = url.lastIndexOf('.'); final String ext = sep > 0 ? url.substring(1 + sep).toUpperCase() : null; if (EMBEDDED_FILE_EXTENSIONS.contains(ext)) choice = EmbeddedDisplayWidget.WIDGET_DESCRIPTOR.getName(); else if (IMAGE_FILE_EXTENSIONS.contains(ext)) choice = PictureWidget.WIDGET_DESCRIPTOR.getName(); else { // Prompt user final List<String> choices = Arrays.asList(LabelWidget.WIDGET_DESCRIPTOR.getName(), EmbeddedDisplayWidget.WIDGET_DESCRIPTOR.getName(), PictureWidget.WIDGET_DESCRIPTOR.getName(), WebBrowserWidget.WIDGET_DESCRIPTOR.getName()); final ChoiceDialog<String> dialog = new ChoiceDialog<>(choices.get(3), choices); // Position dialog dialog.setX(event.getScreenX()); dialog.setY(event.getScreenY()); dialog.setTitle(Messages.WT_FromURL_dialog_title); dialog.setHeaderText(NLS.bind(Messages.WT_FromURL_dialog_headerFMT, reduceURL(url))); dialog.setContentText(Messages.WT_FromURL_dialog_content); final Optional<String> result = dialog.showAndWait(); if (result.isPresent()) choice = result.get(); else return; } if (LabelWidget.WIDGET_DESCRIPTOR.getName().equals(choice)) { logger.log(Level.FINE, "Creating LabelWidget for {0}", url); final LabelWidget widget = (LabelWidget) LabelWidget.WIDGET_DESCRIPTOR.createWidget(); widget.propText().setValue(url); widgets.add(widget); } else if (WebBrowserWidget.WIDGET_DESCRIPTOR.getName().equals(choice)) { logger.log(Level.FINE, "Creating WebBrowserWidget for {0}", url); final WebBrowserWidget widget = (WebBrowserWidget) WebBrowserWidget.WIDGET_DESCRIPTOR.createWidget(); widget.propWidgetURL().setValue(url); widgets.add(widget); } else if (PictureWidget.WIDGET_DESCRIPTOR.getName().equals(choice)) { logger.log(Level.FINE, "Creating PictureWidget for {0}", url); final PictureWidget widget = (PictureWidget) PictureWidget.WIDGET_DESCRIPTOR.createWidget(); widget.propFile().setValue(url); widgets.add(widget); updates.add(() -> updatePictureWidget(widget)); } else if (EmbeddedDisplayWidget.WIDGET_DESCRIPTOR.getName().equals(choice)) { logger.log(Level.FINE, "Creating EmbeddedDisplayWidget for {0}", url); EmbeddedDisplayWidget widget = (EmbeddedDisplayWidget) EmbeddedDisplayWidget.WIDGET_DESCRIPTOR.createWidget(); widget.propFile().setValue(url); widgets.add(widget); updates.add(() -> updateEmbeddedWidget(widget)); } } /** @param display_file Display file for which to create an {@link EmbeddedDisplayWidget}. * @param selection_tracker Used to get the grid steps from its model to be used * in offsetting multiple widgets. * @param widgets The container of the created widgets. * @param updates Updates to perform on widgets */ private static void displayFileAcceptor(final String display_file, final SelectedWidgetUITracker selection_tracker, final List<Widget> widgets, final List<Runnable> updates) { logger.log(Level.FINE, "Creating EmbeddedDisplayWidget for {0}", display_file); final DisplayModel model = selection_tracker.getModel(); final EmbeddedDisplayWidget widget = (EmbeddedDisplayWidget) EmbeddedDisplayWidget.WIDGET_DESCRIPTOR.createWidget(); widget.propFile().setValue(display_file); // Offset multiple widgets by grid size final int index = widgets.size(); widget.propX().setValue(model.propGridStepX().getValue() * index); widget.propY().setValue(model.propGridStepY().getValue() * index); widgets.add(widget); updates.add(() -> updateEmbeddedWidget(widget)); } /** Update an embedded widget's name and size from its input * @param widget {@link EmbeddedDisplayWidget} */ private static void updateEmbeddedWidget(final EmbeddedDisplayWidget widget) { final String display_file = widget.propFile().getValue(); final String resolved; try { resolved = ModelResourceUtil.resolveResource(widget.getTopDisplayModel(), display_file); } catch (Exception ex) { logger.log(Level.WARNING, "Cannot resolve resource " + display_file, ex); return; } try ( final InputStream bis = ModelResourceUtil.openResourceStream(resolved); ) { final ModelReader reader = new ModelReader(bis); final DisplayModel embedded_model = reader.readModel(); final String name = embedded_model.getName(); if (! name.isEmpty()) widget.propName().setValue(name); widget.propWidth().setValue(embedded_model.propWidth().getValue()); widget.propHeight().setValue(embedded_model.propHeight().getValue()); } catch (Exception ex) { logger.log(Level.WARNING, "Error updating embedded widget", ex); } } private static String reduceString(String text) { if (text.length() <= 64) return text; else return StringUtils.join(StringUtils.left(text, 32), "...", StringUtils.right(text, 32)); } private static String reduceStrings(String[] lines) { final int ALLOWED_LINES = 16; // Should be a even number. List<String> validLines = new ArrayList<>(1 + ALLOWED_LINES); if ( lines.length <= ALLOWED_LINES ) Arrays.asList(lines).stream().forEach(l -> validLines.add(reduceString(l))); else { for ( int i = 0; i < ALLOWED_LINES / 2; i++ ) validLines.add(reduceString(lines[i])); validLines.add("..."); for ( int i = lines.length - ALLOWED_LINES / 2; i < lines.length; i++ ) validLines.add(reduceString(lines[i])); } StringBuilder builder = new StringBuilder(); validLines.stream().forEach(l -> builder.append(l).append("\n")); builder.deleteCharAt(builder.length() - 1); return builder.toString(); } /** Return a reduced version of the given {@code url}. * * @param url An URL string that, if long, must be reduced * to a shorter version to be displayed. * @return A reduced version of the given {@code url}. */ private static String reduceURL(String url) { if (url.length() > 64) { String shortURL = url; int leftSlash = 2; int rightSlash = 2; if (url.contains(": leftSlash += 2; else if (url.startsWith("/")) leftSlash += 1; if (StringUtils.countMatches(url, '/') > (leftSlash + rightSlash)) { shortURL = reduceURL(url, leftSlash, rightSlash); if (shortURL.length() <= 80) return shortURL; } if (shortURL.length() > 64) { leftSlash rightSlash if (StringUtils.countMatches(url, '/') > (leftSlash + rightSlash)) { shortURL = reduceURL(url, leftSlash, rightSlash); if (shortURL.length() <= 80) return shortURL; } } if (shortURL.length() > 64) return StringUtils.join(StringUtils.left(url, 32), "...", StringUtils.right(url, 32)); } return url; } private static String reduceURL(String url, int leftSlash, int rightSlash) { int leftSlashIndex = StringUtils.ordinalIndexOf(url, "/", leftSlash); int rightSlashIndex = StringUtils.ordinalIndexOf(StringUtils.reverse(url), "/", rightSlash); return StringUtils.join(StringUtils.left(url, leftSlashIndex + 1), "...", StringUtils.right(url, rightSlashIndex + 1)); } }
package org.csstudio.display.builder.editor.util; import static org.csstudio.display.builder.editor.DisplayEditor.logger; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.Stroke; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.File; import java.io.InputStream; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.function.Consumer; import java.util.logging.Level; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.imageio.ImageIO; import javax.swing.text.Document; import javax.swing.text.html.HTMLEditorKit; import javax.swing.text.rtf.RTFEditorKit; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.StringUtils; import org.csstudio.display.builder.editor.DisplayEditor; import org.csstudio.display.builder.editor.EditorUtil; import org.csstudio.display.builder.editor.Messages; import org.csstudio.display.builder.editor.tracker.SelectedWidgetUITracker; import org.csstudio.display.builder.model.DisplayModel; import org.csstudio.display.builder.model.Widget; import org.csstudio.display.builder.model.WidgetDescriptor; import org.csstudio.display.builder.model.WidgetFactory; import org.csstudio.display.builder.model.persist.ModelReader; import org.csstudio.display.builder.model.persist.ModelWriter; import org.csstudio.display.builder.model.util.ModelResourceUtil; import org.csstudio.display.builder.model.widgets.EmbeddedDisplayWidget; import org.csstudio.display.builder.model.widgets.LabelWidget; import org.csstudio.display.builder.model.widgets.PVWidget; import org.csstudio.display.builder.model.widgets.PictureWidget; import org.csstudio.display.builder.model.widgets.WebBrowserWidget; import org.csstudio.display.builder.representation.ToolkitRepresentation; import org.eclipse.osgi.util.NLS; import javafx.embed.swing.SwingFXUtils; import javafx.geometry.Point2D; import javafx.scene.Node; import javafx.scene.control.ChoiceDialog; import javafx.scene.image.Image; import javafx.scene.image.WritableImage; import javafx.scene.input.ClipboardContent; import javafx.scene.input.DragEvent; import javafx.scene.input.Dragboard; import javafx.scene.input.MouseEvent; import javafx.scene.input.TransferMode; /** Helper for widget drag/drop * * <h3>Handling New File/URL Extensions</h3> * To add the support for a new set of file/URL extensions do the following: * <ul> * <li>Create a new static list of extensions (see {@link #IMAGE_FILE_EXTENSIONS});</li> * <li>Update {@link #SUPPORTED_EXTENSIONS} to include the new list;</li> * <li>Update {@link #installWidgetsFromFiles(List,SelectedWidgetUITracker,List) * to handle files having the new extensions;</li> * <li>Update {@link #installWidgetsFromURL(DragEvent,List) * to handle URLs having the new extensions.</li> * </ul> * * @author Kay Kasemir * @author Claudio Rosati */ @SuppressWarnings("nls") public class WidgetTransfer { private static Color TRANSPARENT = new Color(0, 0, 0, 24); private static Stroke OUTLINE_STROKE = new BasicStroke(2.2F); // The extensions listed here MUST BE ALL UPPERCASE. private static List<String> IMAGE_FILE_EXTENSIONS = Arrays.asList("BMP", "GIF", "JPEG", "JPG", "PNG"); private static List<String> EMBEDDED_FILE_EXTENSIONS = Arrays.asList("BOB", "OPI"); private static List<String> SUPPORTED_EXTENSIONS = Stream.concat(IMAGE_FILE_EXTENSIONS.stream(), EMBEDDED_FILE_EXTENSIONS.stream()).collect(Collectors.toList()); // Lazily initialized list of widgets that have a PV private static List<WidgetDescriptor> pvWidgetDescriptors = null; // Could create custom data format, or use "application/xml". // Transferring as DataFormat("text/plain"), however, allows exchange // with basic text editor, which can be very convenient. /** Add support for 'dragging' a widget out of a node * * @param source Source {@link Node} * @param selection * @param desc Description of widget type to drag * @param image Image to represent the widget, or <code>null</code> */ public static void addDragSupport(final Node source, final DisplayEditor editor, final WidgetDescriptor descriptor, final Image image) { source.setOnDragDetected( ( MouseEvent event ) -> { logger.log(Level.FINE, "Starting drag for {0}", descriptor); editor.getWidgetSelectionHandler().clear(); final Widget widget = descriptor.createWidget(); final String xml; try { xml = ModelWriter.getXML(Arrays.asList(widget)); } catch (Exception ex) { logger.log(Level.WARNING, "Cannot drag-serialize", ex); return; } final Dragboard db = source.startDragAndDrop(TransferMode.COPY); final ClipboardContent content = new ClipboardContent(); content.putString(xml); db.setContent(content); final int width = widget.propWidth().getValue(); final int height = widget.propHeight().getValue(); db.setDragView(createDragImage(widget, image, width, height), width / 2, -height / 2); event.consume(); }); source.setOnDragDone(event -> editor.getAutoScrollHandler().canceTimeline()); } /** Add support for dropping widgets * * @param node Node that will receive the widgets * @param group_handler Group handler * @param selection_tracker The selection tracker. * @param handleDroppedModel Callback for handling the dropped widgets */ public static void addDropSupport( final Node node, final ParentHandler group_handler, final SelectedWidgetUITracker selection_tracker, final Consumer<List<Widget>> handleDroppedModel) { node.setOnDragOver( ( DragEvent event ) -> { final Dragboard db = event.getDragboard(); if (db.hasString() || db.hasUrl() || db.hasRtf() || db.hasHtml() || db.hasImage() || db.hasFiles()) event.acceptTransferModes(TransferMode.COPY_OR_MOVE); group_handler.locateParent(event.getX(), event.getY(), 10, 10); event.consume(); }); node.setOnDragDropped( (DragEvent event) -> { final Dragboard db = event.getDragboard(); final Point2D location = selection_tracker.gridConstrain(event.getX(), event.getY()); final List<Widget> widgets = new ArrayList<>(); final List<Runnable> updates = new ArrayList<>(); if (db.hasFiles() && canAcceptFiles(db.getFiles())) installWidgetsFromFiles(db, selection_tracker, widgets, updates); else if (db.hasImage() && db.getImage() != null) installWidgetsFromImage(db, selection_tracker, widgets); else if (db.hasUrl() && db.getUrl() != null) installWidgetsFromURL(event, widgets, updates); else if (db.hasHtml() && db.getHtml() != null) installWidgetsFromHTML(event, selection_tracker, widgets); else if (db.hasRtf() && db.getRtf() != null) installWidgetsFromRTF(event, selection_tracker, widgets); else if (db.hasString() && db.getString() != null) installWidgetsFromString(event, selection_tracker, widgets); if (widgets.isEmpty()) event.setDropCompleted(false); else { logger.log(Level.FINE, "Dropped {0} widgets.", widgets.size()); GeometryTools.moveWidgets((int) location.getX(), (int) location.getY(), widgets); handleDroppedModel.accept(widgets); // Now that model holds the widgets, perform updates that for example check an image size for (Runnable update : updates) EditorUtil.getExecutor().execute(update); event.setDropCompleted(true); } event.consume(); }); } /** Return {@code true} if there is a {@link File} in {@code files} * whose extension is one of the {@link #SUPPORTED_EXTENSIONS}. * * <P> * <B>Note:<B> only one file will be accepted: the first one * matching the above condition. * * @param files The {@link List} of {@link File}s to be checked. * Can be {@code null} or empty. * @return {@code true} if a file existing whose extension is * contained in {@link #SUPPORTED_EXTENSIONS}. */ private static boolean canAcceptFiles(final List<File> files) { if (files != null && !files.isEmpty()) return files.stream().anyMatch(f -> SUPPORTED_EXTENSIONS.contains(FilenameUtils.getExtension(f.toString()).toUpperCase())); return false; } /** Create a image representing the dragged widget. * * @param widget The {@link Widget} being dragged. * @param image The widget's type image. Can be {@code null}. * @return An {@link Image} instance. */ private static Image createDragImage (final Widget widget, final Image image, final int width, final int height) { final BufferedImage bImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); final Graphics2D g2d = bImage.createGraphics(); g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); g2d.setBackground(TRANSPARENT); g2d.clearRect(0, 0, width, height); g2d.setColor(Color.ORANGE); g2d.setStroke(OUTLINE_STROKE); g2d.drawRect(0, 0, width, height); if ( image != null ) { int w = (int) image.getWidth(); int h = (int) image.getHeight(); BufferedImage bbImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); SwingFXUtils.fromFXImage(image, bbImage); g2d.drawImage(bbImage, (int) ( ( width - w ) / 2.0 ), (int) ( ( height - h ) / 2.0 ), null); } WritableImage dImage = new WritableImage(width, height); SwingFXUtils.toFXImage(bImage, dImage); return dImage; } /** @param image_file The image file used to create and preset a {@link PictureWidget}. * @param selection_tracker Used to get the grid steps from its model to be used * in offsetting multiple widgets. * @param widgets The container of the created widgets. * @param updates Updates to perform on widgets */ private static void imageFileAcceptor(final String image_file, final SelectedWidgetUITracker selection_tracker, final List<Widget> widgets, final List<Runnable> updates) { logger.log(Level.FINE, "Creating PictureWidget for dropped image {0}", image_file); final DisplayModel model = selection_tracker.getModel(); final PictureWidget widget = (PictureWidget) PictureWidget.WIDGET_DESCRIPTOR.createWidget(); widget.propFile().setValue(image_file); final int index = widgets.size(); widget.propX().setValue(model.propGridStepX().getValue() * index); widget.propY().setValue(model.propGridStepY().getValue() * index); widgets.add(widget); updates.add(() -> updatePictureWidget(widget)); } /** Update a picture widget's size from image file * @param widget {@link PictureWidget} */ private static void updatePictureWidget(final PictureWidget widget) { final String image_file = widget.propFile().getValue(); try { final String filename = ModelResourceUtil.resolveResource(widget.getTopDisplayModel(), image_file); final BufferedImage image = ImageIO.read(ModelResourceUtil.openResourceStream(filename)); widget.propWidth().setValue(image.getWidth()); widget.propHeight().setValue(image.getHeight()); } catch (Exception ex) { logger.log(Level.WARNING, "Cannot obtain image size for " + image_file, ex); } } /** @param db The {@link Dragboard} containing the dragged data. * @param selection_tracker Used to get the grid steps from its model to be used * in offsetting multiple widgets. * @param widgets The container of the created widgets. * @param updates Updates to perform on widgets */ private static void installWidgetsFromFiles(final Dragboard db, final SelectedWidgetUITracker selection_tracker, final List<Widget> widgets, final List<Runnable> updates) { final List<File> files = db.getFiles(); for (int i = 0; i < files.size(); i++) { String filename = files.get(i).toString(); // If running under RCP, try to convert dropped files which are always // absolute file system locations into workspace resource final String workspace_file = ModelResourceUtil.getWorkspacePath(filename); if (workspace_file != null) filename = workspace_file; // Attempt to turn into relative path final DisplayModel model = selection_tracker.getModel(); filename = ModelResourceUtil.getRelativePath(model.getUserData(DisplayModel.USER_DATA_INPUT_FILE), filename); final String extension = FilenameUtils.getExtension(filename).toUpperCase(); if (IMAGE_FILE_EXTENSIONS.contains(extension)) imageFileAcceptor(filename, selection_tracker, widgets, updates); else if (EMBEDDED_FILE_EXTENSIONS.contains(extension) ) displayFileAcceptor(filename, selection_tracker, widgets, updates); } } /** @param event The {@link DragEvent} containing the dragged data. * @param selection_tracker Used to get the grid steps from its model to be used * in offsetting multiple widgets. * @param widgets The container of the created widgets. */ private static void installWidgetsFromHTML(final DragEvent event, final SelectedWidgetUITracker selection_tracker, final List<Widget> widgets) { final Dragboard db = event.getDragboard(); String html = db.getHtml(); HTMLEditorKit htmlParser = new HTMLEditorKit(); Document document = htmlParser.createDefaultDocument(); try { htmlParser.read(new ByteArrayInputStream(html.getBytes()), document, 0); installWidgetsFromString(event, document.getText(0, document.getLength()), selection_tracker, widgets); } catch (Exception ex) { logger.log(Level.WARNING, "Invalid HTML string", ex); } } /** @param db The {@link Dragboard} containing the dragged data. * @param selection_tracker Used to get the display model. * @param widgets The container of the created widgets. */ private static void installWidgetsFromImage(final Dragboard db, final SelectedWidgetUITracker selection_tracker, final List<Widget> widgets) { logger.log(Level.FINE, "Dropped image: creating PictureWidget"); final DisplayModel model = selection_tracker.getModel(); final ToolkitRepresentation<?, ?> toolkit = ToolkitRepresentation.getToolkit(selection_tracker.getModel()); final String filename = toolkit.showSaveAsDialog(model, null); if (filename == null) return; final Image image = db.getImage(); if (image == null) return; final PictureWidget widget = (PictureWidget) PictureWidget.WIDGET_DESCRIPTOR.createWidget(); widget.propWidth().setValue((int) image.getWidth()); widget.propHeight().setValue((int) image.getHeight()); widgets.add(widget); // File access should not be on UI thread, // but we need to return the widget right away. // -> Return the widget now, // create the image file later, // and then update the widget's file property EditorUtil.getExecutor().execute(() -> { try { BufferedImage bImage = SwingFXUtils.fromFXImage(image, null); ImageIO.write(bImage, "png", new File(filename)); widget.propFile().setValue(ModelResourceUtil.getRelativePath(model.getUserData(DisplayModel.USER_DATA_INPUT_FILE), filename)); } catch (Exception ex) { logger.log(Level.WARNING, "Cannot save image as " + filename, ex); } }); } /** @param db The {@link Dragboard} containing the dragged data. * @param selection_tracker Used to get the grid steps from its model to be used * in offsetting multiple widgets. * @param widgets The container of the created widgets. */ private static void installWidgetsFromRTF(final DragEvent event, final SelectedWidgetUITracker selection_tracker, final List<Widget> widgets) { final Dragboard db = event.getDragboard(); final String rtf = db.getRtf(); final RTFEditorKit rtfParser = new RTFEditorKit(); final Document document = rtfParser.createDefaultDocument(); try { rtfParser.read(new ByteArrayInputStream(rtf.getBytes()), document, 0); installWidgetsFromString(event, document.getText(0, document.getLength()), selection_tracker, widgets); } catch (Exception ex) { logger.log(Level.WARNING, "Invalid RTF string", ex); } } /** @param event The {@link DragEvent} containing the dragged data. * @param selection_tracker Used to get the grid steps from its model to be used * in offsetting multiple widgets. * @param widgets The container of the created widgets. */ private static void installWidgetsFromString(final DragEvent event, final SelectedWidgetUITracker selection_tracker, final List<Widget> widgets) { final Dragboard db = event.getDragboard(); final String xmlOrText = db.getString(); try { final DisplayModel model = ModelReader.parseXML(xmlOrText); widgets.addAll(model.getChildren()); } catch (Exception ex) { installWidgetsFromString(event, xmlOrText, selection_tracker, widgets); } } private static void installWidgetsFromString(final DragEvent event, final String text, final SelectedWidgetUITracker selection_tracker, final List<Widget> widgets) { // Consider each word a separate PV final String[] words = text.split("[ \n]+"); final boolean multiple = words.length > 1; final List<WidgetDescriptor> descriptors = getPVWidgetDescriptors(); final List<String> choices = new ArrayList<>(descriptors.size() + ( multiple ? 1 : 0 )); final String format = multiple ? Messages.WT_FromString_multipleFMT : Messages.WT_FromString_singleFMT; // Always offer a single LabelWidget for the complete text final String defaultChoice = NLS.bind(Messages.WT_FromString_singleFMT, LabelWidget.WIDGET_DESCRIPTOR.getName()); choices.add(defaultChoice); // When multiple words were dropped, offer multiple label widgets if (multiple) choices.add(NLS.bind(Messages.WT_FromString_multipleFMT, LabelWidget.WIDGET_DESCRIPTOR.getName())); choices.addAll(descriptors.stream().map(d -> NLS.bind(format, d.getName())).collect(Collectors.toList())); Collections.sort(choices); final ChoiceDialog<String> dialog = new ChoiceDialog<>(defaultChoice, choices); dialog.setX(event.getScreenX()-100); dialog.setY(event.getScreenY()-200); dialog.setTitle(Messages.WT_FromString_dialog_title); dialog.setHeaderText(NLS.bind(Messages.WT_FromString_dialog_headerFMT, reduceStrings(words))); dialog.setContentText(Messages.WT_FromString_dialog_content); final Optional<String> result = dialog.showAndWait(); if (! result.isPresent()) return; final String choice = result.get(); if (defaultChoice.equals(choice)) { logger.log(Level.FINE, "Dropped text: created LabelWidget [{0}].", text); // Not a valid XML. Instantiate a Label object. final LabelWidget widget = (LabelWidget) LabelWidget.WIDGET_DESCRIPTOR.createWidget(); widget.propText().setValue(text); widgets.add(widget); } else { // Parse choice back into widget descriptor final MessageFormat msgf = new MessageFormat(format); final String descriptorName; try { descriptorName = msgf.parse(choice)[0].toString(); } catch (Exception ex) { logger.log(Level.SEVERE, "Cannot parse selected widget type " + choice, ex); return; } WidgetDescriptor descriptor = null; if (LabelWidget.WIDGET_DESCRIPTOR.getName().equals(descriptorName)) descriptor = LabelWidget.WIDGET_DESCRIPTOR; else descriptor = descriptors.stream().filter(d -> descriptorName.equals(d.getName())).findFirst().orElse(null); if (descriptor == null) { logger.log(Level.SEVERE, "Cannot obtain widget for " + descriptorName); return; } for (String word : words) { final Widget widget = descriptor.createWidget(); logger.log(Level.FINE, "Dropped text: created {0} [{1}].", new Object[] { widget.getClass().getSimpleName(), word }); if (widget instanceof PVWidget) ((PVWidget) widget).propPVName().setValue(word); else if (widget instanceof LabelWidget) ((LabelWidget) widget).propText().setValue(word); else logger.log(Level.WARNING, "Unexpected widget type [{0}].", widget.getClass().getSimpleName()); final int index = widgets.size(); if (index > 0) { // Place widgets below each other final Widget previous = widgets.get(index - 1); int x = previous.propX().getValue(); int y = previous.propY().getValue() + previous.propHeight().getValue(); // Align (if enabled) final Point2D pos = selection_tracker.gridConstrain(x, y); widget.propX().setValue((int)pos.getX()); widget.propY().setValue((int)pos.getY()); } widgets.add(widget); } } } /** @return Widgets that have a PV */ private static List<WidgetDescriptor> getPVWidgetDescriptors() { if (pvWidgetDescriptors == null) pvWidgetDescriptors = WidgetFactory.getInstance().getWidgetDescriptions() .stream() .filter(d -> d.createWidget() instanceof PVWidget) .collect(Collectors.toList()); return pvWidgetDescriptors; } private static void installWidgetsFromURL(final DragEvent event, final List<Widget> widgets, final List<Runnable> updates) { final String choice; final Dragboard db = event.getDragboard(); String url = db.getUrl(); // Fix URL, which on linux can contain the file name twice: int sep = url.indexOf('\n'); if (sep > 0) url = url.substring(0, sep); // Check URL's extension sep = url.lastIndexOf('.'); final String ext = sep > 0 ? url.substring(1 + sep).toUpperCase() : null; if (EMBEDDED_FILE_EXTENSIONS.contains(ext)) choice = EmbeddedDisplayWidget.WIDGET_DESCRIPTOR.getName(); else if (IMAGE_FILE_EXTENSIONS.contains(ext)) choice = PictureWidget.WIDGET_DESCRIPTOR.getName(); else { // Prompt user final List<String> choices = Arrays.asList(LabelWidget.WIDGET_DESCRIPTOR.getName(), EmbeddedDisplayWidget.WIDGET_DESCRIPTOR.getName(), PictureWidget.WIDGET_DESCRIPTOR.getName(), WebBrowserWidget.WIDGET_DESCRIPTOR.getName()); final ChoiceDialog<String> dialog = new ChoiceDialog<>(choices.get(3), choices); // Position dialog dialog.setX(event.getScreenX()); dialog.setY(event.getScreenY()); dialog.setTitle(Messages.WT_FromURL_dialog_title); dialog.setHeaderText(NLS.bind(Messages.WT_FromURL_dialog_headerFMT, reduceURL(url))); dialog.setContentText(Messages.WT_FromURL_dialog_content); final Optional<String> result = dialog.showAndWait(); if (result.isPresent()) choice = result.get(); else return; } if (LabelWidget.WIDGET_DESCRIPTOR.getName().equals(choice)) { logger.log(Level.FINE, "Creating LabelWidget for {0}", url); final LabelWidget widget = (LabelWidget) LabelWidget.WIDGET_DESCRIPTOR.createWidget(); widget.propText().setValue(url); widgets.add(widget); } else if (WebBrowserWidget.WIDGET_DESCRIPTOR.getName().equals(choice)) { logger.log(Level.FINE, "Creating WebBrowserWidget for {0}", url); final WebBrowserWidget widget = (WebBrowserWidget) WebBrowserWidget.WIDGET_DESCRIPTOR.createWidget(); widget.propWidgetURL().setValue(url); widgets.add(widget); } else if (PictureWidget.WIDGET_DESCRIPTOR.getName().equals(choice)) { logger.log(Level.FINE, "Creating PictureWidget for {0}", url); final PictureWidget widget = (PictureWidget) PictureWidget.WIDGET_DESCRIPTOR.createWidget(); widget.propFile().setValue(url); widgets.add(widget); updates.add(() -> updatePictureWidget(widget)); } else if (EmbeddedDisplayWidget.WIDGET_DESCRIPTOR.getName().equals(choice)) { logger.log(Level.FINE, "Creating EmbeddedDisplayWidget for {0}", url); EmbeddedDisplayWidget widget = (EmbeddedDisplayWidget) EmbeddedDisplayWidget.WIDGET_DESCRIPTOR.createWidget(); widget.propFile().setValue(url); widgets.add(widget); updates.add(() -> updateEmbeddedWidget(widget)); } } /** @param display_file Display file for which to create an {@link EmbeddedDisplayWidget}. * @param selection_tracker Used to get the grid steps from its model to be used * in offsetting multiple widgets. * @param widgets The container of the created widgets. * @param updates Updates to perform on widgets */ private static void displayFileAcceptor(final String display_file, final SelectedWidgetUITracker selection_tracker, final List<Widget> widgets, final List<Runnable> updates) { logger.log(Level.FINE, "Creating EmbeddedDisplayWidget for {0}", display_file); final DisplayModel model = selection_tracker.getModel(); final EmbeddedDisplayWidget widget = (EmbeddedDisplayWidget) EmbeddedDisplayWidget.WIDGET_DESCRIPTOR.createWidget(); widget.propFile().setValue(display_file); // Offset multiple widgets by grid size final int index = widgets.size(); widget.propX().setValue(model.propGridStepX().getValue() * index); widget.propY().setValue(model.propGridStepY().getValue() * index); widgets.add(widget); updates.add(() -> updateEmbeddedWidget(widget)); } /** Update an embedded widget's name and size from its input * @param widget {@link EmbeddedDisplayWidget} */ private static void updateEmbeddedWidget(final EmbeddedDisplayWidget widget) { final String display_file = widget.propFile().getValue(); final String resolved; try { resolved = ModelResourceUtil.resolveResource(widget.getTopDisplayModel(), display_file); } catch (Exception ex) { logger.log(Level.WARNING, "Cannot resolve resource " + display_file, ex); return; } try ( final InputStream bis = ModelResourceUtil.openResourceStream(resolved); ) { final ModelReader reader = new ModelReader(bis); final DisplayModel embedded_model = reader.readModel(); final String name = embedded_model.getName(); if (! name.isEmpty()) widget.propName().setValue(name); widget.propWidth().setValue(embedded_model.propWidth().getValue()); widget.propHeight().setValue(embedded_model.propHeight().getValue()); } catch (Exception ex) { logger.log(Level.WARNING, "Error updating embedded widget", ex); } } private static String reduceString(String text) { if (text.length() <= 64) return text; else return StringUtils.join(StringUtils.left(text, 32), "...", StringUtils.right(text, 32)); } private static String reduceStrings(String[] lines) { final int ALLOWED_LINES = 16; // Should be a even number. List<String> validLines = new ArrayList<>(1 + ALLOWED_LINES); if ( lines.length <= ALLOWED_LINES ) Arrays.asList(lines).stream().forEach(l -> validLines.add(reduceString(l))); else { for ( int i = 0; i < ALLOWED_LINES / 2; i++ ) validLines.add(reduceString(lines[i])); validLines.add("..."); for ( int i = lines.length - ALLOWED_LINES / 2; i < lines.length; i++ ) validLines.add(reduceString(lines[i])); } StringBuilder builder = new StringBuilder(); validLines.stream().forEach(l -> builder.append(l).append("\n")); builder.deleteCharAt(builder.length() - 1); return builder.toString(); } /** Return a reduced version of the given {@code url}. * * @param url An URL string that, if long, must be reduced * to a shorter version to be displayed. * @return A reduced version of the given {@code url}. */ private static String reduceURL(String url) { if (url.length() > 64) { String shortURL = url; int leftSlash = 2; int rightSlash = 2; if (url.contains(": leftSlash += 2; else if (url.startsWith("/")) leftSlash += 1; if (StringUtils.countMatches(url, '/') > (leftSlash + rightSlash)) { shortURL = reduceURL(url, leftSlash, rightSlash); if (shortURL.length() <= 80) return shortURL; } if (shortURL.length() > 64) { leftSlash rightSlash if (StringUtils.countMatches(url, '/') > (leftSlash + rightSlash)) { shortURL = reduceURL(url, leftSlash, rightSlash); if (shortURL.length() <= 80) return shortURL; } } if (shortURL.length() > 64) return StringUtils.join(StringUtils.left(url, 32), "...", StringUtils.right(url, 32)); } return url; } private static String reduceURL(String url, int leftSlash, int rightSlash) { int leftSlashIndex = StringUtils.ordinalIndexOf(url, "/", leftSlash); int rightSlashIndex = StringUtils.ordinalIndexOf(StringUtils.reverse(url), "/", rightSlash); return StringUtils.join(StringUtils.left(url, leftSlashIndex + 1), "...", StringUtils.right(url, rightSlashIndex + 1)); } }
package org.eclipse.emf.emfstore.jaxrs.client; import java.util.List; import org.eclipse.emf.emfstore.internal.server.model.ProjectInfo; import org.eclipse.emf.emfstore.internal.server.model.impl.ProjectInfoImpl; import org.eclipse.emf.emfstore.internal.server.model.versioning.LogMessage; /** * @author Pascal * */ public class JaxrsConnectionManager { public List<ProjectInfo> getProjectList() { // TODO: implement! return null; } public ProjectInfo createEmptyProject(String name, String description, LogMessage logMessage) { // TODO: implement!!! return new ProjectInfoImpl(); } }
package org.jcryptool.analysis.freqanalysis.ui; import java.util.Arrays; import java.util.Comparator; import org.eclipse.swt.SWT; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseMoveListener; import org.eclipse.swt.events.MouseTrackAdapter; import org.eclipse.swt.events.MouseTrackListener; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.Composite; import org.jcryptool.analysis.freqanalysis.calc.FreqAnalysisCalc; import org.jcryptool.analysis.freqanalysis.calc.FreqAnalysisData; import org.jcryptool.analysis.graphtools.derivates.LabelBar; import org.jcryptool.analysis.graphtools.derivates.OverlayLabelBar; /** * @author SLeischnig * */ public class CustomFreqCanvas extends Canvas implements PaintListener, MouseMoveListener, MouseTrackListener { private Composite mycomp; private FreqAnalysisCalc myAnalysis, myOverlayAnalysis; // Flag if mouseover shows details for a single bar... private boolean overlay = false; // Class for drawing calculations private FreqAnalysisGraph frequencyGraph = new FreqAnalysisGraph(null, this.getSize().x, this.getSize().y); // graph dragging variables private boolean draggingEnabled = true; private boolean dragging = false; private int dragBeginX; public final void setOverlayActivated(final boolean isOverlay) { overlay = isOverlay; buildBars(); } public CustomFreqCanvas(final org.eclipse.swt.widgets.Composite parent, final int style) { super(parent, SWT.DOUBLE_BUFFERED); mycomp = parent; // myAnalysis = analysis; setBackground(getDisplay().getSystemColor(SWT.COLOR_WHITE)); int width = 0, height = 0; width = mycomp.getSize().x; height = mycomp.getSize().y; setSize(width, height); myAnalysis = new FreqAnalysisCalc("", 1, 0, null); //$NON-NLS-1$ myOverlayAnalysis = new FreqAnalysisCalc("", 1, 0, null); //$NON-NLS-1$ addPaintListener(this); this.addPaintListener(this); this.addMouseMoveListener(this); this.addMouseTrackListener(this); this.addMouseTrackListener(new MouseTrackAdapter() { @Override public void mouseExit(final MouseEvent evt) { dragging = false; if (getFrequencyGraph().setDraggedPixels(0, false)) { redraw(); // reset the drag } } }); this.addMouseListener(new MouseAdapter() { @Override public void mouseUp(final MouseEvent evt) { if (dragging && draggingEnabled) { int myPixelsDifference = evt.x - dragBeginX; getFrequencyGraph().setDraggedPixels(myPixelsDifference, false); } dragging = false; } @Override public void mouseDown(final MouseEvent evt) { dragging = true; dragBeginX = evt.x; } @Override public void mouseDoubleClick(final MouseEvent evt) { getFrequencyGraph().resetDrag(); redraw(); } }); } /** * sets the Frequency analysis */ public final void setAnalysis(final FreqAnalysisCalc in) { myAnalysis = in; buildBars(); } /** * Sets the overlay Analysis */ public final void setOverlayAnalysis(final FreqAnalysisCalc in) { myOverlayAnalysis = in; buildBars(); } /** * Generates the bars for the drawing procedures */ private void buildBars() { class CustomFreqAnalysisData extends FreqAnalysisData { boolean isOverlayBar; public CustomFreqAnalysisData() { super(); } public void copySuper(final FreqAnalysisData in) { this.absOcc = in.absOcc; this.ch = in.ch; this.charPrinted = in.charPrinted; this.relOcc = in.relOcc; } } /** * @author SLeischnig comparates two frequency analysis data sets for sorting */ class MyComparator implements Comparator<FreqAnalysisData> { @Override public int compare(final FreqAnalysisData a, final FreqAnalysisData b) { if ((a.ch) > (b.ch)) { return 1; } if ((a.ch) == (b.ch)) { return 0; } return -1; } // No need to override equals. } // Copy all Analysis Data in one Array CustomFreqAnalysisData[] allData = new CustomFreqAnalysisData[myAnalysis.getAnalysisArray().length + myOverlayAnalysis.getAnalysisArray().length]; for (int i = 0; i < myAnalysis.getAnalysisArray().length; i++) { allData[i] = new CustomFreqAnalysisData(); allData[i].copySuper(myAnalysis.getAnalysisArray()[i]); allData[i].isOverlayBar = false; } for (int i = 0; i < myOverlayAnalysis.getAnalysisArray().length; i++) { allData[myAnalysis.getAnalysisArray().length + i] = new CustomFreqAnalysisData(); allData[myAnalysis.getAnalysisArray().length + i].copySuper(myOverlayAnalysis.getAnalysisArray()[i]); allData[myAnalysis.getAnalysisArray().length + i].isOverlayBar = true; } // sort all Analysis Data in view of its character values (see comparator class) Arrays.sort(allData, new MyComparator()); char actualChar = (char) 0; int actualIndex = -1; double maxValue = Math.max(max(myAnalysis.getAnalysisArray()), max(myOverlayAnalysis.getAnalysisArray())); double barHeight = 0; // generate Bars getFrequencyGraph().resetBars(); for (int i = 0; i < allData.length; i++) { // Only draw overlay bars when it's activated if (overlay || (!allData[i].isOverlayBar)) { if (allData[i].ch != actualChar) { actualChar = allData[i].ch; actualIndex++; } barHeight = (allData[i].relOcc) / (maxValue); LabelBar myBar; if (!allData[i].isOverlayBar) { myBar = new LabelBar(barHeight, actualIndex, 10, "" + allData[i].absOcc, allData[i].charPrinted); } else { myBar = new OverlayLabelBar(barHeight, actualIndex, 11, "" + allData[i].absOcc, allData[i].charPrinted); } myBar.attachedData.add(allData[i]); getFrequencyGraph().addBar(myBar); } } } /** * returns the maximum relative occurence in the frequency analysis set. * * @param t the frequency analysis set * @return the highest relative occurence in the set */ private static double max(final FreqAnalysisData[] t) { double maximum = -9999; // start with the first value for (int i = 0; i < t.length; i++) { if (t[i].relOcc > maximum) { maximum = t[i].relOcc; // new maximum } } return maximum; } @Override public final void paintControl(final PaintEvent e) { GC gc = e.gc; int width = 0, height = 0; width = this.getSize().x; height = this.getSize().y; getFrequencyGraph().setGC(gc); getFrequencyGraph().updateBounds(width, height); getFrequencyGraph().paintArea(); } public final void setDraggingEnabled(final boolean dragEnabled) { this.draggingEnabled = dragEnabled; } public final boolean isDraggingEnabled() { return draggingEnabled; } public final void setFrequencyGraph(final FreqAnalysisGraph frequencyGraph) { this.frequencyGraph = frequencyGraph; } public final FreqAnalysisGraph getFrequencyGraph() { return frequencyGraph; } @Override public final void mouseMove(final MouseEvent e) { if (dragging && draggingEnabled) { int myPixelsDifference = e.x - dragBeginX; if (getFrequencyGraph().setDraggedPixels(myPixelsDifference, true)) { redraw(); } } if (this.frequencyGraph != null) { frequencyGraph.mouseMove(e); } } @Override public void mouseEnter(MouseEvent e) { if (this.frequencyGraph != null) { frequencyGraph.mouseEnter(e); this.redraw(); } } @Override public void mouseExit(MouseEvent e) { if (this.frequencyGraph != null) { frequencyGraph.mouseExit(e); this.redraw(); } } @Override public void mouseHover(MouseEvent e) { if (this.frequencyGraph != null) { frequencyGraph.mouseHover(e); this.redraw(); } } }
package com.gurkensalat.osm.mosques.jobs; import com.gurkensalat.osm.entity.DitibPlace; import com.gurkensalat.osm.mosques.service.GeocodingService; import com.gurkensalat.osm.repository.DitibPlaceRepository; import com.tandogan.geostuff.opencagedata.entity.GeocodeResponse; import org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.stereotype.Component; import java.util.List; @Configuration @Component public class DitibForwardGeocoderHandler { private final static Logger LOGGER = LoggerFactory.getLogger(DitibForwardGeocoderHandler.class); @Value("${mq.queue.forward-geocode-ditib.minsleep}") private Integer minsleep; @Value("${mq.queue.forward-geocode-ditib.randomsleep}") private Integer randomsleep; @Autowired private GeocodingService geocodingService; @Autowired private DitibPlaceRepository ditibPlaceRepository; @Autowired private SlackNotifier slackNotifier; @RabbitListener(queues = "${mq.queue.forward-geocode-ditib.name}") public void handleMessage(TaskMessage message) { LOGGER.info(" received <{}>", message); String ditibCode = message.getMessage(); List<DitibPlace> places = ditibPlaceRepository.findByKey(ditibCode); if (places != null) { for (DitibPlace place : places) { LOGGER.info(" have to handle: {}", place); if (!(place.isGeocoded())) { // Do some magic... Maybe the service should not write directly to the database... GeocodeResponse response = geocodingService.ditibForward(ditibCode); // Reload the place, it might have been changed by the geocodingService place = ditibPlaceRepository.findOne(place.getId()); // did what we had to, now mark this place as "touched" place.setLastGeocodeAttempt(DateTime.now()); place = ditibPlaceRepository.save(place); long sleeptime = (long) (minsleep + (Math.random() * (double) randomsleep)); LOGGER.debug("Processing finished, sleeping a while ({} seconds)...", sleeptime); try { Thread.sleep(sleeptime * 1000); } catch (InterruptedException ie) { // Not really important... } if (response.getRate() != null) { if (response.getRate().getRemaining() < 100) { slackNotifier.notify(SlackNotifier.CHANNEL_GEOCODING, "Too little attempts left (" + response.getRate().getRemaining() + " out of " + response.getRate().getLimit() + "), sleeping for half an hour"); try { Thread.sleep(30 * 60 * 1000); } catch (InterruptedException ie) { // Not really important... } } } } } } LOGGER.info(" done with handleMessage <{}>", message); } }
package org.opendaylight.protocol.pcep.impl.object; import org.opendaylight.protocol.pcep.spi.ObjectParser; import org.opendaylight.protocol.pcep.spi.ObjectSerializer; import org.opendaylight.protocol.pcep.spi.PCEPDeserializerException; import org.opendaylight.protocol.pcep.spi.TlvHandlerRegistry; import org.opendaylight.protocol.pcep.spi.TlvParser; import org.opendaylight.protocol.pcep.spi.TlvSerializer; import org.opendaylight.protocol.util.ByteArray; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.Tlv; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Preconditions; public abstract class AbstractObjectWithTlvsParser<T> implements ObjectParser, ObjectSerializer { private static final Logger LOG = LoggerFactory.getLogger(AbstractObjectWithTlvsParser.class); private static final int TLV_TYPE_F_LENGTH = 2; private static final int TLV_LENGTH_F_LENGTH = 2; private static final int TLV_HEADER_LENGTH = TLV_LENGTH_F_LENGTH + TLV_TYPE_F_LENGTH; protected static final int PADDED_TO = 4; private final TlvHandlerRegistry tlvReg; protected AbstractObjectWithTlvsParser(final TlvHandlerRegistry tlvReg) { this.tlvReg = Preconditions.checkNotNull(tlvReg); } protected final void parseTlvs(final T builder, final byte[] bytes) throws PCEPDeserializerException { if (bytes == null) { throw new IllegalArgumentException("Byte array is mandatory."); } if (bytes.length == 0) { return; } int length; int byteOffset = 0; int type = 0; while (byteOffset < bytes.length) { type = ByteArray.bytesToInt(ByteArray.subByte(bytes, byteOffset, TLV_TYPE_F_LENGTH)); byteOffset += TLV_TYPE_F_LENGTH; length = ByteArray.bytesToInt(ByteArray.subByte(bytes, byteOffset, TLV_LENGTH_F_LENGTH)); byteOffset += TLV_LENGTH_F_LENGTH; if (TLV_HEADER_LENGTH + length > bytes.length) { throw new PCEPDeserializerException("Wrong length specified. Passed: " + (TLV_HEADER_LENGTH + length) + "; Expected: <= " + (bytes.length - byteOffset) + "."); } final byte[] tlvBytes = ByteArray.subByte(bytes, byteOffset, length); LOG.trace("Attempt to parse tlv from bytes: {}", ByteArray.bytesToHexString(tlvBytes)); final TlvParser parser = this.tlvReg.getTlvParser(type); if (parser != null) { final Tlv tlv = parser.parseTlv(tlvBytes); LOG.trace("Tlv was parsed. {}", tlv); addTlv(builder, tlv); } else { LOG.warn("Unknown TLV received. Type {}. Ignoring it.", type); } byteOffset += length + getPadding(TLV_HEADER_LENGTH + length, PADDED_TO); } } protected final byte[] serializeTlv(final Tlv tlv) { final TlvSerializer serializer = this.tlvReg.getTlvSerializer(tlv); final byte[] typeBytes = ByteArray.intToBytes(serializer.getType(), TLV_TYPE_F_LENGTH); final byte[] valueBytes = serializer.serializeTlv(tlv); final byte[] lengthBytes = ByteArray.intToBytes(valueBytes.length, TLV_LENGTH_F_LENGTH); final byte[] bytes = new byte[TLV_HEADER_LENGTH + valueBytes.length + getPadding(TLV_HEADER_LENGTH + valueBytes.length, PADDED_TO)]; int byteOffset = 0; System.arraycopy(typeBytes, 0, bytes, byteOffset, TLV_TYPE_F_LENGTH); byteOffset += TLV_TYPE_F_LENGTH; System.arraycopy(lengthBytes, 0, bytes, byteOffset, TLV_LENGTH_F_LENGTH); byteOffset += TLV_LENGTH_F_LENGTH; System.arraycopy(valueBytes, 0, bytes, byteOffset, valueBytes.length); return bytes; } public abstract void addTlv(final T builder, final Tlv tlv); protected static int getPadding(final int length, final int padding) { return (padding - (length % padding)) % padding; } }
package uk.org.cinquin.mutinack; import static contrib.uk.org.lidalia.slf4jext.Level.TRACE; import static uk.org.cinquin.mutinack.MutationType.INSERTION; import static uk.org.cinquin.mutinack.MutationType.SUBSTITUTION; import static uk.org.cinquin.mutinack.MutationType.WILDTYPE; import static uk.org.cinquin.mutinack.candidate_sequences.DuplexAssay.DISAGREEMENT; import static uk.org.cinquin.mutinack.candidate_sequences.DuplexAssay.MISSING_STRAND; import static uk.org.cinquin.mutinack.candidate_sequences.DuplexAssay.N_READS_PER_STRAND; import static uk.org.cinquin.mutinack.candidate_sequences.DuplexAssay.QUALITY_AT_POSITION; import static uk.org.cinquin.mutinack.candidate_sequences.PositionAssay.FRACTION_WRONG_PAIRS_AT_POS; import static uk.org.cinquin.mutinack.candidate_sequences.PositionAssay.MAX_AVERAGE_CLIPPING_OF_DUPLEX_AT_POS; import static uk.org.cinquin.mutinack.candidate_sequences.PositionAssay.MAX_DPLX_Q_IGNORING_DISAG; import static uk.org.cinquin.mutinack.candidate_sequences.PositionAssay.MAX_Q_FOR_ALL_DUPLEXES; import static uk.org.cinquin.mutinack.candidate_sequences.PositionAssay.MEDIAN_CANDIDATE_PHRED; import static uk.org.cinquin.mutinack.candidate_sequences.PositionAssay.MEDIAN_PHRED_AT_POS; import static uk.org.cinquin.mutinack.candidate_sequences.PositionAssay.NO_DUPLEXES; import static uk.org.cinquin.mutinack.misc_util.DebugLogControl.NONTRIVIAL_ASSERTIONS; import static uk.org.cinquin.mutinack.misc_util.Util.basesEqual; import static uk.org.cinquin.mutinack.qualities.Quality.ATROCIOUS; import static uk.org.cinquin.mutinack.qualities.Quality.DUBIOUS; import static uk.org.cinquin.mutinack.qualities.Quality.GOOD; import static uk.org.cinquin.mutinack.qualities.Quality.MINIMUM; import static uk.org.cinquin.mutinack.qualities.Quality.POOR; import static uk.org.cinquin.mutinack.qualities.Quality.max; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.IntSummaryStatistics; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Random; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; import java.util.stream.Collectors; import org.eclipse.collections.api.list.MutableList; import org.eclipse.collections.api.list.primitive.MutableFloatList; import org.eclipse.collections.api.multimap.set.MutableSetMultimap; import org.eclipse.collections.api.set.ImmutableSet; import org.eclipse.collections.api.set.MutableSet; import org.eclipse.collections.impl.factory.Lists; import org.eclipse.collections.impl.factory.Sets; import org.eclipse.collections.impl.list.mutable.primitive.FloatArrayList; import org.eclipse.collections.impl.set.mutable.UnifiedSet; import org.eclipse.jdt.annotation.NonNull; import org.eclipse.jdt.annotation.Nullable; import contrib.net.sf.picard.reference.ReferenceSequence; import contrib.net.sf.samtools.CigarOperator; import contrib.net.sf.samtools.SAMRecord; import contrib.net.sf.samtools.SamPairUtil; import contrib.net.sf.samtools.SamPairUtil.PairOrientation; import contrib.net.sf.samtools.util.StringUtil; import contrib.uk.org.lidalia.slf4jext.Logger; import contrib.uk.org.lidalia.slf4jext.LoggerFactory; import gnu.trove.list.array.TByteArrayList; import gnu.trove.map.TByteObjectMap; import gnu.trove.map.hash.TByteObjectHashMap; import gnu.trove.map.hash.THashMap; import gnu.trove.map.hash.TIntObjectHashMap; import gnu.trove.procedure.TObjectProcedure; import gnu.trove.set.hash.TCustomHashSet; import gnu.trove.set.hash.THashSet; import uk.org.cinquin.mutinack.candidate_sequences.CandidateBuilder; import uk.org.cinquin.mutinack.candidate_sequences.CandidateCounter; import uk.org.cinquin.mutinack.candidate_sequences.CandidateDeletion; import uk.org.cinquin.mutinack.candidate_sequences.CandidateSequence; import uk.org.cinquin.mutinack.candidate_sequences.DuplexAssay; import uk.org.cinquin.mutinack.candidate_sequences.ExtendedAlignmentBlock; import uk.org.cinquin.mutinack.candidate_sequences.PositionAssay; import uk.org.cinquin.mutinack.misc_util.Assert; import uk.org.cinquin.mutinack.misc_util.ComparablePair; import uk.org.cinquin.mutinack.misc_util.DebugLogControl; import uk.org.cinquin.mutinack.misc_util.Handle; import uk.org.cinquin.mutinack.misc_util.Pair; import uk.org.cinquin.mutinack.misc_util.SettableDouble; import uk.org.cinquin.mutinack.misc_util.SettableInteger; import uk.org.cinquin.mutinack.misc_util.Util; import uk.org.cinquin.mutinack.misc_util.collections.HashingStrategies; import uk.org.cinquin.mutinack.misc_util.collections.InterningSet; import uk.org.cinquin.mutinack.misc_util.exceptions.AssertionFailedException; import uk.org.cinquin.mutinack.output.LocationExaminationResults; import uk.org.cinquin.mutinack.qualities.DetailedPositionQualities; import uk.org.cinquin.mutinack.qualities.DetailedQualities; import uk.org.cinquin.mutinack.qualities.Quality; import uk.org.cinquin.mutinack.statistics.DoubleAdderFormatter; import uk.org.cinquin.mutinack.statistics.Histogram; public final class SubAnalyzer { private static final Logger logger = LoggerFactory.getLogger(SubAnalyzer.class); public final @NonNull Mutinack analyzer; @NonNull Parameters param; @NonNull AnalysisStats stats;//Will in fact be null until set in SubAnalyzerPhaser but that's OK final @NonNull SettableInteger lastProcessablePosition = new SettableInteger(-1); final @NonNull THashMap<SequenceLocation, THashSet<CandidateSequence>> candidateSequences = new THashMap<>(1_000); int truncateProcessingAt = Integer.MAX_VALUE; int startProcessingAt = 0; MutableList<@NonNull DuplexRead> analyzedDuplexes; float[] averageClipping; int averageClippingOffset = Integer.MAX_VALUE; final @NonNull THashMap<String, @NonNull ExtendedSAMRecord> extSAMCache = new THashMap<>(10_000, 0.5f); private final AtomicInteger threadCount = new AtomicInteger(); @NonNull Map<@NonNull ExtendedSAMRecord, @NonNull SAMRecord> readsToWrite = new THashMap<>(); private final Random random; private static final @NonNull Set<DuplexAssay> assaysToIgnoreForDisagreementQuality = Collections.unmodifiableSet(EnumSet.copyOf(Collections.singletonList(DISAGREEMENT))), assaysToIgnoreForDuplexNStrands = Collections.unmodifiableSet(EnumSet.copyOf(Arrays.asList(N_READS_PER_STRAND, MISSING_STRAND))); static final @NonNull TByteObjectMap<@NonNull String> byteMap; static { byteMap = new TByteObjectHashMap<>(); byteMap.put((byte) 'A', "A"); byteMap.put((byte) 'a', "A"); byteMap.put((byte) 'T', "T"); byteMap.put((byte) 't', "T"); byteMap.put((byte) 'G', "G"); byteMap.put((byte) 'g', "G"); byteMap.put((byte) 'C', "C"); byteMap.put((byte) 'c', "C"); byteMap.put((byte) 'N', "N"); byteMap.put((byte) 'n', "N"); } static final @NonNull TByteObjectMap<byte @NonNull[]> byteArrayMap; static { byteArrayMap = new TByteObjectHashMap<>(); byteArrayMap.put((byte) 'A', new byte[] {'A'}); byteArrayMap.put((byte) 'a', new byte[] {'a'}); byteArrayMap.put((byte) 'T', new byte[] {'T'}); byteArrayMap.put((byte) 't', new byte[] {'t'}); byteArrayMap.put((byte) 'G', new byte[] {'G'}); byteArrayMap.put((byte) 'g', new byte[] {'g'}); byteArrayMap.put((byte) 'C', new byte[] {'C'}); byteArrayMap.put((byte) 'c', new byte[] {'c'}); byteArrayMap.put((byte) 'N', new byte[] {'N'}); byteArrayMap.put((byte) 'n', new byte[] {'n'}); } private volatile boolean writing = false; synchronized void queueOutputRead(@NonNull ExtendedSAMRecord e, @NonNull SAMRecord r, boolean mayAlreadyBeQueued) { Assert.isFalse(writing); final SAMRecord previous; if ((previous = readsToWrite.put(e, r)) != null && !mayAlreadyBeQueued) { throw new IllegalStateException("Read " + e.getFullName() + " already queued for writing; new: " + r.toString() + "; previous: " + previous.toString()); } } void writeOutputReads() { writing = true; try { synchronized(analyzer.outputAlignmentWriter) { for (SAMRecord samRecord: readsToWrite.values()) { Objects.requireNonNull(analyzer.outputAlignmentWriter).addAlignment(samRecord); } } readsToWrite.clear(); } finally { writing = false; } } @SuppressWarnings("null")//Stats not initialized straight away SubAnalyzer(@NonNull Mutinack analyzer) { this.analyzer = analyzer; this.param = analyzer.param; useHashMap = param.alignmentPositionMismatchAllowed == 0; random = new Random(param.randomSeed); } private boolean meetsQ2Thresholds(@NonNull ExtendedSAMRecord extendedRec) { return !extendedRec.formsWrongPair() && extendedRec.getnClipped() <= param.maxAverageBasesClipped && extendedRec.getMappingQuality() >= param.minMappingQualityQ2 && Math.abs(extendedRec.getInsertSize()) <= param.maxInsertSize; } /** * Make sure that concurring reads get associated with a unique candidate. * We should *not* insert candidates directly into candidateSequences. * Get interning as a small, beneficial side effect. * @param candidate * @param location * @return */ private @NonNull CandidateSequence insertCandidateAtPosition(@NonNull CandidateSequence candidate, @NonNull SequenceLocation location) { //No need for synchronization since we should not be //concurrently inserting two candidates at the same position THashSet<CandidateSequence> candidates = candidateSequences.computeIfAbsent(location, k -> new THashSet<>(2)); CandidateSequence candidateMapValue = candidates.get(candidate); if (candidateMapValue == null) { boolean added = candidates.add(candidate); Assert.isTrue(added); } else { candidateMapValue.mergeWith(candidate); candidate = candidateMapValue; } return candidate; } /** * Load all reads currently referred to by candidate sequences and group them into DuplexReads * @param toPosition * @param fromPosition */ void load(int fromPosition, int toPosition) { Assert.isFalse(threadCount.incrementAndGet() > 1); try { if (toPosition < fromPosition) { throw new IllegalArgumentException("Going from " + fromPosition + " to " + toPosition); } final List<@NonNull DuplexRead> resultDuplexes = new ArrayList<>(3_000); loadAll(fromPosition, toPosition, resultDuplexes); analyzedDuplexes = Lists.mutable.withAll(resultDuplexes); } finally { if (NONTRIVIAL_ASSERTIONS) { threadCount.decrementAndGet(); } } } void checkAllDone() { if (!candidateSequences.isEmpty()) { final SettableInteger nLeftBehind = new SettableInteger(-1); candidateSequences.forEach((k,v) -> { Assert.isTrue(v.isEmpty() || (v.iterator().next().getLocation().equals(k)), "Mismatched locations"); String s = v.stream(). filter(c -> c.getLocation().position > truncateProcessingAt + param.maxInsertSize && c.getLocation().position < startProcessingAt - param.maxInsertSize). flatMap(v0 -> v0.getNonMutableConcurringReads().keySet().stream()). map(read -> { if (nLeftBehind.incrementAndGet() == 0) { logger.error("Sequences left behind before " + truncateProcessingAt); } return Integer.toString(read.getAlignmentStart()) + '-' + Integer.toString(read.getAlignmentEnd()); }) .collect(Collectors.joining("; ")); if (!s.equals("")) { logger.error(s); } }); Assert.isFalse(nLeftBehind.get() > 0); } } private final boolean useHashMap; private @NonNull DuplexKeeper getDuplexKeeper(boolean fallBackOnIntervalTree) { final @NonNull DuplexKeeper result; if (MutinackGroup.forceKeeperType != null) { switch(MutinackGroup.forceKeeperType) { case "DuplexHashMapKeeper": if (useHashMap) { result = new DuplexHashMapKeeper(); } else { result = new DuplexArrayListKeeper(5_000); } break; //case "DuplexITKeeper": // result = new DuplexITKeeper(); // break; case "DuplexArrayListKeeper": result = new DuplexArrayListKeeper(5_000); break; default: throw new AssertionFailedException(); } } else { if (useHashMap) { result = new DuplexHashMapKeeper(); } else /*if (fallBackOnIntervalTree) { result = new DuplexITKeeper(); } else */{ result = new DuplexArrayListKeeper(5_000); } } return result; } /** * Group reads into duplexes. * @param toPosition * @param fromPosition * @param finalResult */ private void loadAll( final int fromPosition, final int toPosition, final @NonNull List<DuplexRead> finalResult) { /** * Use a custom hash map type to keep track of duplexes when * alignmentPositionMismatchAllowed is 0. * This provides by far the highest performance. * When alignmentPositionMismatchAllowed is greater than 0, use * either an interval tree or a plain list. The use of an interval * tree instead of a plain list provides a speed benefit only when * there is large number of local duplexes, so switch dynamically * based on that number. The threshold was optimized empirically * and at a gross level. */ final boolean fallBackOnIntervalTree = extSAMCache.size() > 5_000; @NonNull DuplexKeeper duplexKeeper = getDuplexKeeper(fallBackOnIntervalTree); InterningSet<SequenceLocation> sequenceLocationCache = new InterningSet<>(500); final AlignmentExtremetiesDistance ed = new AlignmentExtremetiesDistance( analyzer.groupSettings, param); final SettableInteger nReadsExcludedFromDuplexes = new SettableInteger(0); final TObjectProcedure<@NonNull ExtendedSAMRecord> callLoadRead = rExtended -> { loadRead(rExtended, duplexKeeper, ed, sequenceLocationCache, nReadsExcludedFromDuplexes); return true; }; if (param.jiggle) { List<@NonNull ExtendedSAMRecord> reorderedReads = new ArrayList<>(extSAMCache.values()); Collections.shuffle(reorderedReads, random); reorderedReads.forEach(e -> callLoadRead.execute(e)); } else { extSAMCache.forEachValue(callLoadRead); } sequenceLocationCache.clear();//Not strictly necessary, but might as well release the //memory now if (param.randomizeStrand) { duplexKeeper.forEach(dr -> dr.randomizeStrands(random)); } duplexKeeper.forEach(DuplexRead::computeGlobalProperties); Pair<DuplexRead, DuplexRead> pair; if (param.enableCostlyAssertions && (pair = DuplexRead.checkNoEqualDuplexes(duplexKeeper.getIterable())) != null) { throw new AssertionFailedException("Equal duplexes: " + pair.fst + " and " + pair.snd); } if (param.enableCostlyAssertions) { Assert.isTrue(checkReadsOccurOnceInDuplexes(extSAMCache.values(), duplexKeeper.getIterable(), nReadsExcludedFromDuplexes.get())); } //Group duplexes that have alignment positions that differ by at most //param.alignmentPositionMismatchAllowed //and left/right consensus that differ by at most //param.nVariableBarcodeMismatchesAllowed final DuplexKeeper cleanedUpDuplexes = param.nVariableBarcodeMismatchesAllowed > 0 ? DuplexRead.groupDuplexes( duplexKeeper, duplex -> duplex.computeConsensus(false, param.variableBarcodeLength), () -> getDuplexKeeper(fallBackOnIntervalTree), param, stats, 0) : duplexKeeper; if (param.nVariableBarcodeMismatchesAllowed == 0) { cleanedUpDuplexes.forEach(d -> d.computeConsensus(true, param.variableBarcodeLength)); } //Group duplexes by alignment start (or equivalent) TIntObjectHashMap<List<DuplexRead>> duplexPositions = new TIntObjectHashMap<> (1_000, 0.5f, -999); cleanedUpDuplexes.forEach(dr -> { List<DuplexRead> list = duplexPositions.computeIfAbsent(dr.position0, (Supplier<List<DuplexRead>>) ArrayList::new); list.add(dr); }); if (param.variableBarcodeLength == 0) { final double @NonNull[] insertSizeProb = Objects.requireNonNull(analyzer.insertSizeProbSmooth); duplexPositions.forEachValue(list -> { for (DuplexRead dr: list) { double sizeP = insertSizeProb[ Math.min(insertSizeProb.length - 1, dr.maxInsertSize)]; Assert.isTrue(Double.isNaN(sizeP) || sizeP >= 0, () -> "Insert size problem: " + Arrays.toString(insertSizeProb)); dr.probAtLeastOneCollision = 1 - Math.pow(1 - sizeP, list.size()); } return true; }); } cleanedUpDuplexes.forEach(duplexRead -> duplexRead.analyzeForStats(param, stats)); cleanedUpDuplexes.forEach(finalResult::add); averageClippingOffset = fromPosition; final int arrayLength = toPosition - fromPosition + 1; averageClipping = new float[arrayLength]; int[] duplexNumber = new int[arrayLength]; cleanedUpDuplexes.forEach(duplexRead -> { int start = duplexRead.getUnclippedAlignmentStart() - fromPosition; int stop = duplexRead.getUnclippedAlignmentEnd() - fromPosition; start = Math.min(Math.max(0, start), toPosition - fromPosition); stop = Math.min(Math.max(0, stop), toPosition - fromPosition); for (int i = start; i <= stop; i++) { averageClipping[i] += duplexRead.averageNClipped; duplexNumber[i]++; } }); for (int i = 0; i < averageClipping.length; i++) { int n = duplexNumber[i]; if (n == 0) { Assert.isTrue(averageClipping[i] == 0); } else { averageClipping[i] /= n; } } }//End loadAll private void loadRead(@NonNull ExtendedSAMRecord rExtended, @NonNull DuplexKeeper duplexKeeper, AlignmentExtremetiesDistance ed, InterningSet<SequenceLocation> sequenceLocationCache, SettableInteger nReadsExcludedFromDuplexes) { final @NonNull SequenceLocation location = rExtended.getLocation(); final byte @NonNull[] barcode = rExtended.variableBarcode; final byte @NonNull[] mateBarcode = rExtended.getMateVariableBarcode(); final @NonNull SAMRecord r = rExtended.record; if (rExtended.getMate() == null) { stats.nMateOutOfReach.add(location, 1); } if (r.getMateUnmappedFlag()) { //It is not trivial to tell whether the mate is unmapped because //e.g. it did not sequence properly, or because all of the reads //from the duplex just do not map to the genome. To avoid //artificially inflating local duplex number, do not allow the //read to contribute to computed duplexes. Note that the rest of //the duplex-handling code could technically handle an unmapped //mate, and that the read will still be able to contribute to //local statistics such as average clipping. nReadsExcludedFromDuplexes.incrementAndGet(); return; } boolean foundDuplexRead = false; final boolean matchToLeft = rExtended.duplexLeft(); ed.set(rExtended); for (final DuplexRead duplexRead: duplexKeeper.getOverlapping(ed.temp)) { //stats.nVariableBarcodeCandidateExaminations.increment(location); ed.set(duplexRead); if (ed.getMaxDistance() > param.alignmentPositionMismatchAllowed) { continue; } final boolean barcodeMatch; //During first pass, do not allow any barcode mismatches if (matchToLeft) { barcodeMatch = basesEqual(duplexRead.leftBarcode, barcode, param.acceptNInBarCode) && basesEqual(duplexRead.rightBarcode, mateBarcode, param.acceptNInBarCode); } else { barcodeMatch = basesEqual(duplexRead.leftBarcode, mateBarcode, param.acceptNInBarCode) && basesEqual(duplexRead.rightBarcode, barcode, param.acceptNInBarCode); } if (barcodeMatch) { if (r.getInferredInsertSize() >= 0) { if (r.getFirstOfPairFlag()) { if (param.enableCostlyAssertions) { Assert.isFalse(duplexRead.topStrandRecords.contains(rExtended)); } duplexRead.topStrandRecords.add(rExtended); } else { if (param.enableCostlyAssertions) { Assert.isFalse(duplexRead.bottomStrandRecords.contains(rExtended)); } duplexRead.bottomStrandRecords.add(rExtended); } } else { if (r.getFirstOfPairFlag()) { if (param.enableCostlyAssertions) { Assert.isFalse(duplexRead.bottomStrandRecords.contains(rExtended)); } duplexRead.bottomStrandRecords.add(rExtended); } else { if (param.enableCostlyAssertions) { Assert.isFalse(duplexRead.topStrandRecords.contains(rExtended)); } duplexRead.topStrandRecords.add(rExtended); } } if (param.enableCostlyAssertions) { Assert.noException(duplexRead::assertAllBarcodesEqual); } rExtended.duplexRead = duplexRead; //stats.nVariableBarcodeMatchAfterPositionCheck.increment(location); foundDuplexRead = true; break; } else {//left and/or right barcodes do not match /* leftEqual = basesEqual(duplexRead.leftBarcode, barcode, true, 1); rightEqual = basesEqual(duplexRead.rightBarcode, barcode, true, 1); if (leftEqual || rightEqual) { stats.nVariableBarcodesCloseMisses.increment(location); }*/ } }//End loop over duplexReads if (!foundDuplexRead) { final DuplexRead duplexRead = matchToLeft ? new DuplexRead(analyzer.groupSettings, barcode, mateBarcode, !r.getReadNegativeStrandFlag(), r.getReadNegativeStrandFlag()) : new DuplexRead(analyzer.groupSettings, mateBarcode, barcode, r.getReadNegativeStrandFlag(), !r.getReadNegativeStrandFlag()); if (matchToLeft) { duplexRead.setPositions( rExtended.getOffsetUnclippedStart(), rExtended.getMateOffsetUnclippedEnd()); } else { duplexRead.setPositions( rExtended.getMateOffsetUnclippedStart(), rExtended.getOffsetUnclippedEnd()); } duplexKeeper.add(duplexRead); duplexRead.roughLocation = location; rExtended.duplexRead = duplexRead; if (!matchToLeft) { if (rExtended.getMateAlignmentStart() == rExtended.getAlignmentStart()) { //Reads that completely overlap because of short insert size stats.nPosDuplexCompletePairOverlap.increment(location); } //Arbitrarily choose top strand as the one associated with //first of pair that maps to the lowest position in the contig if (!r.getFirstOfPairFlag()) { duplexRead.topStrandRecords.add(rExtended); } else { duplexRead.bottomStrandRecords.add(rExtended); } if (param.enableCostlyAssertions) { Assert.noException(duplexRead::assertAllBarcodesEqual); } duplexRead.rightAlignmentStart = sequenceLocationCache.intern( new SequenceLocation(rExtended.getReferenceIndex(), rExtended.getReferenceName(), rExtended.getOffsetUnclippedStart())); duplexRead.rightAlignmentEnd = sequenceLocationCache.intern( new SequenceLocation(rExtended.getReferenceIndex(), rExtended.getReferenceName(), rExtended.getOffsetUnclippedEnd())); duplexRead.leftAlignmentStart = sequenceLocationCache.intern( new SequenceLocation(rExtended.getReferenceIndex(), rExtended.getReferenceName(), rExtended.getMateOffsetUnclippedStart())); duplexRead.leftAlignmentEnd = sequenceLocationCache.intern( new SequenceLocation(rExtended.getReferenceIndex(), rExtended.getReferenceName(), rExtended.getMateOffsetUnclippedEnd())); } else {//Read on positive strand if (rExtended.getMateAlignmentStart() == rExtended.getAlignmentStart()) { //Reads that completely overlap because of short insert size? stats.nPosDuplexCompletePairOverlap.increment(location); } //Arbitrarily choose top strand as the one associated with //first of pair that maps to the lowest position in the contig if (r.getFirstOfPairFlag()) { duplexRead.topStrandRecords.add(rExtended); } else { duplexRead.bottomStrandRecords.add(rExtended); } if (param.enableCostlyAssertions) { Assert.noException(duplexRead::assertAllBarcodesEqual); } duplexRead.leftAlignmentStart = sequenceLocationCache.intern( new SequenceLocation(rExtended.getReferenceIndex(), r.getReferenceName(), rExtended.getOffsetUnclippedStart())); duplexRead.leftAlignmentEnd = sequenceLocationCache.intern( new SequenceLocation(rExtended.getReferenceIndex(), r.getReferenceName(), rExtended.getOffsetUnclippedEnd())); duplexRead.rightAlignmentStart = sequenceLocationCache.intern( new SequenceLocation(rExtended.getReferenceIndex(), r.getReferenceName(), rExtended.getMateOffsetUnclippedStart())); duplexRead.rightAlignmentEnd = sequenceLocationCache.intern( new SequenceLocation(rExtended.getReferenceIndex(), r.getReferenceName(), rExtended.getMateOffsetUnclippedEnd())); } Assert.isFalse( duplexRead.leftAlignmentEnd.compareTo(duplexRead.leftAlignmentStart) < 0, (Supplier<Object>) duplexRead.leftAlignmentStart::toString, (Supplier<Object>) duplexRead.leftAlignmentEnd::toString, (Supplier<Object>) duplexRead::toString, (Supplier<Object>) rExtended::getFullName, "Misordered duplex: %s -- %s %s %s"); }//End new duplex creation } private static boolean checkReadsOccurOnceInDuplexes( Collection<@NonNull ExtendedSAMRecord> reads, @NonNull Iterable<DuplexRead> duplexes, int nReadsExcludedFromDuplexes) { ExtendedSAMRecord lostRead = null; int nUnfoundReads = 0; for (final @NonNull ExtendedSAMRecord rExtended: reads) { boolean found = false; for (DuplexRead dr: duplexes) { if (dr.topStrandRecords.contains(rExtended)) { if (found) { throw new AssertionFailedException("Two occurrences of read " + rExtended); } found = true; } if (dr.bottomStrandRecords.contains(rExtended)) { if (found) { throw new AssertionFailedException("Two occurrences of read " + rExtended); } found = true; } } if (!found) { nUnfoundReads++; lostRead = rExtended; } } if (nUnfoundReads != nReadsExcludedFromDuplexes) { throw new AssertionFailedException("Lost " + nUnfoundReads + " but expected " + nReadsExcludedFromDuplexes + "; see perhaps " + lostRead); } return true; } @NonNull LocationExaminationResults examineLocation(final @NonNull SequenceLocation location) { Assert.isFalse(threadCount.incrementAndGet() > 1); try { return examineLocation0(location); } finally { threadCount.decrementAndGet(); } } @SuppressWarnings({"null", "ReferenceEquality"}) /** * This method is *NOT* thread-safe (it modifies DuplexReads associated with location retrieved * from field candidateSequences) * @param location * @return */ @NonNull private LocationExaminationResults examineLocation0(final @NonNull SequenceLocation location) { final LocationExaminationResults result = new LocationExaminationResults(); final THashSet<CandidateSequence> candidateSet0 = candidateSequences.get(location); if (candidateSet0 == null) { stats.nPosUncovered.increment(location); result.analyzedCandidateSequences = Sets.immutable.empty(); return result; } final ImmutableSet<CandidateSequence> candidateSet = // DebugLogControl.COSTLY_ASSERTIONS ? // Collections.unmodifiableSet(candidateSet0) Sets.immutable.ofAll(candidateSet0); //Retrieve relevant duplex reads //It is necessary not to duplicate the duplex reads, hence the use of a set //Identity should be good enough (and is faster) because no two different duplex read //objects we use in this method should be equal according to the equals() method //(although when grouping duplexes we don't check equality for the inner ends of //the reads since they depend on read length) final TCustomHashSet<DuplexRead> duplexReads = new TCustomHashSet<>(HashingStrategies.identityHashingStrategy, 200); candidateSet.forEach(candidate -> { candidate.getQuality().reset(); candidate.getDuplexes().clear();//Should have no effect candidate.restoreConcurringReads(); final Set<DuplexRead> candidateDuplexReads = new TCustomHashSet<>(HashingStrategies.identityHashingStrategy, 200); candidate.getNonMutableConcurringReads().forEachEntry((r, c) -> { @Nullable DuplexRead d = r.duplexRead; if (d != null) { candidateDuplexReads.add(d); } else { //throw new AssertionFailedException("Read without a duplex :" + r); } return true; }); duplexReads.addAll(candidateDuplexReads); }); //Allocate here to avoid repeated allocation in DuplexRead::examineAtLoc final CandidateCounter topCounter = new CandidateCounter(candidateSet, location); final CandidateCounter bottomCounter = new CandidateCounter(candidateSet, location); int[] insertSizes = new int [duplexReads.size()]; SettableDouble averageCollisionProbS = new SettableDouble(0d); SettableInteger index = new SettableInteger(0); duplexReads.forEach(duplexRead -> { Assert.isFalse(duplexRead.invalid); Assert.isTrue(duplexRead.averageNClipped >= 0); Assert.isTrue(param.variableBarcodeLength > 0 || Double.isNaN(duplexRead.probAtLeastOneCollision) || duplexRead.probAtLeastOneCollision >= 0); duplexRead.examineAtLoc( location, result, candidateSet, assaysToIgnoreForDisagreementQuality, topCounter, bottomCounter, analyzer, param, stats); if (index.get() < insertSizes.length) { //Check in case array size was capped (for future use; it is //never capped currently) insertSizes[index.get()] = duplexRead.maxInsertSize; index.incrementAndGet(); } averageCollisionProbS.addAndGet(duplexRead.probAtLeastOneCollision); if (param.variableBarcodeLength == 0 && !duplexRead.missingStrand) { stats.duplexCollisionProbabilityWhen2Strands.insert((int) (1_000f * duplexRead.probAtLeastOneCollision)); } }); if (param.enableCostlyAssertions) { Assert.noException(() -> checkDuplexAndCandidates(duplexReads, candidateSet)); } if (index.get() > 0) { Arrays.parallelSort(insertSizes, 0, index.get()); result.duplexInsertSize10thP = insertSizes[(int) (index.get() * 0.1f)]; result.duplexInsertSize90thP = insertSizes[(int) (index.get() * 0.9f)]; } double averageCollisionProb = averageCollisionProbS.get(); averageCollisionProb /= duplexReads.size(); if (param.variableBarcodeLength == 0) { stats.duplexCollisionProbability.insert((int) (1_000d * averageCollisionProb)); } result.probAtLeastOneCollision = averageCollisionProb; final DetailedQualities<PositionAssay> positionQualities = new DetailedPositionQualities(); if (averageClipping[location.position - averageClippingOffset] > param.maxAverageClippingOfAllCoveringDuplexes) { positionQualities.addUnique( MAX_AVERAGE_CLIPPING_OF_DUPLEX_AT_POS, DUBIOUS); } if (param.enableCostlyAssertions) { Assert.noException(() -> duplexReads.forEach(duplexRead -> { for (int i = duplexRead.topStrandRecords.size() - 1; i >= 0; --i) { ExtendedSAMRecord r = duplexRead.topStrandRecords.get(i); if (r.duplexRead != duplexRead) { throw new AssertionFailedException(); } if (duplexRead.bottomStrandRecords.contains(r)) { throw new AssertionFailedException(); } } for (int i = duplexRead.bottomStrandRecords.size() - 1; i >= 0; --i) { ExtendedSAMRecord r = duplexRead.bottomStrandRecords.get(i); if (r.duplexRead != duplexRead) { throw new AssertionFailedException(); } if (duplexRead.topStrandRecords.contains(r)) { throw new AssertionFailedException(); } } return true; })); } final int totalReadsAtPosition = (int) candidateSet.sumOfInt( c -> c.getNonMutableConcurringReads().size()); final TByteArrayList allPhredQualitiesAtPosition = new TByteArrayList(500); final SettableInteger nWrongPairsAtPosition = new SettableInteger(0); final SettableInteger nPairsAtPosition = new SettableInteger(0); candidateSet.forEach(candidate -> { candidate.addPhredScoresToList(allPhredQualitiesAtPosition); nPairsAtPosition.addAndGet(candidate.getNonMutableConcurringReads().size()); SettableInteger count = new SettableInteger(0); candidate.getNonMutableConcurringReads().forEachKey(r -> { if (r.formsWrongPair()) { count.incrementAndGet(); } return true; }); candidate.setnWrongPairs(count.get()); nWrongPairsAtPosition.addAndGet(candidate.getnWrongPairs()); }); final int nPhredQualities = allPhredQualitiesAtPosition.size(); allPhredQualitiesAtPosition.sort(); final byte positionMedianPhred = nPhredQualities == 0 ? 127 : allPhredQualitiesAtPosition.get(nPhredQualities / 2); if (positionMedianPhred < param.minMedianPhredScoreAtPosition) { positionQualities.addUnique(MEDIAN_PHRED_AT_POS, DUBIOUS); stats.nMedianPhredAtPositionTooLow.increment(location); } stats.medianPositionPhredQuality.insert(positionMedianPhred); if (nWrongPairsAtPosition.get() / ((float) nPairsAtPosition.get()) > param.maxFractionWrongPairsAtPosition) { positionQualities.addUnique(FRACTION_WRONG_PAIRS_AT_POS, DUBIOUS); stats.nFractionWrongPairsAtPositionTooHigh.increment(location); } Quality maxQuality; int totalGoodDuplexes, totalGoodOrDubiousDuplexes, totalGoodDuplexesIgnoringDisag, totalAllDuplexes; Handle<Byte> wildtypeBase = new Handle<>((byte) 'X'); candidateSet.forEach(candidate -> { candidate.getQuality().addAllUnique(positionQualities); processCandidateQualityStep1(candidate, location, result, positionMedianPhred, positionQualities); if (candidate.getMutationType().isWildtype()) { wildtypeBase.set(candidate.getWildtypeSequence()); } }); boolean leave = false; final boolean qualityOKBeforeTopAllele = Quality.nullableMax(positionQualities.getValue(true), GOOD).atLeast(GOOD); Quality topAlleleQuality = null; do { maxQuality = MINIMUM; totalAllDuplexes = 0; totalGoodDuplexes = 0; totalGoodOrDubiousDuplexes = 0; totalGoodDuplexesIgnoringDisag = 0; for (CandidateSequence candidate: candidateSet) { if (leave) { candidate.getQuality().addUnique(PositionAssay.TOP_ALLELE_FREQUENCY, DUBIOUS); } @NonNull MutableSetMultimap<Quality, DuplexRead> map = candidate.getDuplexes(). groupBy(dr -> dr.localAndGlobalQuality.getValue()); if (param.enableCostlyAssertions) { map.forEachKeyMultiValues((k, v) -> Assert.isTrue(Util.getDuplicates(v).isEmpty())); Assert.isTrue(map.multiValuesView().collectInt(v -> v.size()).sum() == candidate.getDuplexes().size()); } @Nullable MutableSet<DuplexRead> gd = map.get(GOOD); candidate.setnGoodDuplexes(gd == null ? 0 : gd.size()); @Nullable MutableSet<DuplexRead> db = map.get(DUBIOUS); candidate.setnGoodOrDubiousDuplexes(candidate.getnGoodDuplexes() + (db == null ? 0 : db.size())); candidate.setnGoodDuplexesIgnoringDisag(candidate.getDuplexes(). count(dr -> dr.localAndGlobalQuality.getValueIgnoring(assaysToIgnoreForDisagreementQuality).atLeast(GOOD))); maxQuality = max(candidate.getQuality().getValue(), maxQuality); totalAllDuplexes += candidate.getnDuplexes(); totalGoodDuplexes += candidate.getnGoodDuplexes(); totalGoodOrDubiousDuplexes += candidate.getnGoodOrDubiousDuplexes(); totalGoodDuplexesIgnoringDisag += candidate.getnGoodDuplexesIgnoringDisag(); processCandidateQualityStep2(candidate, location, result, positionMedianPhred, positionQualities); } if (leave) { break; } else { result.nGoodOrDubiousDuplexes = totalGoodOrDubiousDuplexes; topAlleleQuality = getAlleleFrequencyQuality(candidateSet, result); if (topAlleleQuality == null) { break; } Assert.isTrue(topAlleleQuality == DUBIOUS); positionQualities.addUnique(PositionAssay.TOP_ALLELE_FREQUENCY, topAlleleQuality); leave = true;//Just one more iteration continue; } } while(Boolean.valueOf(null));//Assert never reached if (qualityOKBeforeTopAllele) { registerDuplexMinFracTopCandidate(param, duplexReads, topAlleleQuality == null ? stats.minTopCandFreqQ2PosTopAlleleFreqOK : stats.minTopCandFreqQ2PosTopAlleleFreqKO, location); } if (positionQualities.getValue(true) != null && positionQualities.getValue(true).lowerThan(GOOD)) { result.disagreements.clear(); } else { if (param.maxMutFreqForDisag < 1f) { final int finalTotalGoodOrDubiousDuplexes = totalGoodOrDubiousDuplexes; result.disagreements.forEachKey(disag -> { Mutation m = disag.getSnd(); if (!(lowMutFreq(m, candidateSet, finalTotalGoodOrDubiousDuplexes))) { disag.quality = Quality.min(disag.quality, POOR); } m = disag.getFst(); if (m != null && m.mutationType != WILDTYPE) { if (!(lowMutFreq(m, candidateSet, finalTotalGoodOrDubiousDuplexes))) { disag.quality = Quality.min(disag.quality, POOR); } } return true; }); } stats.nPosDuplexCandidatesForDisagreementQ2.acceptSkip0(location, result.disagQ2Coverage); stats.nPosDuplexCandidatesForDisagreementQ1.acceptSkip0(location, result.disagOneStrandedCoverage); if (param.computeRawMismatches) { candidateSet.forEach(c -> c.getRawMismatchesQ2().forEach(result.rawMismatchesQ2::add)); candidateSet.forEach(c -> c.getRawInsertionsQ2().forEach(result.rawInsertionsQ2::add)); candidateSet.forEach(c -> c.getRawDeletionsQ2().forEach(result.rawDeletionsQ2::add)); } } for (CandidateSequence candidate: candidateSet) { candidate.setTotalAllDuplexes(totalAllDuplexes); candidate.setTotalGoodDuplexes(totalGoodDuplexes); candidate.setTotalGoodOrDubiousDuplexes(totalGoodOrDubiousDuplexes); candidate.setTotalReadsAtPosition(totalReadsAtPosition); } result.nGoodOrDubiousDuplexes = totalGoodOrDubiousDuplexes; result.nGoodDuplexes = totalGoodDuplexes; result.nGoodDuplexesIgnoringDisag = totalGoodDuplexesIgnoringDisag; stats.Q1Q2DuplexCoverage.insert(result.nGoodOrDubiousDuplexes); stats.Q2DuplexCoverage.insert(result.nGoodDuplexes); if (result.nGoodOrDubiousDuplexes == 0) { stats.missingStrandsWhenNoUsableDuplex.insert(result.nMissingStrands); stats.strandCoverageImbalanceWhenNoUsableDuplex.insert(result.strandCoverageImbalance); } if (maxQuality.atMost(POOR)) { stats.nPosQualityPoor.increment(location); switch (wildtypeBase.get()) { case 'A' : stats.nPosQualityPoorA.increment(location); break; case 'T' : stats.nPosQualityPoorT.increment(location); break; case 'G' : stats.nPosQualityPoorG.increment(location); break; case 'C' : stats.nPosQualityPoorC.increment(location); break; case 'X' : case 'N' : break;//Ignore because we do not have a record of wildtype sequence default : throw new AssertionFailedException(); } } else if (maxQuality == DUBIOUS) { stats.nPosQualityQ1.increment(location); } else if (maxQuality == GOOD) { stats.nPosQualityQ2.increment(location); } else { throw new AssertionFailedException(); } result.analyzedCandidateSequences = candidateSet; return result; }//End examineLocation private static void registerDuplexMinFracTopCandidate(Parameters param, TCustomHashSet<DuplexRead> duplexReads, Histogram hist, SequenceLocation location) { duplexReads.forEach(dr -> { Assert.isFalse(dr.totalNRecords == -1); if (dr.totalNRecords < 2 || dr.minFracTopCandidate == Float.MAX_VALUE) { return true; } hist.insert((int) (dr.minFracTopCandidate * 10)); return true; }); } private boolean lowMutFreq(Mutation mut, ImmutableSet<CandidateSequence> candidateSet, int nGOrDDuplexes) { Objects.requireNonNull(mut); Handle<Boolean> result = new Handle<>(true); candidateSet.detect((CandidateSequence c) -> { Mutation cMut = c.getMutation(); if (cMut.equals(mut)) { if (c.getnGoodOrDubiousDuplexes() > param.maxMutFreqForDisag * nGOrDDuplexes) { result.set(false); } return true; } return false; }); return result.get(); } private static float divideWithNanToZero(float f1, float f2) { return f2 == 0f ? 0 : f1 / f2; } private @Nullable Quality getAlleleFrequencyQuality( ImmutableSet<CandidateSequence> candidateSet, LocationExaminationResults result) { MutableFloatList frequencyList = candidateSet.collectFloat(c -> divideWithNanToZero(c.getnGoodOrDubiousDuplexes(), result.nGoodOrDubiousDuplexes), new FloatArrayList(Math.max(2, candidateSet.size()))).//Need second argument to collectInt //to avoid collecting into a set sortThis(); result.alleleFrequencies = frequencyList; while (frequencyList.size() < 2) { frequencyList.addAtIndex(0, Float.NaN); } float topAlleleFrequency = frequencyList.getLast(); if (!(topAlleleFrequency >= param.minTopAlleleFreqQ2 && topAlleleFrequency <= param.maxTopAlleleFreqQ2)) { return DUBIOUS; } return null; } @SuppressWarnings("null") private void processCandidateQualityStep1( final CandidateSequence candidate, final @NonNull SequenceLocation location, final LocationExaminationResults result, final byte positionMedianPhred, final @NonNull DetailedQualities<PositionAssay> positionQualities) { candidate.setMedianPhredAtPosition(positionMedianPhred); final byte candidateMedianPhred = candidate.getMedianPhredScore();//Will be -1 for insertions and deletions if (candidateMedianPhred != -1 && candidateMedianPhred < param.minCandidateMedianPhredScore) { candidate.getQuality().addUnique(MEDIAN_CANDIDATE_PHRED, DUBIOUS); } //TODO Should report min rather than average collision probability? candidate.setProbCollision((float) result.probAtLeastOneCollision); candidate.setInsertSizeAtPos10thP(result.duplexInsertSize10thP); candidate.setInsertSizeAtPos90thP(result.duplexInsertSize90thP); final MutableSet<DuplexRead> candidateDuplexes = Sets.mutable.empty(); candidate.getNonMutableConcurringReads().forEachKey(r -> { DuplexRead dr = r.duplexRead; if (dr != null) { Assert.isFalse(dr.invalid); candidateDuplexes.add(dr); } return true; }); candidate.setDuplexes(candidateDuplexes); candidate.setnDuplexes(candidateDuplexes.size()); if (candidate.getnDuplexes() == 0) { candidate.getQuality().addUnique(NO_DUPLEXES, ATROCIOUS); } if (param.verbosity > 2) { candidate.getIssues().clear();//This *must* be done to avoid interference //between parameter sets, in parameter exploration runs candidateDuplexes.forEach(d -> { candidate.getIssues().put(d, d.localAndGlobalQuality.toLong()); }); } final Quality posQMin = positionQualities.getValue(true); Handle<Quality> maxDuplexQHandle = new Handle<>(ATROCIOUS); candidateDuplexes.each(dr -> { if (posQMin != null) { dr.localAndGlobalQuality.addUnique(QUALITY_AT_POSITION, posQMin); } maxDuplexQHandle.set(Quality.max(maxDuplexQHandle.get(), dr.localAndGlobalQuality.getValue())); }); final @NonNull Quality maxDuplexQ = maxDuplexQHandle.get(); switch(param.candidateQ2Criterion) { case "1Q2Duplex": candidate.getQuality().addUnique(MAX_Q_FOR_ALL_DUPLEXES, maxDuplexQ); break; case "NQ1Duplexes": SettableInteger countQ1Duplexes = new SettableInteger(0); candidateDuplexes.forEach(d -> { if (d.localAndGlobalQuality.getValueIgnoring(assaysToIgnoreForDuplexNStrands). atLeast(GOOD)) { countQ1Duplexes.incrementAndGet(); } }); if (countQ1Duplexes.get() >= param.minQ1Duplexes) { candidate.getQuality().addUnique(PositionAssay.N_Q1_DUPLEXES, GOOD); } break; default: throw new AssertionFailedException(); } if (PositionAssay.COMPUTE_MAX_DPLX_Q_IGNORING_DISAG) { candidateDuplexes.stream(). map(dr -> dr.localAndGlobalQuality.getValueIgnoring(assaysToIgnoreForDisagreementQuality, true)). max(Quality::compareTo).ifPresent(q -> candidate.getQuality().addUnique(MAX_DPLX_Q_IGNORING_DISAG, q)); } candidate.resetLigSiteDistances(); if (maxDuplexQ.atLeast(DUBIOUS)) { candidateDuplexes.forEach(dr -> { if (dr.localAndGlobalQuality.getValue().atLeast(maxDuplexQ)) { candidate.acceptLigSiteDistance(dr.getMaxDistanceToLigSite()); } }); } } private void processCandidateQualityStep2( final CandidateSequence candidate, final @NonNull SequenceLocation location, final LocationExaminationResults result, final byte positionMedianPhred, final @NonNull DetailedQualities<PositionAssay> positionQualities ) { if (!param.rnaSeq) { candidate.getNonMutableConcurringReads().forEachKey(r -> { final int refPosition = location.position; final int readPosition = r.referencePositionToReadPosition(refPosition); if (!r.formsWrongPair()) { final int distance = r.tooCloseToBarcode(readPosition, 0); if (Math.abs(distance) > 160) { throw new AssertionFailedException("Distance problem with candidate " + candidate + " read at read position " + readPosition + " and refPosition " + refPosition + ' ' + r.toString() + " in analyzer" + analyzer.inputBam.getAbsolutePath() + "; distance is " + distance); } if (distance >= 0) { stats.singleAnalyzerQ2CandidateDistanceToLigationSite.insert(distance); } else { stats.Q2CandidateDistanceToLigationSiteN.insert(-distance); } } return true; }); } if (candidate.getMutationType().isWildtype()) { candidate.setSupplementalMessage(null); } else if (candidate.getQuality().getNonNullValue().greaterThan(POOR)) { final StringBuilder supplementalMessage = new StringBuilder(); final Map<String, Integer> stringCounts = new HashMap<>(100); candidate.getNonMutableConcurringReads().forEachKey(er -> { String other = er.record.getMateReferenceName(); if (!er.record.getReferenceName().equals(other)) { String s = other + ':' + er.getMateAlignmentStart(); Integer found = stringCounts.get(s); if (found == null){ stringCounts.put(s, 1); } else { stringCounts.put(s, found + 1); } } return true; }); final Optional<String> mates = stringCounts.entrySet().stream().map(entry -> entry.getKey() + ((entry.getValue() == 1) ? "" : (" (" + entry.getValue() + " repeats)")) + "; "). sorted().reduce(String::concat); final String hasMateOnOtherChromosome = mates.isPresent() ? mates.get() : ""; final IntSummaryStatistics insertSizeStats = candidate.getNonMutableConcurringReads().keySet().stream(). mapToInt(er -> Math.abs(er.getInsertSize())).summaryStatistics(); final int localMaxInsertSize = insertSizeStats.getMax(); final int localMinInsertSize = insertSizeStats.getMin(); candidate.setMinInsertSize(localMinInsertSize); candidate.setMaxInsertSize(localMaxInsertSize); if (localMaxInsertSize < param.minInsertSize || localMinInsertSize > param.maxInsertSize) { candidate.getQuality().add(PositionAssay.INSERT_SIZE, DUBIOUS); } final boolean has0PredictedInsertSize = localMinInsertSize == 0; final NumberFormat nf = DoubleAdderFormatter.nf.get(); @SuppressWarnings("null") final boolean hasNoMate = candidate.getNonMutableConcurringReads().forEachKey( er -> er.record.getMateReferenceName() != null); if (localMaxInsertSize > param.maxInsertSize) { supplementalMessage.append("one predicted insert size is " + nf.format(localMaxInsertSize)).append("; "); } if (localMinInsertSize < param.minInsertSize) { supplementalMessage.append("one predicted insert size is " + nf.format(localMinInsertSize)).append("; "); } candidate.setAverageMappingQuality((int) candidate.getNonMutableConcurringReads().keySet().stream(). mapToInt(r -> r.record.getMappingQuality()).summaryStatistics().getAverage()); if (!"".equals(hasMateOnOtherChromosome)) { supplementalMessage.append("pair elements map to other chromosomes: " + hasMateOnOtherChromosome).append("; "); } if (hasNoMate) { supplementalMessage.append("at least one read has no mate; "); } if ("".equals(hasMateOnOtherChromosome) && !hasNoMate && has0PredictedInsertSize) { supplementalMessage.append("at least one insert has 0 predicted size; "); } if (candidate.getnWrongPairs() > 0) { supplementalMessage.append(candidate.getnWrongPairs() + " wrong pairs; "); } candidate.setSupplementalMessage(supplementalMessage); } } @SuppressWarnings("ReferenceEquality") private static Runnable checkDuplexAndCandidates(Set<DuplexRead> duplexReads, ImmutableSet<CandidateSequence> candidateSet) { for (DuplexRead duplexRead: duplexReads) { duplexRead.allDuplexRecords.each(r -> { if (r.duplexRead != duplexRead) { throw new AssertionFailedException("Read " + r + " associated with duplexes " + r.duplexRead + " and " + duplexRead); } }); } candidateSet.each(c -> { Assert.isTrue(c.getNonMutableConcurringReads().keySet().equals( c.getMutableConcurringReads().keySet())); Set<DuplexRead> duplexesSupportingC = new UnifiedSet<>(30); c.getNonMutableConcurringReads().forEachKey(r -> { DuplexRead d = r.duplexRead; if (d != null) { Assert.isFalse(d.invalid); duplexesSupportingC.add(d); } return true; });//Collect *unique* duplexes candidateSet.each(c2 -> { Assert.isTrue(c.getNonMutableConcurringReads().keySet().equals( c.getMutableConcurringReads().keySet())); if (c2 == c) { return; } if (c2.equals(c)) { throw new AssertionFailedException(); } c2.getNonMutableConcurringReads().keySet().forEach(r -> { if (r.isOpticalDuplicate()) { return; } DuplexRead d = r.duplexRead; if (d != null && duplexesSupportingC.contains(d)) { boolean disowned = !d.allDuplexRecords.contains(r); throw new AssertionFailedException(disowned + " Duplex " + d + " associated with candidates " + c + " and " + c2); } }); }); }); return null; } private boolean checkConstantBarcode(byte[] bases, boolean allowN, int nAllowableMismatches) { if (nAllowableMismatches == 0 && !allowN) { return bases == analyzer.constantBarcode;//OK because of interning } int nMismatches = 0; for (int i = 0; i < analyzer.constantBarcode.length; i++) { if (!basesEqual(analyzer.constantBarcode[i], bases[i], allowN)) { nMismatches ++; if (nMismatches > nAllowableMismatches) return false; } } return true; } @SuppressWarnings("null") ExtendedSAMRecord getExtended(@NonNull SAMRecord record, @NonNull SequenceLocation location) { final @NonNull String readFullName = ExtendedSAMRecord.getReadFullName(record, false); return extSAMCache.computeIfAbsent(readFullName, s -> new ExtendedSAMRecord(record, readFullName, analyzer.groupSettings, analyzer, location, extSAMCache)); } /** * * @return the furthest position in the contig covered by the read */ int processRead( final @NonNull SequenceLocation location, final @NonNull InterningSet<SequenceLocation> locationInterningSet, final @NonNull ExtendedSAMRecord extendedRec, final @NonNull ReferenceSequence ref) { Assert.isFalse(extendedRec.processed, "Double processing of record %s"/*, extendedRec.getFullName()*/); extendedRec.processed = true; final SAMRecord rec = extendedRec.record; final byte[] readBases = rec.getReadBases(); final byte[] refBases = ref.getBases(); final byte[] baseQualities = rec.getBaseQualities(); final int effectiveReadLength = extendedRec.effectiveLength; if (effectiveReadLength == 0) { return -1; } final CandidateBuilder readLocalCandidates = new CandidateBuilder(rec.getReadNegativeStrandFlag(), param.enableCostlyAssertions ? null : (k, v) -> insertCandidateAtPosition(v, k)); final int insertSize = extendedRec.getInsertSize(); final int insertSizeAbs = Math.abs(insertSize); if (insertSizeAbs > param.maxInsertSize) { stats.nReadsInsertSizeAboveMaximum.increment(location); if (param.ignoreSizeOutOfRangeInserts) { return -1; } } if (insertSizeAbs < param.minInsertSize) { stats.nReadsInsertSizeBelowMinimum.increment(location); if (param.ignoreSizeOutOfRangeInserts) { return -1; } } final PairOrientation pairOrientation; if (rec.getReadPairedFlag() && !rec.getReadUnmappedFlag() && !rec.getMateUnmappedFlag() && rec.getReferenceIndex().equals(rec.getMateReferenceIndex()) && ((pairOrientation = SamPairUtil.getPairOrientation(rec)) == PairOrientation.TANDEM || pairOrientation == PairOrientation.RF)) { if (pairOrientation == PairOrientation.TANDEM) { stats.nReadsPairTandem.increment(location); } else if (pairOrientation == PairOrientation.RF) { stats.nReadsPairRF.increment(location); } if (param.ignoreTandemRFPairs) { return -1; } } final boolean readOnNegativeStrand = rec.getReadNegativeStrandFlag(); if (!checkConstantBarcode(extendedRec.constantBarcode, false, param.nConstantBarcodeMismatchesAllowed)) { if (checkConstantBarcode(extendedRec.constantBarcode, true, param.nConstantBarcodeMismatchesAllowed)) { if (readOnNegativeStrand) stats.nConstantBarcodeDodgyNStrand.increment(location); else stats.nConstantBarcodeDodgy.increment(location); if (!param.acceptNInBarCode) return -1; } else { stats.nConstantBarcodeMissing.increment(location); return -1; } } stats.nReadsConstantBarcodeOK.increment(location); if (extendedRec.medianPhred < param.minReadMedianPhredScore) { stats.nReadMedianPhredBelowThreshold.accept(location); return -1; } stats.mappingQualityKeptRecords.insert(rec.getMappingQuality()); SettableInteger refEndOfPreviousAlignment = new SettableInteger(-1); SettableInteger readEndOfPreviousAlignment = new SettableInteger(-1); SettableInteger returnValue = new SettableInteger(-1); if (insertSize == 0) { stats.nReadsInsertNoSize.increment(location); if (param.ignoreZeroInsertSizeReads) { return -1; } } for (ExtendedAlignmentBlock block: extendedRec.getAlignmentBlocks()) { processAlignmentBlock(location, locationInterningSet, readLocalCandidates, ref, !param.rnaSeq, block, extendedRec, rec, insertSize, readOnNegativeStrand, readBases, refBases, baseQualities, effectiveReadLength, refEndOfPreviousAlignment, readEndOfPreviousAlignment, returnValue); } if (param.enableCostlyAssertions) { readLocalCandidates.build().forEach((k, v) -> insertCandidateAtPosition(v, k)); } return returnValue.get(); } private void processAlignmentBlock(@NonNull SequenceLocation location, InterningSet<@NonNull SequenceLocation> locationInterningSet, final CandidateBuilder readLocalCandidates, final @NonNull ReferenceSequence ref, final boolean notRnaSeq, final ExtendedAlignmentBlock block, final @NonNull ExtendedSAMRecord extendedRec, final SAMRecord rec, final int insertSize, final boolean readOnNegativeStrand, final byte[] readBases, final byte[] refBases, final byte[] baseQualities, final int effectiveReadLength, final SettableInteger refEndOfPreviousAlignment0, final SettableInteger readEndOfPreviousAlignment0, final SettableInteger returnValue) { int refPosition = block.getReferenceStart() - 1; int readPosition = block.getReadStart() - 1; final int nBlockBases = block.getLength(); final int refEndOfPreviousAlignment = refEndOfPreviousAlignment0.get(); final int readEndOfPreviousAlignment = readEndOfPreviousAlignment0.get(); returnValue.set(Math.max(returnValue.get(), refPosition + nBlockBases)); /** * When adding an insertion candidate, make sure that a wildtype or * mismatch candidate is also inserted at the same position, even * if it normally would not have been (for example because of low Phred * quality). This should avoid awkward comparisons between e.g. an * insertion candidate and a combo insertion + wildtype candidate. */ boolean forceCandidateInsertion = false; if (refEndOfPreviousAlignment != -1) { final boolean insertion = refPosition == refEndOfPreviousAlignment + 1; final boolean tooLate = (readOnNegativeStrand ? (insertion ? readPosition <= param.ignoreLastNBases : readPosition < param.ignoreLastNBases) : readPosition > rec.getReadLength() - param.ignoreLastNBases) && notRnaSeq; if (tooLate) { if (DebugLogControl.shouldLog(TRACE, logger, param, location)) { logger.info("Ignoring indel too close to end " + readPosition + (readOnNegativeStrand ? " neg strand " : " pos strand ") + readPosition + ' ' + (rec.getReadLength() - 1) + ' ' + extendedRec.getFullName()); } stats.nCandidateIndelAfterLastNBases.increment(location); } else { if (insertion) { stats.nCandidateInsertions.increment(location); if (DebugLogControl.shouldLog(TRACE, logger, param, location)) { logger.info("Insertion at position " + readPosition + " for read " + rec.getReadName() + " (effective length: " + effectiveReadLength + "; reversed:" + readOnNegativeStrand + "; insert size: " + insertSize + ')'); } forceCandidateInsertion = processInsertion( readPosition, refPosition, readEndOfPreviousAlignment, refEndOfPreviousAlignment, locationInterningSet, readLocalCandidates, extendedRec, rec, insertSize, readOnNegativeStrand, readBases, baseQualities, effectiveReadLength); } else if (refPosition < refEndOfPreviousAlignment + 1) { throw new AssertionFailedException("Alignment block misordering"); } else { processDeletion(location, ref, block, readPosition, refPosition, readEndOfPreviousAlignment, refEndOfPreviousAlignment, locationInterningSet, readLocalCandidates, extendedRec, rec, insertSize, readOnNegativeStrand, readBases, refBases, baseQualities, effectiveReadLength); }//End of deletion case }//End of case with accepted indel }//End of case where there was a previous alignment block refEndOfPreviousAlignment0.set(refPosition + (nBlockBases - 1)); readEndOfPreviousAlignment0.set(readPosition + (nBlockBases - 1)); for (int i = 0; i < nBlockBases; i++, readPosition++, refPosition++) { if (i == 1) { forceCandidateInsertion = false; } boolean insertCandidateAtRegularPosition = true; final SequenceLocation locationPH = notRnaSeq && i < nBlockBases - 1 ? //No insertion or deletion; make a note of it SequenceLocation.get(locationInterningSet, extendedRec.getLocation().contigIndex, extendedRec.getLocation().getContigName(), refPosition, true) : null; location = SequenceLocation.get(locationInterningSet, extendedRec.getLocation().contigIndex, extendedRec.getLocation().getContigName(), refPosition); if (baseQualities[readPosition] < param.minBasePhredScoreQ1) { stats.nBasesBelowPhredScore.increment(location); if (forceCandidateInsertion) { insertCandidateAtRegularPosition = false; } else { continue; } } if (refPosition > refBases.length - 1) { logger.warn("Ignoring base mapped at " + refPosition + ", beyond the end of " + ref.getName()); continue; } stats.nCandidateSubstitutionsConsidered.increment(location); if (readBases[readPosition] != StringUtil.toUpperCase(refBases[refPosition]) /*Mismatch*/) { final boolean tooLate = readOnNegativeStrand ? readPosition < param.ignoreLastNBases : readPosition > (rec.getReadLength() - 1) - param.ignoreLastNBases; int distance = extendedRec.tooCloseToBarcode(readPosition, param.ignoreFirstNBasesQ1); boolean goodToInsert = distance < 0 && !tooLate; if (distance >= 0) { if (!extendedRec.formsWrongPair()) { distance = extendedRec.tooCloseToBarcode(readPosition, 0); if (distance <= 0 && insertCandidateAtRegularPosition) { stats.rejectedSubstDistanceToLigationSite.insert(-distance); stats.nCandidateSubstitutionsBeforeFirstNBases.increment(location); } } if (DebugLogControl.shouldLog(TRACE, logger, param, location)) { logger.info("Ignoring subst too close to barcode for read " + rec.getReadName()); } insertCandidateAtRegularPosition = false; } else if (tooLate && insertCandidateAtRegularPosition) { stats.nCandidateSubstitutionsAfterLastNBases.increment(location); if (DebugLogControl.shouldLog(TRACE, logger, param, location)) { logger.info("Ignoring subst too close to read end for read " + rec.getReadName()); } insertCandidateAtRegularPosition = false; } if (goodToInsert || forceCandidateInsertion) { if (DebugLogControl.shouldLog(TRACE, logger, param, location)) { logger.info("Substitution at position " + readPosition + " for read " + rec.getReadName() + " (effective length: " + effectiveReadLength + "; reversed:" + readOnNegativeStrand + "; insert size: " + insertSize + ')'); } final byte wildType = StringUtil.toUpperCase(refBases[refPosition]); final byte mutation = StringUtil.toUpperCase(readBases[readPosition]); switch (mutation) { case 'A': stats.nCandidateSubstitutionsToA.increment(location); break; case 'T': stats.nCandidateSubstitutionsToT.increment(location); break; case 'G': stats.nCandidateSubstitutionsToG.increment(location); break; case 'C': stats.nCandidateSubstitutionsToC.increment(location); break; case 'N': stats.nNs.increment(location); if (!forceCandidateInsertion) { continue; } else { insertCandidateAtRegularPosition = false; } break; default: throw new AssertionFailedException("Unexpected letter: " + StringUtil.toUpperCase(readBases[readPosition])); } distance = -extendedRec.tooCloseToBarcode(readPosition, 0); final byte[] mutSequence = byteArrayMap.get(readBases[readPosition]); CandidateSequence candidate = new CandidateSequence(this, SUBSTITUTION, mutSequence, location, extendedRec, distance); if (!extendedRec.formsWrongPair()) { candidate.acceptLigSiteDistance(distance); } candidate.setInsertSize(insertSize); candidate.setInsertSizeNoBarcodeAccounting(false); candidate.setPositionInRead(readPosition); candidate.setReadEL(effectiveReadLength); candidate.setReadName(extendedRec.getFullName()); candidate.setReadAlignmentStart(extendedRec.getRefAlignmentStart()); candidate.setMateReadAlignmentStart(extendedRec.getMateRefAlignmentStart()); candidate.setReadAlignmentEnd(extendedRec.getRefAlignmentEnd()); candidate.setMateReadAlignmentEnd(extendedRec.getMateRefAlignmentEnd()); candidate.setRefPositionOfMateLigationSite(extendedRec.getRefPositionOfMateLigationSite()); candidate.setWildtypeSequence(wildType); candidate.addBasePhredScore(baseQualities[readPosition]); extendedRec.nReferenceDisagreements++; if (extendedRec.basePhredScores.put(location, baseQualities[readPosition]) != ExtendedSAMRecord.PHRED_NO_ENTRY) { logger.warn("Recording Phred score multiple times at same position " + location); } if (param.computeRawMismatches && insertCandidateAtRegularPosition) { final ComparablePair<String, String> mutationPair = readOnNegativeStrand ? new ComparablePair<>(byteMap.get(Mutation.complement(wildType)), byteMap.get(Mutation.complement(mutation))) : new ComparablePair<>(byteMap.get(wildType), byteMap.get(mutation)); stats.rawMismatchesQ1.accept(location, mutationPair); if (meetsQ2Thresholds(extendedRec) && baseQualities[readPosition] >= param.minBasePhredScoreQ2 && !extendedRec.formsWrongPair() && distance > param.ignoreFirstNBasesQ2) { candidate.getMutableRawMismatchesQ2().add(mutationPair); } } if (insertCandidateAtRegularPosition) { candidate = readLocalCandidates.add(candidate, location); candidate = null; } if (locationPH != null) { CandidateSequence candidate2 = new CandidateSequence(this, WILDTYPE, null, locationPH, extendedRec, distance); if (!extendedRec.formsWrongPair()) { candidate2.acceptLigSiteDistance(distance); } candidate2.setWildtypeSequence(wildType); candidate2 = readLocalCandidates.add(candidate2, locationPH); candidate2 = null; } }//End of mismatched read case } else { //Wildtype read int distance = extendedRec.tooCloseToBarcode(readPosition, param.ignoreFirstNBasesQ1); if (distance >= 0) { if (!extendedRec.formsWrongPair()) { distance = extendedRec.tooCloseToBarcode(readPosition, 0); if (distance <= 0 && insertCandidateAtRegularPosition) { stats.wtRejectedDistanceToLigationSite.insert(-distance); } } if (!forceCandidateInsertion) { continue; } else { insertCandidateAtRegularPosition = false; } } else { if (!extendedRec.formsWrongPair() && distance < -150) { throw new AssertionFailedException("Distance problem 1 at read position " + readPosition + " and refPosition " + refPosition + ' ' + extendedRec.toString() + " in analyzer" + analyzer.inputBam.getAbsolutePath() + "; distance is " + distance + ""); } distance = extendedRec.tooCloseToBarcode(readPosition, 0); if (!extendedRec.formsWrongPair() && insertCandidateAtRegularPosition) { stats.wtAcceptedBaseDistanceToLigationSite.insert(-distance); } } if (((!readOnNegativeStrand && readPosition > readBases.length - 1 - param.ignoreLastNBases) || (readOnNegativeStrand && readPosition < param.ignoreLastNBases))) { if (insertCandidateAtRegularPosition) { stats.nCandidateWildtypeAfterLastNBases.increment(location); } if (!forceCandidateInsertion) { continue; } else { insertCandidateAtRegularPosition = false; } } CandidateSequence candidate = new CandidateSequence(this, WILDTYPE, null, location, extendedRec, -distance); if (!extendedRec.formsWrongPair()) { candidate.acceptLigSiteDistance(-distance); } candidate.setWildtypeSequence(StringUtil.toUpperCase(refBases[refPosition])); candidate.addBasePhredScore(baseQualities[readPosition]); if (extendedRec.basePhredScores.put(location, baseQualities[readPosition]) != ExtendedSAMRecord.PHRED_NO_ENTRY) { logger.warn("Recording Phred score multiple times at same position " + location); } if (insertCandidateAtRegularPosition) { candidate = readLocalCandidates.add(candidate, location); candidate = null; } if (locationPH != null) { CandidateSequence candidate2 = new CandidateSequence(this, WILDTYPE, null, locationPH, extendedRec, -distance); if (!extendedRec.formsWrongPair()) { candidate2.acceptLigSiteDistance(-distance); } candidate2.setWildtypeSequence(StringUtil.toUpperCase(refBases[refPosition])); candidate2 = readLocalCandidates.add(candidate2, locationPH); candidate2 = null; } }//End of wildtype case }//End of loop over alignment bases } private void processDeletion( final @NonNull SequenceLocation location, final @NonNull ReferenceSequence ref, final ExtendedAlignmentBlock block, final int readPosition, final int refPosition, final int readEndOfPreviousAlignment, final int refEndOfPreviousAlignment, InterningSet<@NonNull SequenceLocation> locationInterningSet, final CandidateBuilder readLocalCandidates, final @NonNull ExtendedSAMRecord extendedRec, final SAMRecord rec, final int insertSize, final boolean readOnNegativeStrand, final byte[] readBases, final byte[] refBases, final byte[] baseQualities, final int effectiveReadLength) { //Deletion or skipped region ("N" in Cigar) if (refPosition > refBases.length - 1) { logger.warn("Ignoring rest of read after base mapped at " + refPosition + ", beyond the end of " + ref.getName()); return; } int distance0 = -extendedRec.tooCloseToBarcode(readPosition - 1, param.ignoreFirstNBasesQ1); int distance1 = -extendedRec.tooCloseToBarcode(readEndOfPreviousAlignment + 1, param.ignoreFirstNBasesQ1); int distance = Math.min(distance0, distance1) + 1; final boolean isIntron = block.previousCigarOperator == CigarOperator.N; final boolean Q1reject = distance < 0; if (!isIntron && Q1reject) { if (!extendedRec.formsWrongPair()) { stats.rejectedIndelDistanceToLigationSite.insert(-distance); stats.nCandidateIndelBeforeFirstNBases.increment(location); } logger.trace("Ignoring deletion " + readEndOfPreviousAlignment + param.ignoreFirstNBasesQ1 + ' ' + extendedRec.getFullName()); } else { distance0 = -extendedRec.tooCloseToBarcode(readPosition - 1, 0); distance1 = -extendedRec.tooCloseToBarcode(readEndOfPreviousAlignment + 1, 0); distance = Math.min(distance0, distance1) + 1; if (!isIntron) stats.nCandidateDeletions.increment(location); if (DebugLogControl.shouldLog(TRACE, logger, param, location)) { logger.info("Deletion or intron at position " + readPosition + " for read " + rec.getReadName() + " (effective length: " + effectiveReadLength + "; reversed:" + readOnNegativeStrand + "; insert size: " + insertSize + ')'); } final int deletionLength = refPosition - (refEndOfPreviousAlignment + 1); final @NonNull SequenceLocation newLocation = SequenceLocation.get(locationInterningSet, extendedRec.getLocation().contigIndex, extendedRec.getLocation().getContigName(), refEndOfPreviousAlignment + 1); final @NonNull SequenceLocation deletionEnd = SequenceLocation.get(locationInterningSet, extendedRec.getLocation().contigIndex, extendedRec.getLocation().getContigName(), newLocation.position + deletionLength); final byte @Nullable[] deletedSequence = isIntron ? null : Arrays.copyOfRange(ref.getBases(), refEndOfPreviousAlignment + 1, refPosition); //Add hidden mutations to all locations covered by deletion //So disagreements between deletions that have only overlapping //spans are detected. if (!isIntron) { for (int i = 1; i < deletionLength; i++) { SequenceLocation location2 = SequenceLocation.get(locationInterningSet, extendedRec.getLocation().contigIndex, extendedRec.getLocation().getContigName(), refEndOfPreviousAlignment + 1 + i); CandidateSequence hiddenCandidate = new CandidateDeletion( this, deletedSequence, location2, extendedRec, Integer.MAX_VALUE, MutationType.DELETION, newLocation, deletionEnd); hiddenCandidate.setHidden(true); hiddenCandidate.setInsertSize(insertSize); hiddenCandidate.setInsertSizeNoBarcodeAccounting(false); hiddenCandidate.setPositionInRead(readPosition); hiddenCandidate.setReadEL(effectiveReadLength); hiddenCandidate.setReadName(extendedRec.getFullName()); hiddenCandidate.setReadAlignmentStart(extendedRec.getRefAlignmentStart()); hiddenCandidate.setMateReadAlignmentStart(extendedRec.getMateRefAlignmentStart()); hiddenCandidate.setReadAlignmentEnd(extendedRec.getRefAlignmentEnd()); hiddenCandidate.setMateReadAlignmentEnd(extendedRec.getMateRefAlignmentEnd()); hiddenCandidate.setRefPositionOfMateLigationSite(extendedRec.getRefPositionOfMateLigationSite()); hiddenCandidate = readLocalCandidates.add(hiddenCandidate, location2); hiddenCandidate = null; } } CandidateSequence candidate = new CandidateDeletion(this, deletedSequence, newLocation, extendedRec, distance, isIntron ? MutationType.INTRON : MutationType.DELETION, newLocation, SequenceLocation.get(locationInterningSet, extendedRec.getLocation().contigIndex, extendedRec.getLocation().getContigName(), refPosition)); if (!extendedRec.formsWrongPair()) { candidate.acceptLigSiteDistance(distance); } candidate.setInsertSize(insertSize); candidate.setInsertSizeNoBarcodeAccounting(false); candidate.setPositionInRead(readPosition); candidate.setReadEL(effectiveReadLength); candidate.setReadName(extendedRec.getFullName()); candidate.setReadAlignmentStart(extendedRec.getRefAlignmentStart()); candidate.setMateReadAlignmentStart(extendedRec.getMateRefAlignmentStart()); candidate.setReadAlignmentEnd(extendedRec.getRefAlignmentEnd()); candidate.setMateReadAlignmentEnd(extendedRec.getMateRefAlignmentEnd()); candidate.setRefPositionOfMateLigationSite(extendedRec.getRefPositionOfMateLigationSite()); if (!isIntron) extendedRec.nReferenceDisagreements++; if (!isIntron && param.computeRawMismatches) { Objects.requireNonNull(deletedSequence); final ComparablePair<String, String> mutationPair = readOnNegativeStrand ? new ComparablePair<>(byteMap.get(Mutation.complement(deletedSequence[0])), new String(new Mutation(candidate).reverseComplement().mutationSequence).toUpperCase()) : new ComparablePair<>(byteMap.get(deletedSequence[0]), new String(deletedSequence).toUpperCase()); stats.rawDeletionsQ1.accept(newLocation, mutationPair); stats.rawDeletionLengthQ1.insert(deletedSequence.length); if (meetsQ2Thresholds(extendedRec) && baseQualities[readPosition] >= param.minBasePhredScoreQ2 && !extendedRec.formsWrongPair() && distance > param.ignoreFirstNBasesQ2) { candidate.getMutableRawDeletionsQ2().add(mutationPair); } } candidate = readLocalCandidates.add(candidate, newLocation); candidate = null; } } private boolean processInsertion( final int readPosition, final int refPosition, final int readEndOfPreviousAlignment, final int refEndOfPreviousAlignment, InterningSet<@NonNull SequenceLocation> locationInterningSet, final CandidateBuilder readLocalCandidates, final @NonNull ExtendedSAMRecord extendedRec, final SAMRecord rec, final int insertSize, final boolean readOnNegativeStrand, final byte[] readBases, final byte[] baseQualities, final int effectiveReadLength) { boolean forceCandidateInsertion = false; final @NonNull SequenceLocation location = SequenceLocation.get(locationInterningSet, extendedRec.getLocation().contigIndex, extendedRec.getLocation().getContigName(), refEndOfPreviousAlignment, true); int distance0 = extendedRec.tooCloseToBarcode(readEndOfPreviousAlignment, param.ignoreFirstNBasesQ1); int distance1 = extendedRec.tooCloseToBarcode(readPosition, param.ignoreFirstNBasesQ1); int distance = Math.max(distance0, distance1); distance = -distance + 1; final boolean Q1reject = distance < 0; if (Q1reject) { if (!extendedRec.formsWrongPair()) { stats.rejectedIndelDistanceToLigationSite.insert(-distance); stats.nCandidateIndelBeforeFirstNBases.increment(location); } logger.trace("Ignoring insertion " + readEndOfPreviousAlignment + param.ignoreFirstNBasesQ1 + ' ' + extendedRec.getFullName()); } else { distance0 = extendedRec.tooCloseToBarcode(readEndOfPreviousAlignment, 0); distance1 = extendedRec.tooCloseToBarcode(readPosition, 0); distance = Math.max(distance0, distance1); distance = -distance + 1; final byte [] insertedSequence = Arrays.copyOfRange(readBases, readEndOfPreviousAlignment + 1, readPosition); CandidateSequence candidate = new CandidateSequence( this, INSERTION, insertedSequence, location, extendedRec, distance); if (!extendedRec.formsWrongPair()) { candidate.acceptLigSiteDistance(distance); } candidate.setInsertSize(insertSize); candidate.setPositionInRead(readPosition); candidate.setReadEL(effectiveReadLength); candidate.setReadName(extendedRec.getFullName()); candidate.setReadAlignmentStart(extendedRec.getRefAlignmentStart()); candidate.setMateReadAlignmentStart(extendedRec.getMateRefAlignmentStart()); candidate.setReadAlignmentEnd(extendedRec.getRefAlignmentEnd()); candidate.setMateReadAlignmentEnd(extendedRec.getMateRefAlignmentEnd()); candidate.setRefPositionOfMateLigationSite(extendedRec.getRefPositionOfMateLigationSite()); candidate.setInsertSizeNoBarcodeAccounting(false); if (param.computeRawMismatches) { final byte wildType = readBases[readEndOfPreviousAlignment]; final ComparablePair<String, String> mutationPair = readOnNegativeStrand ? new ComparablePair<>(byteMap.get(Mutation.complement(wildType)), new String(new Mutation(candidate).reverseComplement().mutationSequence).toUpperCase()) : new ComparablePair<>(byteMap.get(wildType), new String(insertedSequence).toUpperCase()); stats.rawInsertionsQ1.accept(location, mutationPair); stats.rawInsertionLengthQ1.insert(insertedSequence.length); if (meetsQ2Thresholds(extendedRec) && baseQualities[readPosition] >= param.minBasePhredScoreQ2 && !extendedRec.formsWrongPair() && distance > param.ignoreFirstNBasesQ2) { candidate.getMutableRawInsertionsQ2().add(mutationPair); } } if (DebugLogControl.shouldLog(TRACE, logger, param, location)) { logger.info("Insertion of " + new String(candidate.getSequence()) + " at ref " + refPosition + " and read position " + readPosition + " for read " + extendedRec.getFullName()); } candidate = readLocalCandidates.add(candidate, location); candidate = null; forceCandidateInsertion = true; if (DebugLogControl.shouldLog(TRACE, logger, param, location)) { logger.info("Added candidate at " + location /*+ "; readLocalCandidates now " + readLocalCandidates.build()*/); } extendedRec.nReferenceDisagreements++; } return forceCandidateInsertion; } public @NonNull Mutinack getAnalyzer() { return analyzer; } }
package launcher.gui; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Font; import java.awt.GridLayout; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.IOException; import java.io.OutputStream; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.text.DefaultCaret; /** * SolidLeon #4 20150227 * * Simple display for showing current progress * @author SolidLeon * */ public class StatusDisplay extends JFrame implements IStatusListener, ActionListener { private JProgressBar overallProgress; private JProgressBar currentProgress; private JTextArea text; /** OutputStream redirecting output to JTextArea 'text' */ private OutputStream textOut; private JButton closeButton; /** Runnable object to 'run' close button is pressed and before disposing */ private Runnable exitRunner; public StatusDisplay() { setPreferredSize(new Dimension(800, 600)); setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); setLayout(new BorderLayout()); setTitle("Launcher Status"); overallProgress = new JProgressBar(); overallProgress.setStringPainted(true); currentProgress = new JProgressBar(); currentProgress.setStringPainted(true); JPanel progressPanel = new JPanel(new BorderLayout()); JPanel progressLabelPanel = new JPanel(new GridLayout(2, 1)); JPanel progressBarPanel = new JPanel(new GridLayout(2, 1)); progressLabelPanel.add(new JLabel("Overall Progress:")); progressLabelPanel.add(new JLabel("Current Progress:")); progressBarPanel.add(overallProgress); progressBarPanel.add(currentProgress); progressPanel.add(progressLabelPanel, BorderLayout.WEST); progressPanel.add(progressBarPanel, BorderLayout.CENTER); add(progressPanel, BorderLayout.NORTH); text = new JTextArea(); text.setFont(new Font("Monospaced", Font.PLAIN, 12)); DefaultCaret caret = (DefaultCaret)text.getCaret(); caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE); add(new JScrollPane(text), BorderLayout.CENTER); closeButton = new JButton("Close"); closeButton.addActionListener(this); add(closeButton, BorderLayout.SOUTH); textOut = new OutputStream() { @Override public void write(int b) throws IOException { text.append(String.valueOf((char) b)); } }; addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { if (closeButton.isEnabled()) { closeButton.doClick(); } else { JOptionPane.showMessageDialog(StatusDisplay.this, "Cannot close the window right now!"); } } }); pack(); setLocationRelativeTo(null); closeButton.setEnabled(false); } @Override public OutputStream getOutputStream() { return textOut; } public void setProgress(JProgressBar bar, int value, int min, int max, String text) { bar.setMinimum(min); bar.setMaximum(max); bar.setValue(value); bar.setString(text); } @Override public void setCurrentProgress(int value, int min, int max, String text) { setProgress(currentProgress, value, min, max, text); } @Override public void setCurrentProgress(int value) { currentProgress.setValue(value); } @Override public void setCurrentProgressToMax() { currentProgress.setValue(currentProgress.getMaximum()); } @Override public void setCurrentProgress(String text) { currentProgress.setString(text); } @Override public int getCurrentProgress() { return currentProgress.getValue(); } @Override public void setOverallProgress(int value, int min, int max) { setProgress(overallProgress, value, min, max, null); } @Override public void setOverallProgress(int value) { overallProgress.setValue(value); } @Override public void setOverallProgress(String text) { overallProgress.setString(text); } @Override public int getOverallProgress() { return overallProgress.getValue(); } @Override public void addOverallProgress(int i) { setOverallProgress(getOverallProgress() + i); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == closeButton) { if (exitRunner != null) exitRunner.run(); dispose(); } } /** * - Sets a runner being executed after close button has been pressed. * - Enabled the close button * - Sets a fancy text for the close button * - Sets overall progress to max * - Sets current progress max to 100 (for cases where the max is 0) * - Sets current progress to max * - Sets 'Done!' as curren progress text */ @Override public void setStatusCompletedExecCommandOnExit(Runnable runner) { this.exitRunner = runner; closeButton.setEnabled(true); closeButton.setText("Completed! Close me!"); overallProgress.setValue(overallProgress.getMaximum()); currentProgress.setMaximum(100); setCurrentProgressToMax(); setCurrentProgress("Done!"); } }
package org.eclipse.xtext.resource.impl; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Set; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.xtext.naming.IQualifiedNameProvider; import org.eclipse.xtext.resource.DescriptionUtils; import org.eclipse.xtext.resource.IContainer; import org.eclipse.xtext.resource.IEObjectDescription; import org.eclipse.xtext.resource.IResourceDescription; import org.eclipse.xtext.resource.IResourceDescriptions; import org.eclipse.xtext.resource.IResourceDescription.Delta; import org.eclipse.xtext.util.IResourceScopeCache; import com.google.common.collect.Collections2; import com.google.common.collect.Sets; import com.google.inject.Inject; import com.google.inject.Provider; /** * @author Sebastian Zarnekow - Initial contribution and API * @author Sven Efftinge */ public class DefaultResourceDescriptionManager implements IResourceDescription.Manager { @Inject private IQualifiedNameProvider nameProvider; @Inject private IContainer.Manager containerManager; @Inject private IResourceScopeCache cache = IResourceScopeCache.NullImpl.INSTANCE; @Inject private DescriptionUtils descriptionUtils; private static final String CACHE_KEY = DefaultResourceDescriptionManager.class.getName() + "#getResourceDescription"; public IResourceDescription getResourceDescription(final Resource resource) { return cache.get(CACHE_KEY, resource, new Provider<IResourceDescription>() { public IResourceDescription get() { return internalGetResourceDescription(resource, nameProvider); } }); } protected IResourceDescription internalGetResourceDescription(Resource resource, IQualifiedNameProvider nameProvider) { return new DefaultResourceDescription(resource, nameProvider); } public void setNameProvider(IQualifiedNameProvider nameProvider) { this.nameProvider = nameProvider; } public IQualifiedNameProvider getNameProvider() { return nameProvider; } public IContainer.Manager getContainerManager() { return containerManager; } public void setContainerManager(IContainer.Manager containerManager) { this.containerManager = containerManager; } public void setCache(IResourceScopeCache cache) { this.cache = cache; } public IResourceScopeCache getCache() { return cache; } public boolean isAffected(Delta delta, IResourceDescription candidate) throws IllegalArgumentException { if (!delta.haveEObjectDescriptionsChanged()) return false; Set<String> names = Sets.newHashSet(); addExportedNames(names,delta.getOld()); addExportedNames(names,delta.getNew()); return !Collections.disjoint(names, getImportedNames(candidate)); } protected Collection<String> getImportedNames(IResourceDescription candidate) { return Collections2.forIterable(candidate.getImportedNames()); } protected void addExportedNames(Set<String> names, IResourceDescription resourceDescriptor) { if (resourceDescriptor==null) return; Iterable<IEObjectDescription> iterable = resourceDescriptor.getExportedObjects(); for (IEObjectDescription ieObjectDescription : iterable) { names.add(ieObjectDescription.getName()); } } public boolean isAffected(Collection<IResourceDescription.Delta> deltas, IResourceDescription candidate, IResourceDescriptions context) { Set<URI> outgoingReferences = descriptionUtils.collectOutgoingReferences(candidate); Set<URI> interestingResources = Sets.newHashSet(); // deleted resources are no longer visible resources // so we collect them pessimistic up-front for (IResourceDescription.Delta delta : deltas) { if (delta.getNew() == null) interestingResources.add(delta.getUri()); } Set<URI> visibleResources = collectVisibleResources(candidate, context); interestingResources.addAll(visibleResources); if (interestingResources.isEmpty()) // should at least contain the resource itself return true; for (IResourceDescription.Delta delta : deltas) { if (delta.haveEObjectDescriptionsChanged()) { URI deltaURI = delta.getUri(); if (outgoingReferences.contains(deltaURI)) { return true; } if (interestingResources.contains(deltaURI)) { if (isAffected(delta, candidate)) { return true; } } } } return false; } protected Set<URI> collectVisibleResources(IResourceDescription description, IResourceDescriptions allDescriptions) { Set<URI> result = null; List<IContainer> containers = containerManager.getVisibleContainers(description, allDescriptions); for (IContainer container: containers) { for(IResourceDescription resourceDescription: container.getResourceDescriptions()) { if (result == null) result = Sets.newHashSet(); result.add(resourceDescription.getURI()); } } if (result == null) return Collections.emptySet(); return result; } public DescriptionUtils getDescriptionUtils() { return descriptionUtils; } public void setDescriptionUtils(DescriptionUtils descriptionUtils) { this.descriptionUtils = descriptionUtils; } }
"package org.jkiss.dbeaver.ui.controls.resultset;\nimport org.eclipse.jface.action.*;\nimport org.ec(...TRUNCATED)
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
154