<commit_before>#include <QDataStream>

#include "Connections/Bootstrapper.hpp"
#include "Connections/Connection.hpp"
#include "Transports/AddressFactory.hpp"
#include "Transports/EdgeListenerFactory.hpp"

#include "BaseOverlay.hpp"

using Dissent::Transports::AddressFactory;
using Dissent::Transports::EdgeListenerFactory;

namespace Dissent {
namespace Overlay {
  BaseOverlay::BaseOverlay(const Id &local_id,
      const QList<Address> &local_endpoints,
      const QList<Address> &remote_endpoints) :
    _local_endpoints(local_endpoints),
    _remote_endpoints(remote_endpoints),
    _local_id(local_id),
    _rpc(new RpcHandler()),
    _cm(new ConnectionManager(_local_id, _rpc))
  {
  }

  BaseOverlay::~BaseOverlay()
  {
  }

  void BaseOverlay::OnStart()
  {
    qDebug() << "Starting node" << _local_id.ToString();

    QObject::connect(_cm.data(), SIGNAL(Disconnected()),
        this, SLOT(HandleDisconnected()));

    foreach(const Address &addr, _local_endpoints) {
      EdgeListener *el = EdgeListenerFactory::GetInstance().CreateEdgeListener(addr);
      QSharedPointer<EdgeListener> pel(el);
      _cm->AddEdgeListener(pel);
      pel->Start();
    }

    QSharedPointer<ConnectionAcquirer> cab(
      new Dissent::Connections::Bootstrapper(_cm, _remote_endpoints));
    _con_acquirers.append(cab);

    foreach(const QSharedPointer<ConnectionAcquirer> &ca, _con_acquirers) {
      ca->Start();
    }
  }

  void BaseOverlay::AddConnectionAcquirer(
      const QSharedPointer<ConnectionAcquirer> &ca)
  {
    _con_acquirers.append(ca);
    if(Started() && !Stopped()) {
      ca->Start();
    }
  }

  void BaseOverlay::OnStop()
  {
    emit Disconnecting();
    foreach(const QSharedPointer<ConnectionAcquirer> &ca, _con_acquirers) {
      ca->Stop();
    }

    _cm->Stop();
  }

  void BaseOverlay::HandleDisconnected()
  {
    emit Disconnected();
  }
}
}
<commit_msg>[Overlay] ConnectionManager needs to be started in order to monitor edge timeouts<commit_after>#include <QDataStream>

#include "Connections/Bootstrapper.hpp"
#include "Connections/Connection.hpp"
#include "Transports/AddressFactory.hpp"
#include "Transports/EdgeListenerFactory.hpp"

#include "BaseOverlay.hpp"

using Dissent::Transports::AddressFactory;
using Dissent::Transports::EdgeListenerFactory;

namespace Dissent {
namespace Overlay {
  BaseOverlay::BaseOverlay(const Id &local_id,
      const QList<Address> &local_endpoints,
      const QList<Address> &remote_endpoints) :
    _local_endpoints(local_endpoints),
    _remote_endpoints(remote_endpoints),
    _local_id(local_id),
    _rpc(new RpcHandler()),
    _cm(new ConnectionManager(_local_id, _rpc))
  {
  }

  BaseOverlay::~BaseOverlay()
  {
  }

  void BaseOverlay::OnStart()
  {
    qDebug() << "Starting node" << _local_id.ToString();

    QObject::connect(_cm.data(), SIGNAL(Disconnected()),
        this, SLOT(HandleDisconnected()));

    foreach(const Address &addr, _local_endpoints) {
      EdgeListener *el = EdgeListenerFactory::GetInstance().CreateEdgeListener(addr);
      QSharedPointer<EdgeListener> pel(el);
      _cm->AddEdgeListener(pel);
      pel->Start();
    }

    QSharedPointer<ConnectionAcquirer> cab(
      new Dissent::Connections::Bootstrapper(_cm, _remote_endpoints));
    _con_acquirers.append(cab);

    _cm->Start();
    foreach(const QSharedPointer<ConnectionAcquirer> &ca, _con_acquirers) {
      ca->Start();
    }
  }

  void BaseOverlay::AddConnectionAcquirer(
      const QSharedPointer<ConnectionAcquirer> &ca)
  {
    _con_acquirers.append(ca);
    if(Started() && !Stopped()) {
      ca->Start();
    }
  }

  void BaseOverlay::OnStop()
  {
    emit Disconnecting();
    foreach(const QSharedPointer<ConnectionAcquirer> &ca, _con_acquirers) {
      ca->Stop();
    }

    _cm->Stop();
  }

  void BaseOverlay::HandleDisconnected()
  {
    emit Disconnected();
  }
}
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include <Navigation.h>

// Nodes
#include <nodes/Gps.h>

Gps gps;

Navigation::Navigation(){

}

void Navigation::cycle(int hz )//, nSync pointer)
{

    switch(hz)
    {
        case 400:
        {
            //printf("Navigation: 400\n");
            break;
        }
        case 200:
        {
            //printf("Navigation: 200\n");
            break;
        }
        case 100:
        {
            //printf("Navigation: 100\n");
            break;
        }
        case 50:
        {
            //printf("Navigation: 50\n");

            break;
        }
        case 10:
        {
            //printf("Navigation: 10\n");

            break;
        }
        case 5:
        {
            //printf("Navigation: 5\n");
            int res = 0;
            res = gps.update();
            printf("***************** TOA: %lld.%.9ld\n", (long long)gps.data.TOA.tv_sec, gps.data.TOA.tv_nsec);
            printf("UTC time: %f\n",gps.data.utc_time);
            printf("gps fix quality: %d\n",gps.data.fix_quality);
            printf("gps latitude: %f\n",gps.data.latitude);
            printf("gps longitude: %f\n",gps.data.longitude);
            printf("gps altitude: %f\n",gps.data.altitude);
            printf("gps Hdop: %f\n",gps.data.hdop);
            printf("gps # sats: %d\n",gps.data.num_sats);
            printf("gps nav mode: %s\n",gps.data.nav_mode);
            printf("gps cog magnetic: %f\n",gps.data.cog_m);
            printf("gps sog kps: %f\n",gps.data.sog_kph);
            printf("gps sog mps: %f\n",gps.data.sog_mps);
            break;
            if(res != 0)
            {
                printf("gps update failed");
            }

        }
    }
}
<commit_msg>Changed include identifyers <> ""<commit_after>#include <stdio.h>
#include "Navigation.h"

// Nodes
#include "Gps.h"

Gps gps;

Navigation::Navigation(){

}

void Navigation::cycle(int hz )//, nSync pointer)
{

    switch(hz)
    {
        case 400:
        {
            //printf("Navigation: 400\n");
            break;
        }
        case 200:
        {
            //printf("Navigation: 200\n");
            break;
        }
        case 100:
        {
            //printf("Navigation: 100\n");
            break;
        }
        case 50:
        {
            //printf("Navigation: 50\n");

            break;
        }
        case 10:
        {
            //printf("Navigation: 10\n");

            break;
        }
        case 5:
        {
            //printf("Navigation: 5\n");
            int res = 0;
            res = gps.update();
            printf("***************** TOA: %lld.%.9ld\n", (long long)gps.data.TOA.tv_sec, gps.data.TOA.tv_nsec);
            printf("UTC time: %f\n",gps.data.utc_time);
            printf("gps fix quality: %d\n",gps.data.fix_quality);
            printf("gps latitude: %f\n",gps.data.latitude);
            printf("gps longitude: %f\n",gps.data.longitude);
            printf("gps altitude: %f\n",gps.data.altitude);
            printf("gps Hdop: %f\n",gps.data.hdop);
            printf("gps # sats: %d\n",gps.data.num_sats);
            printf("gps nav mode: %s\n",gps.data.nav_mode);
            printf("gps cog magnetic: %f\n",gps.data.cog_m);
            printf("gps sog kps: %f\n",gps.data.sog_kph);
            printf("gps sog mps: %f\n",gps.data.sog_mps);
            break;
            if(res != 0)
            {
                printf("gps update failed");
            }

        }
    }
}
<|endoftext|>


<commit_before>#include "King.h"
#include "Rook.h"
#include "Board.h"

namespace Chess {
	King::King(const Position& position, bool white) : Piece(position, white) {
		_hasMoved = false;
	}

	void King::move(const Position& newPosition) {
		position = newPosition;
		_hasMoved = true;
	}

	bool King::hasMoved() const {
		return _hasMoved;
	}

	bool King::isChecked(const Board& board) const {
		// Check other pieces.
		for (int x = 0; x < 8; x++) {
			for (int y = 0; y < 8; y++) {
				Piece* piece = board.getPiece(Position(x, y));

				if (piece != nullptr && isWhite() != piece->isWhite() && piece->notation() != 'k' && piece->notation() != 'K') {
					std::vector<Position> moves = piece->moves(board);
					for (Position move : moves) {
						if (move == position)
							return true;
					}
				}
			}
		}

		// Check opponent's king.
		for (int x = position.x - 1; x <= position.x + 1; x++) {
			for (int y = position.y - 1; y <= position.y + 1; y++) {
				if (Position(x, y).valid()) {
					Piece* piece = board.getPiece(Position(x, y));
					if (piece != nullptr && piece->isWhite() != isWhite() && (piece->notation() == 'k' || piece->notation() == 'K'))
						return true;
				}
			}
		}

		return false;
	}

	char King::notation() const {
		return isWhite() ? 'K' : 'k';
	}

	std::vector<Position> King::moves(const Board& board) const {
		std::vector<Position> validPosition;
		Position tempPosition;

		for (int i = 0; i < 3; i++) {
			tempPosition.x = this->position.x - 1 + i;
			for (int j = 0; j < 3; j++) {
				tempPosition.y = this->position.y - 1 + j;
				if (tempPosition.valid() &&
					( ( board.getPiece(tempPosition) == nullptr ) || (board.getPiece(tempPosition)->isWhite() != this->isWhite()) ) )
					validPosition.push_back(tempPosition);
			}
		}

		// Check for valid castling
		if (!_hasMoved && !isChecked(board)) {
			Rook* leftRook = dynamic_cast<Rook *>(board.getPiece(Position(0, position.y)));
			Rook* rightRook = dynamic_cast<Rook *>(board.getPiece(Position(7, position.y)));
			bool leftCastling = true;
			bool rightCastling = true;
			King castlingKing = King(position,isWhite());

			for (int l = -1; l < 2; l += 2) {
				if (board.getPiece(Position(position.x + 1 * l, position.y)) == nullptr
					&& board.getPiece(Position(position.x + 2 * l, position.y)) == nullptr) {
					for (int k = 1; k < 3; k++) {
						Position tempPosition = position;
						tempPosition.x += k*l;
						castlingKing.position = tempPosition;
						if (l == -1) {
							if (board.getPiece(Position(position.x + 3 * l, position.y)) != nullptr || leftRook->hasMoved() || castlingKing.isChecked(board)) {
								leftCastling = false;
							}
						} else if (l == 1) {
							if (rightRook == nullptr || rightRook->hasMoved() || castlingKing.isChecked(board)) {
								rightCastling = false;
							}
						}
					}
				} else {
					if (l == 1) {
						rightCastling = false;
					} else if (l == -1) {
						leftCastling = false;
					}
				}
			}
			if (leftCastling)
				validPosition.push_back(Position(position.x - 2, position.y));

			if (rightCastling)
				validPosition.push_back(Position(position.x + 2, position.y));
		}

		return validPosition;
	}
}<commit_msg>Fix castling crash<commit_after>#include "King.h"
#include "Rook.h"
#include "Board.h"

namespace Chess {
	King::King(const Position& position, bool white) : Piece(position, white) {
		_hasMoved = false;
	}

	void King::move(const Position& newPosition) {
		position = newPosition;
		_hasMoved = true;
	}

	bool King::hasMoved() const {
		return _hasMoved;
	}

	bool King::isChecked(const Board& board) const {
		// Check other pieces.
		for (int x = 0; x < 8; x++) {
			for (int y = 0; y < 8; y++) {
				Piece* piece = board.getPiece(Position(x, y));

				if (piece != nullptr && isWhite() != piece->isWhite() && piece->notation() != 'k' && piece->notation() != 'K') {
					std::vector<Position> moves = piece->moves(board);
					for (Position move : moves) {
						if (move == position)
							return true;
					}
				}
			}
		}

		// Check opponent's king.
		for (int x = position.x - 1; x <= position.x + 1; x++) {
			for (int y = position.y - 1; y <= position.y + 1; y++) {
				if (Position(x, y).valid()) {
					Piece* piece = board.getPiece(Position(x, y));
					if (piece != nullptr && piece->isWhite() != isWhite() && (piece->notation() == 'k' || piece->notation() == 'K'))
						return true;
				}
			}
		}

		return false;
	}

	char King::notation() const {
		return isWhite() ? 'K' : 'k';
	}

	std::vector<Position> King::moves(const Board& board) const {
		std::vector<Position> validPosition;
		Position tempPosition;

		for (int i = 0; i < 3; i++) {
			tempPosition.x = this->position.x - 1 + i;
			for (int j = 0; j < 3; j++) {
				tempPosition.y = this->position.y - 1 + j;
				if (tempPosition.valid() &&
					( ( board.getPiece(tempPosition) == nullptr ) || (board.getPiece(tempPosition)->isWhite() != this->isWhite()) ) )
					validPosition.push_back(tempPosition);
			}
		}

		// Check for valid castling
		if (!_hasMoved && !isChecked(board)) {
			Rook* leftRook = dynamic_cast<Rook *>(board.getPiece(Position(0, position.y)));
			Rook* rightRook = dynamic_cast<Rook *>(board.getPiece(Position(7, position.y)));
			bool leftCastling = true;
			bool rightCastling = true;
			King castlingKing = King(position,isWhite());

			for (int l = -1; l < 2; l += 2) {
				if (board.getPiece(Position(position.x + 1 * l, position.y)) == nullptr
					&& board.getPiece(Position(position.x + 2 * l, position.y)) == nullptr) {
					for (int k = 1; k < 3; k++) {
						Position tempPosition = position;
						tempPosition.x += k*l;
						castlingKing.position = tempPosition;
						if (l == -1) {
							if (board.getPiece(Position(position.x + 3 * l, position.y)) != nullptr || leftRook == nullptr || leftRook->hasMoved() || castlingKing.isChecked(board)) {
								leftCastling = false;
							}
						} else if (l == 1) {
							if (rightRook == nullptr || rightRook->hasMoved() || castlingKing.isChecked(board)) {
								rightCastling = false;
							}
						}
					}
				} else {
					if (l == 1) {
						rightCastling = false;
					} else if (l == -1) {
						leftCastling = false;
					}
				}
			}
			if (leftCastling)
				validPosition.push_back(Position(position.x - 2, position.y));

			if (rightCastling)
				validPosition.push_back(Position(position.x + 2, position.y));
		}

		return validPosition;
	}
}<|endoftext|>


<commit_before><?hh //strict

/**
 * This file is part of package.
 *
 * (c) Noritaka Horio <holy.shared.design@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace package;

use \ReflectionClass;
use \ReflectionException;

final class PackageSpecification
{

    private PackageNamespace $namespace;
    private DirectoryPath $packageDirectory;

    public function __construct(
        Package $package
    )
    {
        $this->namespace = (string) $package['namespace'];
        $this->packageDirectory = realpath($package['packageDirectory']);
    }

    <<__Memoize>>
    public function getNamespace() : PackageNamespace
    {
        $atoms = explode('\\', $this->namespace);
        $atoms = (new Vector($atoms))->filter((string $atom) ==> {
            return trim($atom) !== '';
        });
        return implode('\\', $atoms);
    }

    public function getPackageDirectory() : DirectoryPath
    {
        return $this->packageDirectory;
    }

    public function resolve<T>(PackageFile $file) : T
    {
        $relativeClass = $this->relativeClassFrom($file);
        $fullName = $this->namespace . $relativeClass;

        try {
            $reflection = new ReflectionClass($fullName);
        } catch (ReflectionException $exception) {
            throw new NotPackageFileException();
        }

        return $reflection->newInstance();
    }

    private function relativeClassFrom(PackageFile $file) : string
    {
        $replaceTargets = [
            $this->packageDirectory . '/',
            '/',
            '.hh'
        ];
        $replaceValues = [
            '',
            '\\',
            ''
        ];
        $relativeClass = str_replace($replaceTargets, $replaceValues, $file);

        return $relativeClass;
    }

}
<commit_msg>add resolveWith<commit_after><?hh //strict

/**
 * This file is part of package.
 *
 * (c) Noritaka Horio <holy.shared.design@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace package;

use \ReflectionClass;
use \ReflectionException;

final class PackageSpecification
{

    private PackageNamespace $namespace;
    private DirectoryPath $packageDirectory;

    public function __construct(
        Package $package
    )
    {
        $this->namespace = (string) $package['namespace'];
        $this->packageDirectory = realpath($package['packageDirectory']);
    }

    <<__Memoize>>
    public function getNamespace() : PackageNamespace
    {
        $atoms = explode('\\', $this->namespace);
        $atoms = (new Vector($atoms))->filter((string $atom) ==> {
            return trim($atom) !== '';
        });
        return implode('\\', $atoms);
    }

    public function getPackageDirectory() : DirectoryPath
    {
        return $this->packageDirectory;
    }

    public function resolve<T>(PackageFile $file) : T
    {
        $reflection = $this->reflectionFrom($file);
        return $reflection->newInstance();
    }

    public function resolveWith<T>(PackageFile $file, array<mixed> $parameters) : T
    {
        $reflection = $this->reflectionFrom($file);
        return $reflection->newInstanceArgs($parameters);
    }

    private function reflectionFrom<T>(PackageFile $file) : ReflectionClass
    {
        $relativeClass = $this->relativeClassFrom($file);
        $fullClassName = $this->namespace . $relativeClass;

        try {
            $reflection = new ReflectionClass($fullClassName);
        } catch (ReflectionException $exception) {
            throw new NotPackageFileException();
        }

        return $reflection;
    }

    private function relativeClassFrom(PackageFile $file) : string
    {
        $replaceTargets = [
            $this->packageDirectory . '/',
            '/',
            '.hh'
        ];
        $replaceValues = [
            '',
            '\\',
            ''
        ];
        $relativeClass = str_replace($replaceTargets, $replaceValues, $file);

        return $relativeClass;
    }

}
<|endoftext|>


<commit_before>/**
 * @file    main.cpp
 * @brief   Simple packet sniffer/monitor using ESP8266 in
 *          promiscuous mode.
 *
 * @author  Simon Lövgren
 * @license MIT
 *
 * Based on "PacketMonitor" by Stefan Kremser:
 * https://github.com/spacehuhn/PacketMonitor
 */

/**
 * ------------------------------------------------------------------
 * Includes
 * ------------------------------------------------------------------
 */
#include <Arduino.h>
#include <ESP8266WiFi.h>

/**
 * ------------------------------------------------------------------
 * Defines
 * ------------------------------------------------------------------
 */
// De-mystify enable/disable functions
#define DISABLE 0
#define ENABLE  1

// Max channel number (US = 11, EU = 13, Japan = 14)
#define MAX_CHANNEL   13

// Deauth alarm level (packet rate per second)
#define DEAUTH_ALARM_LEVEL    5

// How long to sleep in main loop
#define LOOP_DELAY_MS         1000

/**
 * ------------------------------------------------------------------
 * Typedefs
 * ------------------------------------------------------------------
 */

/**
 * ------------------------------------------------------------------
 * Prototypes
 * ------------------------------------------------------------------
 */

static void packetSniffer( uint8_t* buffer, uint16_t length );

/**
 * ------------------------------------------------------------------
 * Private data
 * ------------------------------------------------------------------
 */

// Packet counters
static unsigned long packets             = 0;
static unsigned long deauths             = 0;
static unsigned long totalPackets        = 0;       // Should probably be long long, but can't be bothered to fix the serial print of it...
static unsigned long totalDeauths        = 0;       // Should probably be long long, but can't be bothered to fix the serial print of it...
static unsigned long maxPackets          = 0;
static unsigned long maxDeauths          = 0;
static unsigned long minPackets          = -1;
static unsigned long minDeauths          = -1;

/**
 * ------------------------------------------------------------------
 * Interface implementation
 * ------------------------------------------------------------------
 */

/**
 * ******************************************************************
 * Function
 * ******************************************************************
 */
void setup( void )
{
    // Enable serial communication over UART @ 115200 baud
    Serial.begin( 115200 );

    // Set up ESP8266 in promiscuous mode
    wifi_set_opmode( STATION_MODE );
    wifi_promiscuous_enable( DISABLE );
    WiFi.disconnect();
    wifi_set_promiscuous_rx_cb( packetSniffer );
    wifi_promiscuous_enable( ENABLE );

    // Report setup completed
    Serial.println( "Setup completed." );
}

/**
 * ******************************************************************
 * Function
 * ******************************************************************
 */
void loop( void )
{
    delay( LOOP_DELAY_MS );
    unsigned long currentPackets = packets;
    unsigned long currentDeauths = deauths;

    // Add to total
    totalPackets += currentPackets;
    totalDeauths += currentDeauths;

    // Grab max/min
    if ( currentPackets > maxPackets )
    {
        maxPackets = currentPackets;
    }
    if ( currentPackets < minPackets )
    {
        minPackets = currentPackets;
    }
    if ( currentDeauths > maxDeauths )
    {
        maxDeauths = currentDeauths;
    }
    if ( currentDeauths < minDeauths )
    {
        minDeauths = currentDeauths;
    }

    // Spacing
    Serial.print( "\n" );

    // Print statistics
    Serial.print( "           SEEN    MAX     MIN     TOTAL\n" );
    Serial.print( "           --------------------------------------\n" );
    Serial.printf( "PACKETS    %-4lu    %-4lu    %-4lu    %lu\n", currentPackets, maxPackets, minPackets, totalPackets );
    Serial.printf( "DEAUTHS    %-4lu    %-4lu    %-4lu    %lu\n", currentDeauths, maxDeauths, minDeauths, totalDeauths );

    // Deauth alarm
    if ( deauths > DEAUTH_ALARM_LEVEL )
    {
        Serial.println("\n[ DEAUTH ALARM ]");
    }

    // For additional spacing
    Serial.print( "\n" );

    // Reset counters
    packets = 0;
    deauths = 0;
}

/**
 * ------------------------------------------------------------------
 * Private functions
 * ------------------------------------------------------------------
 */

/**
 * ******************************************************************
 * Function
 * ******************************************************************
 */
static void packetSniffer( uint8_t* buffer, uint16_t length )
{
    // Gets called for each packet
    ++packets;
    if ( buffer[ 12 ] == 0xA0 || buffer[ 12 ] == 0xC0 )
    {
        ++deauths;
    }
}<commit_msg>Set explicit wifi channel in ESP8266/packetsniffer.<commit_after>/**
 * @file    main.cpp
 * @brief   Simple packet sniffer/monitor using ESP8266 in
 *          promiscuous mode.
 *
 * @author  Simon Lövgren
 * @license MIT
 *
 * Based on "PacketMonitor" by Stefan Kremser:
 * https://github.com/spacehuhn/PacketMonitor
 */

/**
 * ------------------------------------------------------------------
 * Includes
 * ------------------------------------------------------------------
 */
#include <Arduino.h>
#include <ESP8266WiFi.h>

/**
 * ------------------------------------------------------------------
 * Defines
 * ------------------------------------------------------------------
 */
// De-mystify enable/disable functions
#define DISABLE 0
#define ENABLE  1

// Max channel number (US = 11, EU = 13, Japan = 14)
#define MAX_CHANNEL   13

// Channel to set
#define CHANNEL       1

// Deauth alarm level (packet rate per second)
#define DEAUTH_ALARM_LEVEL    5

// How long to sleep in main loop
#define LOOP_DELAY_MS         1000

/**
 * ------------------------------------------------------------------
 * Typedefs
 * ------------------------------------------------------------------
 */

/**
 * ------------------------------------------------------------------
 * Prototypes
 * ------------------------------------------------------------------
 */

static void packetSniffer( uint8_t* buffer, uint16_t length );

/**
 * ------------------------------------------------------------------
 * Private data
 * ------------------------------------------------------------------
 */

// Packet counters
static unsigned long packets             = 0;
static unsigned long deauths             = 0;
static unsigned long totalPackets        = 0;       // Should probably be long long, but can't be bothered to fix the serial print of it...
static unsigned long totalDeauths        = 0;       // Should probably be long long, but can't be bothered to fix the serial print of it...
static unsigned long maxPackets          = 0;
static unsigned long maxDeauths          = 0;
static unsigned long minPackets          = -1;
static unsigned long minDeauths          = -1;

/**
 * ------------------------------------------------------------------
 * Interface implementation
 * ------------------------------------------------------------------
 */

/**
 * ******************************************************************
 * Function
 * ******************************************************************
 */
void setup( void )
{
    // Enable serial communication over UART @ 115200 baud
    Serial.begin( 115200 );

    // Set up ESP8266 in promiscuous mode
    wifi_set_opmode( STATION_MODE );
    wifi_promiscuous_enable( DISABLE );
    WiFi.disconnect();
    wifi_set_promiscuous_rx_cb( packetSniffer );
    wifi_promiscuous_enable( ENABLE );

    // Currently only sniffing pre-defined channel.
    // Should rotate through all channels in loop continuously and
    // use yield() instead of sleep.
    wifi_set_channel( CHANNEL );

    // Report setup completed
    Serial.println( "Setup completed." );
}

/**
 * ******************************************************************
 * Function
 * ******************************************************************
 */
void loop( void )
{
    delay( LOOP_DELAY_MS );
    unsigned long currentPackets = packets;
    unsigned long currentDeauths = deauths;

    // Add to total
    totalPackets += currentPackets;
    totalDeauths += currentDeauths;

    // Grab max/min
    if ( currentPackets > maxPackets )
    {
        maxPackets = currentPackets;
    }
    if ( currentPackets < minPackets )
    {
        minPackets = currentPackets;
    }
    if ( currentDeauths > maxDeauths )
    {
        maxDeauths = currentDeauths;
    }
    if ( currentDeauths < minDeauths )
    {
        minDeauths = currentDeauths;
    }

    // Spacing
    Serial.print( "\n" );

    // Print statistics
    Serial.print( "           SEEN    MAX     MIN     TOTAL\n" );
    Serial.print( "           --------------------------------------\n" );
    Serial.printf( "PACKETS    %-4lu    %-4lu    %-4lu    %lu\n", currentPackets, maxPackets, minPackets, totalPackets );
    Serial.printf( "DEAUTHS    %-4lu    %-4lu    %-4lu    %lu\n", currentDeauths, maxDeauths, minDeauths, totalDeauths );

    // Deauth alarm
    if ( deauths > DEAUTH_ALARM_LEVEL )
    {
        Serial.println("\n[ DEAUTH ALARM ]");
    }

    // For additional spacing
    Serial.print( "\n" );

    // Reset counters
    packets = 0;
    deauths = 0;
}

/**
 * ------------------------------------------------------------------
 * Private functions
 * ------------------------------------------------------------------
 */

/**
 * ******************************************************************
 * Function
 * ******************************************************************
 */
static void packetSniffer( uint8_t* buffer, uint16_t length )
{
    // Gets called for each packet
    ++packets;
    if ( buffer[ 12 ] == 0xA0 || buffer[ 12 ] == 0xC0 )
    {
        ++deauths;
    }
}<|endoftext|>


<commit_before>// Copyright 2010-2021, Google Inc.
// 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 Google Inc. 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
// OWNER 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.

#ifdef OS_WIN
#include <windows.h>
#endif  // OS_WIN

#include <QGuiApplication>
#include <QtGui>

#include "base/logging.h"
#include "base/process_mutex.h"
#include "base/system_util.h"
#include "gui/base/util.h"
#include "gui/set_default_dialog/set_default_dialog.h"

#ifdef OS_WIN
#include "base/win_util.h"
#endif  // OS_WIN

int RunSetDefaultDialog(int argc, char *argv[]) {
  Q_INIT_RESOURCE(qrc_set_default_dialog);

  mozc::SystemUtil::DisableIME();

  std::string name = "set_default_dialog.";
  name += mozc::SystemUtil::GetDesktopNameAsString();

  mozc::ProcessMutex mutex(name.c_str());
  if (!mutex.Lock()) {
    LOG(INFO) << "set_default_dialog is already running";
    return -1;
  }

#ifdef OS_WIN
  // For ImeUtil::SetDefault.
  mozc::ScopedCOMInitializer com_initializer;
#endif  // OS_WIN

  auto app = mozc::gui::GuiUtil::InitQt(argc, argv);

  mozc::gui::GuiUtil::InstallTranslator("set_default_dialog");

  mozc::gui::SetDefaultDialog dialog;
  return dialog.exec();
}
<commit_msg>Fix 1 ClangTidyBuild finding:<commit_after>// Copyright 2010-2021, Google Inc.
// 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 Google Inc. 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
// OWNER 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.

#ifdef OS_WIN
#include <windows.h>
#endif  // OS_WIN

#include <QGuiApplication>
#include <QtGui>
#include <string>

#include "base/logging.h"
#include "base/process_mutex.h"
#include "base/system_util.h"
#include "gui/base/util.h"
#include "gui/set_default_dialog/set_default_dialog.h"

#ifdef OS_WIN
#include "base/win_util.h"
#endif  // OS_WIN

int RunSetDefaultDialog(int argc, char *argv[]) {
  Q_INIT_RESOURCE(qrc_set_default_dialog);

  mozc::SystemUtil::DisableIME();

  std::string name = "set_default_dialog.";
  name += mozc::SystemUtil::GetDesktopNameAsString();

  mozc::ProcessMutex mutex(name.c_str());
  if (!mutex.Lock()) {
    LOG(INFO) << "set_default_dialog is already running";
    return -1;
  }

#ifdef OS_WIN
  // For ImeUtil::SetDefault.
  mozc::ScopedCOMInitializer com_initializer;
#endif  // OS_WIN

  auto app = mozc::gui::GuiUtil::InitQt(argc, argv);

  mozc::gui::GuiUtil::InstallTranslator("set_default_dialog");

  mozc::gui::SetDefaultDialog dialog;
  return dialog.exec();
}
<|endoftext|>


<commit_before>#include "Reader/IniConfigReader.hpp"

namespace Utils
{

	IniConfigReader::IniConfigReader(std::string filePath):
		Reader(filePath)
	{

	}

	bool IniConfigReader::Read()
	{
		//TODO: écrire le parser de fichier ini
		return true;
	}

	Config IniConfigReader::GetConfig() const
	{
		return m_config;
	}

}<commit_msg>petite modif<commit_after>#include "Reader/IniConfigReader.hpp"

namespace Utils
{

	IniConfigReader::IniConfigReader(std::string filePath):
		Reader(filePath)
	{

	}

	bool IniConfigReader::Read()
	{
		std::string vCurrentSection = "undefined";

		while(m_file.good())
		{
			//On lit une ligne avec un fonction getLine(pointer sur fonction de détection de commentaire, ou caractère(s) de commentaire)
			std::cout << "lecture" << std::endl;
		}

		if(!m_file.good){
			//TODO : faire une fonction dans Reader pour répertorier les erreurs survenus
			std::cout << "pas ok" << std::endl;
		}

		return true;
	}

	Config IniConfigReader::GetConfig() const
	{
		return m_config;
	}

}<|endoftext|>


<commit_before>#include "ComPortScanner.h"
#include "simpleserial.h"
#include <sstream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <boost/foreach.hpp>

ComPortScanner::ComPortScanner()
{
}
std::string ComPortScanner::CheckPort(boost::asio::io_service &io_service, const std::string &portNum)
{
	try {
		std::string id = "";
		SimpleSerial port = SimpleSerial(io_service, portNum, 115200);
		for (int i = 0; i < 10; i++){
			port.writeString("?\n");
			id = port.readLineAsync(1000);

			std::cout << "Check result: " << portNum<< " -> " << id << std::endl;
			if (id == "discharged") continue;
			if (id.empty()) continue;
			if (id == "<id:0>") throw std::runtime_error(("ID not set in port " + portNum).c_str());
			if (id.substr(0, 4) != "<id:") throw std::runtime_error(("Invalid ID " + id + " received from port " + portNum).c_str());

			id = id.substr(4, 1);
			std::cout << "Found port " << portNum << ", id: " << id << std::endl;
			return id;
		}
		if (id.empty()) throw std::runtime_error(("No ID received from port " + portNum).c_str());
	}
	catch (std::runtime_error const&e){
		std::cout << "Port not accessible: " << portNum << ", error: " << e.what() << std::endl;
	}
	return "";
}

bool ComPortScanner::Verify(boost::asio::io_service &io_service, const std::string &conf_file)
{
	bool ok = true;
	boost::property_tree::ptree ports;
	try {
		read_ini(conf_file, ports);
	}
	catch (...) {
		std::cout << "Error reading old port configuration: " << std::endl;
		return false;
	}
	//BOOST_FOREACH(const boost::property_tree::ptree::value_type &v, ports) {
	for (int i = ID_WHEEL_LEFT; i < ID_OBJECT_COUNT; i++) {
		// v.first is the name of the child.
		// v.second is the child tree.
		std::stringstream portNum;
		//portNum << prefix <<
		std::string _id = std::to_string(i); // v.first;
		try {
			portNum << ports.get<std::string>(std::to_string(i));//(v.second).data();
		}
		catch (...)
		{
			std::cout << "ID: " << _id << " not found in conf file" << std::endl;
			ok = false;
			continue;
		}
		std::string id = CheckPort(io_service, portNum.str());
		if (id.empty()) {
			ok = false;
		}
	}
	return ok;
}

bool ComPortScanner::Scan(boost::asio::io_service &io_service)
{
//	std::map<short, std::string> portMap;
	boost::property_tree::ptree ports;

	bool ok = true;
	for (int i = 0; i < 20; i++) {
		std::stringstream portNum;
		portNum << prefix << i;
		std::string id = CheckPort(io_service, portNum.str());
		if (!id.empty()) {
			ports.put(id, portNum.str());
		}
	}
	if (true){
		write_ini("conf/ports_new.ini", ports);
	}
	if (Verify(io_service, "conf/ports_new.ini")) {
#ifdef WIN32
		_unlink("conf/ports.ini");
#else
		unlink("conf/ports.ini");
#endif
		rename("conf/ports_new.ini", "conf/ports.ini");
		return true;
	}
	return false;

}

ComPortScanner::~ComPortScanner()
{
}
<commit_msg>sanity<commit_after>#include "ComPortScanner.h"
#include "simpleserial.h"
#include <sstream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <boost/foreach.hpp>

ComPortScanner::ComPortScanner()
{
}
std::string ComPortScanner::CheckPort(boost::asio::io_service &io_service, const std::string &portNum)
{
	try {
		std::string id = "";
		SimpleSerial port = SimpleSerial(io_service, portNum, 115200);
		for (int i = 0; i < 10; i++){
			port.writeString("?\n");
			id = port.readLineAsync(1000);

			std::cout << "Check result: " << portNum<< " -> " << id << std::endl;
			if (id == "discharged") continue;
			if (id == "~x~~x~?") continue;
			if (id.empty()) continue;
			if (id == "<id:0>") throw std::runtime_error(("ID not set in port " + portNum).c_str());
			if (id.substr(0, 4) != "<id:") throw std::runtime_error(("Invalid ID " + id + " received from port " + portNum).c_str());

			id = id.substr(4, 1);
			std::cout << "Found port " << portNum << ", id: " << id << std::endl;
			return id;
		}
		if (id.empty()) throw std::runtime_error(("No ID received from port " + portNum).c_str());
	}
	catch (std::runtime_error const&e){
		std::cout << "Port not accessible: " << portNum << ", error: " << e.what() << std::endl;
	}
	return "";
}

bool ComPortScanner::Verify(boost::asio::io_service &io_service, const std::string &conf_file)
{
	bool ok = true;
	boost::property_tree::ptree ports;
	try {
		read_ini(conf_file, ports);
	}
	catch (...) {
		std::cout << "Error reading old port configuration: " << std::endl;
		return false;
	}
	//BOOST_FOREACH(const boost::property_tree::ptree::value_type &v, ports) {
	for (int i = ID_WHEEL_LEFT; i < ID_OBJECT_COUNT; i++) {
		// v.first is the name of the child.
		// v.second is the child tree.
		std::stringstream portNum;
		//portNum << prefix <<
		std::string _id = std::to_string(i); // v.first;
		try {
			portNum << ports.get<std::string>(std::to_string(i));//(v.second).data();
		}
		catch (...)
		{
			std::cout << "ID: " << _id << " not found in conf file" << std::endl;
			ok = false;
			continue;
		}
		std::string id = CheckPort(io_service, portNum.str());
		if (id.empty()) {
			ok = false;
		}
	}
	return ok;
}

bool ComPortScanner::Scan(boost::asio::io_service &io_service)
{
//	std::map<short, std::string> portMap;
	boost::property_tree::ptree ports;

	bool ok = true;
	for (int i = 0; i < 20; i++) {
		std::stringstream portNum;
		portNum << prefix << i;
		std::string id = CheckPort(io_service, portNum.str());
		if (!id.empty()) {
			ports.put(id, portNum.str());
		}
	}
	if (true){
		write_ini("conf/ports_new.ini", ports);
	}
	if (Verify(io_service, "conf/ports_new.ini")) {
#ifdef WIN32
		_unlink("conf/ports.ini");
#else
		unlink("conf/ports.ini");
#endif
		rename("conf/ports_new.ini", "conf/ports.ini");
		return true;
	}
	return false;

}

ComPortScanner::~ComPortScanner()
{
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkCell.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkCell.h"

#include "vtkMarchingSquaresCases.h"
#include "vtkPoints.h"

vtkCxxRevisionMacro(vtkCell, "1.56");

// Construct cell.
vtkCell::vtkCell()
{
  this->Points = vtkPoints::New();
  this->PointIds = vtkIdList::New();
  // Consistent Register/Deletes (ShallowCopy uses Register.)
  this->Points->Register(this);
  this->Points->Delete();
  this->PointIds->Register(this);
  this->PointIds->Delete();
}

vtkCell::~vtkCell()
{
  this->Points->UnRegister(this);
  this->PointIds->UnRegister(this);
}

//
// Instantiate cell from outside
//
void vtkCell::Initialize(int npts, vtkIdType *pts, vtkPoints *p)
{
  this->PointIds->Reset();
  this->Points->Reset();

  for (int i=0; i<npts; i++)
    {
    this->PointIds->InsertId(i,pts[i]);
    this->Points->InsertPoint(i,p->GetPoint(pts[i]));
    }
}

void vtkCell::ShallowCopy(vtkCell *c)
{
  this->Points->ShallowCopy(c->Points);
  if ( this->PointIds )
    {
    this->PointIds->UnRegister(this);
    this->PointIds = c->PointIds;
    this->PointIds->Register(this);
    }
}

void vtkCell::DeepCopy(vtkCell *c)
{
  this->Points->DeepCopy(c->Points);
  this->PointIds->DeepCopy(c->PointIds);
}

#define VTK_RIGHT 0
#define VTK_LEFT 1
#define VTK_MIDDLE 2

// Bounding box intersection modified from Graphics Gems Vol I. The method
// returns a non-zero value if the bounding box is hit. Origin[3] starts
// the ray, dir[3] is the vector components of the ray in the x-y-z
// directions, coord[3] is the location of hit, and t is the parametric
// coordinate along line. (Notes: the intersection ray dir[3] is NOT
// normalized.  Valid intersections will only occur between 0<=t<=1.)
char vtkCell::HitBBox (float bounds[6], float origin[3], float dir[3],
                      float coord[3], float& t)
{
  char    inside=1;
  char    quadrant[3];
  int     i, whichPlane=0;
  float   maxT[3], candidatePlane[3];

  //  First find closest planes
  //
  for (i=0; i<3; i++)
    {
    if ( origin[i] < bounds[2*i] )
      {
      quadrant[i] = VTK_LEFT;
      candidatePlane[i] = bounds[2*i];
      inside = 0;
      }
    else if ( origin[i] > bounds[2*i+1] )
      {
      quadrant[i] = VTK_RIGHT;
      candidatePlane[i] = bounds[2*i+1];
      inside = 0;
      }
    else
      {
      quadrant[i] = VTK_MIDDLE;
      }
    }

  //  Check whether origin of ray is inside bbox
  //
  if (inside)
    {
    coord[0] = origin[0];
    coord[1] = origin[1];
    coord[2] = origin[2];
    t = 0;
    return 1;
    }

  //  Calculate parametric distances to plane
  //
  for (i=0; i<3; i++)
    {
    if ( quadrant[i] != VTK_MIDDLE && dir[i] != 0.0 )
      {
      maxT[i] = (candidatePlane[i]-origin[i]) / dir[i];
      }
    else
      {
      maxT[i] = -1.0;
      }
    }

  //  Find the largest parametric value of intersection
  //
  for (i=0; i<3; i++)
    {
    if ( maxT[whichPlane] < maxT[i] )
      {
      whichPlane = i;
      }
    }

  //  Check for valid intersection along line
  //
  if ( maxT[whichPlane] > 1.0 || maxT[whichPlane] < 0.0 )
    {
    return 0;
    }
  else
    {
    t = maxT[whichPlane];
    }

  //  Intersection point along line is okay.  Check bbox.
  //
  for (i=0; i<3; i++)
    {
    if (whichPlane != i)
      {
      coord[i] = origin[i] + maxT[whichPlane]*dir[i];
      if ( coord[i] < bounds[2*i] || coord[i] > bounds[2*i+1] )
        {
        return 0;
        }
      }
    else
      {
      coord[i] = candidatePlane[i];
      }
    }

    return 1;
}

// Compute cell bounding box (xmin,xmax,ymin,ymax,zmin,zmax). Return pointer
// to array of six float values.
float *vtkCell::GetBounds ()
{
  float *x;
  int i, numPts=this->Points->GetNumberOfPoints();

  this->Bounds[0] = this->Bounds[2] = this->Bounds[4] =  VTK_LARGE_FLOAT;
  this->Bounds[1] = this->Bounds[3] = this->Bounds[5] = -VTK_LARGE_FLOAT;

  for (i=0; i<numPts; i++)
    {
    x = this->Points->GetPoint(i);

    this->Bounds[0] = (x[0] < this->Bounds[0] ? x[0] : this->Bounds[0]);
    this->Bounds[1] = (x[0] > this->Bounds[1] ? x[0] : this->Bounds[1]);
    this->Bounds[2] = (x[1] < this->Bounds[2] ? x[1] : this->Bounds[2]);
    this->Bounds[3] = (x[1] > this->Bounds[3] ? x[1] : this->Bounds[3]);
    this->Bounds[4] = (x[2] < this->Bounds[4] ? x[2] : this->Bounds[4]);
    this->Bounds[5] = (x[2] > this->Bounds[5] ? x[2] : this->Bounds[5]);

    }
  return this->Bounds;
}

// Compute cell bounding box (xmin,xmax,ymin,ymax,zmin,zmax). Copy result into
// user provided array.
void vtkCell::GetBounds(float bounds[6])
{
  this->GetBounds();
  for (int i=0; i < 6; i++)
    {
    bounds[i] = this->Bounds[i];
    }
}

// Compute Length squared of cell (i.e., bounding box diagonal squared).
float vtkCell::GetLength2 ()
{
  double diff, l=0.0;
  int i;

  this->GetBounds();
  for (i=0; i<3; i++)
    {
    diff = this->Bounds[2*i+1] - this->Bounds[2*i];
    l += diff * diff;
    }
  if(l > VTK_LARGE_FLOAT)
    {
    return VTK_LARGE_FLOAT;
    }
  return static_cast<float>(l);
}

// Return center of the cell in parametric coordinates.
// Note that the parametric center is not always located
// at (0.5,0.5,0.5). The return value is the subId that
// the center is in (if a composite cell). If you want the
// center in x-y-z space, invoke the EvaluateLocation() method.
int vtkCell::GetParametricCenter(float pcoords[3])
{
  pcoords[0] = pcoords[1] = pcoords[2] = 0.5;
  return 0;
}

// This method works fine for all "rectangular" cells, not triangular
// and tetrahedral topologies.
float vtkCell::GetParametricDistance(float pcoords[3])
{
  int i;
  float pDist, pDistMax=0.0f;

  for (i=0; i<3; i++)
    {
    if ( pcoords[i] < 0.0 )
      {
      pDist = -pcoords[i];
      }
    else if ( pcoords[i] > 1.0 )
      {
      pDist = pcoords[i] - 1.0f;
      }
    else //inside the cell in the parametric direction
      {
      pDist = 0.0;
      }
    if ( pDist > pDistMax )
      {
      pDistMax = pDist;
      }
    }
  return pDistMax;
}

void vtkCell::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);

  int numIds=this->PointIds->GetNumberOfIds();

  os << indent << "Number Of Points: " << numIds << "\n";

  if ( numIds > 0 )
    {
    float *bounds=this->GetBounds();

    os << indent << "Bounds: \n";
    os << indent << "  Xmin,Xmax: (" << bounds[0] << ", " << bounds[1] << ")\n";
    os << indent << "  Ymin,Ymax: (" << bounds[2] << ", " << bounds[3] << ")\n";
    os << indent << "  Zmin,Zmax: (" << bounds[4] << ", " << bounds[5] << ")\n";

    os << indent << "  Point ids are: ";
    for (int i=0; i < numIds; i++)
      {
      os << this->PointIds->GetId(i);
      if ( i && !(i % 12) )
        {
        os << "\n\t";
        }
      else
        {
        if ( i != (numIds-1) )
          {
          os << ", ";
          }
        }
      }
    os << indent << "\n";
    }
}

// Note: the following code is placed here to deal with cross-library
// symbol export and import on Microsoft compilers.
static vtkMarchingSquaresLineCases VTK_MARCHING_SQUARES_LINECASES[] = {
  {{-1, -1, -1, -1, -1}},
  {{0, 3, -1, -1, -1}},
  {{1, 0, -1, -1, -1}},
  {{1, 3, -1, -1, -1}},
  {{2, 1, -1, -1, -1}},
  {{0, 3, 2, 1, -1}},
  {{2, 0, -1, -1, -1}},
  {{2, 3, -1, -1, -1}},
  {{3, 2, -1, -1, -1}},
  {{0, 2, -1, -1, -1}},
  {{1, 0, 3, 2, -1}},
  {{1, 2, -1, -1, -1}},
  {{3, 1, -1, -1, -1}},
  {{0, 1, -1, -1, -1}},
  {{3, 0, -1, -1, -1}},
  {{-1, -1, -1, -1, -1}}
};

vtkMarchingSquaresLineCases* vtkMarchingSquaresLineCases::GetCases()
{
  return VTK_MARCHING_SQUARES_LINECASES;
}

//----------------------------------------------------------------------------
#ifndef VTK_REMOVE_LEGACY_CODE
vtkCell* vtkCell::MakeObject()
{
  VTK_LEGACY_METHOD(MakeObject, "4.2");
  vtkCell* c = this->NewInstance();
  c->DeepCopy(this);
  return c;
}
#endif
<commit_msg>ERR:Forgot to undefine some #defs<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkCell.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkCell.h"

#include "vtkMarchingSquaresCases.h"
#include "vtkPoints.h"

vtkCxxRevisionMacro(vtkCell, "1.57");

// Construct cell.
vtkCell::vtkCell()
{
  this->Points = vtkPoints::New();
  this->PointIds = vtkIdList::New();
  // Consistent Register/Deletes (ShallowCopy uses Register.)
  this->Points->Register(this);
  this->Points->Delete();
  this->PointIds->Register(this);
  this->PointIds->Delete();
}

vtkCell::~vtkCell()
{
  this->Points->UnRegister(this);
  this->PointIds->UnRegister(this);
}

//
// Instantiate cell from outside
//
void vtkCell::Initialize(int npts, vtkIdType *pts, vtkPoints *p)
{
  this->PointIds->Reset();
  this->Points->Reset();

  for (int i=0; i<npts; i++)
    {
    this->PointIds->InsertId(i,pts[i]);
    this->Points->InsertPoint(i,p->GetPoint(pts[i]));
    }
}

void vtkCell::ShallowCopy(vtkCell *c)
{
  this->Points->ShallowCopy(c->Points);
  if ( this->PointIds )
    {
    this->PointIds->UnRegister(this);
    this->PointIds = c->PointIds;
    this->PointIds->Register(this);
    }
}

void vtkCell::DeepCopy(vtkCell *c)
{
  this->Points->DeepCopy(c->Points);
  this->PointIds->DeepCopy(c->PointIds);
}

#define VTK_RIGHT 0
#define VTK_LEFT 1
#define VTK_MIDDLE 2

// Bounding box intersection modified from Graphics Gems Vol I. The method
// returns a non-zero value if the bounding box is hit. Origin[3] starts
// the ray, dir[3] is the vector components of the ray in the x-y-z
// directions, coord[3] is the location of hit, and t is the parametric
// coordinate along line. (Notes: the intersection ray dir[3] is NOT
// normalized.  Valid intersections will only occur between 0<=t<=1.)
char vtkCell::HitBBox (float bounds[6], float origin[3], float dir[3],
                      float coord[3], float& t)
{
  char    inside=1;
  char    quadrant[3];
  int     i, whichPlane=0;
  float   maxT[3], candidatePlane[3];

  //  First find closest planes
  //
  for (i=0; i<3; i++)
    {
    if ( origin[i] < bounds[2*i] )
      {
      quadrant[i] = VTK_LEFT;
      candidatePlane[i] = bounds[2*i];
      inside = 0;
      }
    else if ( origin[i] > bounds[2*i+1] )
      {
      quadrant[i] = VTK_RIGHT;
      candidatePlane[i] = bounds[2*i+1];
      inside = 0;
      }
    else
      {
      quadrant[i] = VTK_MIDDLE;
      }
    }

  //  Check whether origin of ray is inside bbox
  //
  if (inside)
    {
    coord[0] = origin[0];
    coord[1] = origin[1];
    coord[2] = origin[2];
    t = 0;
    return 1;
    }

  //  Calculate parametric distances to plane
  //
  for (i=0; i<3; i++)
    {
    if ( quadrant[i] != VTK_MIDDLE && dir[i] != 0.0 )
      {
      maxT[i] = (candidatePlane[i]-origin[i]) / dir[i];
      }
    else
      {
      maxT[i] = -1.0;
      }
    }

  //  Find the largest parametric value of intersection
  //
  for (i=0; i<3; i++)
    {
    if ( maxT[whichPlane] < maxT[i] )
      {
      whichPlane = i;
      }
    }

  //  Check for valid intersection along line
  //
  if ( maxT[whichPlane] > 1.0 || maxT[whichPlane] < 0.0 )
    {
    return 0;
    }
  else
    {
    t = maxT[whichPlane];
    }

  //  Intersection point along line is okay.  Check bbox.
  //
  for (i=0; i<3; i++)
    {
    if (whichPlane != i)
      {
      coord[i] = origin[i] + maxT[whichPlane]*dir[i];
      if ( coord[i] < bounds[2*i] || coord[i] > bounds[2*i+1] )
        {
        return 0;
        }
      }
    else
      {
      coord[i] = candidatePlane[i];
      }
    }

    return 1;
}
#undef VTK_RIGHT
#undef VTK_LEFT
#undef VTK_MIDDLE

// Compute cell bounding box (xmin,xmax,ymin,ymax,zmin,zmax). Return pointer
// to array of six float values.
float *vtkCell::GetBounds ()
{
  float *x;
  int i, numPts=this->Points->GetNumberOfPoints();

  this->Bounds[0] = this->Bounds[2] = this->Bounds[4] =  VTK_LARGE_FLOAT;
  this->Bounds[1] = this->Bounds[3] = this->Bounds[5] = -VTK_LARGE_FLOAT;

  for (i=0; i<numPts; i++)
    {
    x = this->Points->GetPoint(i);

    this->Bounds[0] = (x[0] < this->Bounds[0] ? x[0] : this->Bounds[0]);
    this->Bounds[1] = (x[0] > this->Bounds[1] ? x[0] : this->Bounds[1]);
    this->Bounds[2] = (x[1] < this->Bounds[2] ? x[1] : this->Bounds[2]);
    this->Bounds[3] = (x[1] > this->Bounds[3] ? x[1] : this->Bounds[3]);
    this->Bounds[4] = (x[2] < this->Bounds[4] ? x[2] : this->Bounds[4]);
    this->Bounds[5] = (x[2] > this->Bounds[5] ? x[2] : this->Bounds[5]);

    }
  return this->Bounds;
}

// Compute cell bounding box (xmin,xmax,ymin,ymax,zmin,zmax). Copy result into
// user provided array.
void vtkCell::GetBounds(float bounds[6])
{
  this->GetBounds();
  for (int i=0; i < 6; i++)
    {
    bounds[i] = this->Bounds[i];
    }
}

// Compute Length squared of cell (i.e., bounding box diagonal squared).
float vtkCell::GetLength2 ()
{
  double diff, l=0.0;
  int i;

  this->GetBounds();
  for (i=0; i<3; i++)
    {
    diff = this->Bounds[2*i+1] - this->Bounds[2*i];
    l += diff * diff;
    }
  if(l > VTK_LARGE_FLOAT)
    {
    return VTK_LARGE_FLOAT;
    }
  return static_cast<float>(l);
}

// Return center of the cell in parametric coordinates.
// Note that the parametric center is not always located
// at (0.5,0.5,0.5). The return value is the subId that
// the center is in (if a composite cell). If you want the
// center in x-y-z space, invoke the EvaluateLocation() method.
int vtkCell::GetParametricCenter(float pcoords[3])
{
  pcoords[0] = pcoords[1] = pcoords[2] = 0.5;
  return 0;
}

// This method works fine for all "rectangular" cells, not triangular
// and tetrahedral topologies.
float vtkCell::GetParametricDistance(float pcoords[3])
{
  int i;
  float pDist, pDistMax=0.0f;

  for (i=0; i<3; i++)
    {
    if ( pcoords[i] < 0.0 )
      {
      pDist = -pcoords[i];
      }
    else if ( pcoords[i] > 1.0 )
      {
      pDist = pcoords[i] - 1.0f;
      }
    else //inside the cell in the parametric direction
      {
      pDist = 0.0;
      }
    if ( pDist > pDistMax )
      {
      pDistMax = pDist;
      }
    }
  return pDistMax;
}

void vtkCell::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);

  int numIds=this->PointIds->GetNumberOfIds();

  os << indent << "Number Of Points: " << numIds << "\n";

  if ( numIds > 0 )
    {
    float *bounds=this->GetBounds();

    os << indent << "Bounds: \n";
    os << indent << "  Xmin,Xmax: (" << bounds[0] << ", " << bounds[1] << ")\n";
    os << indent << "  Ymin,Ymax: (" << bounds[2] << ", " << bounds[3] << ")\n";
    os << indent << "  Zmin,Zmax: (" << bounds[4] << ", " << bounds[5] << ")\n";

    os << indent << "  Point ids are: ";
    for (int i=0; i < numIds; i++)
      {
      os << this->PointIds->GetId(i);
      if ( i && !(i % 12) )
        {
        os << "\n\t";
        }
      else
        {
        if ( i != (numIds-1) )
          {
          os << ", ";
          }
        }
      }
    os << indent << "\n";
    }
}

// Note: the following code is placed here to deal with cross-library
// symbol export and import on Microsoft compilers.
static vtkMarchingSquaresLineCases VTK_MARCHING_SQUARES_LINECASES[] = {
  {{-1, -1, -1, -1, -1}},
  {{0, 3, -1, -1, -1}},
  {{1, 0, -1, -1, -1}},
  {{1, 3, -1, -1, -1}},
  {{2, 1, -1, -1, -1}},
  {{0, 3, 2, 1, -1}},
  {{2, 0, -1, -1, -1}},
  {{2, 3, -1, -1, -1}},
  {{3, 2, -1, -1, -1}},
  {{0, 2, -1, -1, -1}},
  {{1, 0, 3, 2, -1}},
  {{1, 2, -1, -1, -1}},
  {{3, 1, -1, -1, -1}},
  {{0, 1, -1, -1, -1}},
  {{3, 0, -1, -1, -1}},
  {{-1, -1, -1, -1, -1}}
};

vtkMarchingSquaresLineCases* vtkMarchingSquaresLineCases::GetCases()
{
  return VTK_MARCHING_SQUARES_LINECASES;
}

//----------------------------------------------------------------------------
#ifndef VTK_REMOVE_LEGACY_CODE
vtkCell* vtkCell::MakeObject()
{
  VTK_LEGACY_METHOD(MakeObject, "4.2");
  vtkCell* c = this->NewInstance();
  c->DeepCopy(this);
  return c;
}
#endif
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "private/qdeclarativedebugserver_p.h"
#include "private/qdeclarativedebugservice_p.h"
#include "private/qdeclarativedebugservice_p_p.h"
#include "private/qdeclarativeengine_p.h"

#include <QtCore/QDir>
#include <QtCore/QPluginLoader>
#include <QtCore/QStringList>

#include <private/qobject_p.h>
#include <private/qapplication_p.h>

QT_BEGIN_NAMESPACE

/*
  QDeclarativeDebug Protocol (Version 1):

  handshake:
    1. Client sends
         "QDeclarativeDebugServer" 0 version pluginNames
       version: an int representing the highest protocol version the client knows
       pluginNames: plugins available on client side
    2. Server sends
         "QDeclarativeDebugClient" 0 version pluginNames
       version: an int representing the highest protocol version the client & server know
       pluginNames: plugins available on server side. plugins both in the client and server message are enabled.
  client plugin advertisement
    1. Client sends
         "QDeclarativeDebugServer" 1 pluginNames
  server plugin advertisement
    1. Server sends
         "QDeclarativeDebugClient" 1 pluginNames
  plugin communication:
       Everything send with a header different to "QDeclarativeDebugServer" is sent to the appropriate plugin.
  */

const int protocolVersion = 1;

class QDeclarativeDebugServerPrivate : public QObjectPrivate
{
    Q_DECLARE_PUBLIC(QDeclarativeDebugServer)
public:
    QDeclarativeDebugServerPrivate();

    void advertisePlugins();

    QDeclarativeDebugServerConnection *connection;
    QHash<QString, QDeclarativeDebugService *> plugins;
    QStringList clientPlugins;
    bool gotHello;
    QString waitingForMsgFromService;

private:
    // private slot
    void _q_deliverMessage(const QString &serviceName, const QByteArray &message);
    static QDeclarativeDebugServerConnection *loadConnectionPlugin(const QString &pluginName);
};

QDeclarativeDebugServerPrivate::QDeclarativeDebugServerPrivate() :
    connection(0),
    gotHello(false)
{
}

void QDeclarativeDebugServerPrivate::advertisePlugins()
{
    if (!gotHello)
        return;

    QByteArray message;
    {
        QDataStream out(&message, QIODevice::WriteOnly);
        out << QString(QLatin1String("QDeclarativeDebugClient")) << 1 << plugins.keys();
    }
    connection->send(message);
}

QDeclarativeDebugServerConnection *QDeclarativeDebugServerPrivate::loadConnectionPlugin(
    const QString &pluginName)
{
    QStringList pluginCandidates;
    const QStringList paths = QCoreApplication::libraryPaths();
    foreach (const QString &libPath, paths) {
        const QDir dir(libPath + QLatin1String("/qmltooling"));
        if (dir.exists()) {
            QStringList plugins(dir.entryList(QDir::Files));
            foreach (const QString &pluginPath, plugins) {
                if (QFileInfo(pluginPath).fileName().contains(pluginName))
                    pluginCandidates << dir.absoluteFilePath(pluginPath);
            }
        }
    }

    foreach (const QString &pluginPath, pluginCandidates) {
        QPluginLoader loader(pluginPath);
        if (!loader.load()) {
            continue;
        }
        QDeclarativeDebugServerConnection *connection = 0;
        if (QObject *instance = loader.instance())
            connection = qobject_cast<QDeclarativeDebugServerConnection*>(instance);

        if (connection)
            return connection;
        loader.unload();
    }
    return 0;
}

bool QDeclarativeDebugServer::hasDebuggingClient() const
{
    Q_D(const QDeclarativeDebugServer);
    return d->connection
            && d->connection->isConnected()
            && d->gotHello;
}

QDeclarativeDebugServer *QDeclarativeDebugServer::instance()
{
    static bool commandLineTested = false;
    static QDeclarativeDebugServer *server = 0;

    if (!commandLineTested) {
        commandLineTested = true;

        QApplicationPrivate *appD = static_cast<QApplicationPrivate*>(QObjectPrivate::get(qApp));
#ifndef QDECLARATIVE_NO_DEBUG_PROTOCOL
        // ### remove port definition when protocol is changed
        int port = 0;
        bool block = false;
        bool ok = false;

        // format: qmljsdebugger=port:3768[,block] OR qmljsdebugger=ost[,block]
        if (!appD->qmljsDebugArgumentsString().isEmpty()) {
            if (!QDeclarativeEnginePrivate::qml_debugging_enabled) {
                const QString message =
                    QString::fromAscii("QDeclarativeDebugServer: Ignoring \"-qmljsdebugger=%1\". "
                              "Debugging has not been enabled.").arg(
                                  appD->qmljsDebugArgumentsString());
                qWarning("%s", qPrintable(message));
                return 0;
            }

            QString pluginName;
            if (appD->qmljsDebugArgumentsString().indexOf(QLatin1String("port:")) == 0) {
                int separatorIndex = appD->qmljsDebugArgumentsString().indexOf(QLatin1Char(','));
                port = appD->qmljsDebugArgumentsString().mid(5, separatorIndex - 5).toInt(&ok);
                pluginName = QLatin1String("qmldbg_tcp");
            } else if (appD->qmljsDebugArgumentsString().contains(QLatin1String("ost"))) {
                pluginName = QLatin1String("qmldbg_ost");
                ok = true;
            }

            block = appD->qmljsDebugArgumentsString().contains(QLatin1String("block"));

            if (ok) {
                server = new QDeclarativeDebugServer();

                QDeclarativeDebugServerConnection *connection
                        = QDeclarativeDebugServerPrivate::loadConnectionPlugin(pluginName);
                if (connection) {
                    server->d_func()->connection = connection;

                    connection->setServer(server);
                    connection->setPort(port, block);
                } else {
                    qWarning() << QString::fromAscii("QDeclarativeDebugServer: Ignoring \"-qmljsdebugger=%1\". "
                                                     "Remote debugger plugin has not been found.").arg(appD->qmljsDebugArgumentsString());
                }

            } else {
                qWarning(QString::fromAscii("QDeclarativeDebugServer: Ignoring \"-qmljsdebugger=%1\". "
                                            "Format is -qmljsdebugger=port:<port>[,block]").arg(
                             appD->qmljsDebugArgumentsString()).toAscii().constData());
            }
        }
#else
        if (!appD->qmljsDebugArgumentsString().isEmpty()) {
            qWarning(QString::fromAscii("QDeclarativeDebugServer: Ignoring \"-qmljsdebugger=%1\". "
                                        "QtDeclarative is not configured for debugging.").arg(
                         appD->qmljsDebugArgumentsString()).toAscii().constData());
        }
#endif
    }

    return server;
}

QDeclarativeDebugServer::QDeclarativeDebugServer()
: QObject(*(new QDeclarativeDebugServerPrivate))
{
}

void QDeclarativeDebugServer::receiveMessage(const QByteArray &message)
{
    Q_D(QDeclarativeDebugServer);

    QDataStream in(message);
    if (!d->gotHello) {
        QString name;
        int op;
        in >> name >> op;

        if (name != QLatin1String("QDeclarativeDebugServer")
                || op != 0) {
            qWarning("QDeclarativeDebugServer: Invalid hello message");
            d->connection->disconnect();
            return;
        }

        int version;
        in >> version >> d->clientPlugins;

        // Send the hello answer immediately, since it needs to arrive before
        // the plugins below start sending messages.
        QByteArray helloAnswer;
        {
            QDataStream out(&helloAnswer, QIODevice::WriteOnly);
            out << QString(QLatin1String("QDeclarativeDebugClient")) << 0 << protocolVersion << d->plugins.keys();
        }
        d->connection->send(helloAnswer);

        d->gotHello = true;

        QHash<QString, QDeclarativeDebugService*>::Iterator iter = d->plugins.begin();
        for (; iter != d->plugins.end(); ++iter) {
            QDeclarativeDebugService::Status newStatus = QDeclarativeDebugService::Unavailable;
            if (d->clientPlugins.contains(iter.key()))
                newStatus = QDeclarativeDebugService::Enabled;
            iter.value()->d_func()->status = newStatus;
            iter.value()->statusChanged(newStatus);
        }

        qWarning("QDeclarativeDebugServer: Connection established");
    } else {

        QString debugServer(QLatin1String("QDeclarativeDebugServer"));

        QString name;
        in >> name;

        if (name == debugServer) {
            int op = -1;
            in >> op;

            if (op == 1) {
                // Service Discovery
                QStringList oldClientPlugins = d->clientPlugins;
                in >> d->clientPlugins;

                QHash<QString, QDeclarativeDebugService*>::Iterator iter = d->plugins.begin();
                for (; iter != d->plugins.end(); ++iter) {
                    const QString pluginName = iter.key();
                    QDeclarativeDebugService::Status newStatus = QDeclarativeDebugService::Unavailable;
                    if (d->clientPlugins.contains(pluginName))
                        newStatus = QDeclarativeDebugService::Enabled;

                    if (oldClientPlugins.contains(pluginName)
                            != d->clientPlugins.contains(pluginName)) {
                        iter.value()->d_func()->status = newStatus;
                        iter.value()->statusChanged(newStatus);
                    }
                }
            } else {
                qWarning("QDeclarativeDebugServer: Invalid control message %d", op);
            }
        } else {
            QByteArray message;
            in >> message;

            if (d->waitingForMsgFromService == name) {
                // deliver directly so that it is delivered before waitForMessage is returning.
                d->_q_deliverMessage(name, message);
                d->waitingForMsgFromService.clear();
            } else {
                // deliver message in next event loop run.
                // Fixes the case that the service does start it's own event loop ...,
                // but the networking code doesn't deliver any new messages because readyRead
                // hasn't returned.
                QMetaObject::invokeMethod(this, "_q_deliverMessage", Qt::QueuedConnection,
                                          Q_ARG(QString, name),
                                          Q_ARG(QByteArray, message));
            }
        }
    }
}

void QDeclarativeDebugServerPrivate::_q_deliverMessage(const QString &serviceName, const QByteArray &message)
{
    QHash<QString, QDeclarativeDebugService *>::Iterator iter = plugins.find(serviceName);
    if (iter == plugins.end()) {
        qWarning() << "QDeclarativeDebugServer: Message received for missing plugin" << serviceName;
    } else {
        (*iter)->messageReceived(message);
    }
}

QList<QDeclarativeDebugService*> QDeclarativeDebugServer::services() const
{
    const Q_D(QDeclarativeDebugServer);
    return d->plugins.values();
}

QStringList QDeclarativeDebugServer::serviceNames() const
{
    const Q_D(QDeclarativeDebugServer);
    return d->plugins.keys();
}

bool QDeclarativeDebugServer::addService(QDeclarativeDebugService *service)
{
    Q_D(QDeclarativeDebugServer);
    if (!service || d->plugins.contains(service->name()))
        return false;

    d->plugins.insert(service->name(), service);
    d->advertisePlugins();

    QDeclarativeDebugService::Status newStatus = QDeclarativeDebugService::Unavailable;
    if (d->clientPlugins.contains(service->name()))
        newStatus = QDeclarativeDebugService::Enabled;
    service->d_func()->status = newStatus;
    service->statusChanged(newStatus);
    return true;
}

bool QDeclarativeDebugServer::removeService(QDeclarativeDebugService *service)
{
    Q_D(QDeclarativeDebugServer);
    if (!service || !d->plugins.contains(service->name()))
        return false;

    d->plugins.remove(service->name());
    d->advertisePlugins();

    QDeclarativeDebugService::Status newStatus = QDeclarativeDebugService::NotConnected;
    service->d_func()->server = 0;
    service->d_func()->status = newStatus;
    service->statusChanged(newStatus);
    return true;
}

void QDeclarativeDebugServer::sendMessage(QDeclarativeDebugService *service,
                                          const QByteArray &message)
{
    Q_D(QDeclarativeDebugServer);
    QByteArray msg;
    {
        QDataStream out(&msg, QIODevice::WriteOnly);
        out << service->name() << message;
    }
    d->connection->send(msg);
}

bool QDeclarativeDebugServer::waitForMessage(QDeclarativeDebugService *service)
{
    Q_D(QDeclarativeDebugServer);

    if (!service
            || !d->plugins.contains(service->name())
            || !d->waitingForMsgFromService.isEmpty())
        return false;

    d->waitingForMsgFromService = service->name();

    do {
        d->connection->waitForMessage();
    } while (!d->waitingForMsgFromService.isEmpty());
    return true;
}

QT_END_NAMESPACE

#include "moc_qdeclarativedebugserver_p.cpp"
<commit_msg>DeclarativeDebug: Clear service name when returning from waitForMessage<commit_after>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "private/qdeclarativedebugserver_p.h"
#include "private/qdeclarativedebugservice_p.h"
#include "private/qdeclarativedebugservice_p_p.h"
#include "private/qdeclarativeengine_p.h"

#include <QtCore/QDir>
#include <QtCore/QPluginLoader>
#include <QtCore/QStringList>

#include <private/qobject_p.h>
#include <private/qapplication_p.h>

QT_BEGIN_NAMESPACE

/*
  QDeclarativeDebug Protocol (Version 1):

  handshake:
    1. Client sends
         "QDeclarativeDebugServer" 0 version pluginNames
       version: an int representing the highest protocol version the client knows
       pluginNames: plugins available on client side
    2. Server sends
         "QDeclarativeDebugClient" 0 version pluginNames
       version: an int representing the highest protocol version the client & server know
       pluginNames: plugins available on server side. plugins both in the client and server message are enabled.
  client plugin advertisement
    1. Client sends
         "QDeclarativeDebugServer" 1 pluginNames
  server plugin advertisement
    1. Server sends
         "QDeclarativeDebugClient" 1 pluginNames
  plugin communication:
       Everything send with a header different to "QDeclarativeDebugServer" is sent to the appropriate plugin.
  */

const int protocolVersion = 1;

class QDeclarativeDebugServerPrivate : public QObjectPrivate
{
    Q_DECLARE_PUBLIC(QDeclarativeDebugServer)
public:
    QDeclarativeDebugServerPrivate();

    void advertisePlugins();

    QDeclarativeDebugServerConnection *connection;
    QHash<QString, QDeclarativeDebugService *> plugins;
    QStringList clientPlugins;
    bool gotHello;
    QString waitingForMsgFromService;
    bool waitingForMsgSucceeded;

private:
    // private slot
    void _q_deliverMessage(const QString &serviceName, const QByteArray &message);
    static QDeclarativeDebugServerConnection *loadConnectionPlugin(const QString &pluginName);
};

QDeclarativeDebugServerPrivate::QDeclarativeDebugServerPrivate() :
    connection(0),
    gotHello(false),
    waitingForMsgSucceeded(false)
{
}

void QDeclarativeDebugServerPrivate::advertisePlugins()
{
    if (!gotHello)
        return;

    QByteArray message;
    {
        QDataStream out(&message, QIODevice::WriteOnly);
        out << QString(QLatin1String("QDeclarativeDebugClient")) << 1 << plugins.keys();
    }
    connection->send(message);
}

QDeclarativeDebugServerConnection *QDeclarativeDebugServerPrivate::loadConnectionPlugin(
    const QString &pluginName)
{
    QStringList pluginCandidates;
    const QStringList paths = QCoreApplication::libraryPaths();
    foreach (const QString &libPath, paths) {
        const QDir dir(libPath + QLatin1String("/qmltooling"));
        if (dir.exists()) {
            QStringList plugins(dir.entryList(QDir::Files));
            foreach (const QString &pluginPath, plugins) {
                if (QFileInfo(pluginPath).fileName().contains(pluginName))
                    pluginCandidates << dir.absoluteFilePath(pluginPath);
            }
        }
    }

    foreach (const QString &pluginPath, pluginCandidates) {
        QPluginLoader loader(pluginPath);
        if (!loader.load()) {
            continue;
        }
        QDeclarativeDebugServerConnection *connection = 0;
        if (QObject *instance = loader.instance())
            connection = qobject_cast<QDeclarativeDebugServerConnection*>(instance);

        if (connection)
            return connection;
        loader.unload();
    }
    return 0;
}

bool QDeclarativeDebugServer::hasDebuggingClient() const
{
    Q_D(const QDeclarativeDebugServer);
    return d->connection
            && d->connection->isConnected()
            && d->gotHello;
}

QDeclarativeDebugServer *QDeclarativeDebugServer::instance()
{
    static bool commandLineTested = false;
    static QDeclarativeDebugServer *server = 0;

    if (!commandLineTested) {
        commandLineTested = true;

        QApplicationPrivate *appD = static_cast<QApplicationPrivate*>(QObjectPrivate::get(qApp));
#ifndef QDECLARATIVE_NO_DEBUG_PROTOCOL
        // ### remove port definition when protocol is changed
        int port = 0;
        bool block = false;
        bool ok = false;

        // format: qmljsdebugger=port:3768[,block] OR qmljsdebugger=ost[,block]
        if (!appD->qmljsDebugArgumentsString().isEmpty()) {
            if (!QDeclarativeEnginePrivate::qml_debugging_enabled) {
                const QString message =
                    QString::fromAscii("QDeclarativeDebugServer: Ignoring \"-qmljsdebugger=%1\". "
                              "Debugging has not been enabled.").arg(
                                  appD->qmljsDebugArgumentsString());
                qWarning("%s", qPrintable(message));
                return 0;
            }

            QString pluginName;
            if (appD->qmljsDebugArgumentsString().indexOf(QLatin1String("port:")) == 0) {
                int separatorIndex = appD->qmljsDebugArgumentsString().indexOf(QLatin1Char(','));
                port = appD->qmljsDebugArgumentsString().mid(5, separatorIndex - 5).toInt(&ok);
                pluginName = QLatin1String("qmldbg_tcp");
            } else if (appD->qmljsDebugArgumentsString().contains(QLatin1String("ost"))) {
                pluginName = QLatin1String("qmldbg_ost");
                ok = true;
            }

            block = appD->qmljsDebugArgumentsString().contains(QLatin1String("block"));

            if (ok) {
                server = new QDeclarativeDebugServer();

                QDeclarativeDebugServerConnection *connection
                        = QDeclarativeDebugServerPrivate::loadConnectionPlugin(pluginName);
                if (connection) {
                    server->d_func()->connection = connection;

                    connection->setServer(server);
                    connection->setPort(port, block);
                } else {
                    qWarning() << QString::fromAscii("QDeclarativeDebugServer: Ignoring \"-qmljsdebugger=%1\". "
                                                     "Remote debugger plugin has not been found.").arg(appD->qmljsDebugArgumentsString());
                }

            } else {
                qWarning(QString::fromAscii("QDeclarativeDebugServer: Ignoring \"-qmljsdebugger=%1\". "
                                            "Format is -qmljsdebugger=port:<port>[,block]").arg(
                             appD->qmljsDebugArgumentsString()).toAscii().constData());
            }
        }
#else
        if (!appD->qmljsDebugArgumentsString().isEmpty()) {
            qWarning(QString::fromAscii("QDeclarativeDebugServer: Ignoring \"-qmljsdebugger=%1\". "
                                        "QtDeclarative is not configured for debugging.").arg(
                         appD->qmljsDebugArgumentsString()).toAscii().constData());
        }
#endif
    }

    return server;
}

QDeclarativeDebugServer::QDeclarativeDebugServer()
: QObject(*(new QDeclarativeDebugServerPrivate))
{
}

void QDeclarativeDebugServer::receiveMessage(const QByteArray &message)
{
    Q_D(QDeclarativeDebugServer);

    QDataStream in(message);
    if (!d->gotHello) {
        QString name;
        int op;
        in >> name >> op;

        if (name != QLatin1String("QDeclarativeDebugServer")
                || op != 0) {
            qWarning("QDeclarativeDebugServer: Invalid hello message");
            d->connection->disconnect();
            return;
        }

        int version;
        in >> version >> d->clientPlugins;

        // Send the hello answer immediately, since it needs to arrive before
        // the plugins below start sending messages.
        QByteArray helloAnswer;
        {
            QDataStream out(&helloAnswer, QIODevice::WriteOnly);
            out << QString(QLatin1String("QDeclarativeDebugClient")) << 0 << protocolVersion << d->plugins.keys();
        }
        d->connection->send(helloAnswer);

        d->gotHello = true;

        QHash<QString, QDeclarativeDebugService*>::Iterator iter = d->plugins.begin();
        for (; iter != d->plugins.end(); ++iter) {
            QDeclarativeDebugService::Status newStatus = QDeclarativeDebugService::Unavailable;
            if (d->clientPlugins.contains(iter.key()))
                newStatus = QDeclarativeDebugService::Enabled;
            iter.value()->d_func()->status = newStatus;
            iter.value()->statusChanged(newStatus);
        }

        qWarning("QDeclarativeDebugServer: Connection established");
    } else {

        QString debugServer(QLatin1String("QDeclarativeDebugServer"));

        QString name;
        in >> name;

        if (name == debugServer) {
            int op = -1;
            in >> op;

            if (op == 1) {
                // Service Discovery
                QStringList oldClientPlugins = d->clientPlugins;
                in >> d->clientPlugins;

                QHash<QString, QDeclarativeDebugService*>::Iterator iter = d->plugins.begin();
                for (; iter != d->plugins.end(); ++iter) {
                    const QString pluginName = iter.key();
                    QDeclarativeDebugService::Status newStatus = QDeclarativeDebugService::Unavailable;
                    if (d->clientPlugins.contains(pluginName))
                        newStatus = QDeclarativeDebugService::Enabled;

                    if (oldClientPlugins.contains(pluginName)
                            != d->clientPlugins.contains(pluginName)) {
                        iter.value()->d_func()->status = newStatus;
                        iter.value()->statusChanged(newStatus);
                    }
                }
            } else {
                qWarning("QDeclarativeDebugServer: Invalid control message %d", op);
            }
        } else {
            QByteArray message;
            in >> message;

            if (d->waitingForMsgFromService == name) {
                // deliver directly so that it is delivered before waitForMessage is returning.
                d->_q_deliverMessage(name, message);
                d->waitingForMsgSucceeded = true;
            } else {
                // deliver message in next event loop run.
                // Fixes the case that the service does start it's own event loop ...,
                // but the networking code doesn't deliver any new messages because readyRead
                // hasn't returned.
                QMetaObject::invokeMethod(this, "_q_deliverMessage", Qt::QueuedConnection,
                                          Q_ARG(QString, name),
                                          Q_ARG(QByteArray, message));
            }
        }
    }
}

void QDeclarativeDebugServerPrivate::_q_deliverMessage(const QString &serviceName, const QByteArray &message)
{
    QHash<QString, QDeclarativeDebugService *>::Iterator iter = plugins.find(serviceName);
    if (iter == plugins.end()) {
        qWarning() << "QDeclarativeDebugServer: Message received for missing plugin" << serviceName;
    } else {
        (*iter)->messageReceived(message);
    }
}

QList<QDeclarativeDebugService*> QDeclarativeDebugServer::services() const
{
    const Q_D(QDeclarativeDebugServer);
    return d->plugins.values();
}

QStringList QDeclarativeDebugServer::serviceNames() const
{
    const Q_D(QDeclarativeDebugServer);
    return d->plugins.keys();
}

bool QDeclarativeDebugServer::addService(QDeclarativeDebugService *service)
{
    Q_D(QDeclarativeDebugServer);
    if (!service || d->plugins.contains(service->name()))
        return false;

    d->plugins.insert(service->name(), service);
    d->advertisePlugins();

    QDeclarativeDebugService::Status newStatus = QDeclarativeDebugService::Unavailable;
    if (d->clientPlugins.contains(service->name()))
        newStatus = QDeclarativeDebugService::Enabled;
    service->d_func()->status = newStatus;
    service->statusChanged(newStatus);
    return true;
}

bool QDeclarativeDebugServer::removeService(QDeclarativeDebugService *service)
{
    Q_D(QDeclarativeDebugServer);
    if (!service || !d->plugins.contains(service->name()))
        return false;

    d->plugins.remove(service->name());
    d->advertisePlugins();

    QDeclarativeDebugService::Status newStatus = QDeclarativeDebugService::NotConnected;
    service->d_func()->server = 0;
    service->d_func()->status = newStatus;
    service->statusChanged(newStatus);
    return true;
}

void QDeclarativeDebugServer::sendMessage(QDeclarativeDebugService *service,
                                          const QByteArray &message)
{
    Q_D(QDeclarativeDebugServer);
    QByteArray msg;
    {
        QDataStream out(&msg, QIODevice::WriteOnly);
        out << service->name() << message;
    }
    d->connection->send(msg);
}

bool QDeclarativeDebugServer::waitForMessage(QDeclarativeDebugService *service)
{
    Q_D(QDeclarativeDebugServer);

    if (!service
            || !d->plugins.contains(service->name())
            || !d->waitingForMsgFromService.isEmpty())
        return false;

    d->waitingForMsgSucceeded = false;
    d->waitingForMsgFromService = service->name();

    do {
        d->connection->waitForMessage();
    } while (!d->waitingForMsgSucceeded);
    d->waitingForMsgFromService.clear();
    return true;
}

QT_END_NAMESPACE

#include "moc_qdeclarativedebugserver_p.cpp"
<|endoftext|>


<commit_before>#include "MainFrame.hpp"
#include "misc_ui.hpp"
#include <wx/accel.h>
#include <wx/utils.h>

#include "AboutDialog.hpp"

namespace Slic3r { namespace GUI {

wxBEGIN_EVENT_TABLE(MainFrame, wxFrame)
wxEND_EVENT_TABLE()

MainFrame::MainFrame(const wxString& title, const wxPoint& pos, const wxSize& size)
        : MainFrame(title, pos, size, nullptr) {}
MainFrame::MainFrame(const wxString& title, const wxPoint& pos, const wxSize& size, std::shared_ptr<Settings> _gui_config)
        : wxFrame(NULL, wxID_ANY, title, pos, size), loaded(false),
        tabpanel(nullptr), controller(nullptr), plater(nullptr), gui_config(_gui_config), preset_editor_tabs(std::map<wxWindowID, PresetEditor*>())
{
    // Set icon to either the .ico if windows or png for everything else.
    if (the_os == OS::Windows)
        this->SetIcon(wxIcon(var("Slic3r.ico"), wxBITMAP_TYPE_ICO));
    else
        this->SetIcon(wxIcon(var("Slic3r_128px.png"), wxBITMAP_TYPE_PNG));

    this->init_tabpanel();
    this->init_menubar();

    wxToolTip::SetAutoPop(TOOLTIP_TIMER);

    // initialize status bar
    this->statusbar = new ProgressStatusBar(this, -1);
    this->statusbar->SetStatusText("Version $Slic3r::VERSION - Remember to check for updates at http://slic3r.org/");
    this->SetStatusBar(this->statusbar);

    this->loaded = 1;

    // Initialize layout
    {
        wxSizer* sizer = new wxBoxSizer(wxVERTICAL);
        sizer->Add(this->tabpanel, 1, wxEXPAND);
        sizer->SetSizeHints(this);
        this->Fit();
        this->SetMinSize(wxSize(760, 490));
        this->SetSize(this->GetMinSize());
        wxTheApp->SetTopWindow(this);
        this->Show();
        this->Layout();
    }
/*
    # declare events
    EVT_CLOSE($self, sub {
        my (undef, $event) = @_;

        if ($event->CanVeto) {
            if (!$self->{plater}->prompt_unsaved_changes) {
                $event->Veto;
                return;
            }

            if ($self->{controller} && $self->{controller}->printing) {
                my $confirm = Wx::MessageDialog->new($self, "You are currently printing. Do you want to stop printing and continue anyway?",
                    'Unfinished Print', wxICON_QUESTION | wxYES_NO | wxNO_DEFAULT);
                if ($confirm->ShowModal == wxID_NO) {
                    $event->Veto;
                    return;
                }
            }
        }

        # save window size
        wxTheApp->save_window_pos($self, "main_frame");

        # propagate event
        $event->Skip;
    });
*/
}

/// Private initialization function for the main frame tab panel.
void MainFrame::init_tabpanel()
{
    this->tabpanel = new wxAuiNotebook(this, -1, wxDefaultPosition, wxDefaultSize, wxAUI_NB_TOP);
    auto panel = this->tabpanel;

    panel->Bind(wxEVT_AUINOTEBOOK_PAGE_CHANGED, ([=](wxAuiNotebookEvent& e)
    {
        auto tabpanel = this->tabpanel;
        // TODO: trigger processing for activation event
        if (tabpanel->GetSelection() > 1) {
            tabpanel->SetWindowStyle(tabpanel->GetWindowStyleFlag() | wxAUI_NB_CLOSE_ON_ACTIVE_TAB);
        } else if (this->gui_config->show_host == false && tabpanel->GetSelection() == 1) {
            tabpanel->SetWindowStyle(tabpanel->GetWindowStyleFlag() | wxAUI_NB_CLOSE_ON_ACTIVE_TAB);
        } else {
            tabpanel->SetWindowStyle(tabpanel->GetWindowStyleFlag() | ~wxAUI_NB_CLOSE_ON_ACTIVE_TAB);
        }
    }), panel->GetId());

    panel->Bind(wxEVT_AUINOTEBOOK_PAGE_CLOSE, ([=](wxAuiNotebookEvent& e)
    {
        if (typeid(panel) == typeid(Slic3r::GUI::PresetEditor)) {
            wxDELETE(this->preset_editor_tabs[panel->GetId()]);
        }
        wxTheApp->CallAfter([=] { this->tabpanel->SetSelection(0); });
    }), panel->GetId());

    this->plater = new Slic3r::GUI::Plater(panel, _("Plater"), gui_config);
    this->controller = new Slic3r::GUI::Controller(panel, _("Controller"));

    panel->AddPage(this->plater, this->plater->GetName());
    if (this->gui_config->show_host) panel->AddPage(this->controller, this->controller->GetName());

}

void MainFrame::init_menubar()
{

    wxMenu* menuFile = new wxMenu();
    {
        append_menu_item(menuFile, _(L"Open STL/OBJ/AMF/3MF…"), _("Open a model"), [=](wxCommandEvent& e) { if (this->plater != nullptr) this->plater->add();}, wxID_ANY, "brick_add.png", "Ctrl+O");
    }

    wxMenu* menuPlater = new wxMenu();
    {
    }
    wxMenu* menuObject = new wxMenu();
    {
    }
    wxMenu* menuSettings = new wxMenu();
    {
    }
    wxMenu* menuView = new wxMenu();
    {
    }
    wxMenu* menuWindow = new wxMenu();
    {
    }
    wxMenu* menuHelp = new wxMenu();
    {
        // TODO: Reimplement config wizard
        //menuHelp->AppendSeparator();
        append_menu_item(menuHelp, _("Slic3r &Website"), _("Open the Slic3r website in your browser"), [=](wxCommandEvent& e)
        {
            wxLaunchDefaultBrowser("http://www.slic3r.org");
        });
        append_menu_item(menuHelp, _("Check for &Updates..."), _("Check for new Slic3r versions"), [=](wxCommandEvent& e)
        {
            check_version(true);
        });
        append_menu_item(menuHelp, _("Slic3r &Manual"), _("Open the Slic3r manual in your browser"), [=](wxCommandEvent& e)
        {
            wxLaunchDefaultBrowser("http://manual.slic3r.org/");
        });
        append_menu_item(menuHelp, _("&About Slic3r"), _("Show about dialog"), [=](wxCommandEvent& e)
        {
            auto about = new AboutDialog(nullptr);
            about->ShowModal();
            about->Destroy();
        }, wxID_ABOUT);

    }

    wxMenuBar* menubar = new wxMenuBar();
    menubar->Append(menuFile, _("&File"));
    menubar->Append(menuPlater, _("&Plater"));
    menubar->Append(menuObject, _("&Object"));
    menubar->Append(menuSettings, _("&Settings"));
    menubar->Append(menuView, _("&View"));
    menubar->Append(menuWindow, _("&Window"));
    menubar->Append(menuHelp, _("&Help"));

    this->SetMenuBar(menubar);

}

}} // Namespace Slic3r::GUI
<commit_msg>Properly pull slic3r version string from libslic3r<commit_after>#include "MainFrame.hpp"
#include "misc_ui.hpp"
#include <wx/accel.h>
#include <wx/utils.h>

#include "AboutDialog.hpp"
#include "libslic3r.h"

namespace Slic3r { namespace GUI {

wxBEGIN_EVENT_TABLE(MainFrame, wxFrame)
wxEND_EVENT_TABLE()

MainFrame::MainFrame(const wxString& title, const wxPoint& pos, const wxSize& size)
        : MainFrame(title, pos, size, nullptr) {}
MainFrame::MainFrame(const wxString& title, const wxPoint& pos, const wxSize& size, std::shared_ptr<Settings> _gui_config)
        : wxFrame(NULL, wxID_ANY, title, pos, size), loaded(false),
        tabpanel(nullptr), controller(nullptr), plater(nullptr), gui_config(_gui_config), preset_editor_tabs(std::map<wxWindowID, PresetEditor*>())
{
    // Set icon to either the .ico if windows or png for everything else.
    if (the_os == OS::Windows)
        this->SetIcon(wxIcon(var("Slic3r.ico"), wxBITMAP_TYPE_ICO));
    else
        this->SetIcon(wxIcon(var("Slic3r_128px.png"), wxBITMAP_TYPE_PNG));

    this->init_tabpanel();
    this->init_menubar();

    wxToolTip::SetAutoPop(TOOLTIP_TIMER);

    // initialize status bar
    // we call SetStatusBar() here because MainFrame is the direct owner.
    this->statusbar = new ProgressStatusBar(this, -1);
    wxString welcome_text {_("Version SLIC3R_VERSION_REPLACE - Remember to check for updates at http://slic3r.org/")};
    welcome_text.Replace("SLIC3R_VERSION_REPLACE", wxString(SLIC3R_VERSION));
    this->statusbar->SetStatusText(welcome_text);
    this->SetStatusBar(this->statusbar);

    this->loaded = 1;

    // Initialize layout
    {
        wxSizer* sizer = new wxBoxSizer(wxVERTICAL);
        sizer->Add(this->tabpanel, 1, wxEXPAND);
        sizer->SetSizeHints(this);
        this->Fit();
        this->SetMinSize(wxSize(760, 490));
        this->SetSize(this->GetMinSize());
        wxTheApp->SetTopWindow(this);
        this->Show();
        this->Layout();
    }
/*
    # declare events
    EVT_CLOSE($self, sub {
        my (undef, $event) = @_;

        if ($event->CanVeto) {
            if (!$self->{plater}->prompt_unsaved_changes) {
                $event->Veto;
                return;
            }

            if ($self->{controller} && $self->{controller}->printing) {
                my $confirm = Wx::MessageDialog->new($self, "You are currently printing. Do you want to stop printing and continue anyway?",
                    'Unfinished Print', wxICON_QUESTION | wxYES_NO | wxNO_DEFAULT);
                if ($confirm->ShowModal == wxID_NO) {
                    $event->Veto;
                    return;
                }
            }
        }

        # save window size
        wxTheApp->save_window_pos($self, "main_frame");

        # propagate event
        $event->Skip;
    });
*/
}

/// Private initialization function for the main frame tab panel.
void MainFrame::init_tabpanel()
{
    this->tabpanel = new wxAuiNotebook(this, -1, wxDefaultPosition, wxDefaultSize, wxAUI_NB_TOP);
    auto panel = this->tabpanel;

    panel->Bind(wxEVT_AUINOTEBOOK_PAGE_CHANGED, ([=](wxAuiNotebookEvent& e)
    {
        auto tabpanel = this->tabpanel;
        // TODO: trigger processing for activation event
        if (tabpanel->GetSelection() > 1) {
            tabpanel->SetWindowStyle(tabpanel->GetWindowStyleFlag() | wxAUI_NB_CLOSE_ON_ACTIVE_TAB);
        } else if (this->gui_config->show_host == false && tabpanel->GetSelection() == 1) {
            tabpanel->SetWindowStyle(tabpanel->GetWindowStyleFlag() | wxAUI_NB_CLOSE_ON_ACTIVE_TAB);
        } else {
            tabpanel->SetWindowStyle(tabpanel->GetWindowStyleFlag() | ~wxAUI_NB_CLOSE_ON_ACTIVE_TAB);
        }
    }), panel->GetId());

    panel->Bind(wxEVT_AUINOTEBOOK_PAGE_CLOSE, ([=](wxAuiNotebookEvent& e)
    {
        if (typeid(panel) == typeid(Slic3r::GUI::PresetEditor)) {
            wxDELETE(this->preset_editor_tabs[panel->GetId()]);
        }
        wxTheApp->CallAfter([=] { this->tabpanel->SetSelection(0); });
    }), panel->GetId());

    this->plater = new Slic3r::GUI::Plater(panel, _("Plater"), gui_config);
    this->controller = new Slic3r::GUI::Controller(panel, _("Controller"));

    panel->AddPage(this->plater, this->plater->GetName());
    if (this->gui_config->show_host) panel->AddPage(this->controller, this->controller->GetName());

}

void MainFrame::init_menubar()
{

    wxMenu* menuFile = new wxMenu();
    {
        append_menu_item(menuFile, _(L"Open STL/OBJ/AMF/3MF…"), _("Open a model"), [=](wxCommandEvent& e) { if (this->plater != nullptr) this->plater->add();}, wxID_ANY, "brick_add.png", "Ctrl+O");
    }

    wxMenu* menuPlater = new wxMenu();
    {
    }
    wxMenu* menuObject = new wxMenu();
    {
    }
    wxMenu* menuSettings = new wxMenu();
    {
    }
    wxMenu* menuView = new wxMenu();
    {
    }
    wxMenu* menuWindow = new wxMenu();
    {
    }
    wxMenu* menuHelp = new wxMenu();
    {
        // TODO: Reimplement config wizard
        //menuHelp->AppendSeparator();
        append_menu_item(menuHelp, _("Slic3r &Website"), _("Open the Slic3r website in your browser"), [=](wxCommandEvent& e)
        {
            wxLaunchDefaultBrowser("http://www.slic3r.org");
        });
        append_menu_item(menuHelp, _("Check for &Updates..."), _("Check for new Slic3r versions"), [=](wxCommandEvent& e)
        {
            check_version(true);
        });
        append_menu_item(menuHelp, _("Slic3r &Manual"), _("Open the Slic3r manual in your browser"), [=](wxCommandEvent& e)
        {
            wxLaunchDefaultBrowser("http://manual.slic3r.org/");
        });
        append_menu_item(menuHelp, _("&About Slic3r"), _("Show about dialog"), [=](wxCommandEvent& e)
        {
            auto about = new AboutDialog(nullptr);
            about->ShowModal();
            about->Destroy();
        }, wxID_ABOUT);

    }

    wxMenuBar* menubar = new wxMenuBar();
    menubar->Append(menuFile, _("&File"));
    menubar->Append(menuPlater, _("&Plater"));
    menubar->Append(menuObject, _("&Object"));
    menubar->Append(menuSettings, _("&Settings"));
    menubar->Append(menuView, _("&View"));
    menubar->Append(menuWindow, _("&Window"));
    menubar->Append(menuHelp, _("&Help"));

    this->SetMenuBar(menubar);

}

}} // Namespace Slic3r::GUI
<|endoftext|>