<commit_before>//===-- Console.cpp - Console utils for the interactive uwhd ------- c++ --===//
//
//                               UWH Timer
//
//           This file is distributed under the BSD 3-Clause License.
//                      See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "uwhd/console/Console.h"

#include "uwhd/model/GameModel.h"

#include <iostream>
#include <sstream>
#include <cctype>

#define ANSI_RED     "\x1b[31m"
#define ANSI_GREEN   "\x1b[32m"
#define ANSI_YELLOW  "\x1b[33m"
#define ANSI_BLUE    "\x1b[34m"
#define ANSI_MAGENTA "\x1b[35m"
#define ANSI_CYAN    "\x1b[36m"
#define ANSI_RESET   "\x1b[0m"

bool Console::ParseLine(std::string I) {
  if (I.size() == 0)
    goto Success;

  switch (I[0]) {
  case 'Q':
  case 'q':
    goto ExitLoop;

  case 'B':
  case 'b': {
    std::stringstream SS;
    SS << I.substr(1);
    int Score;
    SS >> Score;
    M.setBlackScore(Score);
    goto Success;
  }

  case 'W':
  case 'w': {
    std::stringstream SS;
    SS << I.substr(1);
    int Score;
    SS >> Score;
    M.setWhiteScore(Score);
    goto Success;
  }

  case 'T':
  case 't': {
    std::stringstream SS;
    SS << I.substr(1);
    int Time;
    SS >> Time;
    M.setGameClock(Time);
    goto Success;
  }

  case 'C':
  case 'c': {
    bool Running = M.gameClockRunning();
    M.setGameClockRunning(!Running);
    goto Success;
  }

  case 'H':
  case 'h': {
    std::cout << "Usage:\n"
              << "  B[0-9]+     - Set the Black Score\n"
              << "  W[0-9]+     - Set the White Score\n"
              << "  T[0-9]+     - Set the Game Clock\n"
              << "  C           - Start/Stop the Game Clock\n"
              << "  G[CFSHRWBO] - Set the Game State\n"
              << "    GC          - Wall Clock\n"
              << "    GF          - First Half\n"
              << "    GS          - Second Half\n"
              << "    GH          - Half Time\n"
              << "    GR          - Ref Time Out\n"
              << "    GW          - White Time Out\n"
              << "    GB          - Black Time Out\n"
              << "    GO          - Game Over\n"
              << "  P[NRWB]     - Set the Timeout State\n"
              << "    PN          - No Timeout\n"
              << "    PR          - Ref Timeout\n"
              << "    PW          - White Timeout\n"
              << "    PB          - Black Timeout\n"
              << "  H           - This menu\n"
              << "  Q           - Quit\n";
    goto Success;
  }

  case 'G':
  case 'g': {
    if (I.size() != 2)
      goto ParseError;

    switch (toupper(I[1])) {
    case 'C': M.setGameState(GameModel::GS_WallClock); goto Success;
    case 'F': M.setGameState(GameModel::GS_FirstHalf); goto Success;
    case 'S': M.setGameState(GameModel::GS_SecondHalf); goto Success;
    case 'H': M.setGameState(GameModel::GS_HalfTime); goto Success;
    case 'O': M.setGameState(GameModel::GS_GameOver); goto Success;
    default:
      goto ParseError;
    }
  }

  case 'P':
  case 'p': {
    if (I.size() != 2)
      goto ParseError;

    switch (toupper(I[1])) {
    case 'N': M.setTimeoutState(GameModel::TS_None); goto Success;
    case 'R': M.setTimeoutState(GameModel::TS_RefTimeout); goto Success;
    case 'W': M.setTimeoutState(GameModel::TS_WhiteTimeout); goto Success;
    case 'B': M.setTimeoutState(GameModel::TS_BlackTimeout); goto Success;
    default:
      goto ParseError;
    }
  }

  case 'S': {
    GameModel New;
    if (!GameModel::deSerialize(I, New)) {
      M.setModel(New);
      goto Success;
    }
    goto ParseError;
  }

  default:
    goto ParseError;
  }

ParseError:
  std::cerr << "Parse error on: '" << I << "'\n";
  return false;

Success:
  return false;

ExitLoop:
  return true;
}

void Console::Loop() {
  while (true) {
    std::cout << M.getModel().dump();
    std::cout << ANSI_CYAN << "[uwhdi] " << ANSI_RESET;

    std::string I;
    std::getline(std::cin, I);

    if (ParseLine(I)) {
      std::cout << "Quitting...\n";
      break;
    }
  }
}

<commit_msg>[console] Fix incorrect and misleading help menu<commit_after>//===-- Console.cpp - Console utils for the interactive uwhd ------- c++ --===//
//
//                               UWH Timer
//
//           This file is distributed under the BSD 3-Clause License.
//                      See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "uwhd/console/Console.h"

#include "uwhd/model/GameModel.h"

#include <iostream>
#include <sstream>
#include <cctype>

#define ANSI_RED     "\x1b[31m"
#define ANSI_GREEN   "\x1b[32m"
#define ANSI_YELLOW  "\x1b[33m"
#define ANSI_BLUE    "\x1b[34m"
#define ANSI_MAGENTA "\x1b[35m"
#define ANSI_CYAN    "\x1b[36m"
#define ANSI_RESET   "\x1b[0m"

bool Console::ParseLine(std::string I) {
  if (I.size() == 0)
    goto Success;

  switch (I[0]) {
  case 'Q':
  case 'q':
    goto ExitLoop;

  case 'B':
  case 'b': {
    std::stringstream SS;
    SS << I.substr(1);
    int Score;
    SS >> Score;
    M.setBlackScore(Score);
    goto Success;
  }

  case 'W':
  case 'w': {
    std::stringstream SS;
    SS << I.substr(1);
    int Score;
    SS >> Score;
    M.setWhiteScore(Score);
    goto Success;
  }

  case 'T':
  case 't': {
    std::stringstream SS;
    SS << I.substr(1);
    int Time;
    SS >> Time;
    M.setGameClock(Time);
    goto Success;
  }

  case 'C':
  case 'c': {
    bool Running = M.gameClockRunning();
    M.setGameClockRunning(!Running);
    goto Success;
  }

  case 'H':
  case 'h': {
    std::cout << "Usage:\n"
              << "  B[0-9]+     - Set the Black Score\n"
              << "  W[0-9]+     - Set the White Score\n"
              << "  T[0-9]+     - Set the Game Clock\n"
              << "  C           - Start/Stop the Game Clock\n"
              << "  G[CFSHRWBO] - Set the Game State\n"
              << "    GC          - Wall Clock\n"
              << "    GF          - First Half\n"
              << "    GS          - Second Half\n"
              << "    GH          - Half Time\n"
              << "    GO          - Game Over\n"
              << "  P[NRWB]     - Set the Timeout State\n"
              << "    PN          - No Timeout\n"
              << "    PR          - Ref Timeout\n"
              << "    PW          - White Timeout\n"
              << "    PB          - Black Timeout\n"
              << "  H           - This menu\n"
              << "  Q           - Quit\n";
    goto Success;
  }

  case 'G':
  case 'g': {
    if (I.size() != 2)
      goto ParseError;

    switch (toupper(I[1])) {
    case 'C': M.setGameState(GameModel::GS_WallClock); goto Success;
    case 'F': M.setGameState(GameModel::GS_FirstHalf); goto Success;
    case 'S': M.setGameState(GameModel::GS_SecondHalf); goto Success;
    case 'H': M.setGameState(GameModel::GS_HalfTime); goto Success;
    case 'O': M.setGameState(GameModel::GS_GameOver); goto Success;
    default:
      goto ParseError;
    }
  }

  case 'P':
  case 'p': {
    if (I.size() != 2)
      goto ParseError;

    switch (toupper(I[1])) {
    case 'N': M.setTimeoutState(GameModel::TS_None); goto Success;
    case 'R': M.setTimeoutState(GameModel::TS_RefTimeout); goto Success;
    case 'W': M.setTimeoutState(GameModel::TS_WhiteTimeout); goto Success;
    case 'B': M.setTimeoutState(GameModel::TS_BlackTimeout); goto Success;
    default:
      goto ParseError;
    }
  }

  case 'S': {
    GameModel New;
    if (!GameModel::deSerialize(I, New)) {
      M.setModel(New);
      goto Success;
    }
    goto ParseError;
  }

  default:
    goto ParseError;
  }

ParseError:
  std::cerr << "Parse error on: '" << I << "'\n";
  return false;

Success:
  return false;

ExitLoop:
  return true;
}

void Console::Loop() {
  while (true) {
    std::cout << M.getModel().dump();
    std::cout << ANSI_CYAN << "[uwhdi] " << ANSI_RESET;

    std::string I;
    std::getline(std::cin, I);

    if (ParseLine(I)) {
      std::cout << "Quitting...\n";
      break;
    }
  }
}

<|endoftext|>


<commit_before>/*
Copyright (c) 2010, Roger Light <roger@atchoo.org>
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.
2. 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.
3. Neither the name of mosquitto 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.
*/

#include <stdint.h>
#include <cstdlib>
#include <mosquitto.h>
#include <mosquittopp.h>

mosquitto::mosquitto()
{
}

mosquitto::~mosquitto()
{
}

int mosquitto::connect(const char *host, int port)
{
	return 0;
}

int mosquitto::disconnect()
{
	return 0;
}

int mosquitto::publish(const char *topic, uint32_t payloadlen, const uint8_t *payload, int qos, bool retain)
{
	return 0;
}

int mosquitto::subscribe(const char *sub, int qos)
{
	return 0;
}

int mosquitto::unsubscribe(const char *sub)
{
	return 0;
}

int mosquitto::loop()
{
	return 0;
}

int mosquitto::read()
{
	return 0;
}

int mosquitto::write()
{
	return 0;
}

<commit_msg>Rename C++ class to mosquittopp.<commit_after>/*
Copyright (c) 2010, Roger Light <roger@atchoo.org>
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.
2. 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.
3. Neither the name of mosquitto 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.
*/

#include <stdint.h>
#include <cstdlib>
#include <mosquitto.h>
#include <mosquittopp.h>

mosquittopp::mosquittopp()
{
}

mosquittopp::~mosquittopp()
{
}

int mosquittopp::connect(const char *host, int port)
{
	return 0;
}

int mosquittopp::disconnect()
{
	return 0;
}

int mosquittopp::publish(const char *topic, uint32_t payloadlen, const uint8_t *payload, int qos, bool retain)
{
	return 0;
}

int mosquittopp::subscribe(const char *sub, int qos)
{
	return 0;
}

int mosquittopp::unsubscribe(const char *sub)
{
	return 0;
}

int mosquittopp::loop()
{
	return 0;
}

int mosquittopp::read()
{
	return 0;
}

int mosquittopp::write()
{
	return 0;
}

<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include "oox/drawingml/shapestylecontext.hxx"

#include "oox/helper/attributelist.hxx"
#include "oox/drawingml/colorchoicecontext.hxx"

using ::rtl::OUString;
using namespace ::oox::core;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::xml::sax;

namespace oox { namespace drawingml {

// ---------------
// CT_ShapeStyle
// ---------------
ShapeStyleContext::ShapeStyleContext( ContextHandler& rParent, Shape& rShape )
: ContextHandler( rParent )
, mrShape( rShape )
{
}

ShapeStyleContext::~ShapeStyleContext()
{
}

// --------------------------------------------------------------------

void ShapeStyleContext::endFastElement( sal_Int32 ) throw (SAXException, RuntimeException)
{
}

// --------------------------------------------------------------------

Reference< XFastContextHandler > ShapeStyleContext::createFastChildContext( sal_Int32 aElementToken, const Reference< XFastAttributeList >& rxAttributes )
    throw ( SAXException, RuntimeException )
{
    Reference< XFastContextHandler > xRet;
    AttributeList aAttribs( rxAttributes );
    switch( aElementToken )
    {
        case A_TOKEN( lnRef ) :     // CT_StyleMatrixReference
        case A_TOKEN( fillRef ) :   // CT_StyleMatrixReference
        case A_TOKEN( effectRef ) : // CT_StyleMatrixReference
        case A_TOKEN( fontRef ) :   // CT_FontReference
        {
            sal_Int32 nToken = getBaseToken( aElementToken );
            ShapeStyleRef& rStyleRef = mrShape.getShapeStyleRefs()[ nToken ];
            rStyleRef.mnThemedIdx = (nToken == XML_fontRef) ? aAttribs.getToken( XML_idx, XML_none ) : aAttribs.getInteger( XML_idx, 0 );
            xRet.set( new ColorContext( *this, rStyleRef.maPhClr ) );
        }
        break;
    }
    return xRet;
}

// --------------------------------------------------------------------

} }

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>n#746996: Wrong text color in smartArt.<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include "oox/drawingml/shapestylecontext.hxx"

#include "oox/helper/attributelist.hxx"
#include "oox/drawingml/colorchoicecontext.hxx"

using ::rtl::OUString;
using namespace ::oox::core;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::xml::sax;

namespace oox { namespace drawingml {

// ---------------
// CT_ShapeStyle
// ---------------
ShapeStyleContext::ShapeStyleContext( ContextHandler& rParent, Shape& rShape )
: ContextHandler( rParent )
, mrShape( rShape )
{
}

ShapeStyleContext::~ShapeStyleContext()
{
}

// --------------------------------------------------------------------

void ShapeStyleContext::endFastElement( sal_Int32 ) throw (SAXException, RuntimeException)
{
}

// --------------------------------------------------------------------

Reference< XFastContextHandler > ShapeStyleContext::createFastChildContext( sal_Int32 aElementToken, const Reference< XFastAttributeList >& rxAttributes )
    throw ( SAXException, RuntimeException )
{
    Reference< XFastContextHandler > xRet;
    AttributeList aAttribs( rxAttributes );
    switch( aElementToken )
    {
        case A_TOKEN( lnRef ) :     // CT_StyleMatrixReference
        case A_TOKEN( fillRef ) :   // CT_StyleMatrixReference
        case A_TOKEN( effectRef ) : // CT_StyleMatrixReference
        case A_TOKEN( fontRef ) :   // CT_FontReference
        {
            sal_Int32 nToken = getBaseToken( aElementToken );
            ShapeStyleRef& rStyleRef = mrShape.getShapeStyleRefs()[ nToken ];
            rStyleRef.mnThemedIdx = (nToken == XML_fontRef) ? aAttribs.getToken( XML_idx, XML_none ) : aAttribs.getInteger( XML_idx, 0 );
            // Set default Text Color. Some xml files don't seem
            // to have color definitions inside fontRef - Use
            // tx1 in such cases
            if( nToken == XML_fontRef && !rStyleRef.maPhClr.isUsed() )
                rStyleRef.maPhClr.setSchemeClr(XML_tx1);
            xRet.set( new ColorContext( *this, rStyleRef.maPhClr ) );
        }
        break;
    }
    return xRet;
}

// --------------------------------------------------------------------

} }

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>#include "EventPlayerHub.h"

#include <chrono>
#include <thread>

namespace myosim {
EventPlayerHub::EventPlayerHub(const EventQueue& events, float playback_speed,
                               const std::string& application_identifier)
    : events_(events),
      playback_speed_(playback_speed),
      tmus_previous_run_end_(0),
      myos_(events.num_myos, nullptr),
      Hub(application_identifier) {
  // Get the timestamp of the first myo event.
  popOnPeriodicEvents();
  if (! events_.queue.empty()) {
    tmus_previous_run_end_ = static_cast<MyoEvent*>(events_.queue.front().get())->timestamp;
  }
  // Get the same number of myos as used in the event queue.
  for (size_t i_myo = 0; i_myo < myos_.size(); ++i_myo) {
    myos_[i_myo] = myo::Hub::waitForMyo(10);
    if (myos_[i_myo] == nullptr) {
      for (size_t j_myo = 0; j_myo < i_myo; ++j_myo) {
        myos_[j_myo] = nullptr;
      }
      break;
    }
  }
}

void EventPlayerHub::popOnPeriodicEvents() {
  while (! events_.queue.empty() &&
         dynamic_cast<PeriodicEvent*>(events_.queue.front().get())) {
    events_.queue.pop_front();
  }
}

void EventPlayerHub::runAll(const std::function<void(void)>& periodic) {
  // tm is time in myo time
  // tc is time in std::chrono::stead_clock time
  uint64_t tmus_previous = 0;
  popOnPeriodicEvents();
  if (! events_.queue.empty()) {
    // We can static_cast here because popOnPeriodicEvents removed all the
    // PeriodicEvents and those are the only events that are not MyoEvents.
    tmus_previous = static_cast<MyoEvent*>(events_.queue.front().get())->timestamp;
  }
  while (! events_.queue.empty()) {
    if (auto ptr = dynamic_cast<PeriodicEvent*>(events_.queue.front().get())) {
      periodic();
    } else if (auto ptr = dynamic_cast<MyoEvent*>(events_.queue.front().get())) {
      auto dtcms = std::chrono::microseconds(ptr->timestamp - tmus_previous);
      auto tc_now = std::chrono::steady_clock::now();
      std::this_thread::sleep_until(tc_now + (dtcms / playback_speed_));
      simulateEvent(ptr);
      tmus_previous = ptr->timestamp;
    }
    events_.queue.pop_front();
  }
}

void EventPlayerHub::run(unsigned int duration_ms) {
  // tm is time in myo time
  // tc is time in std::chrono::stead_clock time
  uint64_t tmus_previous = tmus_previous_run_end_;
  uint64_t tmus_end = tmus_previous + (1000 * duration_ms);

  popOnPeriodicEvents();
  while (! events_.queue.empty()) {
    // We can static_cast here because popOnPeriodicEvents removed all the
    // PeriodicEvents and those are the only events that are not MyoEvents.
    auto ptr_event = static_cast<MyoEvent*>(events_.queue.front().get());
    if (ptr_event->timestamp > tmus_end) {
      // Event doesn't occur in this call to run. Wait until tmus_end.
      auto dtcus = std::chrono::microseconds(tmus_end - tmus_previous);
      auto tc_now = std::chrono::steady_clock::now();
      std::this_thread::sleep_until(tc_now + (dtcus / playback_speed_));
      // Setup tmus_previous_run_end_ for next call to run or runOnce.
      tmus_previous_run_end_ = tmus_end;
      return;
    } else {
      // Wait until the event's timestamp.
      auto dtcus = std::chrono::microseconds(ptr_event->timestamp - tmus_previous);
      auto tc_now = std::chrono::steady_clock::now();
      std::this_thread::sleep_until(tc_now + (dtcus / playback_speed_));
      // Simulate event.
      simulateEvent(ptr_event);
      // Setup for next iteration of while loop.
      tmus_previous = ptr_event->timestamp;
      events_.queue.pop_front();
      popOnPeriodicEvents();
    }
  }
}

void EventPlayerHub::runOnce(unsigned int duration_ms) {
  // tm is time in myo time
  // tc is time in std::chrono::stead_clock time
  uint64_t tmus_previous = tmus_previous_run_end_;
  uint64_t tmus_end = tmus_previous + (1000 * duration_ms);
  popOnPeriodicEvents();
  if (! events_.queue.empty()) {
    auto ptr_event = static_cast<MyoEvent*>(events_.queue.front().get());
    if (ptr_event->timestamp <= tmus_end) {
      tmus_end = ptr_event->timestamp;
      auto dtcus = std::chrono::microseconds(tmus_end - tmus_previous);
      auto tc_now = std::chrono::steady_clock::now();
      std::this_thread::sleep_until(tc_now + (dtcus / playback_speed_));
      tmus_previous_run_end_ = tmus_end;
      simulateEvent(ptr_event);
      events_.queue.pop_front();
      return;
    }
  }
  auto dtcus = std::chrono::microseconds(tmus_end - tmus_previous);
  auto tc_now = std::chrono::steady_clock::now();
  std::this_thread::sleep_until(tc_now + (dtcus / playback_speed_));
  tmus_previous_run_end_ = tmus_end;
}

void EventPlayerHub::simulateEvent(MyoEvent* p_event) {
  if (auto ptr = dynamic_cast<OrientationDataEvent*>(p_event)) {
    simulateOrientationData(myos_[ptr->myo_index], ptr->timestamp, ptr->rotation);
  } else if (auto ptr = dynamic_cast<AccelerometerDataEvent*>(p_event)) {
    simulateAccelerometerData(myos_[ptr->myo_index], ptr->timestamp, ptr->accel);
  } else if (auto ptr = dynamic_cast<GyroscopeDataEvent*>(p_event)) {
    simulateGyroscopeData(myos_[ptr->myo_index], ptr->timestamp, ptr->gyro);
  } else if (auto ptr = dynamic_cast<EmgDataEvent*>(p_event)) {
    simulateEmgData(myos_[ptr->myo_index], ptr->timestamp, ptr->emg);
  } else if (auto ptr = dynamic_cast<PoseEvent*>(p_event)) {
    simulatePose(myos_[ptr->myo_index], ptr->timestamp, ptr->pose);
  } else if (auto ptr = dynamic_cast<UnlockEvent*>(p_event)) {
    simulateUnlock(myos_[ptr->myo_index], ptr->timestamp);
  } else if (auto ptr = dynamic_cast<LockEvent*>(p_event)) {
    simulateLock(myos_[ptr->myo_index], ptr->timestamp);
  } else if (auto ptr = dynamic_cast<PairEvent*>(p_event)) {
    simulatePair(myos_[ptr->myo_index], ptr->timestamp, ptr->firmware_version);
  } else if (auto ptr = dynamic_cast<UnpairEvent*>(p_event)) {
    simulateUnpair(myos_[ptr->myo_index], ptr->timestamp);
  } else if (auto ptr = dynamic_cast<ConnectEvent*>(p_event)) {
    simulateConnect(myos_[ptr->myo_index], ptr->timestamp, ptr->firmware_version);
  } else if (auto ptr = dynamic_cast<DisconnectEvent*>(p_event)) {
    simulateDisconnect(myos_[ptr->myo_index], ptr->timestamp);
  } else if (auto ptr = dynamic_cast<ArmSyncEvent*>(p_event)) {
    simulateArmSync(myos_[ptr->myo_index], ptr->timestamp, ptr->arm,
                    ptr->x_direction, ptr->rotation, ptr->warmup_state);
  } else if (auto ptr = dynamic_cast<ArmUnsyncEvent*>(p_event)) {
    simulateArmUnsync(myos_[ptr->myo_index], ptr->timestamp);
  } else if (auto ptr = dynamic_cast<RssiEvent*>(p_event)) {
    simulateRssi(myos_[ptr->myo_index], ptr->timestamp, ptr->rssi);
  } else if (auto ptr = dynamic_cast<BatteryLevelReceivedEvent*>(p_event)) {
    simulateBatteryLevelReceived(myos_[ptr->myo_index], ptr->timestamp, ptr->level);
  } else if (auto ptr = dynamic_cast<WarmupCompletedEvent*>(p_event)) {
    simulateWarmupCompleted(myos_[ptr->myo_index], ptr->timestamp, ptr->warmup_result);
  }
}
} // namespace myosim
<commit_msg>Rewrite EventPlayerHub::runOnce<commit_after>#include "EventPlayerHub.h"

#include <chrono>
#include <thread>

namespace myosim {
EventPlayerHub::EventPlayerHub(const EventQueue& events, float playback_speed,
                               const std::string& application_identifier)
    : events_(events),
      playback_speed_(playback_speed),
      tmus_previous_run_end_(0),
      myos_(events.num_myos, nullptr),
      Hub(application_identifier) {
  // Get the timestamp of the first myo event.
  popOnPeriodicEvents();
  if (! events_.queue.empty()) {
    tmus_previous_run_end_ = static_cast<MyoEvent*>(events_.queue.front().get())->timestamp;
  }
  // Get the same number of myos as used in the event queue.
  for (size_t i_myo = 0; i_myo < myos_.size(); ++i_myo) {
    myos_[i_myo] = myo::Hub::waitForMyo(10);
    if (myos_[i_myo] == nullptr) {
      for (size_t j_myo = 0; j_myo < i_myo; ++j_myo) {
        myos_[j_myo] = nullptr;
      }
      break;
    }
  }
}

void EventPlayerHub::popOnPeriodicEvents() {
  while (! events_.queue.empty() &&
         dynamic_cast<PeriodicEvent*>(events_.queue.front().get())) {
    events_.queue.pop_front();
  }
}

void EventPlayerHub::runAll(const std::function<void(void)>& periodic) {
  // tm is time in myo time
  // tc is time in std::chrono::stead_clock time
  uint64_t tmus_previous = 0;
  popOnPeriodicEvents();
  if (! events_.queue.empty()) {
    // We can static_cast here because popOnPeriodicEvents removed all the
    // PeriodicEvents and those are the only events that are not MyoEvents.
    tmus_previous = static_cast<MyoEvent*>(events_.queue.front().get())->timestamp;
  }
  while (! events_.queue.empty()) {
    if (auto ptr = dynamic_cast<PeriodicEvent*>(events_.queue.front().get())) {
      periodic();
    } else if (auto ptr = dynamic_cast<MyoEvent*>(events_.queue.front().get())) {
      auto dtcms = std::chrono::microseconds(ptr->timestamp - tmus_previous);
      auto tc_now = std::chrono::steady_clock::now();
      std::this_thread::sleep_until(tc_now + (dtcms / playback_speed_));
      simulateEvent(ptr);
      tmus_previous = ptr->timestamp;
    }
    events_.queue.pop_front();
  }
}

void EventPlayerHub::run(unsigned int duration_ms) {
  // tm is time in myo time
  // tc is time in std::chrono::stead_clock time
  uint64_t tmus_previous = tmus_previous_run_end_;
  uint64_t tmus_end = tmus_previous + (1000 * duration_ms);

  popOnPeriodicEvents();
  while (! events_.queue.empty()) {
    // We can static_cast here because popOnPeriodicEvents removed all the
    // PeriodicEvents and those are the only events that are not MyoEvents.
    auto ptr_event = static_cast<MyoEvent*>(events_.queue.front().get());
    if (ptr_event->timestamp > tmus_end) {
      // Event doesn't occur in this call to run. Wait until tmus_end.
      auto dtcus = std::chrono::microseconds(tmus_end - tmus_previous);
      auto tc_now = std::chrono::steady_clock::now();
      std::this_thread::sleep_until(tc_now + (dtcus / playback_speed_));
      // Setup tmus_previous_run_end_ for next call to run or runOnce.
      tmus_previous_run_end_ = tmus_end;
      return;
    } else {
      // Wait until the event's timestamp.
      auto dtcus = std::chrono::microseconds(ptr_event->timestamp - tmus_previous);
      auto tc_now = std::chrono::steady_clock::now();
      std::this_thread::sleep_until(tc_now + (dtcus / playback_speed_));
      // Simulate event.
      simulateEvent(ptr_event);
      // Setup for next iteration of while loop.
      tmus_previous = ptr_event->timestamp;
      events_.queue.pop_front();
      popOnPeriodicEvents();
    }
  }
}

void EventPlayerHub::runOnce(unsigned int duration_ms) {
  // tm is time in myo time
  // tc is time in std::chrono::stead_clock time
  uint64_t tmus_end = tmus_previous_run_end_ + (1000 * duration_ms);

  popOnPeriodicEvents();
  if (! events_.queue.empty()) {
    // We can static_cast here because popOnPeriodicEvents removed all the
    // PeriodicEvents and those are the only events that are not MyoEvents.
    auto ptr_event = static_cast<MyoEvent*>(events_.queue.front().get());
    if (ptr_event->timestamp > tmus_end) {
      // Event doesn't occur in this call to runOnce. Wait until tmus_end.
      auto dtcus = std::chrono::microseconds(tmus_end - tmus_previous_run_end_);
      auto tc_now = std::chrono::steady_clock::now();
      std::this_thread::sleep_until(tc_now + (dtcus / playback_speed_));
      // Setup tmus_previous_run_end_ for next call to run or runOnce.
      tmus_previous_run_end_ = tmus_end;
      return;
    } else {
      // Wait until the event's timestamp.
      auto dtcus = std::chrono::microseconds(ptr_event->timestamp - tmus_previous_run_end_);
      auto tc_now = std::chrono::steady_clock::now();
      std::this_thread::sleep_until(tc_now + (dtcus / playback_speed_));
      // Simulate event.
      simulateEvent(ptr_event);
      // Setup for next call to run or runOnce.
      tmus_previous_run_end_ = ptr_event->timestamp;
      events_.queue.pop_front();
    }
  }
}

void EventPlayerHub::simulateEvent(MyoEvent* p_event) {
  if (auto ptr = dynamic_cast<OrientationDataEvent*>(p_event)) {
    simulateOrientationData(myos_[ptr->myo_index], ptr->timestamp, ptr->rotation);
  } else if (auto ptr = dynamic_cast<AccelerometerDataEvent*>(p_event)) {
    simulateAccelerometerData(myos_[ptr->myo_index], ptr->timestamp, ptr->accel);
  } else if (auto ptr = dynamic_cast<GyroscopeDataEvent*>(p_event)) {
    simulateGyroscopeData(myos_[ptr->myo_index], ptr->timestamp, ptr->gyro);
  } else if (auto ptr = dynamic_cast<EmgDataEvent*>(p_event)) {
    simulateEmgData(myos_[ptr->myo_index], ptr->timestamp, ptr->emg);
  } else if (auto ptr = dynamic_cast<PoseEvent*>(p_event)) {
    simulatePose(myos_[ptr->myo_index], ptr->timestamp, ptr->pose);
  } else if (auto ptr = dynamic_cast<UnlockEvent*>(p_event)) {
    simulateUnlock(myos_[ptr->myo_index], ptr->timestamp);
  } else if (auto ptr = dynamic_cast<LockEvent*>(p_event)) {
    simulateLock(myos_[ptr->myo_index], ptr->timestamp);
  } else if (auto ptr = dynamic_cast<PairEvent*>(p_event)) {
    simulatePair(myos_[ptr->myo_index], ptr->timestamp, ptr->firmware_version);
  } else if (auto ptr = dynamic_cast<UnpairEvent*>(p_event)) {
    simulateUnpair(myos_[ptr->myo_index], ptr->timestamp);
  } else if (auto ptr = dynamic_cast<ConnectEvent*>(p_event)) {
    simulateConnect(myos_[ptr->myo_index], ptr->timestamp, ptr->firmware_version);
  } else if (auto ptr = dynamic_cast<DisconnectEvent*>(p_event)) {
    simulateDisconnect(myos_[ptr->myo_index], ptr->timestamp);
  } else if (auto ptr = dynamic_cast<ArmSyncEvent*>(p_event)) {
    simulateArmSync(myos_[ptr->myo_index], ptr->timestamp, ptr->arm,
                    ptr->x_direction, ptr->rotation, ptr->warmup_state);
  } else if (auto ptr = dynamic_cast<ArmUnsyncEvent*>(p_event)) {
    simulateArmUnsync(myos_[ptr->myo_index], ptr->timestamp);
  } else if (auto ptr = dynamic_cast<RssiEvent*>(p_event)) {
    simulateRssi(myos_[ptr->myo_index], ptr->timestamp, ptr->rssi);
  } else if (auto ptr = dynamic_cast<BatteryLevelReceivedEvent*>(p_event)) {
    simulateBatteryLevelReceived(myos_[ptr->myo_index], ptr->timestamp, ptr->level);
  } else if (auto ptr = dynamic_cast<WarmupCompletedEvent*>(p_event)) {
    simulateWarmupCompleted(myos_[ptr->myo_index], ptr->timestamp, ptr->warmup_result);
  }
}
} // namespace myosim
<|endoftext|>


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

#include "EventTargetImp.h"

#include <org/w3c/dom/events/Event.h>

#include "DocumentImp.h"
#include "DocumentWindow.h"
#include "EventImp.h"
#include "NodeImp.h"
#include "UIEventImp.h"
#include "WindowImp.h"
#include "html/HTMLTemplateElementImp.h"

namespace org { namespace w3c { namespace dom { namespace bootstrap {

void EventTargetImp::invoke(EventImp* event)
{
    auto found = map.find(event->getType());
    if (found == map.end())
        return;
    std::list<Listener>& listeners = found->second;
    for (auto i = listeners.begin(); i != listeners.end(); ++i) {
        if (event->getStopImmediatePropagationFlag())
            return;
        switch (event->getEventPhase()) {
        case events::Event::CAPTURING_PHASE:
            if (i->useCapture() && !i->useDefault())
                i->listener.handleEvent(event);
            break;
        case events::Event::BUBBLING_PHASE:
            if (!i->useCapture() && !i->useDefault())
                i->listener.handleEvent(event);
            break;
        case events::Event::AT_TARGET:
            if (!i->useDefault())
                i->listener.handleEvent(event);
            break;
        case EventImp::DEFAULT_PHASE:
            if (i->useDefault())
                i->listener.handleEvent(event);
        default:
            break;
        }
    }
}

EventListenerImp* EventTargetImp::getEventHandlerListener(const std::u16string& type)
{
    auto found = map.find(type);
    if (found == map.end())
        return 0;
    std::list<Listener>& listeners = found->second;
    for (auto i = listeners.begin(); i != listeners.end(); ++i) {
        if (i->useEventHandler())
            return dynamic_cast<EventListenerImp*>(i->listener.self());
    }
    return 0;
}

Object EventTargetImp::getEventHandler(const std::u16string& type)
{
    if (EventListenerImp* listener = getEventHandlerListener(type))
        return listener->getEventHandler();
    return 0;
}

// EventTarget
void EventTargetImp::addEventListener(const std::u16string&  type, events::EventListener listener, bool useCapture, unsigned flags)
{
    if (!listener)
        return;
    if (useCapture)
        flags |= UseCapture;
    Listener item{ listener, flags };

    auto found = map.find(type);
    if (found == map.end()) {
        std::list<Listener> listeners;
        listeners.push_back(item);
        map.insert(std::pair<std::u16string, std::list<Listener>>(type, listeners));
        return;
    }

    std::list<Listener>& listeners = found->second;
    for (auto i = listeners.begin(); i != listeners.end(); ++i) {
        if (*i == item)
            return;
    }
    listeners.push_back(item);
}

void EventTargetImp::removeEventListener(const std::u16string&  type, events::EventListener listener, bool useCapture, unsigned flags)
{
    if (!listener)
        return;
    if (useCapture)
        flags |= UseCapture;
    Listener item{ listener, flags };

    auto found = map.find(type);
    if (found == map.end())
        return;

    std::list<Listener>& listeners = found->second;
    for (auto i = listeners.begin(); i != listeners.end(); ++i) {
        if (*i == item) {
            listeners.erase(i);
            return;
        }
    }
}

bool EventTargetImp::dispatchEvent(events::Event evt)
{
    EventImp* event = dynamic_cast<EventImp*>(evt.self());
    if (!event)
        return false;

    auto currentWindow = static_cast<WindowImp*>(ECMAScriptContext::getCurrent());

    event->setDispatchFlag(true);
    event->setTarget(this);

    if (NodeImp* node = dynamic_cast<NodeImp*>(this)) {
        DocumentImp* document = dynamic_cast<DocumentImp*>(node);
        if (!document)
            document = node->getOwnerDocumentImp();
        assert(document);

        document->enter();

        std::list<EventTargetImp*> eventPath;
        for (NodeImp* ancestor = node->parentNode; ancestor; ancestor = ancestor->parentNode) {
            if (auto shadowTree = dynamic_cast<HTMLTemplateElementImp*>(ancestor)) {
                if (NodeImp* host = dynamic_cast<NodeImp*>(shadowTree->getHost().self())) {
                    // TODO: Fix 'target' of the event as well.
                    // TODO: Check the mouseover and mouseout events.
                    ancestor = host;
                    if (!dynamic_cast<UIEventImp*>(event)) {
                        // To repaint the window, we still need to notify the bound document
                        // of the event.
                        // TODO: Support nesting of bound elements.
                        eventPath.push_front(ancestor->getOwnerDocumentImp());
                        break;
                    }
                }
            }
            eventPath.push_front(ancestor);
        }

        // cf. http://www.whatwg.org/specs/web-apps/current-work/multipage/webappapis.html#events-and-the-window-object
        if (document && event->getType() != u"load") {
            if (WindowImp* view = document->getDefaultWindow())
                eventPath.push_front(view->getDocumentWindow().get());
        }

        event->setEventPhase(events::Event::CAPTURING_PHASE);
        for (auto i = eventPath.begin(); i != eventPath.end(); ++i) {
            if (event->getStopPropagationFlag())
                break;
            event->setCurrentTarget(*i);
            (*i)->invoke(event);
        }

        event->setEventPhase(events::Event::AT_TARGET);
        if (!event->getStopPropagationFlag()) {
            event->setCurrentTarget(node);
            node->invoke(event);
        }

        if (event->getBubbles()) {
            event->setEventPhase(events::Event::BUBBLING_PHASE);
            for (auto i = eventPath.rbegin(); i != eventPath.rend(); ++i) {
                if (event->getStopPropagationFlag())
                    break;
                event->setCurrentTarget(*i);
                (*i)->invoke(event);
            }
        }

        if (!event->getDefaultPrevented()) {
            // TODO: Call default actions;
            // cf. http://www.w3.org/TR/DOM-Level-3-Events/#event-flow-default-cancel
            // cf. http://www.w3.org/TR/xbl/#the-default-phase0
            event->setEventPhase(EventImp::DEFAULT_PHASE);
            event->setCurrentTarget(node);
            node->invoke(event);
            if (event->getBubbles()) {
                for (auto i = eventPath.rbegin(); i != eventPath.rend(); ++i) {
                    if (event->getDefaultPrevented())
                        break;
                    event->setCurrentTarget(*i);
                    (*i)->invoke(event);
                }
            }
        }

        document->exit();

    } else if (DocumentWindow* window = dynamic_cast<DocumentWindow*>(this)) {
        auto proxy = dynamic_cast<WindowImp*>(window->getDocument().getDefaultView().self());
        window->enter(proxy);
        event->setEventPhase(events::Event::AT_TARGET);
        event->setCurrentTarget(this);
        invoke(event);
        window->exit(proxy);
    }
    event->setDispatchFlag(false);
    event->setEventPhase(events::Event::AT_TARGET);
    event->setCurrentTarget(0);

    return !event->getDefaultPrevented();
}

EventTargetImp::EventTargetImp() :
    ObjectMixin()
{
}

EventTargetImp::EventTargetImp(EventTargetImp* org) :
    ObjectMixin()
{
    // TODO: Check what needs to be copied.
}

}}}}  // org::w3c::dom::bootstrap
<commit_msg>(EventTargetImp::dispatchEvent): Refine<commit_after>/*
 * Copyright 2011-2013 Esrille Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "EventTargetImp.h"

#include <org/w3c/dom/events/Event.h>

#include "DocumentImp.h"
#include "DocumentWindow.h"
#include "EventImp.h"
#include "NodeImp.h"
#include "UIEventImp.h"
#include "WindowImp.h"
#include "html/HTMLTemplateElementImp.h"

namespace org { namespace w3c { namespace dom { namespace bootstrap {

void EventTargetImp::invoke(EventImp* event)
{
    auto found = map.find(event->getType());
    if (found == map.end())
        return;
    std::list<Listener>& listeners = found->second;
    for (auto i = listeners.begin(); i != listeners.end(); ++i) {
        if (event->getStopImmediatePropagationFlag())
            return;
        switch (event->getEventPhase()) {
        case events::Event::CAPTURING_PHASE:
            if (i->useCapture() && !i->useDefault())
                i->listener.handleEvent(event);
            break;
        case events::Event::BUBBLING_PHASE:
            if (!i->useCapture() && !i->useDefault())
                i->listener.handleEvent(event);
            break;
        case events::Event::AT_TARGET:
            if (!i->useDefault())
                i->listener.handleEvent(event);
            break;
        case EventImp::DEFAULT_PHASE:
            if (i->useDefault())
                i->listener.handleEvent(event);
        default:
            break;
        }
    }
}

EventListenerImp* EventTargetImp::getEventHandlerListener(const std::u16string& type)
{
    auto found = map.find(type);
    if (found == map.end())
        return 0;
    std::list<Listener>& listeners = found->second;
    for (auto i = listeners.begin(); i != listeners.end(); ++i) {
        if (i->useEventHandler())
            return dynamic_cast<EventListenerImp*>(i->listener.self());
    }
    return 0;
}

Object EventTargetImp::getEventHandler(const std::u16string& type)
{
    if (EventListenerImp* listener = getEventHandlerListener(type))
        return listener->getEventHandler();
    return 0;
}

// EventTarget
void EventTargetImp::addEventListener(const std::u16string&  type, events::EventListener listener, bool useCapture, unsigned flags)
{
    if (!listener)
        return;
    if (useCapture)
        flags |= UseCapture;
    Listener item{ listener, flags };

    auto found = map.find(type);
    if (found == map.end()) {
        std::list<Listener> listeners;
        listeners.push_back(item);
        map.insert(std::pair<std::u16string, std::list<Listener>>(type, listeners));
        return;
    }

    std::list<Listener>& listeners = found->second;
    for (auto i = listeners.begin(); i != listeners.end(); ++i) {
        if (*i == item)
            return;
    }
    listeners.push_back(item);
}

void EventTargetImp::removeEventListener(const std::u16string&  type, events::EventListener listener, bool useCapture, unsigned flags)
{
    if (!listener)
        return;
    if (useCapture)
        flags |= UseCapture;
    Listener item{ listener, flags };

    auto found = map.find(type);
    if (found == map.end())
        return;

    std::list<Listener>& listeners = found->second;
    for (auto i = listeners.begin(); i != listeners.end(); ++i) {
        if (*i == item) {
            listeners.erase(i);
            return;
        }
    }
}

bool EventTargetImp::dispatchEvent(events::Event evt)
{
    EventImp* event = dynamic_cast<EventImp*>(evt.self());
    if (!event)
        return false;

    event->setDispatchFlag(true);
    event->setTarget(this);

    if (NodeImp* node = dynamic_cast<NodeImp*>(this)) {
        DocumentImp* document = dynamic_cast<DocumentImp*>(node);
        if (!document)
            document = node->getOwnerDocumentImp();
        assert(document);

        document->enter();

        std::list<EventTargetImp*> eventPath;
        for (NodeImp* ancestor = node->parentNode; ancestor; ancestor = ancestor->parentNode) {
            if (auto shadowTree = dynamic_cast<HTMLTemplateElementImp*>(ancestor)) {
                if (NodeImp* host = dynamic_cast<NodeImp*>(shadowTree->getHost().self())) {
                    // TODO: Fix 'target' of the event as well.
                    // TODO: Check the mouseover and mouseout events.
                    ancestor = host;
                    if (!dynamic_cast<UIEventImp*>(event)) {
                        // To repaint the window, we still need to notify the bound document
                        // of the event.
                        // TODO: Support nesting of bound elements.
                        eventPath.push_front(ancestor->getOwnerDocumentImp());
                        break;
                    }
                }
            }
            eventPath.push_front(ancestor);
        }

        // cf. http://www.whatwg.org/specs/web-apps/current-work/multipage/webappapis.html#events-and-the-window-object
        if (document && event->getType() != u"load") {
            if (WindowImp* view = document->getDefaultWindow())
                eventPath.push_front(view->getDocumentWindow().get());
        }

        event->setEventPhase(events::Event::CAPTURING_PHASE);
        for (auto i = eventPath.begin(); i != eventPath.end(); ++i) {
            if (event->getStopPropagationFlag())
                break;
            event->setCurrentTarget(*i);
            (*i)->invoke(event);
        }

        event->setEventPhase(events::Event::AT_TARGET);
        if (!event->getStopPropagationFlag()) {
            event->setCurrentTarget(node);
            node->invoke(event);
        }

        if (event->getBubbles()) {
            event->setEventPhase(events::Event::BUBBLING_PHASE);
            for (auto i = eventPath.rbegin(); i != eventPath.rend(); ++i) {
                if (event->getStopPropagationFlag())
                    break;
                event->setCurrentTarget(*i);
                (*i)->invoke(event);
            }
        }

        if (!event->getDefaultPrevented()) {
            // TODO: Call default actions;
            // cf. http://www.w3.org/TR/DOM-Level-3-Events/#event-flow-default-cancel
            // cf. http://www.w3.org/TR/xbl/#the-default-phase0
            event->setEventPhase(EventImp::DEFAULT_PHASE);
            event->setCurrentTarget(node);
            node->invoke(event);
            if (event->getBubbles()) {
                for (auto i = eventPath.rbegin(); i != eventPath.rend(); ++i) {
                    if (event->getDefaultPrevented())
                        break;
                    event->setCurrentTarget(*i);
                    (*i)->invoke(event);
                }
            }
        }

        document->exit();

    } else if (DocumentWindow* window = dynamic_cast<DocumentWindow*>(this)) {
        auto proxy = dynamic_cast<WindowImp*>(window->getDocument().getDefaultView().self());
        window->enter(proxy);
        event->setEventPhase(events::Event::AT_TARGET);
        event->setCurrentTarget(this);
        invoke(event);
        window->exit(proxy);
    }
    event->setDispatchFlag(false);
    event->setEventPhase(events::Event::AT_TARGET);
    event->setCurrentTarget(0);

    return !event->getDefaultPrevented();
}

EventTargetImp::EventTargetImp() :
    ObjectMixin()
{
}

EventTargetImp::EventTargetImp(EventTargetImp* org) :
    ObjectMixin()
{
    // TODO: Check what needs to be copied.
}

}}}}  // org::w3c::dom::bootstrap
<|endoftext|>


<commit_before><commit_msg>fix crash on string<commit_after><|endoftext|>


<commit_before>#include <GLUI/GLUI.h>

#include <math.h>		   //----------------------------------------------------------
#include <GLFW/glfw3.h>    //    Only for testing, won't be needed when using GLUI
#include <iostream>		   //----------------------------------------------------------

using namespace glui;

int main() {
	GLUI::init();

	Window win("GLUI Test", 800, 600, false, 0, NULL);

	Renderer::init(&win);

	glui::Rectangle rect = {100, 100, 100, 50};
	Layout* layout = new AbsoluteLayout(&win, 800, 600);

	Font* font30 = new Font("arial.ttf", 30);
	if (!font30->inited()) {
		win.destroy();
		std::cout << "Could not load arial.ttf!\n";
		return -1;
	}

	Font* font20 = new Font("arial.ttf", 20);
	if (!font20->inited()) {
		win.destroy();
		std::cout << "Could not load arial.ttf!\n";
		return -1;
	}

    Theme theme = {};
    theme.body					= color::lightGrey;
    theme.check					= color::black;
    theme.circle				= color::black;
    theme.hover					= color::grey;
    theme.outline				= color::black;
    theme.press					= color::darkGrey;
    theme.text					= color::black;
    theme.popupBackground		= color::lightGrey;
    theme.popupText				= color::black;

    TextStyle buttonText = { 30, font30 };
    TextStyle textBoxText = { 20, font20 };
    ButtonDescriptor desc = { buttonText,
        [&]()->void {
            char** chars = new char*[2];
            chars[0] = (char*)"Cancel";
            chars[1] = (char*)"Ok";

            PopupDescriptor pDesc = {};
            pDesc.width = 300;
            pDesc.height = 200;
            pDesc.title = "Popup!";
            pDesc.text = "This is a popup!";
            pDesc.btnNum = 2;
            pDesc.btnText = (const char**)chars;
            pDesc.window = &win;
            pDesc.bodyTextStyle = textBoxText;
            pDesc.buttonTextStyle = buttonText;

            int result = Window::popup(pDesc, theme);

            std::cout << "popup returned: " << result << "\n";
        },
        3, theme
    };

    Button button(rect, layout, "Press", desc);

    TextBoxDescriptor tdesc = { textBoxText , 1, 2, theme };

    rect.h = 30;
    rect.x = 500;
    rect.w = 200;

    TextBox textBox(rect, layout, tdesc);

    rect.y = 200;

    TextBox textBox2(rect, layout, tdesc);

    GLPanel panel({ 10, 290, 300, 300 }, {300, 300}, layout,
                  []()->void { //Render function
                      glEnable(GL_DEPTH_TEST);
                      glClearColor(0.2f, 0.3f, 0.8f, 1);
                      glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

                      //gluPerspective(80, 1, 0.1, 1000);

                      /*
                      glPushMatrix();

                      float rotSpeed = 30;

                      glTranslatef(0, 0, -4);
                      glRotatef(glfwGetTime() * rotSpeed / 1, 1, 0, 0);
                      glRotatef(glfwGetTime() * rotSpeed / 2, 0, 1, 0);
                      glRotatef(glfwGetTime() * rotSpeed / 3, 0, 0, 1);

                      glCallList(box);

                      glPopMatrix();
                       */
                  },
                  [](GLPanelMouseData* data)->void {

                  }, theme);

    CheckBoxDescriptor checkBoxDesc = {
        { 30, font30 },
        3,
        false,
        theme
    };

    CheckBox checkBox({100, 200, 30, 30}, layout, "toggle", checkBoxDesc);
	while (win.isOpen()) {
		win.poll();

        button.poll();
        textBox.poll();
        textBox2.poll();
        panel.poll();
        checkBox.poll();

		Renderer::clear(color::grey);

		Renderer::beginDraw();

        button.render();
        textBox.render();
        textBox2.render();
        panel.render();
        checkBox.render();

		Renderer::endDraw();

		win.swap();
	}

	win.destroy();

	GLUI::destroy();

	return 0;
}
<commit_msg>fixed cube<commit_after>#include <GLUI/GLUI.h>

#include <math.h>		   //----------------------------------------------------------
#include <GLFW/glfw3.h>    //    Only for testing, won't be needed when using GLUI
#include <iostream>		   //----------------------------------------------------------

#define DEG_TO_RAD 0.0174532925199

using namespace glui;

int main() {
	GLUI::init();

	Window win("GLUI Test", 800, 600, false, 0, NULL);

	Renderer::init(&win);

	glui::Rectangle rect = {100, 100, 100, 50};
	Layout* layout = new AbsoluteLayout(&win, 800, 600);

	Font* font30 = new Font("arial.ttf", 30);
	if (!font30->inited()) {
		win.destroy();
		std::cout << "Could not load arial.ttf!\n";
		return -1;
	}

	Font* font20 = new Font("arial.ttf", 20);
	if (!font20->inited()) {
		win.destroy();
		std::cout << "Could not load arial.ttf!\n";
		return -1;
	}

    Theme theme = {};
    theme.body					= color::lightGrey;
    theme.check					= color::black;
    theme.circle				= color::black;
    theme.hover					= color::grey;
    theme.outline				= color::black;
    theme.press					= color::darkGrey;
    theme.text					= color::black;
    theme.popupBackground		= color::lightGrey;
    theme.popupText				= color::black;

    TextStyle buttonText = { 30, font30 };
    TextStyle textBoxText = { 20, font20 };
    ButtonDescriptor desc = { buttonText,
        [&]()->void {
            char** chars = new char*[2];
            chars[0] = (char*)"Cancel";
            chars[1] = (char*)"Ok";

            PopupDescriptor pDesc = {};
            pDesc.width = 300;
            pDesc.height = 200;
            pDesc.title = "Popup!";
            pDesc.text = "This is a popup!";
            pDesc.btnNum = 2;
            pDesc.btnText = (const char**)chars;
            pDesc.window = &win;
            pDesc.bodyTextStyle = textBoxText;
            pDesc.buttonTextStyle = buttonText;

            int result = Window::popup(pDesc, theme);

            std::cout << "popup returned: " << result << "\n";
        },
        3, theme
    };

    Button button(rect, layout, "Press", desc);

    TextBoxDescriptor tdesc = { textBoxText , 1, 2, theme };

    rect.h = 30;
    rect.x = 500;
    rect.w = 200;

    TextBox textBox(rect, layout, tdesc);

    rect.y = 200;

    TextBox textBox2(rect, layout, tdesc);

    float vertices[] = {
        -0.5f,0.5f,-0.5f,
        -0.5f,-0.5f,-0.5f,
        0.5f,-0.5f,-0.5f,
        0.5f,0.5f,-0.5f,

        -0.5f,0.5f,0.5f,
        -0.5f,-0.5f,0.5f,
        0.5f,-0.5f,0.5f,
        0.5f,0.5f,0.5f,

        0.5f,0.5f,-0.5f,
        0.5f,-0.5f,-0.5f,
        0.5f,-0.5f,0.5f,
        0.5f,0.5f,0.5f,

        -0.5f,0.5f,-0.5f,
        -0.5f,-0.5f,-0.5f,
        -0.5f,-0.5f,0.5f,
        -0.5f,0.5f,0.5f,

        -0.5f,0.5f,0.5f,
        -0.5f,0.5f,-0.5f,
        0.5f,0.5f,-0.5f,
        0.5f,0.5f,0.5f,

        -0.5f,-0.5f,0.5f,
        -0.5f,-0.5f,-0.5f,
        0.5f,-0.5f,-0.5f,
        0.5f,-0.5f,0.5f
    };

    float colors[] = {
        1.0f, 0.0f, 0.0f,
        1.0f, 0.0f, 0.0f,
        1.0f, 0.0f, 0.0f,
        1.0f, 0.0f, 0.0f,

        1.0f, 1.0f, 0.0f,
        1.0f, 1.0f, 0.0f,
        1.0f, 1.0f, 0.0f,
        1.0f, 1.0f, 0.0f,

        0.0f, 1.0f, 0.0f,
        0.0f, 1.0f, 0.0f,
        0.0f, 1.0f, 0.0f,
        0.0f, 1.0f, 0.0f,

        1.0f, 0.0f, 1.0f,
        1.0f, 0.0f, 1.0f,
        1.0f, 0.0f, 1.0f,
        1.0f, 0.0f, 1.0f,

        0.0f, 1.0f, 1.0f,
        0.0f, 1.0f, 1.0f,
        0.0f, 1.0f, 1.0f,
        0.0f, 1.0f, 1.0f,

        0.0f, 0.0f, 1.0f,
        0.0f, 0.0f, 1.0f,
        0.0f, 0.0f, 1.0f,
        0.0f, 0.0f, 1.0f
    };

    GLuint indices[] = {
        0,1,3,
        3,1,2,
        4,5,7,
        7,5,6,
        8,9,11,
        11,9,10,
        12,13,15,
        15,13,14,
        16,17,19,
        19,17,18,
        20,21,23,
        23,21,22

    };

    GLuint vao;
    GLuint vbo1;
    GLuint vbo2;
    GLuint vbo3;

    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);

    glGenBuffers(1, &vbo1);
    glBindBuffer(GL_ARRAY_BUFFER, vbo1);
    glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 3 * 6 * 4, vertices, GL_STATIC_DRAW);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
    glBindBuffer(GL_ARRAY_BUFFER, 0);

    glGenBuffers(1, &vbo2);
    glBindBuffer(GL_ARRAY_BUFFER, vbo2);
    glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 3 * 6 * 4, colors, GL_STATIC_DRAW);
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, 0);
    glBindBuffer(GL_ARRAY_BUFFER, 0);

    glGenBuffers(1, &vbo3);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo3);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLint) * 3 * 6 * 2, indices, GL_STATIC_DRAW);

    glBindVertexArray(0);

    std::string vertSource = "";

    vertSource += "#version 330 core\n";

    vertSource += "in vec3 position;\n";
    vertSource += "in vec3 color;\n";
    vertSource += "uniform mat4 rx;\n";
    vertSource += "uniform mat4 ry;\n";
    vertSource += "uniform mat4 rz;\n";
    vertSource += "uniform mat4 modelview;\n";
    vertSource += "uniform mat4 projection;\n";

    vertSource += "out vec3 color_vary;\n";

    vertSource += "void main(void) {\n";
    vertSource += "gl_Position = projection * modelview * rx * ry * rz * vec4(position.xyz, 1);\n";
    vertSource += "color_vary = color;\n";
    vertSource += "}\n";

    std::string fragSource = "";

    fragSource += "#version 330 core\n";
    fragSource += "out vec4 out_color;\n";

    fragSource += "in vec3 color_vary;\n";

    fragSource += "void main(void) {\n";

    fragSource += "out_color = vec4(color_vary.xyz, 1.0);\n";

    fragSource += "}\n";

    GLuint vertShader = glCreateShader(GL_VERTEX_SHADER);
    GLuint fragShader = glCreateShader(GL_FRAGMENT_SHADER);
    GLchar* shadersource = (GLchar*)vertSource.c_str();
    glShaderSource(vertShader, 1, &shadersource, 0);
    shadersource = (GLchar*)fragSource.c_str();
    glShaderSource(fragShader, 1, &shadersource, 0);

    glCompileShader(vertShader);

    GLint compiled = 0;
    glGetShaderiv(vertShader, GL_COMPILE_STATUS, &compiled);
    if (compiled == GL_FALSE) {
        GLint maxLength = 0;
        glGetShaderiv(vertShader, GL_INFO_LOG_LENGTH, &maxLength);

        GLchar* message = (GLchar*)malloc(sizeof(GLchar)*maxLength);
        glGetShaderInfoLog(vertShader, maxLength, &maxLength, message);

        std::cout << "Vertex Shader failed to compile:\n";
        std::cout << message << "\n";

        glDeleteShader(vertShader);
        return -1;
    }

    glCompileShader(fragShader);

    glGetShaderiv(fragShader, GL_COMPILE_STATUS, &compiled);
    if (compiled == GL_FALSE) {
        GLint maxLength = 0;
        glGetShaderiv(fragShader, GL_INFO_LOG_LENGTH, &maxLength);

        GLchar* message = (GLchar*)malloc(sizeof(GLchar)*maxLength);
        glGetShaderInfoLog(fragShader, maxLength, &maxLength, message);

        std::cout << "Fragment Shader failed to compile:\n";
        std::cout << message << "\n";

        glDeleteShader(fragShader);
        return -1;
    }

    GLuint shaderProgram = glCreateProgram();

    glAttachShader(shaderProgram, vertShader);
    glAttachShader(shaderProgram, fragShader);

    glBindAttribLocation(shaderProgram, 0, "position");
    glBindAttribLocation(shaderProgram, 1, "color");

    glLinkProgram(shaderProgram);
    glValidateProgram(shaderProgram);

    GLuint projectionLoc = glGetUniformLocation(shaderProgram, "projection");
    GLuint modelviewLoc = glGetUniformLocation(shaderProgram, "modelview");
    GLuint rxLoc = glGetUniformLocation(shaderProgram, "rx");
    GLuint ryLoc = glGetUniformLocation(shaderProgram, "ry");
    GLuint rzLoc = glGetUniformLocation(shaderProgram, "rz");

    float* modelview = new float[16];
    modelview[0] = 2;
    modelview[1] = 0;
    modelview[2] = 0;
    modelview[3] = 0;

    modelview[4] = 0;
    modelview[5] = 2;
    modelview[6] = 0;
    modelview[7] = 0;

    modelview[8] = 0;
    modelview[9] = 0;
    modelview[10] = 1;
    modelview[11] = 0;

    modelview[12] = 0;
    modelview[13] = 0;
    modelview[14] = -4;
    modelview[15] = 1;

    float xtheta = 0;
    float ytheta = 45;
    float ztheta = 0;

    float cx = cos(xtheta*DEG_TO_RAD);
    float sx = sin(xtheta*DEG_TO_RAD);
    float cy = cos(ytheta*DEG_TO_RAD);
    float sy = sin(ytheta*DEG_TO_RAD);
    float cz = cos(ztheta*DEG_TO_RAD);
    float sz = sin(ztheta*DEG_TO_RAD);

    float* rx = new float[16];
    rx[0] = 1;
    rx[1] = 0;
    rx[2] = 0;
    rx[3] = 0;

    rx[4] = 0;
    rx[5] = cx;
    rx[6] = sx;
    rx[7] = 0;

    rx[8] = 0;
    rx[9] = -sx;
    rx[10] = cx;
    rx[11] = 0;

    rx[12] = 0;
    rx[13] = 0;
    rx[14] = 0;
    rx[15] = 1;

    float* ry = new float[16];
    ry[0] = cy;
    ry[1] = 0;
    ry[2] = -sy;
    ry[3] = 0;

    ry[4] = 0;
    ry[5] = 1;
    ry[6] = 0;
    ry[7] = 0;

    ry[8] = sy;
    ry[9] = 0;
    ry[10] = cy;
    ry[11] = 0;

    ry[12] = 0;
    ry[13] = 0;
    ry[14] = 0;
    ry[15] = 1;

    float* rz = new float[16];
    rz[0] = cz;
    rz[1] = sz;
    rz[2] = 0;
    rz[3] = 0;

    rz[4] = -sz;
    rz[5] = cz;
    rz[6] = 0;
    rz[7] = 0;

    rz[8] = 0;
    rz[9] = 0;
    rz[10] = 1;
    rz[11] = 0;

    rz[12] = 0;
    rz[13] = 0;
    rz[14] = 0;
    rz[15] = 1;

    float aspect = 1;
    float fov = 80;
    float far = 1000;
    float near = 0.01f;

    float t = tan(DEG_TO_RAD*fov/2);

    float* projection = new float[16];
    projection[0] = 1/(t*aspect);
    projection[1] = 0;
    projection[2] = 0;
    projection[3] = 0;

    projection[4] = 0;
    projection[5] = 1/t;
    projection[6] = 0;
    projection[7] = 0;

    projection[8] = 0;
    projection[9] = 0;
    projection[10] = -(far + near)/(far - near);
    projection[11] = -1;

    projection[12] = 0;
    projection[13] = 0;
    projection[14] = -(2*far*near)/(far - near);
    projection[15] = 0;

    glUseProgram(shaderProgram);

    glUniformMatrix4fv(rxLoc, 1, false, rx);
    glUniformMatrix4fv(ryLoc, 1, false, ry);
    glUniformMatrix4fv(rzLoc, 1, false, rz);
    glUniformMatrix4fv(modelviewLoc, 1, false, modelview);
    glUniformMatrix4fv(projectionLoc, 1, false, projection);

    glUseProgram(0);

    GLPanel panel({ 10, 290, 300, 300 }, {300, 300}, layout,
                  [&]()->void { //Render function
                      glEnable(GL_DEPTH_TEST);
                      glClearColor(0.2f, 0.3f, 0.8f, 1);
                      glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

                     float rotSpeed = 30;

                      xtheta = glfwGetTime() * rotSpeed / 1;
                      ytheta = glfwGetTime() * rotSpeed / 2;
                      ztheta = glfwGetTime() * rotSpeed / 3;

                      cx = cos(xtheta*DEG_TO_RAD);
                      sx = sin(xtheta*DEG_TO_RAD);
                      cy = cos(ytheta*DEG_TO_RAD);
                      sy = sin(ytheta*DEG_TO_RAD);
                      cz = cos(ztheta*DEG_TO_RAD);
                      sz = sin(ztheta*DEG_TO_RAD);

                      rx[5] = cx;
                      rx[6] = sx;
                      rx[9] = -sx;
                      rx[10] = cx;

                      ry[0] = cy;
                      ry[2] = -sy;
                      ry[8] = sy;
                      ry[10] = cy;

                      rz[0] = cz;
                      rz[1] = sz;
                      rz[4] = -sz;
                      rz[5] = cz;

                      glBindVertexArray(vao);
                      glEnableVertexAttribArray(0);
                      glEnableVertexAttribArray(1);

                      glUseProgram(shaderProgram);

                      glUniformMatrix4fv(rxLoc, 1, false, rx);
                      glUniformMatrix4fv(ryLoc, 1, false, ry);
                      glUniformMatrix4fv(rzLoc, 1, false, rz);

                      glDrawElements(GL_TRIANGLES, 6*6, GL_UNSIGNED_INT, 0);

                      glUseProgram(0);

                      glDisableVertexAttribArray(0);
                      glDisableVertexAttribArray(1);
                      glBindVertexArray(0);
                  },
                  [](GLPanelMouseData* data)->void {

                  }, theme);

    CheckBoxDescriptor checkBoxDesc = {
        { 30, font30 },
        3,
        false,
        theme
    };

    CheckBox checkBox({100, 200, 30, 30}, layout, "toggle", checkBoxDesc);
	while (win.isOpen()) {
		win.poll();

        button.poll();
        textBox.poll();
        textBox2.poll();
        panel.poll();
        checkBox.poll();

		Renderer::clear(color::grey);

		Renderer::beginDraw();

        button.render();
        textBox.render();
        textBox2.render();
        panel.render();
        checkBox.render();

		Renderer::endDraw();

		win.swap();
	}

	win.destroy();

	GLUI::destroy();

	return 0;
}
<|endoftext|>


<commit_before>/*
    Copyright (C) 2012  Dan Vratil <dvratil@redhat.com>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "kcm_kscreen.h"
#include "widget.h"

#include <KPluginFactory>
#include <KAboutData>
#include <KMessageBox>
#include <KLocalizedString>

#include <QHBoxLayout>
#include <QTimer>
#include <qstandardpaths.h>
#include <QLabel>

#include <QQuickView>

#include <kscreen/config.h>
#include <kscreen/output.h>
#include <kscreen/getconfigoperation.h>
#include <kscreen/setconfigoperation.h>

#include <qquickitem.h>

K_PLUGIN_FACTORY(KCMDisplayConfigurationFactory, registerPlugin<KCMKScreen>();)

using namespace KScreen;

Q_DECLARE_METATYPE(KScreen::OutputPtr)
Q_DECLARE_METATYPE(KScreen::ScreenPtr)

KCMKScreen::KCMKScreen(QWidget* parent, const QVariantList& args)
    : KCModule(parent, args)
    , mKScreenWidget(0)
{
    setButtons(Apply | Default);

    KAboutData* about =
        new KAboutData(QStringLiteral("kcm_kscreen"),
                    i18n("Display Configuration"),
                    QString(KSCREEN_VERSION), i18n("Configuration for displays"),
                    KAboutLicense::GPL_V2, i18n("(c), 2012-2013 Daniel Vrátil"));

    about->addAuthor(i18n("Daniel Vrátil"), i18n("Maintainer") , QStringLiteral("dvratil@redhat.com"));
    setAboutData(about);

    setSizePolicy(QSizePolicy::Preferred, QSizePolicy::MinimumExpanding);
}

void KCMKScreen::configReady(ConfigOperation* op)
{
    QHBoxLayout *layout = new QHBoxLayout(this);

    if (op->hasError()) {
        mKScreenWidget = 0;
        delete mKScreenWidget;
        QLabel *errorLabel = new QLabel(this);
        layout->addWidget(errorLabel);
        errorLabel->setText(i18n("No kscreen backend found. Please check your kscreen installation."));
        return;
    }

    if (!mKScreenWidget) {
        mKScreenWidget = new Widget(this);
        layout->addWidget(mKScreenWidget);
        connect(mKScreenWidget, SIGNAL(changed()),
                this, SLOT(changed()));
    }

    mKScreenWidget->setConfig(qobject_cast<GetConfigOperation*>(op)->config());
}

KCMKScreen::~KCMKScreen()
{
}

void KCMKScreen::save()
{
    qDebug() << "Saving";

    if (!mKScreenWidget) {
        return;
    }

    const KScreen::ConfigPtr &config = mKScreenWidget->currentConfig();

    bool atLeastOneEnabledOutput = false;
    Q_FOREACH(const KScreen::OutputPtr &output, config->outputs()) {
        KScreen::ModePtr mode = output->currentMode();

        if (output->isEnabled()) {
            atLeastOneEnabledOutput = true;
        }

        qDebug() << output->name() << output->id() << output.data() << "\n"
                << "	Connected:" << output->isConnected() << "\n"
                << "	Enabled:" << output->isEnabled() << "\n"
                << "	Primary:" << output->isPrimary() << "\n"
                << "	Rotation:" << output->rotation() << "\n"
                << "	Mode:" << (mode ? mode->name() : QStringLiteral("unknown")) << "@" << (mode ? mode->refreshRate() : 0.0) << "Hz" << "\n"
                << "    Position:" << output->pos().x() << "x" << output->pos().y();
    }

    if (!atLeastOneEnabledOutput) {
        if (KMessageBox::warningYesNo(this, i18n("Are you sure you want to disable all outputs?"),
            i18n("Disable All Outputs"),
            KGuiItem(i18n("&Disable All Outputs"), QIcon::fromTheme(QLatin1String("dialog-ok-apply"))),
            KGuiItem(i18n("&Reconfigure"), QIcon::fromTheme(QLatin1String("dialog-cancel"))),
            QString(), KMessageBox::Dangerous) == KMessageBox::No)
        {
            return;
        }
    }

    if (!Config::canBeApplied(config)) {
        KMessageBox::information(this,
            i18n("Sorry, your configuration could not be applied.\n\n"
                 "Common reasons are that the overall screen size is too big, or you enabled more displays than supported by your GPU."),
                 i18n("Unsupported configuration"));
        return;
    }

    /* Store the current config, apply settings */
    auto *op = new SetConfigOperation(config);
    /* Block until the operation is completed, otherwise KCMShell will terminate
     * before we get to execute the Operation */
    op->exec();
}

void KCMKScreen::defaults()
{
    qDebug() << "LOAD";
    load();
}

void KCMKScreen::load()
{
    qDebug() << "LOAD";
    connect(new GetConfigOperation(), &GetConfigOperation::finished,
            this, &KCMKScreen::configReady);
}

#include "kcm_kscreen.moc"
<commit_msg>kcm: Add i18n semantic context @title:window to dialog boxes<commit_after>/*
    Copyright (C) 2012  Dan Vratil <dvratil@redhat.com>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "kcm_kscreen.h"
#include "widget.h"

#include <KPluginFactory>
#include <KAboutData>
#include <KMessageBox>
#include <KLocalizedString>

#include <QHBoxLayout>
#include <QTimer>
#include <qstandardpaths.h>
#include <QLabel>

#include <QQuickView>

#include <kscreen/config.h>
#include <kscreen/output.h>
#include <kscreen/getconfigoperation.h>
#include <kscreen/setconfigoperation.h>

#include <qquickitem.h>

K_PLUGIN_FACTORY(KCMDisplayConfigurationFactory, registerPlugin<KCMKScreen>();)

using namespace KScreen;

Q_DECLARE_METATYPE(KScreen::OutputPtr)
Q_DECLARE_METATYPE(KScreen::ScreenPtr)

KCMKScreen::KCMKScreen(QWidget* parent, const QVariantList& args)
    : KCModule(parent, args)
    , mKScreenWidget(0)
{
    setButtons(Apply | Default);

    KAboutData* about =
        new KAboutData(QStringLiteral("kcm_kscreen"),
                    i18n("Display Configuration"),
                    QString(KSCREEN_VERSION), i18n("Configuration for displays"),
                    KAboutLicense::GPL_V2, i18n("(c), 2012-2013 Daniel Vrátil"));

    about->addAuthor(i18n("Daniel Vrátil"), i18n("Maintainer") , QStringLiteral("dvratil@redhat.com"));
    setAboutData(about);

    setSizePolicy(QSizePolicy::Preferred, QSizePolicy::MinimumExpanding);
}

void KCMKScreen::configReady(ConfigOperation* op)
{
    QHBoxLayout *layout = new QHBoxLayout(this);

    if (op->hasError()) {
        mKScreenWidget = 0;
        delete mKScreenWidget;
        QLabel *errorLabel = new QLabel(this);
        layout->addWidget(errorLabel);
        errorLabel->setText(i18n("No kscreen backend found. Please check your kscreen installation."));
        return;
    }

    if (!mKScreenWidget) {
        mKScreenWidget = new Widget(this);
        layout->addWidget(mKScreenWidget);
        connect(mKScreenWidget, SIGNAL(changed()),
                this, SLOT(changed()));
    }

    mKScreenWidget->setConfig(qobject_cast<GetConfigOperation*>(op)->config());
}

KCMKScreen::~KCMKScreen()
{
}

void KCMKScreen::save()
{
    qDebug() << "Saving";

    if (!mKScreenWidget) {
        return;
    }

    const KScreen::ConfigPtr &config = mKScreenWidget->currentConfig();

    bool atLeastOneEnabledOutput = false;
    Q_FOREACH(const KScreen::OutputPtr &output, config->outputs()) {
        KScreen::ModePtr mode = output->currentMode();

        if (output->isEnabled()) {
            atLeastOneEnabledOutput = true;
        }

        qDebug() << output->name() << output->id() << output.data() << "\n"
                << "	Connected:" << output->isConnected() << "\n"
                << "	Enabled:" << output->isEnabled() << "\n"
                << "	Primary:" << output->isPrimary() << "\n"
                << "	Rotation:" << output->rotation() << "\n"
                << "	Mode:" << (mode ? mode->name() : QStringLiteral("unknown")) << "@" << (mode ? mode->refreshRate() : 0.0) << "Hz" << "\n"
                << "    Position:" << output->pos().x() << "x" << output->pos().y();
    }

    if (!atLeastOneEnabledOutput) {
        if (KMessageBox::warningYesNo(this, i18n("Are you sure you want to disable all outputs?"),
            i18nc("@title:window", "Disable All Outputs"),
            KGuiItem(i18n("&Disable All Outputs"), QIcon::fromTheme(QLatin1String("dialog-ok-apply"))),
            KGuiItem(i18n("&Reconfigure"), QIcon::fromTheme(QLatin1String("dialog-cancel"))),
            QString(), KMessageBox::Dangerous) == KMessageBox::No)
        {
            return;
        }
    }

    if (!Config::canBeApplied(config)) {
        KMessageBox::information(this,
            i18n("Sorry, your configuration could not be applied.\n\n"
                 "Common reasons are that the overall screen size is too big, or you enabled more displays than supported by your GPU."),
                 i18nc("@title:window", "Unsupported Configuration"));
        return;
    }

    /* Store the current config, apply settings */
    auto *op = new SetConfigOperation(config);
    /* Block until the operation is completed, otherwise KCMShell will terminate
     * before we get to execute the Operation */
    op->exec();
}

void KCMKScreen::defaults()
{
    qDebug() << "LOAD";
    load();
}

void KCMKScreen::load()
{
    qDebug() << "LOAD";
    connect(new GetConfigOperation(), &GetConfigOperation::finished,
            this, &KCMKScreen::configReady);
}

#include "kcm_kscreen.moc"
<|endoftext|>


<commit_before>/*
 * KDots
 * Copyright (c) 2011, 2012, 2014, 2015 Minh Ngo <minh@fedoraproject.org>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. 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.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
 */
#include "boardmodel.hpp"
#include "boardmodel_p.hpp"

#include <QDebug>

#include <KMessageBox>
#include <KLocalizedString>

#include <interface/irival.hpp>

#include "iboardview.hpp"
#include "graph.hpp"
#include "polygonfinder.hpp"
#include "stepqueue.hpp"

namespace KDots
{
  BoardModelPrivate::BoardModelPrivate(const GameConfig& config,
                                       std::unique_ptr<StepQueue>&& step_queue,
                                       BoardModel *parent)
    : QObject(parent)
    , m_graph(new Graph(config.m_width, config.m_height))
    , m_steps(std::move(step_queue))
    , m_config(config)
    , q_ptr(parent)
  {
  }

  void BoardModelPrivate::drawPolygon(PolyList polygons)
  {
    for (Polygon_ptr& polygon : polygons)
    {
      if (!polygon->isFilled())
        continue;

      polygon->setOwner(m_steps->getCurrentOwner());
      m_polygons.push_back(polygon);

      Point prevPoint = polygon->points().back();

      for (const Point& currPoint : polygon->points())
      {
        m_graph->addEdge(prevPoint, currPoint);
        prevPoint = currPoint;
      }
    }
  }

  namespace
  {
    QString getResult(int firstPoints, int secondPoints)
    {
      if (firstPoints > secondPoints)
        return i18n("The first player win!");

      if (firstPoints < secondPoints)
        return i18n("The second player win!");

      return i18n("Dead heat!");
    }
  }

  void BoardModelPrivate::continueStep()
  {
    const auto& allPoints = m_steps->getAllPoints();
    if (allPoints.size() + m_steps->emptyCapturedCount() == m_graph->width() * m_graph->height())
    {
      const int first = m_steps->getMarks(Owner::FIRST);
      const int second = m_steps->getMarks(Owner::SECOND);

      const QString& message = getResult(first, second);
      KMessageBox::information(0, message, message);
      return;
    }

    m_steps->nextStep();
  }

  void BoardModelPrivate::emitStatus()
  {
    const QString& firstMark = QString::number(m_steps->getMarks(Owner::FIRST));
    const QString& secondMark = QString::number(m_steps->getMarks(Owner::SECOND));

    Q_Q(BoardModel);
    emit q->statusUpdated(QString::fromAscii("First:\t%1\tSecond:\t%2").arg(firstMark, secondMark));
  }

  void BoardModelPrivate::addPoint(const Point& point)
  {
    Q_Q(BoardModel);

    if (sender() == m_rival.get())
    {
      if (m_rival->owner() != m_steps->getCurrentOwner())
        return;
    }
    else
    {
      if (m_rival->owner() == m_steps->getCurrentOwner())
        return;
    }

    Graph& graph = *m_graph;
    GraphPoint& currentPoint = graph[point];

    if (currentPoint.owner() != Owner::NONE || currentPoint.isCaptured())
      return;

    const Owner current = m_steps->getCurrentOwner();

    currentPoint.setOwner(current);

    m_steps->addPoint(point);

    PolygonFinder findPolygon(graph, current);

    //O(n)
    const PolyList& polyList = findPolygon(point);

    const auto& points = m_steps->getPoints(StepQueue::other(current));
    if (points.empty() || polyList.empty())
    {
      continueStep();
      emitStatus();
      emit q->pointAdded(point);
      return;
    }

    const Owner otherOwner = StepQueue::other(current);

    const auto& otherOwnerPoints = m_steps->getPoints(otherOwner);
    for (const Point& p : otherOwnerPoints)
    {
      GraphPoint& gpoint = graph[p];
      if (gpoint.isCaptured())
        continue;

      for (const Polygon_ptr& polygon : polyList)
      {
        if (polygon->contains(p))
        {
          if (gpoint.owner() == otherOwner)
          {
            polygon->setFilled(true);
            m_steps->addCaptured();
          }

          gpoint.capture();
          break;
        }
      }
    }

    for (Graph::iterator itr = graph.begin(), itrEnd = graph.end();
        itr != itrEnd; ++itr)
    {
      if (itr->isCaptured() || itr->owner() != Owner::NONE)
        continue;

      for (const Polygon_ptr& polygon : polyList)
      {
        const Point& newPoint = itr.point();

        if (polygon->contains(newPoint) && polygon->isFilled())
        {
          itr->capture();
          m_steps->addEmptyCaptured();
          break;
        }
      }
    }

    drawPolygon(polyList);

    continueStep();
    emitStatus();
    emit q->pointAdded(point);
  }

  //////////////////////////////////////////////////////////////////////////////

  BoardModel::BoardModel(const GameConfig& config,
                         std::unique_ptr<StepQueue>&& step_queue,
                         QObject *parent)
    : QObject(parent)
    , d_ptr(new BoardModelPrivate(config, std::move(step_queue), this))
  {
  }

  BoardModel::~BoardModel()
  {
  }

  void BoardModel::setView(std::unique_ptr<IBoardView>&& view)
  {
    Q_D(BoardModel);
    d->m_view = std::move(view);
    d->m_view->setModel(this);

    connect(d->m_view.get(), SIGNAL(pointClicked(const Point&)),
            d, SLOT(addPoint(const Point&)));
  }

  void BoardModel::setRival(std::unique_ptr<IRival>&& rival)
  {
    Q_D(BoardModel);
    d->m_rival = std::move(rival);

    connect(this, SIGNAL(pointAdded(const Point&)),
            d->m_rival.get(), SLOT(onPointAdded(const Point&)));
    connect(d->m_rival.get(), SIGNAL(needAddPoint(const Point&)),
            d, SLOT(addPoint(const Point&)));

    d->m_rival->setBoardModel(this);
  }

  const GameConfig& BoardModel::gameConfig() const
  {
    Q_D(const BoardModel);
    return d->m_config;
  }

  //Hardcore undo process
  void BoardModel::undo()
  {
    Q_D(BoardModel);
    emit freezeView(true);
    d->m_graph.reset(new Graph(d->m_config.m_width, d->m_config.m_height));
    d->m_polygons.clear();
    auto points(d->m_steps->getAllPoints());

    if (!points.empty())
      points.pop_back();
    d->m_steps->clear();

    for (const Point& point : points)
      d->addPoint(point);

    emit freezeView(false);
  }

  const std::vector<Polygon_ptr>& BoardModel::polygons() const
  {
    Q_D(const BoardModel);
    return d->m_polygons;
  }

  const Graph& BoardModel::graph() const
  {
    Q_D(const BoardModel);
    return *d->m_graph;
  }

  const StepQueue& BoardModel::stepQueue() const
  {
    Q_D(const BoardModel);
    return *d->m_steps;
  }
}

#include "moc_boardmodel.cpp"
#include "moc_boardmodel_p.cpp"
<commit_msg>Adding a string that needs to be translated<commit_after>/*
 * KDots
 * Copyright (c) 2011, 2012, 2014, 2015 Minh Ngo <minh@fedoraproject.org>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. 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.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
 */
#include "boardmodel.hpp"
#include "boardmodel_p.hpp"

#include <QDebug>

#include <KMessageBox>
#include <KLocalizedString>

#include <interface/irival.hpp>

#include "iboardview.hpp"
#include "graph.hpp"
#include "polygonfinder.hpp"
#include "stepqueue.hpp"

namespace KDots
{
  BoardModelPrivate::BoardModelPrivate(const GameConfig& config,
                                       std::unique_ptr<StepQueue>&& step_queue,
                                       BoardModel *parent)
    : QObject(parent)
    , m_graph(new Graph(config.m_width, config.m_height))
    , m_steps(std::move(step_queue))
    , m_config(config)
    , q_ptr(parent)
  {
  }

  void BoardModelPrivate::drawPolygon(PolyList polygons)
  {
    for (Polygon_ptr& polygon : polygons)
    {
      if (!polygon->isFilled())
        continue;

      polygon->setOwner(m_steps->getCurrentOwner());
      m_polygons.push_back(polygon);

      Point prevPoint = polygon->points().back();

      for (const Point& currPoint : polygon->points())
      {
        m_graph->addEdge(prevPoint, currPoint);
        prevPoint = currPoint;
      }
    }
  }

  namespace
  {
    QString getResult(int firstPoints, int secondPoints)
    {
      if (firstPoints > secondPoints)
        return i18n("The first player win!");

      if (firstPoints < secondPoints)
        return i18n("The second player win!");

      return i18n("Dead heat!");
    }
  }

  void BoardModelPrivate::continueStep()
  {
    const auto& allPoints = m_steps->getAllPoints();
    if (allPoints.size() + m_steps->emptyCapturedCount() == m_graph->width() * m_graph->height())
    {
      const int first = m_steps->getMarks(Owner::FIRST);
      const int second = m_steps->getMarks(Owner::SECOND);

      const QString& message = getResult(first, second);
      KMessageBox::information(0, message, message);
      return;
    }

    m_steps->nextStep();
  }

  void BoardModelPrivate::emitStatus()
  {
    const QString& firstMark = QString::number(m_steps->getMarks(Owner::FIRST));
    const QString& secondMark = QString::number(m_steps->getMarks(Owner::SECOND));

    Q_Q(BoardModel);
    emit q->statusUpdated(i18n("First:\t%1\tSecond:\t%2").arg(firstMark, secondMark));
  }

  void BoardModelPrivate::addPoint(const Point& point)
  {
    Q_Q(BoardModel);

    if (sender() == m_rival.get())
    {
      if (m_rival->owner() != m_steps->getCurrentOwner())
        return;
    }
    else
    {
      if (m_rival->owner() == m_steps->getCurrentOwner())
        return;
    }

    Graph& graph = *m_graph;
    GraphPoint& currentPoint = graph[point];

    if (currentPoint.owner() != Owner::NONE || currentPoint.isCaptured())
      return;

    const Owner current = m_steps->getCurrentOwner();

    currentPoint.setOwner(current);

    m_steps->addPoint(point);

    PolygonFinder findPolygon(graph, current);

    //O(n)
    const PolyList& polyList = findPolygon(point);

    const auto& points = m_steps->getPoints(StepQueue::other(current));
    if (points.empty() || polyList.empty())
    {
      continueStep();
      emitStatus();
      emit q->pointAdded(point);
      return;
    }

    const Owner otherOwner = StepQueue::other(current);

    const auto& otherOwnerPoints = m_steps->getPoints(otherOwner);
    for (const Point& p : otherOwnerPoints)
    {
      GraphPoint& gpoint = graph[p];
      if (gpoint.isCaptured())
        continue;

      for (const Polygon_ptr& polygon : polyList)
      {
        if (polygon->contains(p))
        {
          if (gpoint.owner() == otherOwner)
          {
            polygon->setFilled(true);
            m_steps->addCaptured();
          }

          gpoint.capture();
          break;
        }
      }
    }

    for (Graph::iterator itr = graph.begin(), itrEnd = graph.end();
        itr != itrEnd; ++itr)
    {
      if (itr->isCaptured() || itr->owner() != Owner::NONE)
        continue;

      for (const Polygon_ptr& polygon : polyList)
      {
        const Point& newPoint = itr.point();

        if (polygon->contains(newPoint) && polygon->isFilled())
        {
          itr->capture();
          m_steps->addEmptyCaptured();
          break;
        }
      }
    }

    drawPolygon(polyList);

    continueStep();
    emitStatus();
    emit q->pointAdded(point);
  }

  //////////////////////////////////////////////////////////////////////////////

  BoardModel::BoardModel(const GameConfig& config,
                         std::unique_ptr<StepQueue>&& step_queue,
                         QObject *parent)
    : QObject(parent)
    , d_ptr(new BoardModelPrivate(config, std::move(step_queue), this))
  {
  }

  BoardModel::~BoardModel()
  {
  }

  void BoardModel::setView(std::unique_ptr<IBoardView>&& view)
  {
    Q_D(BoardModel);
    d->m_view = std::move(view);
    d->m_view->setModel(this);

    connect(d->m_view.get(), SIGNAL(pointClicked(const Point&)),
            d, SLOT(addPoint(const Point&)));
  }

  void BoardModel::setRival(std::unique_ptr<IRival>&& rival)
  {
    Q_D(BoardModel);
    d->m_rival = std::move(rival);

    connect(this, SIGNAL(pointAdded(const Point&)),
            d->m_rival.get(), SLOT(onPointAdded(const Point&)));
    connect(d->m_rival.get(), SIGNAL(needAddPoint(const Point&)),
            d, SLOT(addPoint(const Point&)));

    d->m_rival->setBoardModel(this);
  }

  const GameConfig& BoardModel::gameConfig() const
  {
    Q_D(const BoardModel);
    return d->m_config;
  }

  //Hardcore undo process
  void BoardModel::undo()
  {
    Q_D(BoardModel);
    emit freezeView(true);
    d->m_graph.reset(new Graph(d->m_config.m_width, d->m_config.m_height));
    d->m_polygons.clear();
    auto points(d->m_steps->getAllPoints());

    if (!points.empty())
      points.pop_back();
    d->m_steps->clear();

    for (const Point& point : points)
      d->addPoint(point);

    emit freezeView(false);
  }

  const std::vector<Polygon_ptr>& BoardModel::polygons() const
  {
    Q_D(const BoardModel);
    return d->m_polygons;
  }

  const Graph& BoardModel::graph() const
  {
    Q_D(const BoardModel);
    return *d->m_graph;
  }

  const StepQueue& BoardModel::stepQueue() const
  {
    Q_D(const BoardModel);
    return *d->m_steps;
  }
}

#include "moc_boardmodel.cpp"
#include "moc_boardmodel_p.cpp"
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2014 Pavel Kirienko <pavel.kirienko@gmail.com>
 */

#include <uavcan/protocol/node_status_provider.hpp>
#include <uavcan/debug.hpp>
#include <cassert>

namespace uavcan
{

bool NodeStatusProvider::isNodeInfoInitialized() const
{
    // Hardware/Software versions are not required
    return !node_info_.name.empty();
}

int NodeStatusProvider::publish()
{
    const MonotonicDuration uptime = getNode().getMonotonicTime() - creation_timestamp_;
    UAVCAN_ASSERT(uptime.isPositive());
    node_info_.status.uptime_sec = uptime.toMSec() / 1000;

    UAVCAN_ASSERT(node_info_.status.status_code <= protocol::NodeStatus::FieldTypes::status_code::max());

    return node_status_pub_.broadcast(node_info_.status);
}

void NodeStatusProvider::publishWithErrorHandling()
{
    if (getNode().isPassiveMode())
    {
        UAVCAN_TRACE("NodeStatusProvider", "NodeStatus pub skipped - passive mode");
    }
    else
    {
        const int res = publish();
        if (res < 0)
        {
            getNode().registerInternalFailure("NodeStatus pub failed");
        }
    }
}

void NodeStatusProvider::handleTimerEvent(const TimerEvent&)
{
    publishWithErrorHandling();
}

void NodeStatusProvider::handleGlobalDiscoveryRequest(const protocol::GlobalDiscoveryRequest&)
{
    UAVCAN_TRACE("NodeStatusProvider", "Got GlobalDiscoveryRequest");
    publishWithErrorHandling();
}

void NodeStatusProvider::handleGetNodeInfoRequest(const protocol::GetNodeInfo::Request&,
                                                  protocol::GetNodeInfo::Response& rsp)
{
    UAVCAN_TRACE("NodeStatusProvider", "Got GetNodeInfo request");
    UAVCAN_ASSERT(isNodeInfoInitialized());
    rsp = node_info_;
}

int NodeStatusProvider::startAndPublish()
{
    if (!isNodeInfoInitialized())
    {
        UAVCAN_TRACE("NodeStatusProvider", "Node info was not initialized");
        return -ErrNotInited;
    }

    int res = publish(); // Initial broadcast
    if (res < 0)
    {
        goto fail;
    }

    res = gdr_sub_.start(GlobalDiscoveryRequestCallback(this, &NodeStatusProvider::handleGlobalDiscoveryRequest));
    if (res < 0)
    {
        goto fail;
    }

    res = gni_srv_.start(GetNodeInfoCallback(this, &NodeStatusProvider::handleGetNodeInfoRequest));
    if (res < 0)
    {
        goto fail;
    }

    TimerBase::startPeriodic(MonotonicDuration::fromMSec(protocol::NodeStatus::PUBLICATION_PERIOD_MS));

    return res;

fail:
    UAVCAN_ASSERT(res < 0);
    gdr_sub_.stop();
    gni_srv_.stop();
    TimerBase::stop();
    return res;
}

void NodeStatusProvider::setStatusCode(uint8_t code)
{
    node_info_.status.status_code = code;
}

void NodeStatusProvider::setName(const char* name)
{
    if ((name != NULL) && (*name != '\0') && (node_info_.name.empty()))
    {
        node_info_.name = name;  // The string contents will be copied, not just pointer.
    }
}

void NodeStatusProvider::setSoftwareVersion(const protocol::SoftwareVersion& version)
{
    if (node_info_.software_version == protocol::SoftwareVersion())
    {
        node_info_.software_version = version;
    }
}

void NodeStatusProvider::setHardwareVersion(const protocol::HardwareVersion& version)
{
    if (node_info_.hardware_version == protocol::HardwareVersion())
    {
        node_info_.hardware_version = version;
    }
}

}
<commit_msg>Properly handling the initial node status broadcast in passive mode<commit_after>/*
 * Copyright (C) 2014 Pavel Kirienko <pavel.kirienko@gmail.com>
 */

#include <uavcan/protocol/node_status_provider.hpp>
#include <uavcan/debug.hpp>
#include <cassert>

namespace uavcan
{

bool NodeStatusProvider::isNodeInfoInitialized() const
{
    // Hardware/Software versions are not required
    return !node_info_.name.empty();
}

int NodeStatusProvider::publish()
{
    const MonotonicDuration uptime = getNode().getMonotonicTime() - creation_timestamp_;
    UAVCAN_ASSERT(uptime.isPositive());
    node_info_.status.uptime_sec = uptime.toMSec() / 1000;

    UAVCAN_ASSERT(node_info_.status.status_code <= protocol::NodeStatus::FieldTypes::status_code::max());

    return node_status_pub_.broadcast(node_info_.status);
}

void NodeStatusProvider::publishWithErrorHandling()
{
    if (getNode().isPassiveMode())
    {
        UAVCAN_TRACE("NodeStatusProvider", "NodeStatus pub skipped - passive mode");
    }
    else
    {
        const int res = publish();
        if (res < 0)
        {
            getNode().registerInternalFailure("NodeStatus pub failed");
        }
    }
}

void NodeStatusProvider::handleTimerEvent(const TimerEvent&)
{
    publishWithErrorHandling();
}

void NodeStatusProvider::handleGlobalDiscoveryRequest(const protocol::GlobalDiscoveryRequest&)
{
    UAVCAN_TRACE("NodeStatusProvider", "Got GlobalDiscoveryRequest");
    publishWithErrorHandling();
}

void NodeStatusProvider::handleGetNodeInfoRequest(const protocol::GetNodeInfo::Request&,
                                                  protocol::GetNodeInfo::Response& rsp)
{
    UAVCAN_TRACE("NodeStatusProvider", "Got GetNodeInfo request");
    UAVCAN_ASSERT(isNodeInfoInitialized());
    rsp = node_info_;
}

int NodeStatusProvider::startAndPublish()
{
    if (!isNodeInfoInitialized())
    {
        UAVCAN_TRACE("NodeStatusProvider", "Node info was not initialized");
        return -ErrNotInited;
    }

    int res = -1;

    if (!getNode().isPassiveMode())
    {
        res = publish();
        if (res < 0)  // Initial broadcast
        {
            goto fail;
        }
    }

    res = gdr_sub_.start(GlobalDiscoveryRequestCallback(this, &NodeStatusProvider::handleGlobalDiscoveryRequest));
    if (res < 0)
    {
        goto fail;
    }

    res = gni_srv_.start(GetNodeInfoCallback(this, &NodeStatusProvider::handleGetNodeInfoRequest));
    if (res < 0)
    {
        goto fail;
    }

    TimerBase::startPeriodic(MonotonicDuration::fromMSec(protocol::NodeStatus::PUBLICATION_PERIOD_MS));

    return res;

fail:
    UAVCAN_ASSERT(res < 0);
    gdr_sub_.stop();
    gni_srv_.stop();
    TimerBase::stop();
    return res;
}

void NodeStatusProvider::setStatusCode(uint8_t code)
{
    node_info_.status.status_code = code;
}

void NodeStatusProvider::setName(const char* name)
{
    if ((name != NULL) && (*name != '\0') && (node_info_.name.empty()))
    {
        node_info_.name = name;  // The string contents will be copied, not just pointer.
    }
}

void NodeStatusProvider::setSoftwareVersion(const protocol::SoftwareVersion& version)
{
    if (node_info_.software_version == protocol::SoftwareVersion())
    {
        node_info_.software_version = version;
    }
}

void NodeStatusProvider::setHardwareVersion(const protocol::HardwareVersion& version)
{
    if (node_info_.hardware_version == protocol::HardwareVersion())
    {
        node_info_.hardware_version = version;
    }
}

}
<|endoftext|>