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

  Program:   Insight Segmentation & Registration Toolkit
  Module:    RGBImageSeriesReadWrite.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

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

=========================================================================*/

//  Software Guide : BeginLatex
//
//  RGB images are commonly used for representing data acquired from
//  cryogenic sections, optical microscopy and endoscopy. This example
//  illustrates how to read and write RGB color images to and from a file.
//  This requires the following headers as shown.
//
//  \index{itk::RGBPixel!Image}
//  \index{RGB!writing Image}
//  \index{RGB!reading Image}
//
//  Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
#include "itkRGBPixel.h"
#include "itkImage.h"
#include "itkImageSeriesReader.h"
#include "itkImageFileWriter.h"
#include "itkNumericSeriesFileNames.h"
// Software Guide : EndCodeSnippet

int main( int argc, char ** argv )
{
  // Verify the number of parameters in the command line
  if( argc < 3 )
    {
    std::cerr << "Usage: " << std::endl;
    std::cerr << argv[0] << " inputRGBImageFile  outputRGBImageFile " << std::endl;
    return -1;
    }

  // Software Guide : BeginLatex
  //
  // The \doxygen{RGBPixel} class is templated over the type used to
  // represent each one of the red, green and Blue components. A typical
  // instantiation of the RGB image class might be as follows.
  //
  //  \index{itk::RGBPixel!Instantiation}
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef itk::RGBPixel< unsigned char >   PixelType;
  typedef itk::Image< PixelType, 2 >       ImageType;
  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // The image type is used as a template parameter to instantiate
  // the reader and writer.
  //
  // \index{itk::ImageSeriesReader!RGB Image}
  // \index{itk::ImageFileWriter!RGB Image}
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef itk::ImageSeriesReader< ImageType >  ReaderType;
  typedef itk::ImageFileWriter<   ImageType >  WriterType;

  ReaderType::Pointer reader = ReaderType::New();
  WriterType::Pointer writer = WriterType::New();
  // Software Guide : EndCodeSnippet

  const char * inputFilename  = argv[1];
  const char * outputFilename = argv[2];

  // Software Guide : BeginCodeSnippet
  typedef itk::NumericSeriesFileNames    NameGeneratorType;

  NameGeneratorType::Pointer nameGenerator = NameGeneratorType::New();

  nameGenerator->SetStartIndex( 0 );
  nameGenerator->SetEndIndex( 100 );
  nameGenerator->SetIncrementIndex( 1 );
  nameGenerator->SetSeriesFormat("file%4d.png");
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  The filenames of the input and output files must be provided to the
  //  reader and writer respectively.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  reader->SetFileNames( nameGenerator->GetFileNames()  );
  writer->SetFileName( outputFilename );
  // Software Guide : EndCodeSnippet

  ImageType::Pointer image = reader->GetOutput();
  writer->SetInput( image );

  //  Software Guide : BeginLatex
  //
  //  Finally, execution of the pipeline can be triggered by invoking the
  //  Update() method in the writer.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  writer->Update();
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  You may have noticed that apart from the declaraton of the
  //  \code{PixelType} there is nothing in this code that is specific for RGB
  //  images. All the actions required to support color images are implemented
  //  internally in the \doxygen{ImageIO} objects.
  //
  //  Software Guide : EndLatex

  return 0;
}

<commit_msg>ENH: Code improved. try/catch exception block added. range of slices now      captured from the command line.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    RGBImageSeriesReadWrite.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

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

=========================================================================*/

//  Software Guide : BeginLatex
//
//  RGB images are commonly used for representing data acquired from
//  cryogenic sections, optical microscopy and endoscopy. This example
//  illustrates how to read and write RGB color images to and from a file.
//  This requires the following headers as shown.
//
//  \index{itk::RGBPixel!Image}
//  \index{RGB!writing Image}
//  \index{RGB!reading Image}
//
//  Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
#include "itkRGBPixel.h"
#include "itkImage.h"
#include "itkImageSeriesReader.h"
#include "itkImageFileWriter.h"
#include "itkNumericSeriesFileNames.h"
#include "itkPNGImageIO.h"
// Software Guide : EndCodeSnippet

int main( int argc, char ** argv )
{
  // Verify the number of parameters in the command line
  if( argc < 4 )
    {
    std::cerr << "Usage: " << std::endl;
    std::cerr << argv[0] << "first last  outputRGBImageFile " << std::endl;
    return -1;
    }

  // Software Guide : BeginLatex
  //
  // The \doxygen{RGBPixel} class is templated over the type used to
  // represent each one of the red, green and Blue components. A typical
  // instantiation of the RGB image class might be as follows.
  //
  //  \index{itk::RGBPixel!Instantiation}
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef itk::RGBPixel< unsigned char >        PixelType;
  const unsigned int Dimension = 3;

  typedef itk::Image< PixelType, Dimension >    ImageType;
  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // The image type is used as a template parameter to instantiate
  // the reader and writer.
  //
  // \index{itk::ImageSeriesReader!RGB Image}
  // \index{itk::ImageFileWriter!RGB Image}
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef itk::ImageSeriesReader< ImageType >  ReaderType;
  typedef itk::ImageFileWriter<   ImageType >  WriterType;

  ReaderType::Pointer reader = ReaderType::New();
  WriterType::Pointer writer = WriterType::New();
  // Software Guide : EndCodeSnippet

  const unsigned int first = atoi( argv[1] );
  const unsigned int last  = atoi( argv[2] );

  const char * outputFilename = argv[3];

  // Software Guide : BeginCodeSnippet
  typedef itk::NumericSeriesFileNames    NameGeneratorType;

  NameGeneratorType::Pointer nameGenerator = NameGeneratorType::New();

  nameGenerator->SetStartIndex( first );
  nameGenerator->SetEndIndex( last );
  nameGenerator->SetIncrementIndex( 1 );

  nameGenerator->SetSeriesFormat( "vwe%04d.png" );
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  The ImageIO object that actually performs the read process
  //  is now connected to the ImageSeriesReader.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  reader->SetImageIO( itk::PNGImageIO::New() );
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  The filenames of the input and output files must be provided to the
  //  reader and writer respectively.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  reader->SetFileNames( nameGenerator->GetFileNames()  );

  writer->SetFileName( outputFilename );
  // Software Guide : EndCodeSnippet

  try
    {
    reader->Update();
    }
  catch( itk::ExceptionObject & excp )
    {
    std::cerr << "Error reading the series " << std::endl;
    std::cerr << excp << std::endl;
    }

  ImageType::Pointer image = reader->GetOutput();
  writer->SetInput( image );

  //  Software Guide : BeginLatex
  //
  //  Finally, execution of the pipeline can be triggered by invoking the
  //  Update() method in the writer.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  writer->Update();
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  You may have noticed that apart from the declaraton of the
  //  \code{PixelType} there is nothing in this code that is specific for RGB
  //  images. All the actions required to support color images are implemented
  //  internally in the \doxygen{ImageIO} objects.
  //
  //  Software Guide : EndLatex

  return 0;
}

<|endoftext|>


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

#include "iceoryx_dust/posix_wrapper/message_queue.hpp"
#include "iceoryx_dust/posix_wrapper/named_pipe.hpp"
#include "iceoryx_hoofs/internal/posix_wrapper/unix_domain_socket.hpp"

#include "test.hpp"

#include <chrono>

namespace
{
using namespace ::testing;
using namespace iox;
using namespace iox::posix;
using namespace iox::units::duration_literals;

#if defined(__APPLE__)
using IpcChannelTypes = Types<UnixDomainSocket>;
#elif defined(_WIN32)
using IpcChannelTypes = Types<NamedPipe>;
#elif defined(unix) || defined(__unix) || defined(__unix__)
using IpcChannelTypes = Types<UnixDomainSocket, NamedPipe>;
#else
using IpcChannelTypes = Types<MessageQueue, UnixDomainSocket, NamedPipe>;
#endif

/// NOLINTJUSTIFICATION only used in testing
/// NOLINTBEGIN(hicpp-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays)
constexpr char goodName[] = "channel_test";
constexpr char anotherGoodName[] = "horst";
constexpr char theUnknown[] = "WhoeverYouAre";
constexpr char slashName[] = "/miau";
/// NOLINTEND(hicpp-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays)

/// @req
/// @brief This test suite verifies that the abstract interface IpcChannelType is fulfilled by both the UnixDomainSocket
/// class and the MessageQueue class
/// @pre server and client object are allocated and move to the member object of the fixture
/// @post StdErr is capture and outputed to StdCout
/// @note Specific functionality of the underlying implementations of an IpcChannelType are tested in
/// "UnixDomainSocket_test"
template <typename T>
class IpcChannel_test : public Test
{
  public:
    using IpcChannelType = T;

    void SetUp() override
    {
        IOX_DISCARD_RESULT(IpcChannelType::unlinkIfExists(goodName));

        auto serverResult = IpcChannelType::create(goodName, IpcChannelSide::SERVER, MaxMsgSize, MaxMsgNumber);
        ASSERT_THAT(serverResult.has_error(), Eq(false));
        server = std::move(serverResult.value());
        ::testing::internal::CaptureStderr();

        auto clientResult = IpcChannelType::create(goodName, IpcChannelSide::CLIENT, MaxMsgSize, MaxMsgNumber);
        ASSERT_THAT(clientResult.has_error(), Eq(false));
        client = std::move(clientResult.value());
    }

    void TearDown() override
    {
        std::string output = ::testing::internal::GetCapturedStderr();
        if (Test::HasFailure())
        {
            std::cout << output << std::endl;
        }
    }

    static const size_t MaxMsgSize;
    static constexpr uint64_t MaxMsgNumber = 10U;
    IpcChannelType server;
    IpcChannelType client;
};

template <typename T>
const size_t IpcChannel_test<T>::MaxMsgSize = IpcChannelType::MAX_MESSAGE_SIZE;
template <typename T>
constexpr uint64_t IpcChannel_test<T>::MaxMsgNumber;

#ifdef __clang__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wgnu-zero-variadic-macro-arguments"
#endif
TYPED_TEST_SUITE(IpcChannel_test, IpcChannelTypes);
#ifdef __clang__
#pragma GCC diagnostic pop
#endif

TYPED_TEST(IpcChannel_test, CreateWithTooLargeMessageSizeLeadsToError)
{
    ::testing::Test::RecordProperty("TEST_ID", "c9e63950-e7f1-4efc-9d55-a5c445ee7dee");
    auto serverResult = TestFixture::IpcChannelType::create(
        goodName, IpcChannelSide::SERVER, TestFixture::MaxMsgSize + 1, TestFixture::MaxMsgNumber);
    EXPECT_TRUE(serverResult.has_error());
    ASSERT_THAT(serverResult.get_error(), Eq(IpcChannelError::MAX_MESSAGE_SIZE_EXCEEDED));
}

TYPED_TEST(IpcChannel_test, CreateNoNameLeadsToError)
{
    ::testing::Test::RecordProperty("TEST_ID", "3ffe2cf2-26f4-4b93-8baf-d997dc71e610");
    auto serverResult = TestFixture::IpcChannelType::create("", IpcChannelSide::SERVER);
    EXPECT_TRUE(serverResult.has_error());
    ASSERT_THAT(serverResult.get_error(), Eq(IpcChannelError::INVALID_CHANNEL_NAME));
}

TYPED_TEST(IpcChannel_test, CreateWithLeadingSlashWorks)
{
    ::testing::Test::RecordProperty("TEST_ID", "89340ebd-f80d-480b-833f-da37dff06cef");
    auto serverResult = TestFixture::IpcChannelType::create(slashName, IpcChannelSide::SERVER);
    EXPECT_FALSE(serverResult.has_error());
}

TYPED_TEST(IpcChannel_test, CreateAgainWorks)
{
    ::testing::Test::RecordProperty("TEST_ID", "74f7e785-36fc-418c-9807-3dc95ae8aa91");
    // if there is a leftover from a crashed channel, we can create a new one. This is simulated by creating twice
    auto first = TestFixture::IpcChannelType::create(anotherGoodName, IpcChannelSide::SERVER);
    EXPECT_FALSE(first.has_error());
    auto second = TestFixture::IpcChannelType::create(anotherGoodName, IpcChannelSide::SERVER);
    EXPECT_FALSE(second.has_error());
}

TYPED_TEST(IpcChannel_test, CreateAgainAndEmptyWorks)
{
    ::testing::Test::RecordProperty("TEST_ID", "c6bf30dc-661d-47f9-8365-2cda5ca067f9");
    if (std::is_same<typename TestFixture::IpcChannelType, NamedPipe>::value)
    {
        // A NamedPipe server creates and destroys a pipe only when it was created
        // by itself. It is a normal use case that multiple instances can send
        // or receive concurrently via the same named pipe therefore the ctor of
        // the named pipe does not purge the underlying data.
        return;
    }

    using namespace iox::units;
    using namespace std::chrono;

    auto serverResult = TestFixture::IpcChannelType::create(anotherGoodName, IpcChannelSide::SERVER);
    EXPECT_FALSE(serverResult.has_error());
    auto server = std::move(serverResult.value());

    auto clientResult = TestFixture::IpcChannelType::create(anotherGoodName, IpcChannelSide::CLIENT);
    EXPECT_FALSE(clientResult.has_error());
    auto client = std::move(clientResult.value());

    // send and receive as usual
    std::string message = "Hey, I'm talking to you";
    bool sent = client.send(message).has_error();
    EXPECT_FALSE(sent);

    auto receivedMessage = server.receive();
    ASSERT_THAT(receivedMessage.has_error(), Eq(false));
    EXPECT_EQ(message, *receivedMessage);

    // send a message, create the server again and there is no message
    std::string newMessage = "I'm still talking to you brother";
    sent = client.send(newMessage).has_error();
    EXPECT_FALSE(sent);

    auto second = TestFixture::IpcChannelType::create(anotherGoodName, IpcChannelSide::SERVER);
    EXPECT_FALSE(second.has_error());
    server = std::move(second.value());

    Duration timeout = 100_ms;
    auto received = server.timedReceive(timeout);
    ASSERT_TRUE(received.has_error());
    ASSERT_THAT(received.get_error(), Eq(IpcChannelError::TIMEOUT));
}

TYPED_TEST(IpcChannel_test, ClientWithoutServerLeadsToNoSuchChannelError)
{
    ::testing::Test::RecordProperty("TEST_ID", "6a0f75fc-cb6a-4593-a815-ea587c8e9d9e");
    auto clientResult = TestFixture::IpcChannelType::create(anotherGoodName, IpcChannelSide::CLIENT);
    EXPECT_TRUE(clientResult.has_error());
    ASSERT_THAT(clientResult.get_error(), Eq(IpcChannelError::NO_SUCH_CHANNEL));
}

TYPED_TEST(IpcChannel_test, NotDestroyingServerLeadsToNonOutdatedClient)
{
    ::testing::Test::RecordProperty("TEST_ID", "b3eef376-ae04-425b-aa5e-6b0ec4360253");
    auto serverResult = TestFixture::IpcChannelType::create(anotherGoodName, IpcChannelSide::SERVER);
    EXPECT_FALSE(serverResult.has_error());
    auto server = std::move(serverResult.value());

    auto clientResult = TestFixture::IpcChannelType::create(anotherGoodName, IpcChannelSide::CLIENT);
    EXPECT_FALSE(clientResult.has_error());
    auto client = std::move(clientResult.value());

    auto outdated = client.isOutdated();
    EXPECT_FALSE(outdated.has_error());
    EXPECT_FALSE(outdated.value());
}

TYPED_TEST(IpcChannel_test, DestroyingServerLeadsToOutdatedClient)
{
    ::testing::Test::RecordProperty("TEST_ID", "441c4480-57e7-4607-a7e1-df7a9f2f19d0");
    if (std::is_same<typename TestFixture::IpcChannelType, UnixDomainSocket>::value
        || std::is_same<typename TestFixture::IpcChannelType, NamedPipe>::value
        || std::is_same<typename TestFixture::IpcChannelType, MessageQueue>::value)
    {
        // isOutdated cannot be realized for unix domain sockets, named pipes or message queues
        return;
    }

    auto serverResult = TestFixture::IpcChannelType::create(anotherGoodName, IpcChannelSide::SERVER);
    EXPECT_FALSE(serverResult.has_error());
    auto server = std::move(serverResult.value());

    auto clientResult = TestFixture::IpcChannelType::create(anotherGoodName, IpcChannelSide::CLIENT);
    EXPECT_FALSE(clientResult.has_error());
    auto client = std::move(clientResult.value());

    // destroy the server and the client is outdated
    auto dest = server.destroy();
    ASSERT_FALSE(dest.has_error());

    auto outdated = client.isOutdated();
    EXPECT_FALSE(outdated.has_error());
    EXPECT_TRUE(outdated.value());
}

#if !defined(_WIN32)
// From:
// https://docs.microsoft.com/en-us/windows/win32/memory/sharing-files-and-memory
// The shared memory is not destroyed until every process called CloseHandle on
// that shared memory. If a process as an abnormal termination the kernel calls
// CloseHandle on every open handle, therefore shared memory remains should be
// impossible.
TYPED_TEST(IpcChannel_test, UnlinkExistingOneWorks)
{
    ::testing::Test::RecordProperty("TEST_ID", "ea22483b-4484-4d6d-b2b7-b574eaeb4b95");
    auto first = TestFixture::IpcChannelType::create(anotherGoodName, IpcChannelSide::SERVER);
    EXPECT_FALSE(first.has_error());
    auto ret = TestFixture::IpcChannelType::unlinkIfExists(anotherGoodName);
    ASSERT_FALSE(ret.has_error());
    EXPECT_TRUE(ret.value());
}

TYPED_TEST(IpcChannel_test, UnlinkNonExistingOneWorks)
{
    ::testing::Test::RecordProperty("TEST_ID", "c2ecbedc-be63-4f07-bceb-293d5a82c3cd");
    auto ret = TestFixture::IpcChannelType::unlinkIfExists(theUnknown);
    ASSERT_FALSE(ret.has_error());
    EXPECT_FALSE(ret.value());
}
#endif

TYPED_TEST(IpcChannel_test, SendAndReceiveWorks)
{
    ::testing::Test::RecordProperty("TEST_ID", "76a3df9f-736e-4803-af11-912927c352d4");
    std::string message = "Hey, I'm talking to you";
    bool sent = this->client.send(message).has_error();
    EXPECT_FALSE(sent);

    std::string anotherMessage = "This is a message";
    sent = this->client.send(anotherMessage).has_error();
    EXPECT_FALSE(sent);

    auto receivedMessage = this->server.receive();
    ASSERT_THAT(receivedMessage.has_error(), Eq(false));
    EXPECT_EQ(message, *receivedMessage);

    receivedMessage = this->server.receive();
    ASSERT_THAT(receivedMessage.has_error(), Eq(false));
    EXPECT_EQ(anotherMessage, *receivedMessage);
}

TYPED_TEST(IpcChannel_test, InvalidAfterDestroy)
{
    ::testing::Test::RecordProperty("TEST_ID", "4d878a64-95a4-4f15-8e09-f439c5dbd8eb");
    ASSERT_FALSE(this->client.destroy().has_error());
    ASSERT_FALSE(this->client.isInitialized());
    ASSERT_FALSE(this->server.destroy().has_error());
    ASSERT_FALSE(this->server.isInitialized());
}

TYPED_TEST(IpcChannel_test, SendAfterClientDestroyLeadsToError)
{
    ::testing::Test::RecordProperty("TEST_ID", "dde79f4d-7bb5-4627-8d26-0bbc3dbf4d7d");
    auto dest = this->client.destroy();
    ASSERT_FALSE(dest.has_error());

    std::string message = "Should never be sent";
    bool sendError = this->client.send(message).has_error();
    EXPECT_TRUE(sendError);
}

TYPED_TEST(IpcChannel_test, SendAfterServerDestroyLeadsToError)
{
    ::testing::Test::RecordProperty("TEST_ID", "95919ff0-ffe2-47e1-8a1d-0cb1e1df02df");
    if (std::is_same<typename TestFixture::IpcChannelType, MessageQueue>::value
        || std::is_same<typename TestFixture::IpcChannelType, NamedPipe>::value)
    {
        // NamedPipes are as long opened as long there is one instance
        // We still can send to the message queue is we destroy the server
        // it would be outdated, this is checked in another test
        return;
    }

    auto dest = this->server.destroy();
    ASSERT_FALSE(dest.has_error());

    std::string message = "Try to send me";
    auto sendResult = this->client.send(message);
    EXPECT_TRUE(sendResult.has_error());
}

TYPED_TEST(IpcChannel_test, ReceiveAfterServerDestroyLeadsToError)
{
    ::testing::Test::RecordProperty("TEST_ID", "a704f003-097c-486b-92d3-4284f6b5abbe");
    std::string message = "hello world!";
    bool sendError = this->client.send(message).has_error();
    EXPECT_FALSE(sendError);

    auto dest = this->server.destroy();
    ASSERT_FALSE(dest.has_error());

    bool receiveError = this->server.receive().has_error();
    EXPECT_THAT(receiveError, Eq(true));
}

TYPED_TEST(IpcChannel_test, SendMoreThanAllowedLeadsToError)
{
    ::testing::Test::RecordProperty("TEST_ID", "4e49c2fe-7278-4bc5-b91f-41777287e452");
    std::string shortMessage = "Iceoryx rules.";
    ASSERT_THAT(this->client.send(shortMessage).has_error(), Eq(false));

    std::string longMessage(this->server.MAX_MESSAGE_SIZE + 8, 'x');
    ASSERT_THAT(this->client.send(longMessage).has_error(), Eq(true));

    auto receivedMessage = this->server.receive();
    ASSERT_THAT(receivedMessage.has_error(), Eq(false));
    EXPECT_EQ(shortMessage, receivedMessage.value());
}

TYPED_TEST(IpcChannel_test, SendMaxMessageSizeWorks)
{
    ::testing::Test::RecordProperty("TEST_ID", "f471df17-d49a-43cd-85a9-bbe457cfd012");
    std::string message(this->MaxMsgSize - 1, 'x');
    auto clientReturn = this->client.send(message);
    ASSERT_THAT(clientReturn.has_error(), Eq(false));

    auto receivedMessage = this->server.receive();
    ASSERT_THAT(receivedMessage.has_error(), Eq(false));
    EXPECT_EQ(message, receivedMessage.value());
}

TYPED_TEST(IpcChannel_test, wildCreate)
{
    ::testing::Test::RecordProperty("TEST_ID", "98d6003c-3f1a-4a8b-a524-ec1071bc9527");
    auto result = TestFixture::IpcChannelType::create();
    ASSERT_THAT(result.has_error(), Eq(true));
}

#if !(defined(__APPLE__) || defined(unix) || defined(__unix) || defined(__unix__))
TYPED_TEST(IpcChannel_test, TimedSendWorks)
{
    ::testing::Test::RecordProperty("TEST_ID", "12fe0ee5-37f8-4c34-ba44-ed50872a5fd9");
    using namespace iox::units;
    using namespace std::chrono;

    std::string msg = "ISG rules. And some more                                                                        "
                      "data to have a bit                                                                              "
                      "longer message";

    Duration maxTimeout = 100_ms;

    // send till it breaks
    for (;;)
    {
        auto before = system_clock::now();
        auto result = this->client.timedSend(msg, maxTimeout);
        auto after = system_clock::now();
        if (result.has_error())
        {
            ASSERT_THAT(result.get_error(), Eq(IpcChannelError::TIMEOUT));
            // Do not exceed timeout
            auto timeDiff = units::Duration(after - before);
            EXPECT_GT(timeDiff, maxTimeout);

            break;
        }
    }
}
#endif

TYPED_TEST(IpcChannel_test, TimedReceiveWorks)
{
    ::testing::Test::RecordProperty("TEST_ID", "978c8c4e-9829-4467-b664-45457104d4a9");
    using namespace iox::units;
    using namespace std::chrono;

    std::string msg = "very useful text for tranmission";
    Duration timeout = 100_ms;

    ASSERT_FALSE(this->client.send(msg).has_error());

    auto received = this->server.timedReceive(timeout);
    ASSERT_FALSE(received.has_error());

    EXPECT_EQ(received.value(), msg);

    auto before = system_clock::now();
    received = this->server.timedReceive(timeout);
    auto after = system_clock::now();

    ASSERT_TRUE(received.has_error());
    ASSERT_THAT(received.get_error(), Eq(IpcChannelError::TIMEOUT));

    auto timeDiff = units::Duration(after - before);
    EXPECT_GT(timeDiff, timeout);
}
} // namespace
<commit_msg>iox-#1036 Remove test_ipc_channel from dust since it is already moved to posh<commit_after><|endoftext|>


<commit_before>///
/// @file  S2.hpp.
/// @brief S2 function declarations.
///
/// Copyright (C) 2015 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#ifndef S2_HPP
#define S2_HPP

#include <int128.hpp>
#include <stdint.h>

namespace primecount {

/// ------------------------ S2_trivial() ----------------------------

int64_t S2_trivial(int64_t x,
                   int64_t y,
                   int64_t z,
                   int64_t c,
                   int threads);

#ifdef HAVE_INT128_T

int128_t S2_trivial(int128_t x,
                    int64_t y,
                    int64_t z,
                    int64_t c,
                    int threads);

#endif

/// ------------------------ S2_easy() -------------------------------

int64_t S2_easy(int64_t x,
                int64_t y,
                int64_t z,
                int64_t c,
                int threads);

#ifdef HAVE_INT128_T

int128_t S2_easy(int128_t x,
                 int64_t y,
                 int64_t z,
                 int64_t c,
                 int threads);

#endif

/// ------------------------ S2_hard() -------------------------------

int64_t S2_hard(int64_t x,
                int64_t y,
                int64_t z,
                int64_t c,
                int64_t s2_hard_approx,
                int threads);

#ifdef HAVE_INT128_T

int128_t S2_hard(int128_t x,
                 int64_t y,
                 int64_t z,
                 int64_t c,
                 int128_t s2_hard_approx,
                 int threads);

#endif

} // namespace primecount

#endif
<commit_msg>Add MPI functions<commit_after>///
/// @file  S2.hpp.
/// @brief S2 function declarations.
///
/// Copyright (C) 2015 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#ifndef S2_HPP
#define S2_HPP

#include <int128.hpp>
#include <stdint.h>

namespace primecount {

/// ------------------------ S2_trivial() ----------------------------

int64_t S2_trivial(int64_t x,
                   int64_t y,
                   int64_t z,
                   int64_t c,
                   int threads);

#ifdef HAVE_INT128_T

int128_t S2_trivial(int128_t x,
                    int64_t y,
                    int64_t z,
                    int64_t c,
                    int threads);

#endif

/// ------------------------ S2_easy() -------------------------------

int64_t S2_easy(int64_t x,
                int64_t y,
                int64_t z,
                int64_t c,
                int threads);

#ifdef HAVE_INT128_T

int128_t S2_easy(int128_t x,
                 int64_t y,
                 int64_t z,
                 int64_t c,
                 int threads);

#endif

#ifdef HAVE_MPI

int64_t S2_easy_mpi(int64_t x,
                    int64_t y,
                    int64_t z,
                    int64_t c,
                    int threads);

#ifdef HAVE_INT128_T

int128_t S2_easy_mpi(int128_t x,
                     int64_t y,
                     int64_t z,
                     int64_t c,
                     int threads);

#endif

#endif

/// ------------------------ S2_hard() -------------------------------

int64_t S2_hard(int64_t x,
                int64_t y,
                int64_t z,
                int64_t c,
                int64_t s2_hard_approx,
                int threads);

#ifdef HAVE_INT128_T

int128_t S2_hard(int128_t x,
                 int64_t y,
                 int64_t z,
                 int64_t c,
                 int128_t s2_hard_approx,
                 int threads);

#endif

#ifdef HAVE_MPI

int64_t S2_hard_mpi(int64_t x,
                    int64_t y,
                    int64_t z,
                    int64_t c,
                    int64_t s2_hard_approx,
                    int threads);

#ifdef HAVE_INT128_T

int128_t S2_hard_mpi(int128_t x,
                     int64_t y,
                     int64_t z,
                     int64_t c,
                     int128_t s2_hard_approx,
                     int threads);

#endif

#endif

} // namespace primecount

#endif
<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////
//
// SneezyMUD - All rights reserved, SneezyMUD Coding Team
//
//
//////////////////////////////////////////////////////////////////////////

#include "stdsneezy.h"
#include "format.h"

void TBeing::doScore()
{
  struct time_info_data playing_time;
  sstring Buf, tString;

  sendTo(fmt("You have %s%d%s/%s%d%s hit points, %s%d%s/%s%d%s moves and ") %	 red() % getHit() % norm() %
	 green() % hitLimit() % norm() %
	 purple() % getMove() % norm() %
	 green() % moveLimit() % norm());

  if (hasClass(CLASS_DEIKHAN) || hasClass(CLASS_CLERIC))
    Buf = fmt("%s%.2f%c %spiety.\n\r") % cyan() % getPiety() % '%' % norm();
  else if (hasClass(CLASS_SHAMAN))
    Buf = fmt("%s%d %slifeforce.\n\r") % red() % getLifeforce() % norm();
  else
    Buf = fmt("%s%d%s/%s%d%s mana.\n\r") %
      orange() % getMana() % norm() %
      green() % manaLimit() % norm();

  sendTo(Buf);

  sendTo(fmt("You are %s.\n\r") % DescMoves((((double) getMove()) / ((double)         moveLimit()))));

  tString = displayExp().comify();

  sendTo(fmt("You have %s%s%s exp, and have %s%d%s talens plus %s%d%s talens in the bank.\n\r") % cyan() % tString % norm() %
         purple() % getMoney() % norm() %
         purple() % getBank() % norm());

  if (desc) {
    tString = (fmt("%.2f") % desc->session.xp).comify();

    sendTo(fmt("You have earned %s%s%s exp this session.\n\r") % cyan() % tString % norm());

    if (getExp() < getMaxExp()) {
      tString = (fmt("%.2f") % getMaxExp()).comify();
      sendTo(fmt("Your most exp before your last death was: %s%s%s\n\r") % cyan() % tString % norm());
    }

    int total=0, count=0;
    for (spellNumT tSpell = MIN_SPELL; tSpell < MAX_SKILL; tSpell++){
      if(getDisciplineNumber(tSpell, FALSE)!=DISC_NONE &&
	 doesKnowSkill(tSpell)){
	total += getSkillValue(tSpell);
	++count;
      }
    }
    sendTo(fmt("You have a total of %s%i%s skill points with an average of %s%i%s per skill.\n\r") %
	   cyan() % total % norm() %
	   cyan() % (int)(total/count) % norm());

    realTimePassed((time(0) - desc->session.connect), 0, &playing_time);
    if (playing_time.day)
      playing_time.hours += playing_time.day * 24;

    sendTo(fmt("You have been playing for %s%d%s hour%s, %s%d%s minute%s and %s%d%s second%s in this session.\n\r") %         purple() % playing_time.hours   % norm() % (playing_time.hours   == 1 ? "" : "s") %
         purple() % playing_time.minutes % norm() % (playing_time.minutes == 1 ? "" : "s") %
         purple() % playing_time.seconds % norm() % (playing_time.seconds == 1 ? "" : "s"));
  }

  realTimePassed((time(0) - player.time.logon) + player.time.played,
                 0, &playing_time);

  sendTo(fmt("For a lifetime total of %s%d%s day%s and %s%d%s hour%s.\n\r") %         purple() % playing_time.day   % norm() % (playing_time.day   == 1 ? "" : "s") %
         purple() % playing_time.hours % norm() % (playing_time.hours == 1 ? "" : "s"));

  classIndT i;
  // since XP tables are all the same, the only time this should be
  // different is if they have gained in one class, but not another
  // we first check for this situation
  bool allClassesSame = true;
  for (i = MAGE_LEVEL_IND; i < MAX_CLASSES; i++)
    if (getLevel(i) && getLevel(i) != GetMaxLevel())
      allClassesSame = false;

  if (allClassesSame)
    sendTo(fmt("Your level: %s lev %2d          This ranks you as:\n\r") %           getProfName() % GetMaxLevel());
  else {
    sendTo("Your level: ");
    bool shownFirst = false;
    for (i = MAGE_LEVEL_IND; i < MAX_CLASSES; i++) {
      if (getLevel(i)) {
        sendTo(fmt("%s%s lev %2d") %             (shownFirst ? ", " : "") %
	       classInfo[i].name.cap() % getLevel(i));
        shownFirst = true;
      }
    }
    sendTo("          This ranks you as:\n\r");
  }

  Buf = parseTitle(desc);
  Buf += "\n\r";
  // Done this way just in case the player uses a % in their title.
  sendTo(COLOR_BASIC, fmt("%s") % Buf);

  for (i = MAGE_LEVEL_IND; i < MAX_CLASSES; i++) {
    if (getLevel(i) && getLevel(i) < MAX_MORT) {
      double need = getExpClassLevel(i, getLevel(i) + 1) - getExp();
      tString = (fmt("%.2f") % need).comify();

      if (allClassesSame) {
        sendTo(fmt("You need %s%s%s experience points to be a %sLevel %d %s%s.\n\r") %             purple() % tString % norm() % purple() % (getLevel(i)+1) %
	       getProfName() % norm());
        break;
      } else {
        // leveled in one class, but not another, show each class as own line
        sendTo(fmt("You need %s%s%s experience points to be a %sLevel %d %s%s.\n\r") %             purple() % tString % norm() % purple() % (getLevel(i)+1) %
             classInfo[i].name.cap() % norm());
      }
    }
  }

  if (!getCond(THIRST))
    sendTo(COLOR_BASIC, "<R>You are totally parched.<1>\n\r");
  else if ((getCond(THIRST) > 0) && (getCond(THIRST) <= 5))
    sendTo("Your throat is very dry.\n\r");
  else if ((getCond(THIRST) > 5) && (getCond(THIRST) <= 10))
    sendTo("You could use a little drink.\n\r");
  else if ((getCond(THIRST) > 10) && (getCond(THIRST) <= 20))
    sendTo("You are slightly thirsty.\n\r");
  else if (getCond(THIRST) > 20)
    sendTo("Your thirst is the least of your worries.\n\r");

  if (!getCond(FULL))
    sendTo(COLOR_BASIC, "<R>You are totally famished.<1>\n\r");
  else if ((getCond(FULL) > 0) && (getCond(FULL) <= 5))
    sendTo("Your stomach is growling loudly.\n\r");
  else if ((getCond(FULL) > 5) && (getCond(FULL) <= 10))
    sendTo("You could use a little bite to eat.\n\r");
  else if ((getCond(FULL) > 10) && (getCond(FULL) <= 20))
    sendTo("You are slightly hungry.\n\r");
  else if (getCond(FULL) > 20)
    sendTo("Your hunger is the least of your worries.\n\r");

  if (getCond(DRUNK) >= 20)
    sendTo("You are VERY drunk.\n\r");
  else if (getCond(DRUNK) >= 15)
    sendTo("You are very drunk.\n\r");
  else if (getCond(DRUNK) >= 10)
    sendTo("You are drunk.\n\r");
  else if (getCond(DRUNK) >= 4)
    sendTo("You are intoxicated.\n\r");
  else if (getCond(DRUNK) > 0)
    sendTo("You are feeling tipsy.\n\r");

  if (fight())
    act("You are fighting $N.", FALSE, this, NULL, fight(), TO_CHAR);
  else if (task) {
    sendTo(fmt("You are %s.\n\r") % tasks[task->task].name);
  } else {
    TBeing *tbr;
    switch (getPosition()) {
      case POSITION_DEAD:
        sendTo("You are DEAD!\n\r");
        break;
      case POSITION_MORTALLYW:
        sendTo("You are mortally wounded!  You should seek help!\n\r");
        break;
      case POSITION_INCAP:
        sendTo("You are incapacitated, slowly fading away.\n\r");
        break;
      case POSITION_STUNNED:
        sendTo("You are stunned! You can't move.\n\r");
        break;
      case POSITION_SLEEPING:
        if (riding) {
          Buf="You are sleeping on ";

          if (riding->getName())
            Buf+=objs(riding);
          else
            Buf+="A bad object";

          Buf+=".\n\r";
        } else
          Buf="You are sleeping.\n\r";

        sendTo(Buf);
        break;
      case POSITION_RESTING:
        if (riding) {
          Buf = "You are resting on ";
          if (riding->getName())
            Buf+=objs(riding);
          else
            Buf+="A horse with a bad short description, BUG THIS!";

          Buf+=".\n\r";
        } else
          Buf = "You are resting.\n\r";

        sendTo(Buf);
        break;
      case POSITION_CRAWLING:
        sendTo("You are crawling.\n\r");
        break;
      case POSITION_SITTING:
        if (riding) {
          Buf="You are sitting on ";
          if (riding->getName())
            Buf += objs(riding);
          else
	    Buf += "A bad object!";

          Buf += ".\n\r";
        } else
          Buf="You are sitting.\n\r";

        sendTo(Buf);
        break;
      case POSITION_FLYING:
         if (roomp && roomp->isUnderwaterSector())
          sendTo("You are swimming about.");
        else
          sendTo("You are flying about.\n\r");

        break;
      case POSITION_STANDING:
        sendTo("You are standing.\n\r");
        break;
      case POSITION_MOUNTED:
        tbr = dynamic_cast<TBeing *>(riding);
        if (tbr && tbr->horseMaster() == this) {
	  Buf = "You are here, riding ";
	  Buf += pers(tbr);
	  Buf += ".\n\r";
          sendTo(COLOR_MOBS, Buf);
        } else if (tbr) {
	  Buf = fmt("You are here, also riding on %s's %s%s.\n\r") %
	    pers(tbr->horseMaster()) %
	    persfname(tbr) %
	    (tbr->isAffected(AFF_INVISIBLE) ? " (invisible)" : "");

          sendTo(COLOR_MOBS, Buf);
        } else
          sendTo("You are standing.\n\r");
        break;
      default:
        sendTo("You are floating.\n\r");
        break;
    }
  }

  sendTo(fmt("You are in %s%s%s attack mode.\n\r") %         cyan() % attack_modes[getCombatMode()] % norm());

  if (getWimpy())
    sendTo(fmt("You are in wimpy mode, and will flee at %d hit points.\n\r") %
	   getWimpy());

  describeLimbDamage(this);
  sendTo(COLOR_BASIC, describeAffects(this, SHOW_ME));
}
<commit_msg>added a divide by zero check<commit_after>//////////////////////////////////////////////////////////////////////////
//
// SneezyMUD - All rights reserved, SneezyMUD Coding Team
//
//
//////////////////////////////////////////////////////////////////////////

#include "stdsneezy.h"
#include "format.h"

void TBeing::doScore()
{
  struct time_info_data playing_time;
  sstring Buf, tString;

  sendTo(fmt("You have %s%d%s/%s%d%s hit points, %s%d%s/%s%d%s moves and ") %	 red() % getHit() % norm() %
	 green() % hitLimit() % norm() %
	 purple() % getMove() % norm() %
	 green() % moveLimit() % norm());

  if (hasClass(CLASS_DEIKHAN) || hasClass(CLASS_CLERIC))
    Buf = fmt("%s%.2f%c %spiety.\n\r") % cyan() % getPiety() % '%' % norm();
  else if (hasClass(CLASS_SHAMAN))
    Buf = fmt("%s%d %slifeforce.\n\r") % red() % getLifeforce() % norm();
  else
    Buf = fmt("%s%d%s/%s%d%s mana.\n\r") %
      orange() % getMana() % norm() %
      green() % manaLimit() % norm();

  sendTo(Buf);

  sendTo(fmt("You are %s.\n\r") % DescMoves((((double) getMove()) / ((double)         moveLimit()))));

  tString = displayExp().comify();

  sendTo(fmt("You have %s%s%s exp, and have %s%d%s talens plus %s%d%s talens in the bank.\n\r") % cyan() % tString % norm() %
         purple() % getMoney() % norm() %
         purple() % getBank() % norm());

  if (desc) {
    tString = (fmt("%.2f") % desc->session.xp).comify();

    sendTo(fmt("You have earned %s%s%s exp this session.\n\r") % cyan() % tString % norm());

    if (getExp() < getMaxExp()) {
      tString = (fmt("%.2f") % getMaxExp()).comify();
      sendTo(fmt("Your most exp before your last death was: %s%s%s\n\r") % cyan() % tString % norm());
    }

    int total=0, count=0;
    for (spellNumT tSpell = MIN_SPELL; tSpell < MAX_SKILL; tSpell++){
      if(getDisciplineNumber(tSpell, FALSE)!=DISC_NONE &&
	 doesKnowSkill(tSpell)){
	total += getSkillValue(tSpell);
	++count;
      }
    }
    if(count > 0){
      sendTo(fmt("You have a total of %s%i%s skill points with an average of %s%i%s per skill.\n\r") %
	     cyan() % total % norm() %
	     cyan() % (int)(total/count) % norm());
    }

    realTimePassed((time(0) - desc->session.connect), 0, &playing_time);
    if (playing_time.day)
      playing_time.hours += playing_time.day * 24;

    sendTo(fmt("You have been playing for %s%d%s hour%s, %s%d%s minute%s and %s%d%s second%s in this session.\n\r") %         purple() % playing_time.hours   % norm() % (playing_time.hours   == 1 ? "" : "s") %
         purple() % playing_time.minutes % norm() % (playing_time.minutes == 1 ? "" : "s") %
         purple() % playing_time.seconds % norm() % (playing_time.seconds == 1 ? "" : "s"));
  }

  realTimePassed((time(0) - player.time.logon) + player.time.played,
                 0, &playing_time);

  sendTo(fmt("For a lifetime total of %s%d%s day%s and %s%d%s hour%s.\n\r") %         purple() % playing_time.day   % norm() % (playing_time.day   == 1 ? "" : "s") %
         purple() % playing_time.hours % norm() % (playing_time.hours == 1 ? "" : "s"));

  classIndT i;
  // since XP tables are all the same, the only time this should be
  // different is if they have gained in one class, but not another
  // we first check for this situation
  bool allClassesSame = true;
  for (i = MAGE_LEVEL_IND; i < MAX_CLASSES; i++)
    if (getLevel(i) && getLevel(i) != GetMaxLevel())
      allClassesSame = false;

  if (allClassesSame)
    sendTo(fmt("Your level: %s lev %2d          This ranks you as:\n\r") %           getProfName() % GetMaxLevel());
  else {
    sendTo("Your level: ");
    bool shownFirst = false;
    for (i = MAGE_LEVEL_IND; i < MAX_CLASSES; i++) {
      if (getLevel(i)) {
        sendTo(fmt("%s%s lev %2d") %             (shownFirst ? ", " : "") %
	       classInfo[i].name.cap() % getLevel(i));
        shownFirst = true;
      }
    }
    sendTo("          This ranks you as:\n\r");
  }

  Buf = parseTitle(desc);
  Buf += "\n\r";
  // Done this way just in case the player uses a % in their title.
  sendTo(COLOR_BASIC, fmt("%s") % Buf);

  for (i = MAGE_LEVEL_IND; i < MAX_CLASSES; i++) {
    if (getLevel(i) && getLevel(i) < MAX_MORT) {
      double need = getExpClassLevel(i, getLevel(i) + 1) - getExp();
      tString = (fmt("%.2f") % need).comify();

      if (allClassesSame) {
        sendTo(fmt("You need %s%s%s experience points to be a %sLevel %d %s%s.\n\r") %             purple() % tString % norm() % purple() % (getLevel(i)+1) %
	       getProfName() % norm());
        break;
      } else {
        // leveled in one class, but not another, show each class as own line
        sendTo(fmt("You need %s%s%s experience points to be a %sLevel %d %s%s.\n\r") %             purple() % tString % norm() % purple() % (getLevel(i)+1) %
             classInfo[i].name.cap() % norm());
      }
    }
  }

  if (!getCond(THIRST))
    sendTo(COLOR_BASIC, "<R>You are totally parched.<1>\n\r");
  else if ((getCond(THIRST) > 0) && (getCond(THIRST) <= 5))
    sendTo("Your throat is very dry.\n\r");
  else if ((getCond(THIRST) > 5) && (getCond(THIRST) <= 10))
    sendTo("You could use a little drink.\n\r");
  else if ((getCond(THIRST) > 10) && (getCond(THIRST) <= 20))
    sendTo("You are slightly thirsty.\n\r");
  else if (getCond(THIRST) > 20)
    sendTo("Your thirst is the least of your worries.\n\r");

  if (!getCond(FULL))
    sendTo(COLOR_BASIC, "<R>You are totally famished.<1>\n\r");
  else if ((getCond(FULL) > 0) && (getCond(FULL) <= 5))
    sendTo("Your stomach is growling loudly.\n\r");
  else if ((getCond(FULL) > 5) && (getCond(FULL) <= 10))
    sendTo("You could use a little bite to eat.\n\r");
  else if ((getCond(FULL) > 10) && (getCond(FULL) <= 20))
    sendTo("You are slightly hungry.\n\r");
  else if (getCond(FULL) > 20)
    sendTo("Your hunger is the least of your worries.\n\r");

  if (getCond(DRUNK) >= 20)
    sendTo("You are VERY drunk.\n\r");
  else if (getCond(DRUNK) >= 15)
    sendTo("You are very drunk.\n\r");
  else if (getCond(DRUNK) >= 10)
    sendTo("You are drunk.\n\r");
  else if (getCond(DRUNK) >= 4)
    sendTo("You are intoxicated.\n\r");
  else if (getCond(DRUNK) > 0)
    sendTo("You are feeling tipsy.\n\r");

  if (fight())
    act("You are fighting $N.", FALSE, this, NULL, fight(), TO_CHAR);
  else if (task) {
    sendTo(fmt("You are %s.\n\r") % tasks[task->task].name);
  } else {
    TBeing *tbr;
    switch (getPosition()) {
      case POSITION_DEAD:
        sendTo("You are DEAD!\n\r");
        break;
      case POSITION_MORTALLYW:
        sendTo("You are mortally wounded!  You should seek help!\n\r");
        break;
      case POSITION_INCAP:
        sendTo("You are incapacitated, slowly fading away.\n\r");
        break;
      case POSITION_STUNNED:
        sendTo("You are stunned! You can't move.\n\r");
        break;
      case POSITION_SLEEPING:
        if (riding) {
          Buf="You are sleeping on ";

          if (riding->getName())
            Buf+=objs(riding);
          else
            Buf+="A bad object";

          Buf+=".\n\r";
        } else
          Buf="You are sleeping.\n\r";

        sendTo(Buf);
        break;
      case POSITION_RESTING:
        if (riding) {
          Buf = "You are resting on ";
          if (riding->getName())
            Buf+=objs(riding);
          else
            Buf+="A horse with a bad short description, BUG THIS!";

          Buf+=".\n\r";
        } else
          Buf = "You are resting.\n\r";

        sendTo(Buf);
        break;
      case POSITION_CRAWLING:
        sendTo("You are crawling.\n\r");
        break;
      case POSITION_SITTING:
        if (riding) {
          Buf="You are sitting on ";
          if (riding->getName())
            Buf += objs(riding);
          else
	    Buf += "A bad object!";

          Buf += ".\n\r";
        } else
          Buf="You are sitting.\n\r";

        sendTo(Buf);
        break;
      case POSITION_FLYING:
         if (roomp && roomp->isUnderwaterSector())
          sendTo("You are swimming about.");
        else
          sendTo("You are flying about.\n\r");

        break;
      case POSITION_STANDING:
        sendTo("You are standing.\n\r");
        break;
      case POSITION_MOUNTED:
        tbr = dynamic_cast<TBeing *>(riding);
        if (tbr && tbr->horseMaster() == this) {
	  Buf = "You are here, riding ";
	  Buf += pers(tbr);
	  Buf += ".\n\r";
          sendTo(COLOR_MOBS, Buf);
        } else if (tbr) {
	  Buf = fmt("You are here, also riding on %s's %s%s.\n\r") %
	    pers(tbr->horseMaster()) %
	    persfname(tbr) %
	    (tbr->isAffected(AFF_INVISIBLE) ? " (invisible)" : "");

          sendTo(COLOR_MOBS, Buf);
        } else
          sendTo("You are standing.\n\r");
        break;
      default:
        sendTo("You are floating.\n\r");
        break;
    }
  }

  sendTo(fmt("You are in %s%s%s attack mode.\n\r") %         cyan() % attack_modes[getCombatMode()] % norm());

  if (getWimpy())
    sendTo(fmt("You are in wimpy mode, and will flee at %d hit points.\n\r") %
	   getWimpy());

  describeLimbDamage(this);
  sendTo(COLOR_BASIC, describeAffects(this, SHOW_ME));
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: xsdvalidationpropertyhandler.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 20:33:57 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    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., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef EXTENSIONS_SOURCE_PROPCTRLR_XSDVALIDATIONPROPERTYHANDLER_HXX
#define EXTENSIONS_SOURCE_PROPCTRLR_XSDVALIDATIONPROPERTYHANDLER_HXX

#ifndef EXTENSIONS_SOURCE_PROPCTRLR_PROPERTYHANDLER_HXX
#include "propertyhandler.hxx"
#endif

/** === begin UNO includes === **/
/** === end UNO includes === **/

#include <memory>

//........................................................................
namespace pcr
{
//........................................................................

    class XSDValidationHelper;
    //====================================================================
    //= XSDValidationPropertyHandler
    //====================================================================
    class XSDValidationPropertyHandler : public PropertyHandler
    {
    private:
        ::std::auto_ptr< XSDValidationHelper >  m_pHelper;

    public:
        // HandlerFactory
        inline static IPropertyHandler* Create(
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB,
            const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxIntrospectee,
            const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel >& _rxContextDocument,
            const ::com::sun::star::uno::Reference< ::com::sun::star::script::XTypeConverter >& _rxTypeConverter
        )
        {
            return new XSDValidationPropertyHandler( _rxIntrospectee, _rxContextDocument, _rxTypeConverter );
        }

    protected:
        XSDValidationPropertyHandler(
            const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxIntrospectee,
            const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel >& _rxContextDocument,
            const ::com::sun::star::uno::Reference< ::com::sun::star::script::XTypeConverter >& _rxTypeConverter
        );
        ~XSDValidationPropertyHandler();

    protected:
        // IPropertyHandler overriables
        virtual bool                        SAL_CALL supportsUIDescriptor(  PropertyId _nPropId ) const;
        virtual ::com::sun::star::uno::Any  SAL_CALL getPropertyValue( PropertyId _nPropId, bool _bLazy = true ) const;
        virtual void                        SAL_CALL setPropertyValue( PropertyId _nPropId, const ::com::sun::star::uno::Any& _rValue );
        virtual ::std::vector< ::rtl::OUString >
                                            SAL_CALL getSupersededProperties( ) const;
        virtual ::std::vector< ::rtl::OUString >
                                            SAL_CALL getActuatingProperties( ) const;
        virtual void                        SAL_CALL describePropertyUI( PropertyId _nPropId, PropertyUIDescriptor& /* [out] */ _rDescriptor ) const;
        virtual void                        SAL_CALL initializePropertyUI( PropertyId _nPropId, IPropertyBrowserUI* _pUpdater );
        virtual bool                        SAL_CALL requestUserInputOnButtonClick( PropertyId _nPropId, bool _bPrimary, ::com::sun::star::uno::Any& _rData );
        virtual void                        SAL_CALL executeButtonClick( PropertyId _nPropId, bool _bPrimary, const ::com::sun::star::uno::Any& _rData, IPropertyBrowserUI* _pUpdater );
        virtual void                        SAL_CALL actuatingPropertyChanged( PropertyId _nActuatingPropId, const ::com::sun::star::uno::Any& _rNewValue, const ::com::sun::star::uno::Any& _rOldValue, IPropertyBrowserUI* _pUpdater, bool );
        virtual void                        SAL_CALL startAllPropertyChangeListening( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& _rxListener );
        virtual void                        SAL_CALL stopAllPropertyChangeListening( );

        // PropertyHandler overridables
        virtual ::std::vector< ::com::sun::star::beans::Property >
                                            SAL_CALL implDescribeSupportedProperties() const;

    private:
        bool    implPrepareRemoveCurrentDataType() SAL_THROW(());
        bool    implDoRemoveCurrentDataType() SAL_THROW(());

        bool    implPrepareCloneDataCurrentType( ::rtl::OUString& _rNewName ) SAL_THROW(());
        bool    implDoCloneCurrentDataType( const ::rtl::OUString& _rNewName ) SAL_THROW(());

        /** retrieves the names of the data types which our introspectee can be validated against
        */
        void    implGetAvailableDataTypeNames( ::std::vector< ::rtl::OUString >& /* [out] */ _rNames ) const SAL_THROW(());
    };

//........................................................................
} // namespace pcr
//........................................................................

#endif // EXTENSIONS_SOURCE_PROPCTRLR_XSDVALIDATIONPROPERTYHANDLER_HXX

<commit_msg>INTEGRATION: CWS pbrwuno (1.3.88); FILE MERGED 2005/11/02 11:43:48 fs 1.3.88.13: #i10000# exception specifications 2005/10/25 07:13:16 fs 1.3.88.12: #i53095# knitting lose ends (amongst others, make the handlers available as service) 2005/10/24 08:42:11 fs 1.3.88.11: start making the handlers full-fledged components, with using a new infrastructure replacing extensions/source/inc/componentmodule.* 2005/10/17 14:09:42 fs 1.3.88.10: #i53095# some cleanup of remaining TODOs 2005/10/13 13:01:12 fs 1.3.88.9: #i53095# introduce an XObjectInspector/Model 2005/10/11 13:30:01 fs 1.3.88.8: #i53095# phase 3: introduced XPropertyHandler and XObjectInspectorUI same open issues as in previous phase (plus probably some more, since not everything is tested, yet :-\) 2005/10/05 07:16:22 fs 1.3.88.7: RESYNC: (1.3-1.4); FILE MERGED 2005/09/05 07:41:56 fs 1.3.88.6: #i53095# phase 3, part 1: introduced XPropertyControl and relatives, describing one control in the ObjectInspector, responsible for one property known issues: - rebuildPropertyUI can cause problems now: If the user clicks into   the control for property A, which causes property B to be committed,   which causes the UI for property A to be rebuilt, then this will   crash currently. Reason: rebuildPropertyUI now synchronously replaces   the VCL-Window of the rebuilt control, which is exactly the one   which is still in some MouseButtonDown-handler.   possible solutions:   - see if rebuiltPropertyUI can be obsoleted - handlers should be able     to just obtain the XPropertyControl from the PropertyUI, and     re-initialize the control. Shouldn't they?`   - make one of the steps in the chain (mouse-click, handler-call,     rebuildPropertyUI-callback) asynchronous. 2005/08/18 12:44:36 fs 1.3.88.5: #i53095#, phase 2<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: xsdvalidationpropertyhandler.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: vg $ $Date: 2006-03-14 11:35:25 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    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., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef EXTENSIONS_SOURCE_PROPCTRLR_XSDVALIDATIONPROPERTYHANDLER_HXX
#define EXTENSIONS_SOURCE_PROPCTRLR_XSDVALIDATIONPROPERTYHANDLER_HXX

#ifndef EXTENSIONS_SOURCE_PROPCTRLR_PROPERTYHANDLER_HXX
#include "propertyhandler.hxx"
#endif

/** === begin UNO includes === **/
/** === end UNO includes === **/

#include <memory>

//........................................................................
namespace pcr
{
//........................................................................

    class XSDValidationHelper;
    //====================================================================
    //= XSDValidationPropertyHandler
    //====================================================================
    class XSDValidationPropertyHandler;
    typedef HandlerComponentBase< XSDValidationPropertyHandler > XSDValidationPropertyHandler_Base;
    class XSDValidationPropertyHandler : public XSDValidationPropertyHandler_Base
    {
    private:
        ::std::auto_ptr< XSDValidationHelper >  m_pHelper;

    public:
        XSDValidationPropertyHandler(
            const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& _rxContext
        );

        static ::rtl::OUString SAL_CALL getImplementationName_static(  ) throw (::com::sun::star::uno::RuntimeException);
        static ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames_static(  ) throw (::com::sun::star::uno::RuntimeException);

    protected:
        ~XSDValidationPropertyHandler();

    protected:
        // XPropertyHandler overriables
        virtual ::com::sun::star::uno::Any  SAL_CALL getPropertyValue( const ::rtl::OUString& _rPropertyName ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);
        virtual void                        SAL_CALL setPropertyValue( const ::rtl::OUString& _rPropertyName, const ::com::sun::star::uno::Any& _rValue ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Sequence< ::rtl::OUString >
                                            SAL_CALL getSupersededProperties( ) throw (::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Sequence< ::rtl::OUString >
                                            SAL_CALL getActuatingProperties( ) throw (::com::sun::star::uno::RuntimeException);
        virtual void                        SAL_CALL describePropertyLine( const ::rtl::OUString& _rPropertyName, ::com::sun::star::inspection::LineDescriptor& /* [out] */ _rDescriptor, const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControlFactory >& _rxControlFactory ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::NullPointerException, ::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::inspection::InteractiveSelectionResult
                                            SAL_CALL onInteractivePropertySelection( const ::rtl::OUString& _rPropertyName, sal_Bool _bPrimary, ::com::sun::star::uno::Any& _rData, const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XObjectInspectorUI >& _rxInspectorUI ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::NullPointerException, ::com::sun::star::uno::RuntimeException);
        virtual void                        SAL_CALL actuatingPropertyChanged( const ::rtl::OUString& _rActuatingPropertyName, const ::com::sun::star::uno::Any& _rNewValue, const ::com::sun::star::uno::Any& _rOldValue, const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XObjectInspectorUI >& _rxInspectorUI, sal_Bool ) throw (::com::sun::star::lang::NullPointerException, ::com::sun::star::uno::RuntimeException);
        virtual void                        SAL_CALL addPropertyChangeListener( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& _rxListener ) throw (::com::sun::star::uno::RuntimeException);
        virtual void                        SAL_CALL removePropertyChangeListener( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& _rxListener ) throw (::com::sun::star::uno::RuntimeException);

        // PropertyHandler overridables
        virtual ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >
                                            SAL_CALL doDescribeSupportedProperties() const;
        virtual void onNewComponent();

    private:
        bool    implPrepareRemoveCurrentDataType() SAL_THROW(());
        bool    implDoRemoveCurrentDataType() SAL_THROW(());

        bool    implPrepareCloneDataCurrentType( ::rtl::OUString& _rNewName ) SAL_THROW(());
        bool    implDoCloneCurrentDataType( const ::rtl::OUString& _rNewName ) SAL_THROW(());

        /** retrieves the names of the data types which our introspectee can be validated against
        */
        void    implGetAvailableDataTypeNames( ::std::vector< ::rtl::OUString >& /* [out] */ _rNames ) const SAL_THROW(());
    };

//........................................................................
} // namespace pcr
//........................................................................

#endif // EXTENSIONS_SOURCE_PROPCTRLR_XSDVALIDATIONPROPERTYHANDLER_HXX

<|endoftext|>


<commit_before>#include "BorderlessWindow.h"

#include <QDesktopWidget>
#include <QPushButton>

#include <tchar.h>
#include <dwmapi.h>
#include <windowsx.h>

HWND g_winId = 0;

WinWindow* BorderlessWindow::mainPanel;
QApplication* BorderlessWindow::a;

BorderlessWindow::BorderlessWindow(QApplication* app, HBRUSH windowBackground, const int width, const int height)
    : hWnd(0),
      hInstance(GetModuleHandle(NULL)),
      closed(false),
      visible(false),
      borderless(false),
      borderlessResizeable(true),
      aeroShadow(false)
{
    WNDCLASSEX wcx = {0};
    wcx.cbSize = sizeof(WNDCLASSEX);
    wcx.style = CS_HREDRAW | CS_VREDRAW;
    wcx.hInstance = hInstance;
    wcx.lpfnWndProc = WndProc;
    wcx.cbClsExtra = 0;
    wcx.cbWndExtra = 0;
    wcx.lpszClassName = _T("WindowClass");
    wcx.hbrBackground = windowBackground;
    wcx.hCursor = LoadCursor(hInstance, IDC_ARROW);
    RegisterClassEx(&wcx);
    if (FAILED(RegisterClassEx(&wcx)))
    {
        throw std::runtime_error("Couldn't register window class");
    }

    // Center window at runtime
    QRect rec = QApplication::desktop()->screenGeometry();
    int screenWidth = rec.width(), screenHeight = rec.height();
    int offsetX = (screenWidth - width) / 2;
    int offsetY = (screenHeight - height) / 2;

    hWnd = CreateWindow(_T("WindowClass"), _T("Horizon Launcher"), static_cast<DWORD>(Style::windowed), offsetX, offsetY, width, height, 0, 0, hInstance, nullptr);

    if (!hWnd)
    {
        throw std::runtime_error("Encountered an unknown error while constructing the launcher window.");
    }

    SetWindowLongPtr(hWnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(this));

    mainPanel = new WinWindow(hWnd);
    g_winId = (HWND)mainPanel->winId();

    show();
    toggleBorderless();

    a = app;
}

BorderlessWindow::~BorderlessWindow()
{
    hide();
    DestroyWindow(hWnd);
}

HDC g_hdc;
PAINTSTRUCT g_ps;

LRESULT CALLBACK BorderlessWindow::WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    BorderlessWindow* window = reinterpret_cast<BorderlessWindow*>(GetWindowLongPtr(hWnd, GWLP_USERDATA));
    if (!window)
    {
        return DefWindowProc(hWnd, message, wParam, lParam);
    }

    switch (message)
    {
    case WM_KEYDOWN:
    {
        switch (wParam)
        {
        case VK_F5:
        {
            window->borderlessResizeable = !window->borderlessResizeable;
            break;
        }
        case VK_F6:
        {
            window->toggleShadow();
            window->toggleBorderless();
            SetFocus(g_winId);
            break;
        }
        case VK_F7:
        {
            window->toggleShadow();
            break;
        }
        }

        if (wParam != VK_TAB)
        {
            return DefWindowProc(hWnd, message, wParam, lParam);
        }

        SetFocus(g_winId);
        break;
    }
    case WM_SYSCOMMAND: // ALT + SPACE or F10 system menu
    {
        if (wParam == SC_KEYMENU)
        {
            RECT winrect;
            GetWindowRect(hWnd, &winrect);
            TrackPopupMenu(GetSystemMenu(hWnd, false), TPM_TOPALIGN | TPM_LEFTALIGN, winrect.left + 5, winrect.top + 5, 0, hWnd, NULL);
            break;
        }
        else
        {
            return DefWindowProc(hWnd, message, wParam, lParam);
        }
    }
    case WM_SETFOCUS:
    {
        QString str("Got focus");
        QWidget* widget = QWidget::find((WId)HWND(wParam));
        if (widget)
        {
            str += QString(" from %1 (%2)").arg(widget->objectName()).arg(widget->metaObject()->className());
        }

        str += "\n";
        OutputDebugStringA(str.toLocal8Bit().data());
        break;
    }
    case WM_NCCALCSIZE:
    {
        // this kills the window frame and title bar we added with
        // WS_THICKFRAME and WS_CAPTION
        if (window->borderless)
        {
            return 0;
        }

        break;
    }
    case WM_KILLFOCUS:
    {
        QString str("Lost focus");
        QWidget* widget = QWidget::find((WId) HWND (wParam));
        if (widget)
        {
            str += QString(" to %1 (%2)").arg(widget->objectName()).arg(widget->metaObject()->className());
        }
        str += "\n";

        OutputDebugStringA(str.toLocal8Bit().data());
        break;
    }
    case WM_DESTROY:
    {
        delete(mainPanel);
        PostQuitMessage(0);
        break;
    }
    case WM_NCHITTEST:
    {
        if (window->borderless)
        {
            if (window->borderlessResizeable)
            {
                const LONG c_borderWidth = 8; //in pixels
                RECT winrect;
                GetWindowRect(hWnd, &winrect);
                long x = GET_X_LPARAM(lParam);
                long y = GET_Y_LPARAM(lParam);

                // bottom left corner
                if (x >= winrect.left && x < winrect.left + c_borderWidth &&
                        y < winrect.bottom && y >= winrect.bottom - c_borderWidth)
                {
                    return HTBOTTOMLEFT;
                }
                // bottom right corner
                if (x < winrect.right && x >= winrect.right - c_borderWidth &&
                        y < winrect.bottom && y >= winrect.bottom - c_borderWidth)
                {
                    return HTBOTTOMRIGHT;
                }
                // top left corner
                if (x >= winrect.left && x < winrect.left + c_borderWidth &&
                        y >= winrect.top && y < winrect.top + c_borderWidth)
                {
                    return HTTOPLEFT;
                }
                // top right corner
                if (x < winrect.right && x >= winrect.right - c_borderWidth &&
                        y >= winrect.top && y < winrect.top + c_borderWidth)
                {
                    return HTTOPRIGHT;
                }
                // left border
                if (x >= winrect.left && x < winrect.left + c_borderWidth)
                {
                    return HTLEFT;
                }
                // right border
                if (x < winrect.right && x >= winrect.right - c_borderWidth)
                {
                    return HTRIGHT;
                }
                // bottom border
                if (y < winrect.bottom && y >= winrect.bottom - c_borderWidth)
                {
                    return HTBOTTOM;
                }
                // top border
                if (y >= winrect.top && y < winrect.top + c_borderWidth)
                {
                    return HTTOP;
                }
            }
            return HTCAPTION;
        }
        break;
    }
    case WM_SIZE:
    {
        RECT winrect;
        GetClientRect(hWnd, &winrect);

        WINDOWPLACEMENT wp;
        wp.length = sizeof(WINDOWPLACEMENT);
        GetWindowPlacement(hWnd, &wp);
        if (wp.showCmd == SW_MAXIMIZE)
        {
            QPushButton* pushButtonMaximize = mainPanel->findChild<QPushButton*>("pushButtonMaximize");
            pushButtonMaximize->setStyleSheet(
                "#pushButtonMaximize {"
                    "image: url(:/Resource/Icons/Restore.png);
                }"
                "#pushButtonMaximize:hover {"
                    "image: url(:/Resource/Icons/RestoreHover.png);"
                "}"
            );
            mainPanel->setGeometry(8, 8, winrect.right - 16, winrect.bottom - 16);
        }
        else
        {
            QPushButton* pushButtonMaximize = mainPanel->findChild<QPushButton*>("pushButtonMaximize");
            pushButtonMaximize->setStyleSheet(
                "#pushButtonMaximize {"
                    "image: url(:/Resource/Icons/Maximize.png);"
                "}"
                "#pushButtonMaximize:hover {"
                    "image: url(:/Resource/Icons/MaximizeHover.png);"
                "}"
            );
            mainPanel->setGeometry(0, 0, winrect.right, winrect.bottom);
        }
        break;
    }
    case WM_GETMINMAXINFO:
    {
        MINMAXINFO* minMaxInfo = (MINMAXINFO*) lParam;
        if (window->minimumSize.required)
        {
            minMaxInfo->ptMinTrackSize.x = window->getMinimumWidth();;
            minMaxInfo->ptMinTrackSize.y = window->getMinimumHeight();
        }

        if (window->maximumSize.required)
        {
            minMaxInfo->ptMaxTrackSize.x = window->getMaximumWidth();
            minMaxInfo->ptMaxTrackSize.y = window->getMaximumHeight();
        }
        return 0;
    }
    }
    return DefWindowProc(hWnd, message, wParam, lParam);
}

void BorderlessWindow::toggleBorderless()
{
    if (visible)
    {
        Style newStyle = (borderless) ? Style::windowed : Style::aeroBorderless;
        SetWindowLongPtr(hWnd, GWL_STYLE, static_cast<LONG>(newStyle));

        borderless = !borderless;
        if (newStyle == Style::aeroBorderless)
        {
            toggleShadow();
        }
        // redraw frame
        SetWindowPos(hWnd, 0, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE);
        show();
    }
}

void BorderlessWindow::toggleShadow()
{
    if (borderless)
    {
        aeroShadow = !aeroShadow;
        const MARGINS c_shadowOn = {1, 1, 1, 1};
        const MARGINS c_shadowOff = {0, 0, 0, 0};
        DwmExtendFrameIntoClientArea(hWnd, (aeroShadow) ? (&c_shadowOn) : (&c_shadowOff));
    }
}

void BorderlessWindow::toggleResizeable()
{
    borderlessResizeable = borderlessResizeable ? false : true;
}

bool BorderlessWindow::isResizeable()
{
    return borderlessResizeable ? true : false;
}

void BorderlessWindow::show()
{
    ShowWindow(hWnd, SW_SHOW);
    visible = true;
}

void BorderlessWindow::hide()
{
    ShowWindow(hWnd, SW_HIDE);
    visible = false;
}

bool BorderlessWindow::isVisible()
{
    return visible ? true : false;
}

// Minimum size
void BorderlessWindow::setMinimumSize(const int width, const int height)
{
    this->minimumSize.required = true;
    this->minimumSize.width = width;
    this->minimumSize.height = height;
}

bool BorderlessWindow::isSetMinimumSize()
{
    return this->minimumSize.required;
}

void BorderlessWindow::removeMinimumSize()
{
    this->minimumSize.required = false;
    this->minimumSize.width = 0;
    this->minimumSize.height = 0;
}

int BorderlessWindow::getMinimumWidth()
{
    return minimumSize.width;
}

int BorderlessWindow::getMinimumHeight()
{
    return minimumSize.height;
}

// Maximum size
void BorderlessWindow::setMaximumSize(const int width, const int height)
{
    this->maximumSize.required = true;
    this->maximumSize.width = width;
    this->maximumSize.height = height;
}

bool BorderlessWindow::isSetMaximumSize()
{
    return this->maximumSize.required;
}

void BorderlessWindow::removeMaximumSize()
{
    this->maximumSize.required = false;
    this->maximumSize.width = 0;
    this->maximumSize.height = 0;
}

int BorderlessWindow::getMaximumWidth()
{
    return maximumSize.width;
}

int BorderlessWindow::getMaximumHeight()
{
    return maximumSize.height;
}
<commit_msg>Remove trailing whitespace from BorderlessWindow<commit_after>#include "BorderlessWindow.h"

#include <QDesktopWidget>
#include <QPushButton>

#include <tchar.h>
#include <dwmapi.h>
#include <windowsx.h>

HWND g_winId = 0;

WinWindow* BorderlessWindow::mainPanel;
QApplication* BorderlessWindow::a;

BorderlessWindow::BorderlessWindow(QApplication* app, HBRUSH windowBackground, const int width, const int height)
    : hWnd(0),
      hInstance(GetModuleHandle(NULL)),
      closed(false),
      visible(false),
      borderless(false),
      borderlessResizeable(true),
      aeroShadow(false)
{
    WNDCLASSEX wcx = {0};
    wcx.cbSize = sizeof(WNDCLASSEX);
    wcx.style = CS_HREDRAW | CS_VREDRAW;
    wcx.hInstance = hInstance;
    wcx.lpfnWndProc = WndProc;
    wcx.cbClsExtra = 0;
    wcx.cbWndExtra = 0;
    wcx.lpszClassName = _T("WindowClass");
    wcx.hbrBackground = windowBackground;
    wcx.hCursor = LoadCursor(hInstance, IDC_ARROW);
    RegisterClassEx(&wcx);
    if (FAILED(RegisterClassEx(&wcx)))
    {
        throw std::runtime_error("Couldn't register window class");
    }

    // Center window at runtime
    QRect rec = QApplication::desktop()->screenGeometry();
    int screenWidth = rec.width(), screenHeight = rec.height();
    int offsetX = (screenWidth - width) / 2;
    int offsetY = (screenHeight - height) / 2;

    hWnd = CreateWindow(_T("WindowClass"), _T("Horizon Launcher"), static_cast<DWORD>(Style::windowed), offsetX, offsetY, width, height, 0, 0, hInstance, nullptr);

    if (!hWnd)
    {
        throw std::runtime_error("Encountered an unknown error while constructing the launcher window.");
    }

    SetWindowLongPtr(hWnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(this));

    mainPanel = new WinWindow(hWnd);
    g_winId = (HWND)mainPanel->winId();

    show();
    toggleBorderless();

    a = app;
}

BorderlessWindow::~BorderlessWindow()
{
    hide();
    DestroyWindow(hWnd);
}

HDC g_hdc;
PAINTSTRUCT g_ps;

LRESULT CALLBACK BorderlessWindow::WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    BorderlessWindow* window = reinterpret_cast<BorderlessWindow*>(GetWindowLongPtr(hWnd, GWLP_USERDATA));
    if (!window)
    {
        return DefWindowProc(hWnd, message, wParam, lParam);
    }

    switch (message)
    {
    case WM_KEYDOWN:
    {
        switch (wParam)
        {
        case VK_F5:
        {
            window->borderlessResizeable = !window->borderlessResizeable;
            break;
        }
        case VK_F6:
        {
            window->toggleShadow();
            window->toggleBorderless();
            SetFocus(g_winId);
            break;
        }
        case VK_F7:
        {
            window->toggleShadow();
            break;
        }
        }

        if (wParam != VK_TAB)
        {
            return DefWindowProc(hWnd, message, wParam, lParam);
        }

        SetFocus(g_winId);
        break;
    }
    case WM_SYSCOMMAND: // ALT + SPACE or F10 system menu
    {
        if (wParam == SC_KEYMENU)
        {
            RECT winrect;
            GetWindowRect(hWnd, &winrect);
            TrackPopupMenu(GetSystemMenu(hWnd, false), TPM_TOPALIGN | TPM_LEFTALIGN, winrect.left + 5, winrect.top + 5, 0, hWnd, NULL);
            break;
        }
        else
        {
            return DefWindowProc(hWnd, message, wParam, lParam);
        }
    }
    case WM_SETFOCUS:
    {
        QString str("Got focus");
        QWidget* widget = QWidget::find((WId)HWND(wParam));
        if (widget)
        {
            str += QString(" from %1 (%2)").arg(widget->objectName()).arg(widget->metaObject()->className());
        }

        str += "\n";
        OutputDebugStringA(str.toLocal8Bit().data());
        break;
    }
    case WM_NCCALCSIZE:
    {
        // this kills the window frame and title bar we added with
        // WS_THICKFRAME and WS_CAPTION
        if (window->borderless)
        {
            return 0;
        }

        break;
    }
    case WM_KILLFOCUS:
    {
        QString str("Lost focus");
        QWidget* widget = QWidget::find((WId) HWND (wParam));
        if (widget)
        {
            str += QString(" to %1 (%2)").arg(widget->objectName()).arg(widget->metaObject()->className());
        }
        str += "\n";

        OutputDebugStringA(str.toLocal8Bit().data());
        break;
    }
    case WM_DESTROY:
    {
        delete(mainPanel);
        PostQuitMessage(0);
        break;
    }
    case WM_NCHITTEST:
    {
        if (window->borderless)
        {
            if (window->borderlessResizeable)
            {
                const LONG c_borderWidth = 8; //in pixels
                RECT winrect;
                GetWindowRect(hWnd, &winrect);
                long x = GET_X_LPARAM(lParam);
                long y = GET_Y_LPARAM(lParam);

                // bottom left corner
                if (x >= winrect.left && x < winrect.left + c_borderWidth &&
                        y < winrect.bottom && y >= winrect.bottom - c_borderWidth)
                {
                    return HTBOTTOMLEFT;
                }
                // bottom right corner
                if (x < winrect.right && x >= winrect.right - c_borderWidth &&
                        y < winrect.bottom && y >= winrect.bottom - c_borderWidth)
                {
                    return HTBOTTOMRIGHT;
                }
                // top left corner
                if (x >= winrect.left && x < winrect.left + c_borderWidth &&
                        y >= winrect.top && y < winrect.top + c_borderWidth)
                {
                    return HTTOPLEFT;
                }
                // top right corner
                if (x < winrect.right && x >= winrect.right - c_borderWidth &&
                        y >= winrect.top && y < winrect.top + c_borderWidth)
                {
                    return HTTOPRIGHT;
                }
                // left border
                if (x >= winrect.left && x < winrect.left + c_borderWidth)
                {
                    return HTLEFT;
                }
                // right border
                if (x < winrect.right && x >= winrect.right - c_borderWidth)
                {
                    return HTRIGHT;
                }
                // bottom border
                if (y < winrect.bottom && y >= winrect.bottom - c_borderWidth)
                {
                    return HTBOTTOM;
                }
                // top border
                if (y >= winrect.top && y < winrect.top + c_borderWidth)
                {
                    return HTTOP;
                }
            }
            return HTCAPTION;
        }
        break;
    }
    case WM_SIZE:
    {
        RECT winrect;
        GetClientRect(hWnd, &winrect);

        WINDOWPLACEMENT wp;
        wp.length = sizeof(WINDOWPLACEMENT);
        GetWindowPlacement(hWnd, &wp);
        if (wp.showCmd == SW_MAXIMIZE)
        {
            QPushButton* pushButtonMaximize = mainPanel->findChild<QPushButton*>("pushButtonMaximize");
            pushButtonMaximize->setStyleSheet(
                "#pushButtonMaximize {"
                    "image: url(:/Resource/Icons/Restore.png);
                }"
                "#pushButtonMaximize:hover {"
                    "image: url(:/Resource/Icons/RestoreHover.png);"
                "}"
            );
            mainPanel->setGeometry(8, 8, winrect.right - 16, winrect.bottom - 16);
        }
        else
        {
            QPushButton* pushButtonMaximize = mainPanel->findChild<QPushButton*>("pushButtonMaximize");
            pushButtonMaximize->setStyleSheet(
                "#pushButtonMaximize {"
                    "image: url(:/Resource/Icons/Maximize.png);"
                "}"
                "#pushButtonMaximize:hover {"
                    "image: url(:/Resource/Icons/MaximizeHover.png);"
                "}"
            );
            mainPanel->setGeometry(0, 0, winrect.right, winrect.bottom);
        }
        break;
    }
    case WM_GETMINMAXINFO:
    {
        MINMAXINFO* minMaxInfo = (MINMAXINFO*) lParam;
        if (window->minimumSize.required)
        {
            minMaxInfo->ptMinTrackSize.x = window->getMinimumWidth();;
            minMaxInfo->ptMinTrackSize.y = window->getMinimumHeight();
        }

        if (window->maximumSize.required)
        {
            minMaxInfo->ptMaxTrackSize.x = window->getMaximumWidth();
            minMaxInfo->ptMaxTrackSize.y = window->getMaximumHeight();
        }
        return 0;
    }
    }
    return DefWindowProc(hWnd, message, wParam, lParam);
}

void BorderlessWindow::toggleBorderless()
{
    if (visible)
    {
        Style newStyle = (borderless) ? Style::windowed : Style::aeroBorderless;
        SetWindowLongPtr(hWnd, GWL_STYLE, static_cast<LONG>(newStyle));

        borderless = !borderless;
        if (newStyle == Style::aeroBorderless)
        {
            toggleShadow();
        }
        // redraw frame
        SetWindowPos(hWnd, 0, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE);
        show();
    }
}

void BorderlessWindow::toggleShadow()
{
    if (borderless)
    {
        aeroShadow = !aeroShadow;
        const MARGINS c_shadowOn = {1, 1, 1, 1};
        const MARGINS c_shadowOff = {0, 0, 0, 0};
        DwmExtendFrameIntoClientArea(hWnd, (aeroShadow) ? (&c_shadowOn) : (&c_shadowOff));
    }
}

void BorderlessWindow::toggleResizeable()
{
    borderlessResizeable = borderlessResizeable ? false : true;
}

bool BorderlessWindow::isResizeable()
{
    return borderlessResizeable ? true : false;
}

void BorderlessWindow::show()
{
    ShowWindow(hWnd, SW_SHOW);
    visible = true;
}

void BorderlessWindow::hide()
{
    ShowWindow(hWnd, SW_HIDE);
    visible = false;
}

bool BorderlessWindow::isVisible()
{
    return visible ? true : false;
}

// Minimum size
void BorderlessWindow::setMinimumSize(const int width, const int height)
{
    this->minimumSize.required = true;
    this->minimumSize.width = width;
    this->minimumSize.height = height;
}

bool BorderlessWindow::isSetMinimumSize()
{
    return this->minimumSize.required;
}

void BorderlessWindow::removeMinimumSize()
{
    this->minimumSize.required = false;
    this->minimumSize.width = 0;
    this->minimumSize.height = 0;
}

int BorderlessWindow::getMinimumWidth()
{
    return minimumSize.width;
}

int BorderlessWindow::getMinimumHeight()
{
    return minimumSize.height;
}

// Maximum size
void BorderlessWindow::setMaximumSize(const int width, const int height)
{
    this->maximumSize.required = true;
    this->maximumSize.width = width;
    this->maximumSize.height = height;
}

bool BorderlessWindow::isSetMaximumSize()
{
    return this->maximumSize.required;
}

void BorderlessWindow::removeMaximumSize()
{
    this->maximumSize.required = false;
    this->maximumSize.width = 0;
    this->maximumSize.height = 0;
}

int BorderlessWindow::getMaximumWidth()
{
    return maximumSize.width;
}

int BorderlessWindow::getMaximumHeight()
{
    return maximumSize.height;
}
<|endoftext|>