<commit_before>/**
 *
 * Copyright (c) 2006-2017, Speedment, Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); You may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at:
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.speedment.tool.core.internal.component;

import com.speedment.common.injector.InjectBundle;
import com.speedment.common.injector.Injector;
import com.speedment.common.injector.annotation.Inject;
import static com.speedment.common.invariant.NullUtil.requireNonNulls;
import com.speedment.common.logger.Logger;
import com.speedment.common.logger.LoggerManager;
import com.speedment.common.mapstream.MapStream;
import com.speedment.generator.translator.TranslatorSupport;
import com.speedment.runtime.config.Dbms;
import com.speedment.runtime.config.Project;
import com.speedment.runtime.config.Schema;
import com.speedment.runtime.config.internal.immutable.ImmutableProject;
import com.speedment.runtime.config.trait.HasMainInterface;
import com.speedment.runtime.core.component.PasswordComponent;
import com.speedment.runtime.core.component.ProjectComponent;
import com.speedment.runtime.core.internal.util.Settings;
import com.speedment.runtime.core.util.ProgressMeasure;
import com.speedment.tool.config.DbmsProperty;
import com.speedment.tool.config.DocumentProperty;
import com.speedment.tool.config.ProjectProperty;
import com.speedment.tool.config.component.DocumentPropertyComponent;
import com.speedment.tool.config.internal.component.DocumentPropertyComponentImpl;
import com.speedment.tool.core.MainApp;
import com.speedment.tool.core.brand.Palette;
import com.speedment.tool.core.component.RuleComponent;
import com.speedment.tool.core.component.UserInterfaceComponent;
import com.speedment.tool.core.internal.brand.SpeedmentBrand;
import com.speedment.tool.core.internal.notification.NotificationImpl;
import com.speedment.tool.core.internal.util.ConfigFileHelper;
import com.speedment.tool.core.internal.util.InjectionLoader;
import com.speedment.tool.core.notification.Notification;
import com.speedment.tool.core.util.BrandUtil;
import com.speedment.tool.core.util.OutputUtil;
import com.speedment.tool.propertyeditor.PropertyEditor;
import com.speedment.tool.propertyeditor.internal.component.PropertyEditorComponentImpl;
import de.jensd.fx.glyphs.GlyphsDude;
import de.jensd.fx.glyphs.fontawesome.FontAwesomeIcon;
import de.jensd.fx.glyphs.fontawesome.FontAwesomeIconView;
import java.io.File;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.List;
import java.util.Map;
import static java.util.Objects.requireNonNull;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Predicate;
import static java.util.stream.Collectors.toList;
import javafx.application.Application;
import javafx.application.Platform;
import static javafx.application.Platform.runLater;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.ButtonBar.ButtonData;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.util.Pair;

/**
 *
 * @author <NAME>
 */
public final class UserInterfaceComponentImpl implements UserInterfaceComponent {
    
        public static InjectBundle include() {
        return InjectBundle.of(
            DocumentPropertyComponentImpl.class,
            SpeedmentBrand.class,
            InjectionLoader.class,
            ConfigFileHelper.class,
            PropertyEditorComponentImpl.class,
            RuleComponentImpl.class,
            IssueComponentImpl.class
        );
    }
    
    private final static Logger LOGGER = LoggerManager.getLogger(UserInterfaceComponentImpl.class);

    private static final String GITHUB_URI = "https://github.com/speedment/speedment/";
    private static final String GITTER_URI = "https://gitter.im/speedment/speedment/";
    public static final String DIALOG_PANE_ICON_SIZE = "2.5em";
    
    private static final Predicate<File> OPEN_DIRECTORY_CONDITIONS = file
        -> file != null
        && file.exists()
        && file.isDirectory();
    
    private static final Predicate<Optional<char[]>> NO_PASSWORD_SPECIFIED
        = pass -> !pass.isPresent() || pass.get().length == 0;
    
    private final ObjectProperty<StoredNode> hiddenProjectTree = new SimpleObjectProperty<>();
    private final ObjectProperty<StoredNode> hiddenWorkspace   = new SimpleObjectProperty<>();
    private final ObjectProperty<StoredNode> hiddenOutput      = new SimpleObjectProperty<>();
    
    private final ObservableList<Notification> notifications;
    private final ObservableList<Node> outputMessages;
    private final ObservableList<TreeItem<DocumentProperty>> selectedTreeItems;
    private final ObservableList<PropertyEditor.Item> properties;
    private final Map<Class<?>, List<UserInterfaceComponent.ContextMenuBuilder<?>>> contextMenuBuilders;
    
    private final AtomicBoolean canGenerate;
    
    private @Inject DocumentPropertyComponent documentPropertyComponent;
    private @Inject PasswordComponent passwordComponent;
    private @Inject ProjectComponent projectComponent;
    private @Inject ConfigFileHelper configFileHelper;
    private @Inject InjectionLoader loader;
    private @Inject RuleComponent rules;
    
    private @Inject Injector injector;
    
    private Stage stage;
    private Application application;
    private ProjectProperty project;
    
    private UserInterfaceComponentImpl() {
        notifications        = FXCollections.observableArrayList();
        outputMessages       = FXCollections.observableArrayList();
        selectedTreeItems    = FXCollections.observableArrayList();
        properties           = FXCollections.observableArrayList();
        contextMenuBuilders  = new ConcurrentHashMap<>();
        canGenerate          = new AtomicBoolean(true);
    }
    
    public void start(Application application, Stage stage) {
        this.stage       = requireNonNull(stage);
        this.application = requireNonNull(application);
        this.project     = new ProjectProperty();
        
        LoggerManager.getFactory().addListener(ev -> {
            switch (ev.getLevel()) {
                case DEBUG : case TRACE : case INFO : {
                    addToOutputMessages(OutputUtil.info(ev.getMessage()));
                    break;
                }
                case WARN : {
                    addToOutputMessages(OutputUtil.warning(ev.getMessage()));
                    showNotification(ev.getMessage(), Palette.WARNING);
                    break;
                }
                case ERROR : case FATAL : {
                    addToOutputMessages(OutputUtil.error(ev.getMessage()));                   
                    // Hack to remove stack trace from message.
                    String msg = ev.getMessage();
                    if (msg.contains("\tat ")) {
                        msg = msg.substring(0, msg.indexOf("\tat "));
                    }
                    break;
                }
            }
        });
        
        final Project loaded = projectComponent.getProject();
        if (loaded != null) {
            project.merge(documentPropertyComponent, loaded);
        }
    }
    
    // synchronize to avoid asynchronous calls from logger
    private synchronized void addToOutputMessages(Node node) {
        outputMessages.add(node);
    }
    
    /*************************************************************/
    /*                     Global properties                     */
    /*************************************************************/
 
    @Override
    public ProjectProperty projectProperty() {
        return project;
    }

    @Override
    public Application getApplication() {<commit_msg>tool-core: Output messages should only be added from FX thread #229<commit_after>/**
 *
 * Copyright (c) 2006-2017, Speedment, Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); You may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at:
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.speedment.tool.core.internal.component;

import com.speedment.common.injector.InjectBundle;
import com.speedment.common.injector.Injector;
import com.speedment.common.injector.annotation.Inject;
import static com.speedment.common.invariant.NullUtil.requireNonNulls;
import com.speedment.common.logger.Logger;
import com.speedment.common.logger.LoggerManager;
import com.speedment.common.mapstream.MapStream;
import com.speedment.generator.translator.TranslatorSupport;
import com.speedment.runtime.config.Dbms;
import com.speedment.runtime.config.Project;
import com.speedment.runtime.config.Schema;
import com.speedment.runtime.config.internal.immutable.ImmutableProject;
import com.speedment.runtime.config.trait.HasMainInterface;
import com.speedment.runtime.core.component.PasswordComponent;
import com.speedment.runtime.core.component.ProjectComponent;
import com.speedment.runtime.core.internal.util.Settings;
import com.speedment.runtime.core.util.ProgressMeasure;
import com.speedment.tool.config.DbmsProperty;
import com.speedment.tool.config.DocumentProperty;
import com.speedment.tool.config.ProjectProperty;
import com.speedment.tool.config.component.DocumentPropertyComponent;
import com.speedment.tool.config.internal.component.DocumentPropertyComponentImpl;
import com.speedment.tool.core.MainApp;
import com.speedment.tool.core.brand.Palette;
import com.speedment.tool.core.component.RuleComponent;
import com.speedment.tool.core.component.UserInterfaceComponent;
import com.speedment.tool.core.internal.brand.SpeedmentBrand;
import com.speedment.tool.core.internal.notification.NotificationImpl;
import com.speedment.tool.core.internal.util.ConfigFileHelper;
import com.speedment.tool.core.internal.util.InjectionLoader;
import com.speedment.tool.core.notification.Notification;
import com.speedment.tool.core.util.BrandUtil;
import com.speedment.tool.core.util.OutputUtil;
import com.speedment.tool.propertyeditor.PropertyEditor;
import com.speedment.tool.propertyeditor.internal.component.PropertyEditorComponentImpl;
import de.jensd.fx.glyphs.GlyphsDude;
import de.jensd.fx.glyphs.fontawesome.FontAwesomeIcon;
import de.jensd.fx.glyphs.fontawesome.FontAwesomeIconView;
import java.io.File;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.List;
import java.util.Map;
import static java.util.Objects.requireNonNull;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Predicate;
import static java.util.stream.Collectors.toList;
import javafx.application.Application;
import javafx.application.Platform;
import static javafx.application.Platform.runLater;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.ButtonBar.ButtonData;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.util.Pair;

/**
 *
 * @author <NAME>
 */
public final class UserInterfaceComponentImpl implements UserInterfaceComponent {
    
        public static InjectBundle include() {
        return InjectBundle.of(
            DocumentPropertyComponentImpl.class,
            SpeedmentBrand.class,
            InjectionLoader.class,
            ConfigFileHelper.class,
            PropertyEditorComponentImpl.class,
            RuleComponentImpl.class,
            IssueComponentImpl.class
        );
    }
    
    private final static Logger LOGGER = LoggerManager.getLogger(UserInterfaceComponentImpl.class);

    private static final String GITHUB_URI = "https://github.com/speedment/speedment/";
    private static final String GITTER_URI = "https://gitter.im/speedment/speedment/";
    public static final String DIALOG_PANE_ICON_SIZE = "2.5em";
    
    private static final Predicate<File> OPEN_DIRECTORY_CONDITIONS = file
        -> file != null
        && file.exists()
        && file.isDirectory();
    
    private static final Predicate<Optional<char[]>> NO_PASSWORD_SPECIFIED
        = pass -> !pass.isPresent() || pass.get().length == 0;
    
    private final ObjectProperty<StoredNode> hiddenProjectTree = new SimpleObjectProperty<>();
    private final ObjectProperty<StoredNode> hiddenWorkspace   = new SimpleObjectProperty<>();
    private final ObjectProperty<StoredNode> hiddenOutput      = new SimpleObjectProperty<>();
    
    private final ObservableList<Notification> notifications;
    private final ObservableList<Node> outputMessages;
    private final ObservableList<TreeItem<DocumentProperty>> selectedTreeItems;
    private final ObservableList<PropertyEditor.Item> properties;
    private final Map<Class<?>, List<UserInterfaceComponent.ContextMenuBuilder<?>>> contextMenuBuilders;
    
    private final AtomicBoolean canGenerate;
    
    private @Inject DocumentPropertyComponent documentPropertyComponent;
    private @Inject PasswordComponent passwordComponent;
    private @Inject ProjectComponent projectComponent;
    private @Inject ConfigFileHelper configFileHelper;
    private @Inject InjectionLoader loader;
    private @Inject RuleComponent rules;
    
    private @Inject Injector injector;
    
    private Stage stage;
    private Application application;
    private ProjectProperty project;
    
    private UserInterfaceComponentImpl() {
        notifications        = FXCollections.observableArrayList();
        outputMessages       = FXCollections.observableArrayList();
        selectedTreeItems    = FXCollections.observableArrayList();
        properties           = FXCollections.observableArrayList();
        contextMenuBuilders  = new ConcurrentHashMap<>();
        canGenerate          = new AtomicBoolean(true);
    }
    
    public void start(Application application, Stage stage) {
        this.stage       = requireNonNull(stage);
        this.application = requireNonNull(application);
        this.project     = new ProjectProperty();
        
        LoggerManager.getFactory().addListener(ev -> {
            switch (ev.getLevel()) {
                case DEBUG : case TRACE : case INFO : {
                    addToOutputMessages(OutputUtil.info(ev.getMessage()));
                    break;
                }
                case WARN : {
                    addToOutputMessages(OutputUtil.warning(ev.getMessage()));
                    showNotification(ev.getMessage(), Palette.WARNING);
                    break;
                }
                case ERROR : case FATAL : {
                    addToOutputMessages(OutputUtil.error(ev.getMessage()));                   
                    // Hack to remove stack trace from message.
                    String msg = ev.getMessage();
                    if (msg.contains("\tat ")) {
                        msg = msg.substring(0, msg.indexOf("\tat "));
                    }
                    break;
                }
            }
        });
        
        final Project loaded = projectComponent.getProject();
        if (loaded != null) {
            project.merge(documentPropertyComponent, loaded);
        }
    }
    
    private void addToOutputMessages(Node node) {
        runLater(() -> outputMessages.add(node));
    }
    
    /*************************************************************/
    /*                     Global properties                     */
    /*************************************************************/
 
    @Override
    public ProjectProperty projectProperty() {
        return project;
    }

    @Override
    public Application getApplication() {
{'fraction_non_alphanumeric': 0.10263036985986676, 'fraction_numerical': 0.0020101079715138985, 'mean_word_length': 3.442091836734694, 'pattern_counts': {'":': 0, '<': 43, '<?xml version=': 0, '>': 50, 'https://': 4, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5634296', 'n_tokens_mistral': 4499, 'n_tokens_neox': 4420, 'n_words': 959}