<commit_before>/**
 * New BSD License
 * http://www.opensource.org/licenses/bsd-license.php
 * Copyright (c) 2009, RaptorProject (http://code.google.com/p/raptor-chess-interface/)
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 * Neither the name of the RaptorProject nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package raptor.swt.chess.analysis;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;

import raptor.Raptor;
import raptor.chess.Game;
import raptor.chess.Move;
import raptor.chess.util.GameUtils;
import raptor.engine.uci.UCIBestMove;
import raptor.engine.uci.UCIEngine;
import raptor.engine.uci.UCIInfo;
import raptor.engine.uci.UCIInfoListener;
import raptor.engine.uci.UCIMove;
import raptor.engine.uci.UCIOption;
import raptor.engine.uci.info.BestLineFoundInfo;
import raptor.engine.uci.info.CPULoadInfo;
import raptor.engine.uci.info.DepthInfo;
import raptor.engine.uci.info.NodesPerSecondInfo;
import raptor.engine.uci.info.NodesSearchedInfo;
import raptor.engine.uci.info.ScoreInfo;
import raptor.engine.uci.info.TimeInfo;
import raptor.engine.uci.options.UCIButton;
import raptor.pref.PreferenceKeys;
import raptor.service.ThreadService;
import raptor.service.UCIEngineService;
import raptor.swt.RaptorTable;
import raptor.swt.UCIEnginePropertiesDialog;
import raptor.swt.chess.ChessBoardController;
import raptor.swt.chess.EngineAnalysisWidget;
import raptor.util.RaptorStringUtils;

public class SimpleAnalysisWidget implements EngineAnalysisWidget {
	private static final Log LOG = LogFactory
			.getLog(SimpleAnalysisWidget.class);

	protected ChessBoardController controller;
	protected Composite composite, topLine;
	protected UCIEngine currentEngine;
	protected CLabel engineComboCLabel;
	protected CLabel nodesPerSecondLabelLabel;
	protected CLabel nodesPerSecondLabel;
	protected CLabel cpuPercentageLabelLabel;
	protected CLabel cpuPercentageLabel;
	protected Combo engineCombo;
	protected RaptorTable bestMoves;
	protected Button stopButton, startButton, propertiesButton;
	protected boolean ignoreEngineSelection;
	protected boolean isInStart = false;
	protected UCIInfoListener listener = new UCIInfoListener() {
		public void engineSentBestMove(UCIBestMove uciBestMove) {
		}

		public void engineSentInfo(final UCIInfo[] infos) {
			Raptor.getInstance().getDisplay().asyncExec(new Runnable() {
				public void run() {
					String score = null;
					String time = null;
					String depth = null;
					String nodes = null;
					String cpu = null;
					String nps = null;
					List<String> pvs = new ArrayList<String>(3);

					for (UCIInfo info : infos) {
						if (info instanceof ScoreInfo) {
							ScoreInfo scoreInfo = (ScoreInfo) info;
							if (((ScoreInfo) info).getMateInMoves() != 0) {
								score = "Mate in " + scoreInfo.getMateInMoves();
							} else if (scoreInfo.isLowerBoundScore()) {
								score = "-inf";
							} else if (scoreInfo.isUpperBoundScore()) {
								score = "+inf";
							} else {
								score = ""
										+ new BigDecimal(scoreInfo
												.getValueInCentipawns() / 100.0)
												.setScale(
														2,
														BigDecimal.ROUND_HALF_UP)
												.toString();
							}
						} else if (info instanceof DepthInfo) {
							DepthInfo depthInfo = (DepthInfo) info;
							depth = depthInfo.getSearchDepthPlies() + " plies";
						} else if (info instanceof NodesSearchedInfo) {
							NodesSearchedInfo nodesSearchedInfo = (NodesSearchedInfo) info;
							nodes = RaptorStringUtils.formatAsNumber(""
									+ nodesSearchedInfo.getNodesSearched()
									/ 1000);
						} else if (info instanceof CPULoadInfo) {
							CPULoadInfo cpuLoad = (CPULoadInfo) info;
							cpu = new BigDecimal(
									cpuLoad.getCpuUsage() / 1000.0 * 100)
									.setScale(0, BigDecimal.ROUND_HALF_UP)
									.toString();
						} else if (info instanceof NodesPerSecondInfo) {
							NodesPerSecondInfo nodesPerSecondInfo = (NodesPerSecondInfo) info;
							nps = RaptorStringUtils.formatAsNumber(""
									+ nodesPerSecondInfo.getNodesPerSecond()
									/ 1000);
						} else if (info instanceof TimeInfo) {
							TimeInfo timeInfo = (TimeInfo) info;
							time = new BigDecimal(
									timeInfo.getTimeMillis() / 1000.0)
									.setScale(1, BigDecimal.ROUND_HALF_UP)
									.toString();
						} else if (info instanceof BestLineFoundInfo) {
							BestLineFoundInfo bestLineFoundInfo = (BestLineFoundInfo) info;
							StringBuilder line = new StringBuilder(100);
							Game gameClone = controller.getGame()
									.deepCopy(true);
							gameClone.addState(Game.UPDATING_SAN_STATE);
							gameClone
									.clearState(Game.UPDATING_ECO_HEADERS_STATE);

							boolean isFirstMove = true;

							for (UCIMove move : bestLineFoundInfo.getMoves()) {
								try {
									Move gameMove = gameClone.makeMove(move
											.getStartSquare(), move
											.getEndSquare(), move
											.getPromotedPiece());
									String san = GameUtils
											.convertSanToUseUnicode(gameMove
													.getSan(), gameMove
													.isWhitesMove());
									String moveNumber = isFirstMove
											&& !gameMove.isWhitesMove() ? gameMove
											.getFullMoveCount()
											+ ") ... "
											: gameMove.isWhitesMove() ? gameMove
													.getFullMoveCount()
													+ ") "
													: "";
									line
											.append((line.equals("") ? "" : " ")
													+ moveNumber
													+ san
													+ (gameClone.isInCheck() ? "+"
															: ""));
									isFirstMove = false;
								} catch (Throwable t) {
									LOG
											.warn(
													"Illegal line found skipping line.",
													t);
									break;
								}
							}
							pvs.add(line.toString());
						}
					}

					final String finalScore = score;
					final String finalTime = time;
					final String finalDepth = depth;
					final String finalNodes = nodes;
					final List<String> finalPVs = pvs;
					final String finalCPU = cpu;
					final String finalNPS = nps;

					Raptor.getInstance().getDisplay().asyncExec(new Runnable() {
						public void run() {
							if (!finalPVs.isEmpty()) {
								String[][] data = new String[bestMoves<commit_msg>Added a check for disposed before updating from a UCI info.<commit_after>/**
 * New BSD License
 * http://www.opensource.org/licenses/bsd-license.php
 * Copyright (c) 2009, RaptorProject (http://code.google.com/p/raptor-chess-interface/)
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 * Neither the name of the RaptorProject nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package raptor.swt.chess.analysis;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;

import raptor.Raptor;
import raptor.chess.Game;
import raptor.chess.Move;
import raptor.chess.util.GameUtils;
import raptor.engine.uci.UCIBestMove;
import raptor.engine.uci.UCIEngine;
import raptor.engine.uci.UCIInfo;
import raptor.engine.uci.UCIInfoListener;
import raptor.engine.uci.UCIMove;
import raptor.engine.uci.UCIOption;
import raptor.engine.uci.info.BestLineFoundInfo;
import raptor.engine.uci.info.CPULoadInfo;
import raptor.engine.uci.info.DepthInfo;
import raptor.engine.uci.info.NodesPerSecondInfo;
import raptor.engine.uci.info.NodesSearchedInfo;
import raptor.engine.uci.info.ScoreInfo;
import raptor.engine.uci.info.TimeInfo;
import raptor.engine.uci.options.UCIButton;
import raptor.pref.PreferenceKeys;
import raptor.service.ThreadService;
import raptor.service.UCIEngineService;
import raptor.swt.RaptorTable;
import raptor.swt.UCIEnginePropertiesDialog;
import raptor.swt.chess.ChessBoardController;
import raptor.swt.chess.EngineAnalysisWidget;
import raptor.util.RaptorStringUtils;

public class SimpleAnalysisWidget implements EngineAnalysisWidget {
	private static final Log LOG = LogFactory
			.getLog(SimpleAnalysisWidget.class);

	protected ChessBoardController controller;
	protected Composite composite, topLine;
	protected UCIEngine currentEngine;
	protected CLabel engineComboCLabel;
	protected CLabel nodesPerSecondLabelLabel;
	protected CLabel nodesPerSecondLabel;
	protected CLabel cpuPercentageLabelLabel;
	protected CLabel cpuPercentageLabel;
	protected Combo engineCombo;
	protected RaptorTable bestMoves;
	protected Button stopButton, startButton, propertiesButton;
	protected boolean ignoreEngineSelection;
	protected boolean isInStart = false;
	protected UCIInfoListener listener = new UCIInfoListener() {
		public void engineSentBestMove(UCIBestMove uciBestMove) {
		}

		public void engineSentInfo(final UCIInfo[] infos) {
			Raptor.getInstance().getDisplay().asyncExec(new Runnable() {
				public void run() {
					String score = null;
					String time = null;
					String depth = null;
					String nodes = null;
					String cpu = null;
					String nps = null;
					List<String> pvs = new ArrayList<String>(3);

					for (UCIInfo info : infos) {
						if (info instanceof ScoreInfo) {
							ScoreInfo scoreInfo = (ScoreInfo) info;
							if (((ScoreInfo) info).getMateInMoves() != 0) {
								score = "Mate in " + scoreInfo.getMateInMoves();
							} else if (scoreInfo.isLowerBoundScore()) {
								score = "-inf";
							} else if (scoreInfo.isUpperBoundScore()) {
								score = "+inf";
							} else {
								score = ""
										+ new BigDecimal(scoreInfo
												.getValueInCentipawns() / 100.0)
												.setScale(
														2,
														BigDecimal.ROUND_HALF_UP)
												.toString();
							}
						} else if (info instanceof DepthInfo) {
							DepthInfo depthInfo = (DepthInfo) info;
							depth = depthInfo.getSearchDepthPlies() + " plies";
						} else if (info instanceof NodesSearchedInfo) {
							NodesSearchedInfo nodesSearchedInfo = (NodesSearchedInfo) info;
							nodes = RaptorStringUtils.formatAsNumber(""
									+ nodesSearchedInfo.getNodesSearched()
									/ 1000);
						} else if (info instanceof CPULoadInfo) {
							CPULoadInfo cpuLoad = (CPULoadInfo) info;
							cpu = new BigDecimal(
									cpuLoad.getCpuUsage() / 1000.0 * 100)
									.setScale(0, BigDecimal.ROUND_HALF_UP)
									.toString();
						} else if (info instanceof NodesPerSecondInfo) {
							NodesPerSecondInfo nodesPerSecondInfo = (NodesPerSecondInfo) info;
							nps = RaptorStringUtils.formatAsNumber(""
									+ nodesPerSecondInfo.getNodesPerSecond()
									/ 1000);
						} else if (info instanceof TimeInfo) {
							TimeInfo timeInfo = (TimeInfo) info;
							time = new BigDecimal(
									timeInfo.getTimeMillis() / 1000.0)
									.setScale(1, BigDecimal.ROUND_HALF_UP)
									.toString();
						} else if (info instanceof BestLineFoundInfo) {
							BestLineFoundInfo bestLineFoundInfo = (BestLineFoundInfo) info;
							StringBuilder line = new StringBuilder(100);
							Game gameClone = controller.getGame()
									.deepCopy(true);
							gameClone.addState(Game.UPDATING_SAN_STATE);
							gameClone
									.clearState(Game.UPDATING_ECO_HEADERS_STATE);

							boolean isFirstMove = true;

							for (UCIMove move : bestLineFoundInfo.getMoves()) {
								try {
									Move gameMove = gameClone.makeMove(move
											.getStartSquare(), move
											.getEndSquare(), move
											.getPromotedPiece());
									String san = GameUtils
											.convertSanToUseUnicode(gameMove
													.getSan(), gameMove
													.isWhitesMove());
									String moveNumber = isFirstMove
											&& !gameMove.isWhitesMove() ? gameMove
											.getFullMoveCount()
											+ ") ... "
											: gameMove.isWhitesMove() ? gameMove
													.getFullMoveCount()
													+ ") "
													: "";
									line
											.append((line.equals("") ? "" : " ")
													+ moveNumber
													+ san
													+ (gameClone.isInCheck() ? "+"
															: ""));
									isFirstMove = false;
								} catch (Throwable t) {
									LOG
											.warn(
													"Illegal line found skipping line.",
													t);
									break;
								}
							}
							pvs.add(line.toString());
						}
					}

					final String finalScore = score;
					final String finalTime = time;
					final String finalDepth = depth;
					final String finalNodes = nodes;
					final List<String> finalPVs = pvs;
					final String finalCPU = cpu;
					final String finalNPS = nps;

					Raptor.getInstance().getDisplay().asyncExec(new Runnable() {
						public void run() {
							if (composite.isDisposed()) {
								return;
							}
							if (!finalPVs.isEmpty()) {
								String[][] data = new String[bestMoves
{'fraction_non_alphanumeric': 0.08914209115281502, 'fraction_numerical': 0.004508895929807458, 'mean_word_length': 3.1742115971515767, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6742628', 'n_tokens_mistral': 6457, 'n_tokens_neox': 4684, 'n_words': 1282}