<commit_before>// Copyright 2017 The Ray Authors.
//
// 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 "ray/util/logging.h"

#include <chrono>
#include <cstdlib>
#include <iostream>

#include "absl/strings/str_format.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "ray/util/filesystem.h"

using namespace testing;

namespace ray {

int64_t current_time_ms() {
  std::chrono::milliseconds ms_since_epoch =
      std::chrono::duration_cast<std::chrono::milliseconds>(
          std::chrono::steady_clock::now().time_since_epoch());
  return ms_since_epoch.count();
}

// This is not really test.
// This file just print some information using the logging macro.

void PrintLog() {
  RAY_LOG(DEBUG) << "This is the"
                 << " DEBUG"
                 << " message";
  RAY_LOG(INFO) << "This is the"
                << " INFO message";
  RAY_LOG(WARNING) << "This is the"
                   << " WARNING message";
  RAY_LOG(ERROR) << "This is the"
                 << " ERROR message";
  RAY_CHECK(true) << "This is a RAY_CHECK"
                  << " message but it won't show up";
  // The following 2 lines should not run since it will cause program failure.
  // RAY_LOG(FATAL) << "This is the FATAL message";
  // RAY_CHECK(false) << "This is a RAY_CHECK message but it won't show up";
}

TEST(PrintLogTest, LogTestWithoutInit) {
  // Without RayLog::StartRayLog, this should also work.
  PrintLog();
}

#if GTEST_HAS_STREAM_REDIRECTION
using testing::internal::CaptureStderr;
using testing::internal::GetCapturedStderr;

namespace {
void VerifyOnlyNthOccurenceLogged(bool fallback_to_debug) {
  const std::string kLogStr = "this is a test log";
  CaptureStderr();
  static int non_fallback_counter = 0;
  static int fallback_counter = 0;
  int &counter = fallback_to_debug ? fallback_counter : non_fallback_counter;
  for (int i = 0; i < 9; i++) {
    counter++;
    if (fallback_to_debug) {
      RAY_LOG_EVERY_N_OR_DEBUG(INFO, 3) << kLogStr;
    } else {
      RAY_LOG_EVERY_N(INFO, 3) << kLogStr;
    }
  }
  std::string output = GetCapturedStderr();
  for (int i = counter - 8; i <= counter; i++) {
    std::string expected_str = absl::StrFormat("[%d] this is a test log", i);
    if (i % 3 == 1) {
      EXPECT_THAT(output, HasSubstr(expected_str));
    } else {
      EXPECT_THAT(output, Not(HasSubstr(expected_str)));
    }
  }

  size_t occurrences = 0;
  std::string::size_type start = 0;

  while ((start = output.find(kLogStr, start)) != std::string::npos) {
    ++occurrences;
    start += kLogStr.length();
  }
  EXPECT_EQ(occurrences, 3);
}

void VerifyAllOccurenceLogged() {
  const std::string kLogStr = "this is a test log";
  CaptureStderr();
  for (int i = 0; i < 10; i++) {
    RAY_LOG_EVERY_N_OR_DEBUG(INFO, 3) << kLogStr;
  }
  std::string output = GetCapturedStderr();
  size_t occurrences = 0;
  std::string::size_type start = 0;
  while ((start = output.find("[0] this is a test log", start)) != std::string::npos) {
    ++occurrences;
    start += kLogStr.length();
  }
  EXPECT_EQ(occurrences, 10);
}

void VerifyNothingLogged(bool fallback_to_debug) {
  const std::string kLogStr = "this is a test log";
  CaptureStderr();
  for (int i = 0; i < 10; i++) {
    if (fallback_to_debug) {
      RAY_LOG_EVERY_N_OR_DEBUG(INFO, 3) << kLogStr;
    } else {
      RAY_LOG_EVERY_N(INFO, 3) << kLogStr;
    };
  }
  std::string output = GetCapturedStderr();

  size_t occurrences = 0;
  std::string::size_type start = 0;

  while ((start = output.find(kLogStr, start)) != std::string::npos) {
    ++occurrences;
    start += kLogStr.length();
  }
  EXPECT_EQ(occurrences, 0);
}
}  // namespace

TEST(PrintLogTest, TestRayLogEveryN) {
  RayLog::severity_threshold_ = RayLogLevel::INFO;
  VerifyOnlyNthOccurenceLogged(/*fallback_to_debug*/ false);

  RayLog::severity_threshold_ = RayLogLevel::DEBUG;
  VerifyOnlyNthOccurenceLogged(/*fallback_to_debug*/ false);

  RayLog::severity_threshold_ = RayLogLevel::WARNING;
  VerifyNothingLogged(/*fallback_to_debug*/ false);

  RayLog::severity_threshold_ = RayLogLevel::INFO;
}

TEST(PrintLogTest, TestRayLogEveryNOrDebug) {
  RayLog::severity_threshold_ = RayLogLevel::INFO;
  VerifyOnlyNthOccurenceLogged(/*fallback_to_debug*/ true);

  RayLog::severity_threshold_ = RayLogLevel::DEBUG;
  VerifyAllOccurenceLogged();

  RayLog::severity_threshold_ = RayLogLevel::WARNING;
  VerifyNothingLogged(/*fallback_to_debug*/ true);

  RayLog::severity_threshold_ = RayLogLevel::INFO;
}

TEST(PrintLogTest, TestRayLogEveryMs) {
  CaptureStderr();
  const std::string kLogStr = "this is a test log";
  auto start_time = std::chrono::steady_clock::now().time_since_epoch();
  size_t num_iterations = 0;
  while (std::chrono::steady_clock::now().time_since_epoch() - start_time <
         std::chrono::milliseconds(100)) {
    num_iterations++;
    RAY_LOG_EVERY_MS(INFO, 10) << kLogStr;
  }
  std::string output = GetCapturedStderr();
  size_t occurrences = 0;
  std::string::size_type start = 0;

  while ((start = output.find(kLogStr, start)) != std::string::npos) {
    ++occurrences;
    start += kLogStr.length();
  }
  EXPECT_LT(occurrences, num_iterations);
  EXPECT_GT(occurrences, 5);
  EXPECT_LT(occurrences, 15);
}

#endif /* GTEST_HAS_STREAM_REDIRECTION */

TEST(PrintLogTest, LogTestWithInit) {
  // Test empty app name.
  RayLog::StartRayLog("", RayLogLevel::DEBUG, ray::GetUserTempDir());
  PrintLog();
  RayLog::ShutDownRayLog();
}

// This test will output large amount of logs to stderr, should be disabled in travis.
TEST(LogPerfTest, PerfTest) {
  RayLog::StartRayLog(
      "/fake/path/to/appdire/LogPerfTest", RayLogLevel::ERROR, ray::GetUserTempDir());
  int rounds = 10;

  int64_t start_time = current_time_ms();
  for (int i = 0; i < rounds; ++i) {
    RAY_LOG(DEBUG) << "This is the "
                   << "RAY_DEBUG message";
  }
  int64_t elapsed = current_time_ms() - start_time;
  std::cout << "Testing DEBUG log for " << rounds << " rounds takes " << elapsed << " ms."
            << std::endl;

  start_time = current_time_ms();
  for (int i = 0; i < rounds; ++i) {
    RAY_LOG(ERROR) << "This is the "
                   << "RAY_ERROR message";
  }
  elapsed = current_time_ms() - start_time;
  std::cout << "Testing RAY_ERROR log for " << rounds << " rounds takes " << elapsed
            << " ms." << std::endl;

  start_time = current_time_ms();
  for (int i = 0; i < rounds; ++i) {
    RAY_CHECK(i >= 0) << "This is a RAY_CHECK "
                      << "message but it won't show up";
  }
  elapsed = current_time_ms() - start_time;
  std::cout << "Testing RAY_CHECK(true) for " << rounds << " rounds takes " << elapsed
            << " ms." << std::endl;
  RayLog::ShutDownRayLog();
}

TEST(PrintLogTest, TestCheckOp) {
  int i = 1;
  RAY_CHECK_EQ(i, 1);
  ASSERT_DEATH(RAY_CHECK_EQ(i, 2), "1 vs 2");

  RAY_CHECK_NE(i, 0);
  ASSERT_DEATH(RAY_CHECK_NE(i, 1), "1 vs 1");

  RAY_CHECK_LE(i, 1);
  ASSERT_DEATH(RAY_CHECK_LE(i, 0), "1 vs 0");

  RAY_CHECK_LT(i, 2);
  ASSERT_DEATH(RAY_CHECK_LT(i, 1), "1 vs 1");

  RAY_CHECK_GE(i, 1);
  ASSERT_DEATH(RAY_CHECK_GE(i, 2), "1 vs 2");

  RAY_CHECK_GT(i, 0);
  ASSERT_DEATH(RAY_CHECK_GT(i, 1), "1 vs 1");

  int j = 0;
  RAY_CHECK_NE(i, j);
  ASSERT_DEATH(RAY_CHECK_EQ(i, j), "1 vs 0");
}

std::string TestFunctionLevel0() {
  std::ostringstream oss;
  oss << ray::StackTrace();
  std::string stack_trace = oss.str();
  RAY_LOG(INFO) << "TestFunctionLevel0\n" << stack_trace;
  return stack_trace;
}

std::string TestFunctionLevel1() {
  RAY_LOG(INFO) << "TestFunctionLevel1:";
  return TestFunctionLevel0();
}

std::string TestFunctionLevel2() {
  RAY_LOG(INFO) << "TestFunctionLevel2:";
  return TestFunctionLevel1();
}

TEST(PrintLogTest, TestStackTrace) {
  auto ret0 = TestFunctionLevel0();
  EXPECT_TRUE(ret0.find("TestFunctionLevel0") != std::string::npos) << ret0;
  auto ret1 = TestFunctionLevel1();
  EXPECT_TRUE(ret1.find("TestFunctionLevel1") != std::string::npos) << ret1;
  auto ret2 = TestFunctionLevel2();
  EXPECT_TRUE(ret2.find("TestFunctionLevel2") != std::string::npos) << ret2;
}

int TerminateHandlerLevel0() {
  RAY_LOG(INFO) << "TerminateHandlerLevel0";
  auto terminate_handler = std::get_terminate();
  (*terminate_handler)();
  return 0;
}

int TerminateHandlerLevel1() {
  RAY_LOG(INFO) << "TerminateHandlerLevel1";
  TerminateHandlerLevel0();
  return 1;
}

TEST(PrintLogTest, TestTerminateHandler) {
  ray::RayLog::InstallTerminateHandler();
  ASSERT_DEATH(TerminateHandlerLevel1(),
               ".*TerminateHandlerLevel0.*TerminateHandlerLevel1.*");
}

TEST(PrintLogTest, TestFailureSignalHandler) {
  ray::RayLog::InstallFailureSignalHandler(nullptr);
  ASSERT_DEATH(abort(), ".*SIGABRT received.*");
}

}  // namespace ray

int main(int argc, char **argv) {
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<commit_msg>Disable stack trace logging tests for windows (#26488)<commit_after>// Copyright 2017 The Ray Authors.
//
// 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 "ray/util/logging.h"

#include <chrono>
#include <cstdlib>
#include <iostream>

#include "absl/strings/str_format.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "ray/util/filesystem.h"

using namespace testing;

namespace ray {

int64_t current_time_ms() {
  std::chrono::milliseconds ms_since_epoch =
      std::chrono::duration_cast<std::chrono::milliseconds>(
          std::chrono::steady_clock::now().time_since_epoch());
  return ms_since_epoch.count();
}

// This is not really test.
// This file just print some information using the logging macro.

void PrintLog() {
  RAY_LOG(DEBUG) << "This is the"
                 << " DEBUG"
                 << " message";
  RAY_LOG(INFO) << "This is the"
                << " INFO message";
  RAY_LOG(WARNING) << "This is the"
                   << " WARNING message";
  RAY_LOG(ERROR) << "This is the"
                 << " ERROR message";
  RAY_CHECK(true) << "This is a RAY_CHECK"
                  << " message but it won't show up";
  // The following 2 lines should not run since it will cause program failure.
  // RAY_LOG(FATAL) << "This is the FATAL message";
  // RAY_CHECK(false) << "This is a RAY_CHECK message but it won't show up";
}

TEST(PrintLogTest, LogTestWithoutInit) {
  // Without RayLog::StartRayLog, this should also work.
  PrintLog();
}

#if GTEST_HAS_STREAM_REDIRECTION
using testing::internal::CaptureStderr;
using testing::internal::GetCapturedStderr;

namespace {
void VerifyOnlyNthOccurenceLogged(bool fallback_to_debug) {
  const std::string kLogStr = "this is a test log";
  CaptureStderr();
  static int non_fallback_counter = 0;
  static int fallback_counter = 0;
  int &counter = fallback_to_debug ? fallback_counter : non_fallback_counter;
  for (int i = 0; i < 9; i++) {
    counter++;
    if (fallback_to_debug) {
      RAY_LOG_EVERY_N_OR_DEBUG(INFO, 3) << kLogStr;
    } else {
      RAY_LOG_EVERY_N(INFO, 3) << kLogStr;
    }
  }
  std::string output = GetCapturedStderr();
  for (int i = counter - 8; i <= counter; i++) {
    std::string expected_str = absl::StrFormat("[%d] this is a test log", i);
    if (i % 3 == 1) {
      EXPECT_THAT(output, HasSubstr(expected_str));
    } else {
      EXPECT_THAT(output, Not(HasSubstr(expected_str)));
    }
  }

  size_t occurrences = 0;
  std::string::size_type start = 0;

  while ((start = output.find(kLogStr, start)) != std::string::npos) {
    ++occurrences;
    start += kLogStr.length();
  }
  EXPECT_EQ(occurrences, 3);
}

void VerifyAllOccurenceLogged() {
  const std::string kLogStr = "this is a test log";
  CaptureStderr();
  for (int i = 0; i < 10; i++) {
    RAY_LOG_EVERY_N_OR_DEBUG(INFO, 3) << kLogStr;
  }
  std::string output = GetCapturedStderr();
  size_t occurrences = 0;
  std::string::size_type start = 0;
  while ((start = output.find("[0] this is a test log", start)) != std::string::npos) {
    ++occurrences;
    start += kLogStr.length();
  }
  EXPECT_EQ(occurrences, 10);
}

void VerifyNothingLogged(bool fallback_to_debug) {
  const std::string kLogStr = "this is a test log";
  CaptureStderr();
  for (int i = 0; i < 10; i++) {
    if (fallback_to_debug) {
      RAY_LOG_EVERY_N_OR_DEBUG(INFO, 3) << kLogStr;
    } else {
      RAY_LOG_EVERY_N(INFO, 3) << kLogStr;
    };
  }
  std::string output = GetCapturedStderr();

  size_t occurrences = 0;
  std::string::size_type start = 0;

  while ((start = output.find(kLogStr, start)) != std::string::npos) {
    ++occurrences;
    start += kLogStr.length();
  }
  EXPECT_EQ(occurrences, 0);
}
}  // namespace

TEST(PrintLogTest, TestRayLogEveryN) {
  RayLog::severity_threshold_ = RayLogLevel::INFO;
  VerifyOnlyNthOccurenceLogged(/*fallback_to_debug*/ false);

  RayLog::severity_threshold_ = RayLogLevel::DEBUG;
  VerifyOnlyNthOccurenceLogged(/*fallback_to_debug*/ false);

  RayLog::severity_threshold_ = RayLogLevel::WARNING;
  VerifyNothingLogged(/*fallback_to_debug*/ false);

  RayLog::severity_threshold_ = RayLogLevel::INFO;
}

TEST(PrintLogTest, TestRayLogEveryNOrDebug) {
  RayLog::severity_threshold_ = RayLogLevel::INFO;
  VerifyOnlyNthOccurenceLogged(/*fallback_to_debug*/ true);

  RayLog::severity_threshold_ = RayLogLevel::DEBUG;
  VerifyAllOccurenceLogged();

  RayLog::severity_threshold_ = RayLogLevel::WARNING;
  VerifyNothingLogged(/*fallback_to_debug*/ true);

  RayLog::severity_threshold_ = RayLogLevel::INFO;
}

TEST(PrintLogTest, TestRayLogEveryMs) {
  CaptureStderr();
  const std::string kLogStr = "this is a test log";
  auto start_time = std::chrono::steady_clock::now().time_since_epoch();
  size_t num_iterations = 0;
  while (std::chrono::steady_clock::now().time_since_epoch() - start_time <
         std::chrono::milliseconds(100)) {
    num_iterations++;
    RAY_LOG_EVERY_MS(INFO, 10) << kLogStr;
  }
  std::string output = GetCapturedStderr();
  size_t occurrences = 0;
  std::string::size_type start = 0;

  while ((start = output.find(kLogStr, start)) != std::string::npos) {
    ++occurrences;
    start += kLogStr.length();
  }
  EXPECT_LT(occurrences, num_iterations);
  EXPECT_GT(occurrences, 5);
  EXPECT_LT(occurrences, 15);
}

#endif /* GTEST_HAS_STREAM_REDIRECTION */

TEST(PrintLogTest, LogTestWithInit) {
  // Test empty app name.
  RayLog::StartRayLog("", RayLogLevel::DEBUG, ray::GetUserTempDir());
  PrintLog();
  RayLog::ShutDownRayLog();
}

// This test will output large amount of logs to stderr, should be disabled in travis.
TEST(LogPerfTest, PerfTest) {
  RayLog::StartRayLog(
      "/fake/path/to/appdire/LogPerfTest", RayLogLevel::ERROR, ray::GetUserTempDir());
  int rounds = 10;

  int64_t start_time = current_time_ms();
  for (int i = 0; i < rounds; ++i) {
    RAY_LOG(DEBUG) << "This is the "
                   << "RAY_DEBUG message";
  }
  int64_t elapsed = current_time_ms() - start_time;
  std::cout << "Testing DEBUG log for " << rounds << " rounds takes " << elapsed << " ms."
            << std::endl;

  start_time = current_time_ms();
  for (int i = 0; i < rounds; ++i) {
    RAY_LOG(ERROR) << "This is the "
                   << "RAY_ERROR message";
  }
  elapsed = current_time_ms() - start_time;
  std::cout << "Testing RAY_ERROR log for " << rounds << " rounds takes " << elapsed
            << " ms." << std::endl;

  start_time = current_time_ms();
  for (int i = 0; i < rounds; ++i) {
    RAY_CHECK(i >= 0) << "This is a RAY_CHECK "
                      << "message but it won't show up";
  }
  elapsed = current_time_ms() - start_time;
  std::cout << "Testing RAY_CHECK(true) for " << rounds << " rounds takes " << elapsed
            << " ms." << std::endl;
  RayLog::ShutDownRayLog();
}

TEST(PrintLogTest, TestCheckOp) {
  int i = 1;
  RAY_CHECK_EQ(i, 1);
  ASSERT_DEATH(RAY_CHECK_EQ(i, 2), "1 vs 2");

  RAY_CHECK_NE(i, 0);
  ASSERT_DEATH(RAY_CHECK_NE(i, 1), "1 vs 1");

  RAY_CHECK_LE(i, 1);
  ASSERT_DEATH(RAY_CHECK_LE(i, 0), "1 vs 0");

  RAY_CHECK_LT(i, 2);
  ASSERT_DEATH(RAY_CHECK_LT(i, 1), "1 vs 1");

  RAY_CHECK_GE(i, 1);
  ASSERT_DEATH(RAY_CHECK_GE(i, 2), "1 vs 2");

  RAY_CHECK_GT(i, 0);
  ASSERT_DEATH(RAY_CHECK_GT(i, 1), "1 vs 1");

  int j = 0;
  RAY_CHECK_NE(i, j);
  ASSERT_DEATH(RAY_CHECK_EQ(i, j), "1 vs 0");
}

#ifndef _WIN32
std::string TestFunctionLevel0() {
  std::ostringstream oss;
  oss << ray::StackTrace();
  std::string stack_trace = oss.str();
  RAY_LOG(INFO) << "TestFunctionLevel0\n" << stack_trace;
  return stack_trace;
}

std::string TestFunctionLevel1() {
  RAY_LOG(INFO) << "TestFunctionLevel1:";
  return TestFunctionLevel0();
}

std::string TestFunctionLevel2() {
  RAY_LOG(INFO) << "TestFunctionLevel2:";
  return TestFunctionLevel1();
}

TEST(PrintLogTest, TestStackTrace) {
  auto ret0 = TestFunctionLevel0();
  EXPECT_TRUE(ret0.find("TestFunctionLevel0") != std::string::npos) << ret0;
  auto ret1 = TestFunctionLevel1();
  EXPECT_TRUE(ret1.find("TestFunctionLevel1") != std::string::npos) << ret1;
  auto ret2 = TestFunctionLevel2();
  EXPECT_TRUE(ret2.find("TestFunctionLevel2") != std::string::npos) << ret2;
}

int TerminateHandlerLevel0() {
  RAY_LOG(INFO) << "TerminateHandlerLevel0";
  auto terminate_handler = std::get_terminate();
  (*terminate_handler)();
  return 0;
}

int TerminateHandlerLevel1() {
  RAY_LOG(INFO) << "TerminateHandlerLevel1";
  TerminateHandlerLevel0();
  return 1;
}

TEST(PrintLogTest, TestTerminateHandler) {
  ray::RayLog::InstallTerminateHandler();
  ASSERT_DEATH(TerminateHandlerLevel1(),
               ".*TerminateHandlerLevel0.*TerminateHandlerLevel1.*");
}
#endif

TEST(PrintLogTest, TestFailureSignalHandler) {
  ray::RayLog::InstallFailureSignalHandler(nullptr);
  ASSERT_DEATH(abort(), ".*SIGABRT received.*");
}

}  // namespace ray

int main(int argc, char **argv) {
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: XMLEventImportHelper.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 12:48:48 $
 *
 *  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 _XMLOFF_EVENTIMPORTHELPER_HXX
#define _XMLOFF_EVENTIMPORTHELPER_HXX

#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif

#ifndef _XMLOFF_XMLEVENT_HXX
#include "xmlevent.hxx"
#endif

#include <map>
#include <list>

namespace com { namespace sun { namespace star {
    namespace xml { namespace sax { class XAttributeList; } }
} } }
namespace rtl { class OUString; }
class XMLEventContextFactory;
class XMLEventsImportContext;
struct XMLEventNameTranslation;

typedef ::std::map< ::rtl::OUString, XMLEventContextFactory* > FactoryMap;
typedef ::std::map< XMLEventName, ::rtl::OUString > NameMap;
typedef ::std::list< NameMap* > NameMapList;

/**
 * Helps the XMLEventsImportContext.
 *
 * This class stores
 * a) the translation from XML event names to API event names, and
 * b) a mapping from script language names to XMLEventContextFactory objects
 *    (that handle particular languages).
 *
 * Event name translation tables may be added, i.e. they will be joined
 * together. If different translations are needed (i.e., if the same XML name
 * needs to be translated to different API names in different contexts), then
 * translation tables may be saved on a translation table stack.
 */
class XMLEventImportHelper
{
    /// map of XMLEventContextFactory objects
    FactoryMap aFactoryMap;

    /// map from XML to API names
    NameMap* pEventNameMap;

    /// stack of previous aEventNameMap
    NameMapList aEventNameMapList;

public:
    XMLEventImportHelper();

    ~XMLEventImportHelper();

    /// register a handler for a particular language type
    void RegisterFactory( const ::rtl::OUString& rLanguage,
                          XMLEventContextFactory* aFactory );

    /// add event name translation to the internal table
    void AddTranslationTable( const XMLEventNameTranslation* pTransTable );

    /// save the old translation table on a stack and install an empty table
    void PushTranslationTable();

    /// recover the top-most previously saved translation table
    void PopTranslationTable();

    /// create an appropriate import context for a particular event
    SvXMLImportContext* CreateContext(
        SvXMLImport& rImport,
        sal_uInt16 nPrefix,
        const ::rtl::OUString& rLocalName,
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::xml::sax::XAttributeList> & xAttrList,
        XMLEventsImportContext* rEvents,
        const ::rtl::OUString& rXmlEventName,
        const ::rtl::OUString& rLanguage);

};

#endif
<commit_msg>INTEGRATION: CWS vgbugs07 (1.4.276); FILE MERGED 2007/06/04 13:23:17 vg 1.4.276.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: XMLEventImportHelper.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 14:39:33 $
 *
 *  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 _XMLOFF_EVENTIMPORTHELPER_HXX
#define _XMLOFF_EVENTIMPORTHELPER_HXX

#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif

#ifndef _XMLOFF_XMLEVENT_HXX
#include <xmloff/xmlevent.hxx>
#endif

#include <map>
#include <list>

namespace com { namespace sun { namespace star {
    namespace xml { namespace sax { class XAttributeList; } }
} } }
namespace rtl { class OUString; }
class XMLEventContextFactory;
class XMLEventsImportContext;
struct XMLEventNameTranslation;

typedef ::std::map< ::rtl::OUString, XMLEventContextFactory* > FactoryMap;
typedef ::std::map< XMLEventName, ::rtl::OUString > NameMap;
typedef ::std::list< NameMap* > NameMapList;

/**
 * Helps the XMLEventsImportContext.
 *
 * This class stores
 * a) the translation from XML event names to API event names, and
 * b) a mapping from script language names to XMLEventContextFactory objects
 *    (that handle particular languages).
 *
 * Event name translation tables may be added, i.e. they will be joined
 * together. If different translations are needed (i.e., if the same XML name
 * needs to be translated to different API names in different contexts), then
 * translation tables may be saved on a translation table stack.
 */
class XMLEventImportHelper
{
    /// map of XMLEventContextFactory objects
    FactoryMap aFactoryMap;

    /// map from XML to API names
    NameMap* pEventNameMap;

    /// stack of previous aEventNameMap
    NameMapList aEventNameMapList;

public:
    XMLEventImportHelper();

    ~XMLEventImportHelper();

    /// register a handler for a particular language type
    void RegisterFactory( const ::rtl::OUString& rLanguage,
                          XMLEventContextFactory* aFactory );

    /// add event name translation to the internal table
    void AddTranslationTable( const XMLEventNameTranslation* pTransTable );

    /// save the old translation table on a stack and install an empty table
    void PushTranslationTable();

    /// recover the top-most previously saved translation table
    void PopTranslationTable();

    /// create an appropriate import context for a particular event
    SvXMLImportContext* CreateContext(
        SvXMLImport& rImport,
        sal_uInt16 nPrefix,
        const ::rtl::OUString& rLocalName,
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::xml::sax::XAttributeList> & xAttrList,
        XMLEventsImportContext* rEvents,
        const ::rtl::OUString& rXmlEventName,
        const ::rtl::OUString& rLanguage);

};

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * REALM CONFIDENTIAL
 * __________________
 *
 *  [2011] - [2012] Realm Inc
 *  All Rights Reserved.
 *
 * NOTICE:  All information contained herein is, and remains
 * the property of Realm Incorporated and its suppliers,
 * if any.  The intellectual and technical concepts contained
 * herein are proprietary to Realm Incorporated
 * and its suppliers and may be covered by U.S. and Foreign Patents,
 * patents in process, and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Realm Incorporated.
 *
 **************************************************************************/
#ifndef REALM_UTIL_TERMINATE_HPP
#define REALM_UTIL_TERMINATE_HPP

#include <cstdlib>
#include <sstream>
#include <string>

#include <realm/util/features.h>
#include <realm/version.hpp>

#define REALM_TERMINATE(msg) realm::util::terminate((msg), __FILE__, __LINE__)

namespace realm {
namespace util {
REALM_NORETURN void terminate_internal(std::stringstream&) noexcept;

REALM_NORETURN inline void terminate(const char* message, const char* file, long line) noexcept
{
    std::stringstream ss;
    ss << file << ":" << line << ": " REALM_VER_CHUNK " " << message << "\n";
    terminate_internal(ss);
}

template <typename T1, typename T2>
REALM_NORETURN void terminate(const char* message, const char* file, long line, T1 info1, T2 info2) noexcept
{
    std::stringstream ss;
    ss << file << ":" << line << ": " REALM_VER_CHUNK " " << message << " [" << info1 << ", " << info2 << "]\n";
    terminate_internal(ss);
}

template <typename T1, typename T2, typename T3, typename T4>
REALM_NORETURN void terminate(const char* message, const char* file, long line, T1 info1, T2 info2, T3 info3,
                              T4 info4) noexcept
{
    std::stringstream ss;
    ss << file << ":" << line << ": " REALM_VER_CHUNK " " << message
        << " [" << info1 << ", " << info2 << ", " << info3 << ", " << info4 << "]\n";
    terminate_internal(ss);
}

template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
REALM_NORETURN void terminate(const char* message, const char* file, long line, T1 info1, T2 info2, T3 info3,
                              T4 info4, T5 info5, T6 info6) noexcept
{
    std::stringstream ss;
    ss << file << ":" << line << ": " REALM_VER_CHUNK " " << message
        << " [" << info1 << ", " << info2 << ", " << info3 << ", "
        << info4 << ", " << info5 << ", " << info6 << "]\n";
    terminate_internal(ss);
}

} // namespace util
} // namespace realm

#endif // REALM_UTIL_TERMINATE_HPP
<commit_msg>Refactored util::terminate() to use variadics<commit_after>/*************************************************************************
 *
 * REALM CONFIDENTIAL
 * __________________
 *
 *  [2011] - [2012] Realm Inc
 *  All Rights Reserved.
 *
 * NOTICE:  All information contained herein is, and remains
 * the property of Realm Incorporated and its suppliers,
 * if any.  The intellectual and technical concepts contained
 * herein are proprietary to Realm Incorporated
 * and its suppliers and may be covered by U.S. and Foreign Patents,
 * patents in process, and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Realm Incorporated.
 *
 **************************************************************************/
#ifndef REALM_UTIL_TERMINATE_HPP
#define REALM_UTIL_TERMINATE_HPP

#include <cstdlib>
#include <sstream>

#include <realm/util/features.h>
#include <realm/version.hpp>

#define REALM_TERMINATE(msg) realm::util::terminate((msg), __FILE__, __LINE__)

namespace realm {
namespace util {
REALM_NORETURN void terminate_internal(std::stringstream&) noexcept;

REALM_NORETURN inline void terminate(const char* message, const char* file, long line) noexcept
{
    std::stringstream ss;
    ss << file << ":" << line << ": " REALM_VER_CHUNK " " << message << "\n";
    terminate_internal(ss);
}

template<typename T, typename... Ts>
REALM_NORETURN void terminate(const char* message, const char* file, long line,
                              T first_info, Ts... other_infos) noexcept
{
    std::stringstream ss;
    using variadics_unpacker = int[];

    static_assert(sizeof...(other_infos) == 1 || sizeof...(other_infos) == 3 || sizeof...(other_infos) == 5,
                  "Called realm::util::terminate() with wrong number of arguments");

    ss << file << ':' << line << ": " REALM_VER_CHUNK " " << message << " [" << first_info;
    (void) variadics_unpacker { 0, (ss << ", " << other_infos, void(), 0)... };
    ss << "]" << std::endl;

    terminate_internal(ss);
}

} // namespace util
} // namespace realm

#endif // REALM_UTIL_TERMINATE_HPP
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */

#include <bordrhdl.hxx>
#include <sax/tools/converter.hxx>
#include <xmloff/xmltoken.hxx>
#include <xmloff/xmluconv.hxx>
#include <rtl/ustrbuf.hxx>
#include <com/sun/star/uno/Any.hxx>
#include <com/sun/star/table/BorderLine2.hpp>

using namespace ::com::sun::star;
using namespace ::xmloff::token;

const sal_uInt16 API_LINE_SOLID   = 0;
const sal_uInt16 API_LINE_DOTTED  = 1;
const sal_uInt16 API_LINE_DASHED  = 2;
const sal_uInt16 API_LINE_DOUBLE  = 3;
const sal_uInt16 API_LINE_THINTHICK_SMALLGAP  = 4;
const sal_uInt16 API_LINE_THINTHICK_MEDIUMGAP  = 5;
const sal_uInt16 API_LINE_THINTHICK_LARGEGAP  = 6;
const sal_uInt16 API_LINE_THICKTHIN_SMALLGAP  = 7;
const sal_uInt16 API_LINE_THICKTHIN_MEDIUMGAP  = 8;
const sal_uInt16 API_LINE_THICKTHIN_LARGEGAP  = 9;
const sal_uInt16 API_LINE_EMBOSSED  = 10;
const sal_uInt16 API_LINE_ENGRAVED  = 11;
const sal_uInt16 API_LINE_OUTSET  = 12;
const sal_uInt16 API_LINE_INSET  = 13;
const sal_uInt16 API_LINE_FINE_DASHED  = 14;
const sal_uInt16 API_LINE_NONE = USHRT_MAX;

#define DEF_LINE_WIDTH_0        1
#define DEF_LINE_WIDTH_1        35
#define DEF_LINE_WIDTH_2        88

#define SVX_XML_BORDER_WIDTH_THIN 0
#define SVX_XML_BORDER_WIDTH_MIDDLE 1
#define SVX_XML_BORDER_WIDTH_THICK 2

SvXMLEnumMapEntry pXML_BorderStyles[] =
{
    { XML_NONE,                 API_LINE_NONE   },
    { XML_HIDDEN,               API_LINE_NONE   },
    { XML_SOLID,                API_LINE_SOLID  },
    { XML_DOUBLE,               API_LINE_DOUBLE },
    { XML_DOTTED,               API_LINE_DOTTED },
    { XML_DASHED,               API_LINE_DASHED },
    { XML_GROOVE,               API_LINE_ENGRAVED },
    { XML_RIDGE,                API_LINE_EMBOSSED },
    { XML_INSET,                API_LINE_INSET  },
    { XML_OUTSET,               API_LINE_OUTSET },
    { XML_FINE_DASHED,          API_LINE_FINE_DASHED },
    { XML_TOKEN_INVALID,        0 }
};

SvXMLEnumMapEntry pXML_NamedBorderWidths[] =
{
    { XML_THIN,             SVX_XML_BORDER_WIDTH_THIN   },
    { XML_MIDDLE,           SVX_XML_BORDER_WIDTH_MIDDLE },
    { XML_THICK,            SVX_XML_BORDER_WIDTH_THICK  },
    { XML_TOKEN_INVALID,    0 }
};
// mapping tables to map external xml input to internal box line widths

static sal_uInt16 const aBorderWidths[] =
{
    DEF_LINE_WIDTH_0,
    DEF_LINE_WIDTH_1,
    DEF_LINE_WIDTH_2
};

static void lcl_frmitems_setXMLBorderStyle( table::BorderLine2 & rBorderLine, sal_uInt16 nStyle )
{
    sal_Int16 eStyle = -1; // None
    if ( nStyle != API_LINE_NONE )
        eStyle = sal_Int16( nStyle );

    rBorderLine.LineStyle = eStyle;
}

//
// class XMLEscapementPropHdl
//

XMLBorderWidthHdl::~XMLBorderWidthHdl()
{
    // nothing to do
}

bool XMLBorderWidthHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    SvXMLTokenEnumerator aTokenEnum( rStrImpValue );

    sal_Int32 nInWidth, nDistance, nOutWidth;

    OUString aToken;
    if( !aTokenEnum.getNextToken( aToken ) )
        return false;

    if (!rUnitConverter.convertMeasureToCore( nInWidth, aToken, 0, 500 ))
        return false;

    if( !aTokenEnum.getNextToken( aToken ) )
        return false;

    if (!rUnitConverter.convertMeasureToCore( nDistance, aToken, 0, 500 ))
        return false;

    if( !aTokenEnum.getNextToken( aToken ) )
        return false;

    if (!rUnitConverter.convertMeasureToCore( nOutWidth, aToken, 0, 500 ))
        return false;

    table::BorderLine2 aBorderLine;
    if(!(rValue >>= aBorderLine))
        aBorderLine.Color = 0;

    aBorderLine.InnerLineWidth = sal::static_int_cast< sal_Int16 >(nInWidth);
    aBorderLine.OuterLineWidth = sal::static_int_cast< sal_Int16 >(nOutWidth);
    aBorderLine.LineDistance   = sal::static_int_cast< sal_Int16 >(nDistance);

    rValue <<= aBorderLine;
    return true;
}

bool XMLBorderWidthHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    OUStringBuffer aOut;

    table::BorderLine2 aBorderLine;
    if(!(rValue >>= aBorderLine))
        return false;

    bool bDouble = false;
    switch ( aBorderLine.LineStyle )
    {
        case API_LINE_DOUBLE:
        case API_LINE_THINTHICK_SMALLGAP:
        case API_LINE_THINTHICK_MEDIUMGAP:
        case API_LINE_THINTHICK_LARGEGAP:
        case API_LINE_THICKTHIN_SMALLGAP:
        case API_LINE_THICKTHIN_MEDIUMGAP:
        case API_LINE_THICKTHIN_LARGEGAP:
            bDouble = true;
            break;
        default:
            break;
    }

    if( ( aBorderLine.LineDistance == 0 && aBorderLine.InnerLineWidth == 0 ) || !bDouble )
        return false;

    rUnitConverter.convertMeasureToXML( aOut, aBorderLine.InnerLineWidth );
    aOut.append( ' ' );
    rUnitConverter.convertMeasureToXML( aOut, aBorderLine.LineDistance );
    aOut.append( ' ' );
    rUnitConverter.convertMeasureToXML( aOut, aBorderLine.OuterLineWidth );

    rStrExpValue = aOut.makeStringAndClear();
    return true;
}

//
// class XMLEscapementHeightPropHdl
//

XMLBorderHdl::~XMLBorderHdl()
{
    // nothing to do
}

bool XMLBorderHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    OUString aToken;
    SvXMLTokenEnumerator aTokens( rStrImpValue );

    bool bHasStyle = false;
    bool bHasWidth = false;
    bool bHasColor = false;

    sal_uInt16 nStyle = USHRT_MAX;
    sal_uInt16 nWidth = 0;
    sal_uInt16 nNamedWidth = USHRT_MAX;
    sal_Int32 nColor = 0;

    sal_Int32 nTemp;
    while( aTokens.getNextToken( aToken ) && !aToken.isEmpty() )
    {
        if( !bHasWidth &&
            rUnitConverter.convertEnum( nNamedWidth, aToken,
                                        pXML_NamedBorderWidths ) )
        {
            bHasWidth = true;
        }
        else if( !bHasStyle &&
                 rUnitConverter.convertEnum( nStyle, aToken,
                                              pXML_BorderStyles ) )
        {
            bHasStyle = true;
        }
        else if (!bHasColor && ::sax::Converter::convertColor(nColor, aToken))
        {
            bHasColor = true;
        }
        else if( !bHasWidth &&
                 rUnitConverter.convertMeasureToCore( nTemp, aToken, 0,
                                                 USHRT_MAX ) )
        {
            nWidth = (sal_uInt16)nTemp;
            bHasWidth = true;
        }
        else
        {
            // missformed
            return false;
        }
    }

    // if there is no style or a different style than none but no width,
       // then the declaration is not valid.
    if( !bHasStyle || (API_LINE_NONE != nStyle && !bHasWidth) )
        return false;

    table::BorderLine2 aBorderLine;
    if(!(rValue >>= aBorderLine))
    {
        aBorderLine.Color = 0;
        aBorderLine.InnerLineWidth = 0;
        aBorderLine.OuterLineWidth = 0;
        aBorderLine.LineDistance   = 0;
        aBorderLine.LineWidth      = 0;
    }

    // first of all, delete an empty line
    if( (bHasStyle && API_LINE_NONE == nStyle) ||
        (bHasWidth && USHRT_MAX == nNamedWidth && 0 == nWidth) )
    {
        aBorderLine.InnerLineWidth = 0;
        aBorderLine.OuterLineWidth = 0;
        aBorderLine.LineDistance   = 0;
        aBorderLine.LineWidth = 0;
    }
    else if( bHasWidth )
    {
        if( USHRT_MAX != nNamedWidth )
        {
            aBorderLine.LineWidth = aBorderWidths[nNamedWidth];
        }
        else
        {
            aBorderLine.LineWidth = nWidth;
            lcl_frmitems_setXMLBorderStyle( aBorderLine, nStyle );
        }
    }
    else
    {
        aBorderLine.LineWidth = 0;
        lcl_frmitems_setXMLBorderStyle( aBorderLine, nStyle );
    }

    // set color
    if( bHasColor )
    {
        aBorderLine.Color = nColor;
    }

    rValue <<= aBorderLine;
    return true;
}

bool XMLBorderHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& /* rUnitConverter */ ) const
{
    OUStringBuffer aOut;

    table::BorderLine2 aBorderLine;
    if(!(rValue >>= aBorderLine))
        return false;

    sal_Int32 nWidth = aBorderLine.LineWidth;

    if( nWidth == 0 )
    {
        aOut.append( GetXMLToken( XML_NONE ) );
    }
    else
    {
        ::sax::Converter::convertMeasure( aOut, nWidth,
               util::MeasureUnit::MM_100TH, util::MeasureUnit::POINT);

        aOut.append( ' ' );

        XMLTokenEnum eStyleToken = XML_SOLID;
        switch ( aBorderLine.LineStyle )
        {
            case API_LINE_DASHED:
                eStyleToken = XML_DASHED;
                break;
            case API_LINE_DOTTED:
                eStyleToken = XML_DOTTED;
                break;
            case API_LINE_DOUBLE:
            case API_LINE_THINTHICK_SMALLGAP:
            case API_LINE_THINTHICK_MEDIUMGAP:
            case API_LINE_THINTHICK_LARGEGAP:
            case API_LINE_THICKTHIN_SMALLGAP:
            case API_LINE_THICKTHIN_MEDIUMGAP:
            case API_LINE_THICKTHIN_LARGEGAP:
                eStyleToken = XML_DOUBLE;
                break;
            case API_LINE_EMBOSSED:
                eStyleToken = XML_RIDGE;
                break;
            case API_LINE_ENGRAVED:
                eStyleToken = XML_GROOVE;
                break;
            case API_LINE_OUTSET:
                eStyleToken = XML_OUTSET;
                break;
            case API_LINE_INSET:
                eStyleToken = XML_INSET;
                break;
            case API_LINE_FINE_DASHED:
                eStyleToken = XML_FINE_DASHED;
                break;
            case API_LINE_SOLID:
            default:
                break;
        }
        aOut.append( GetXMLToken( eStyleToken ) );

        aOut.append( ' ' );

        ::sax::Converter::convertColor( aOut, aBorderLine.Color );
    }

    rStrExpValue = aOut.makeStringAndClear();

    return true;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Remove this duplicate and use the UNO constant values instead.<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */

#include <bordrhdl.hxx>
#include <sax/tools/converter.hxx>
#include <xmloff/xmltoken.hxx>
#include <xmloff/xmluconv.hxx>
#include <rtl/ustrbuf.hxx>
#include <com/sun/star/uno/Any.hxx>
#include <com/sun/star/table/BorderLine2.hpp>
#include <com/sun/star/table/BorderLineStyle.hpp>

using namespace ::com::sun::star;
using namespace ::xmloff::token;

#define DEF_LINE_WIDTH_0        1
#define DEF_LINE_WIDTH_1        35
#define DEF_LINE_WIDTH_2        88

#define SVX_XML_BORDER_WIDTH_THIN 0
#define SVX_XML_BORDER_WIDTH_MIDDLE 1
#define SVX_XML_BORDER_WIDTH_THICK 2

SvXMLEnumMapEntry pXML_BorderStyles[] =
{
    { XML_NONE,          table::BorderLineStyle::NONE   },
    { XML_HIDDEN,        table::BorderLineStyle::NONE   },
    { XML_SOLID,         table::BorderLineStyle::SOLID  },
    { XML_DOUBLE,        table::BorderLineStyle::DOUBLE },
    { XML_DOTTED,        table::BorderLineStyle::DOTTED },
    { XML_DASHED,        table::BorderLineStyle::DASHED },
    { XML_GROOVE,        table::BorderLineStyle::ENGRAVED },
    { XML_RIDGE,         table::BorderLineStyle::EMBOSSED },
    { XML_INSET,         table::BorderLineStyle::INSET  },
    { XML_OUTSET,        table::BorderLineStyle::OUTSET },
    { XML_FINE_DASHED,   table::BorderLineStyle::FINE_DASHED },
    { XML_TOKEN_INVALID, 0 }
};

SvXMLEnumMapEntry pXML_NamedBorderWidths[] =
{
    { XML_THIN,             SVX_XML_BORDER_WIDTH_THIN   },
    { XML_MIDDLE,           SVX_XML_BORDER_WIDTH_MIDDLE },
    { XML_THICK,            SVX_XML_BORDER_WIDTH_THICK  },
    { XML_TOKEN_INVALID,    0 }
};
// mapping tables to map external xml input to internal box line widths

static sal_uInt16 const aBorderWidths[] =
{
    DEF_LINE_WIDTH_0,
    DEF_LINE_WIDTH_1,
    DEF_LINE_WIDTH_2
};

static void lcl_frmitems_setXMLBorderStyle( table::BorderLine2 & rBorderLine, sal_uInt16 nStyle )
{
    sal_Int16 eStyle = -1; // None
    if (nStyle != table::BorderLineStyle::NONE)
        eStyle = sal_Int16( nStyle );

    rBorderLine.LineStyle = eStyle;
}

//
// class XMLEscapementPropHdl
//

XMLBorderWidthHdl::~XMLBorderWidthHdl()
{
    // nothing to do
}

bool XMLBorderWidthHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    SvXMLTokenEnumerator aTokenEnum( rStrImpValue );

    sal_Int32 nInWidth, nDistance, nOutWidth;

    OUString aToken;
    if( !aTokenEnum.getNextToken( aToken ) )
        return false;

    if (!rUnitConverter.convertMeasureToCore( nInWidth, aToken, 0, 500 ))
        return false;

    if( !aTokenEnum.getNextToken( aToken ) )
        return false;

    if (!rUnitConverter.convertMeasureToCore( nDistance, aToken, 0, 500 ))
        return false;

    if( !aTokenEnum.getNextToken( aToken ) )
        return false;

    if (!rUnitConverter.convertMeasureToCore( nOutWidth, aToken, 0, 500 ))
        return false;

    table::BorderLine2 aBorderLine;
    if(!(rValue >>= aBorderLine))
        aBorderLine.Color = 0;

    aBorderLine.InnerLineWidth = sal::static_int_cast< sal_Int16 >(nInWidth);
    aBorderLine.OuterLineWidth = sal::static_int_cast< sal_Int16 >(nOutWidth);
    aBorderLine.LineDistance   = sal::static_int_cast< sal_Int16 >(nDistance);

    rValue <<= aBorderLine;
    return true;
}

bool XMLBorderWidthHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    OUStringBuffer aOut;

    table::BorderLine2 aBorderLine;
    if(!(rValue >>= aBorderLine))
        return false;

    bool bDouble = false;
    switch ( aBorderLine.LineStyle )
    {
        case table::BorderLineStyle::DOUBLE:
        case table::BorderLineStyle::THINTHICK_SMALLGAP:
        case table::BorderLineStyle::THINTHICK_MEDIUMGAP:
        case table::BorderLineStyle::THINTHICK_LARGEGAP:
        case table::BorderLineStyle::THICKTHIN_SMALLGAP:
        case table::BorderLineStyle::THICKTHIN_MEDIUMGAP:
        case table::BorderLineStyle::THICKTHIN_LARGEGAP:
            bDouble = true;
            break;
        default:
            break;
    }

    if( ( aBorderLine.LineDistance == 0 && aBorderLine.InnerLineWidth == 0 ) || !bDouble )
        return false;

    rUnitConverter.convertMeasureToXML( aOut, aBorderLine.InnerLineWidth );
    aOut.append( ' ' );
    rUnitConverter.convertMeasureToXML( aOut, aBorderLine.LineDistance );
    aOut.append( ' ' );
    rUnitConverter.convertMeasureToXML( aOut, aBorderLine.OuterLineWidth );

    rStrExpValue = aOut.makeStringAndClear();
    return true;
}

//
// class XMLEscapementHeightPropHdl
//

XMLBorderHdl::~XMLBorderHdl()
{
    // nothing to do
}

bool XMLBorderHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    OUString aToken;
    SvXMLTokenEnumerator aTokens( rStrImpValue );

    bool bHasStyle = false;
    bool bHasWidth = false;
    bool bHasColor = false;

    sal_uInt16 nStyle = USHRT_MAX;
    sal_uInt16 nWidth = 0;
    sal_uInt16 nNamedWidth = USHRT_MAX;
    sal_Int32 nColor = 0;

    sal_Int32 nTemp;
    while( aTokens.getNextToken( aToken ) && !aToken.isEmpty() )
    {
        if( !bHasWidth &&
            rUnitConverter.convertEnum( nNamedWidth, aToken,
                                        pXML_NamedBorderWidths ) )
        {
            bHasWidth = true;
        }
        else if( !bHasStyle &&
                 rUnitConverter.convertEnum( nStyle, aToken,
                                              pXML_BorderStyles ) )
        {
            bHasStyle = true;
        }
        else if (!bHasColor && ::sax::Converter::convertColor(nColor, aToken))
        {
            bHasColor = true;
        }
        else if( !bHasWidth &&
                 rUnitConverter.convertMeasureToCore( nTemp, aToken, 0,
                                                 USHRT_MAX ) )
        {
            nWidth = (sal_uInt16)nTemp;
            bHasWidth = true;
        }
        else
        {
            // missformed
            return false;
        }
    }

    // if there is no style or a different style than none but no width,
       // then the declaration is not valid.
    if (!bHasStyle || (table::BorderLineStyle::NONE != nStyle && !bHasWidth))
        return false;

    table::BorderLine2 aBorderLine;
    if(!(rValue >>= aBorderLine))
    {
        aBorderLine.Color = 0;
        aBorderLine.InnerLineWidth = 0;
        aBorderLine.OuterLineWidth = 0;
        aBorderLine.LineDistance   = 0;
        aBorderLine.LineWidth      = 0;
    }

    // first of all, delete an empty line
    if ((bHasStyle && table::BorderLineStyle::NONE == nStyle) ||
        (bHasWidth && USHRT_MAX == nNamedWidth && 0 == nWidth) )
    {
        aBorderLine.InnerLineWidth = 0;
        aBorderLine.OuterLineWidth = 0;
        aBorderLine.LineDistance   = 0;
        aBorderLine.LineWidth = 0;
    }
    else if( bHasWidth )
    {
        if( USHRT_MAX != nNamedWidth )
        {
            aBorderLine.LineWidth = aBorderWidths[nNamedWidth];
        }
        else
        {
            aBorderLine.LineWidth = nWidth;
            lcl_frmitems_setXMLBorderStyle( aBorderLine, nStyle );
        }
    }
    else
    {
        aBorderLine.LineWidth = 0;
        lcl_frmitems_setXMLBorderStyle( aBorderLine, nStyle );
    }

    // set color
    if( bHasColor )
    {
        aBorderLine.Color = nColor;
    }

    rValue <<= aBorderLine;
    return true;
}

bool XMLBorderHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& /* rUnitConverter */ ) const
{
    OUStringBuffer aOut;

    table::BorderLine2 aBorderLine;
    if(!(rValue >>= aBorderLine))
        return false;

    sal_Int32 nWidth = aBorderLine.LineWidth;

    if( nWidth == 0 )
    {
        aOut.append( GetXMLToken( XML_NONE ) );
    }
    else
    {
        ::sax::Converter::convertMeasure( aOut, nWidth,
               util::MeasureUnit::MM_100TH, util::MeasureUnit::POINT);

        aOut.append( ' ' );

        XMLTokenEnum eStyleToken = XML_SOLID;
        switch ( aBorderLine.LineStyle )
        {
            case table::BorderLineStyle::DASHED:
                eStyleToken = XML_DASHED;
                break;
            case table::BorderLineStyle::DOTTED:
                eStyleToken = XML_DOTTED;
                break;
            case table::BorderLineStyle::DOUBLE:
            case table::BorderLineStyle::THINTHICK_SMALLGAP:
            case table::BorderLineStyle::THINTHICK_MEDIUMGAP:
            case table::BorderLineStyle::THINTHICK_LARGEGAP:
            case table::BorderLineStyle::THICKTHIN_SMALLGAP:
            case table::BorderLineStyle::THICKTHIN_MEDIUMGAP:
            case table::BorderLineStyle::THICKTHIN_LARGEGAP:
                eStyleToken = XML_DOUBLE;
                break;
            case table::BorderLineStyle::EMBOSSED:
                eStyleToken = XML_RIDGE;
                break;
            case table::BorderLineStyle::ENGRAVED:
                eStyleToken = XML_GROOVE;
                break;
            case table::BorderLineStyle::OUTSET:
                eStyleToken = XML_OUTSET;
                break;
            case table::BorderLineStyle::INSET:
                eStyleToken = XML_INSET;
                break;
            case table::BorderLineStyle::FINE_DASHED:
                eStyleToken = XML_FINE_DASHED;
                break;
            case table::BorderLineStyle::SOLID:
            default:
                break;
        }
        aOut.append( GetXMLToken( eStyleToken ) );

        aOut.append( ' ' );

        ::sax::Converter::convertColor( aOut, aBorderLine.Color );
    }

    rStrExpValue = aOut.makeStringAndClear();

    return true;
}

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


<commit_before>#include "MainWindow.h"
#include "ui_MainWindow.h"
#include <QTextCursor>
#include <QFileInfo>
#include <QDebug>
#include <QMessageBox>
#include <QCloseEvent>

#include "Widgets/InputWidget.h"
#include "Widgets/HistoryWidget.h"
#include "Managers/HistoryManager.h"
#include "Managers/FileManager.h"
#include "Managers/MarkovRunManager.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    _has_unsaved_data(true),
    _current_file("")
{
    ui->setupUi(this);

    updateWindowTitle();
    redoAvailable(false);
    undoAvailable(false);
    copyAvailable(false);

    //Connect MainWindow menu
    connect(ui->actionExit, SIGNAL(triggered()), this, SLOT(close()));
    connect(ui->actionUndo, SIGNAL(triggered()), this, SIGNAL(undo()));
    connect(ui->actionRedo, SIGNAL(triggered()), this, SIGNAL(redo()));
    connect(ui->actionSelect_All, SIGNAL(triggered()), this, SIGNAL(selectAll()));
    connect(ui->actionCopy, SIGNAL(triggered()), this, SIGNAL(copy()));
    connect(ui->actionPaste, SIGNAL(triggered()), this, SIGNAL(paste()));
    connect(ui->actionCut, SIGNAL(triggered()), this, SIGNAL(cut()));
    connect(ui->actionDelete, SIGNAL(triggered()), this, SIGNAL(deleteSelection()));
    connect(ui->actionNew, SIGNAL(triggered()), this, SIGNAL(newFile()));
    connect(ui->actionOpen, SIGNAL(triggered()), this, SIGNAL(open()));
    connect(ui->actionSave, SIGNAL(triggered()), this, SIGNAL(save()));
    connect(ui->actionSave_As, SIGNAL(triggered()), this, SIGNAL(saveAs()));

    //Connect InputWidget and HistoryManager
    HistoryManager* history_manager = HistoryManager::getInstance();

    connect(ui->input, SIGNAL(addToHistory(QString)),
            history_manager, SLOT(addToHistory(QString)));
    connect(history_manager, SIGNAL(wordSelected(QString)),
            ui->input, SLOT(setInput(QString)));

    //Connect HistoryWidget and HistoryManager
    connect(ui->history, SIGNAL(inputWordSelected(QString)),
            history_manager, SIGNAL(wordSelected(QString)));
    connect(ui->history, SIGNAL(removeFromHistory(QString)),
            history_manager, SLOT(removeFromHistory(QString)));
    connect(history_manager, SIGNAL(historyChanged(QVector<QString>)),
            ui->history, SLOT(historyChanged(QVector<QString>)));

    //Connect MainWindows and FileManager
    FileManager* file_manager = FileManager::getInstance();
    connect(this, SIGNAL(newFile()), file_manager, SLOT(newFile()));
    connect(this, SIGNAL(open()), file_manager, SLOT(open()));
    connect(this, SIGNAL(save()), file_manager, SLOT(save()));
    connect(this, SIGNAL(saveAs()), file_manager, SLOT(saveAs()));
    connect(file_manager, SIGNAL(hasUnsavedData(bool)),
            this, SLOT(hasUnsavedData(bool)));
    connect(file_manager, SIGNAL(fileNameChanged(QString)),
            this, SLOT(fileNameChanged(QString)));

    //Connect MainWindows and EditorWindowWidget
    connect(this, SIGNAL(undo()), ui->editorWindow, SLOT(undo()));
    connect(this, SIGNAL(redo()), ui->editorWindow, SLOT(redo()));
    connect(this, SIGNAL(selectAll()), ui->editorWindow, SLOT(selectAll()));
    connect(this, SIGNAL(copy()), ui->editorWindow, SLOT(copy()));
    connect(this, SIGNAL(paste()), ui->editorWindow, SLOT(paste()));
    connect(this, SIGNAL(cut()), ui->editorWindow, SLOT(cut()));
    connect(this, SIGNAL(deleteSelection()),
            ui->editorWindow, SLOT(deleteSelection()));

    connect(ui->editorWindow, SIGNAL(redoAvailable(bool)),
            this, SLOT(redoAvailable(bool)));
    connect(ui->editorWindow, SIGNAL(undoAvailable(bool)),
            this, SLOT(undoAvailable(bool)));
    connect(ui->editorWindow, SIGNAL(copyAvailable(bool)),
            this, SLOT(copyAvailable(bool)));

    //Connect InputWidget and MarkovRunManager
    MarkovRunManager* run_manager = MarkovRunManager::getInstance();

    connect(ui->input, SIGNAL(run(QString)),
            run_manager, SLOT(runWithoutDebug(QString)));
    connect(ui->input, SIGNAL(runWithDebug(QString)),
            run_manager, SLOT(runWithDebug(QString)));

    connect(run_manager, SIGNAL(runWithoutDebugStarted(QString)),
            ui->input, SLOT(runStarted()));
    connect(run_manager, SIGNAL(debugStarted(QString)),
            ui->input, SLOT(runStarted()));

    connect(run_manager, SIGNAL(runWithoutDebugFinishFail(QString,RunError,int)),
            ui->input, SLOT(runFinished()));
    connect(run_manager, SIGNAL(runWithoutDebugFinishSuccess(QString,QString,int)),
            ui->input, SLOT(runFinished()));
    connect(run_manager, SIGNAL(debugFinishFail(QString,RunError,int)),
            ui->input, SLOT(runFinished()));
    connect(run_manager, SIGNAL(debugFinishSuccess(QString,QString,int)),
            ui->input, SLOT(runFinished()));
    connect(run_manager, SIGNAL(canRunSourceCode(bool)),
            ui->input, SLOT(canRunAlgorithm(bool)));

    //Read file to open from command line
    QStringList arguments = QCoreApplication::arguments();
    if(arguments.size() >= 2)
    {
        QString file_name = arguments.at(1);
        FileManager::getInstance()->openFile(file_name);
    }
    else
    {
        ui->editorWindow->setDefaultSourceCode(tr("//Alphabet\nT = {}\n\n//Rules\n//a -> b"));
    }

}

void MainWindow::updateWindowTitle()
{
    QString file = _current_file;
    if(file == "")
        file = tr("Untitiled");

    QFileInfo fileInfo(file);
    QString filename(fileInfo.fileName());

    QString saved="";
    if(_has_unsaved_data)
        saved = "*";

    QString title = tr("%1%2 - Yad Studio").arg(filename, saved);
    this->setWindowTitle(title);
}

void MainWindow::fileNameChanged(QString new_name)
{
    _current_file = new_name;
    updateWindowTitle();
}

void MainWindow::hasUnsavedData(bool has_unsaved_data)
{
    _has_unsaved_data = has_unsaved_data;
    updateWindowTitle();
}

void MainWindow::redoAvailable(bool v)
{
    ui->actionRedo->setEnabled(v);
}

void MainWindow::undoAvailable(bool v)
{
    ui->actionUndo->setEnabled(v);
}

void MainWindow::copyAvailable(bool v)
{
    ui->actionCopy->setEnabled(v);
    ui->actionCut->setEnabled(v);
    ui->actionDelete->setEnabled(v);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::closeEvent(QCloseEvent * event)
{
    if(FileManager::getInstance()->hasUnsavedData())
    {
        QMessageBox msgBox;
        msgBox.setText(tr("The document has been modified."));
        msgBox.setInformativeText(tr("Do you want to save your changes?"));
        msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
        msgBox.setDefaultButton(QMessageBox::Save);
        int ret = msgBox.exec();

        if(ret == QMessageBox::Save)
        {
            FileManager::getInstance()->save();
            QMainWindow::closeEvent(event);
        }
        else if(ret == QMessageBox::Discard)
        {
            QMainWindow::closeEvent(event);
        }
        else
        {
            event->ignore();
        }

    }
    else
    {
        QMainWindow::closeEvent(event);
    }
}
<commit_msg>close #49 Connect SourceCodeManager and EditorWindowWidget<commit_after>#include "MainWindow.h"
#include "ui_MainWindow.h"
#include <QTextCursor>
#include <QFileInfo>
#include <QDebug>
#include <QMessageBox>
#include <QCloseEvent>

#include "Widgets/InputWidget.h"
#include "Widgets/HistoryWidget.h"
#include "Managers/HistoryManager.h"
#include "Managers/FileManager.h"
#include "Managers/MarkovRunManager.h"
#include "Managers/SourceCodeManager.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    _has_unsaved_data(true),
    _current_file("")
{
    ui->setupUi(this);

    updateWindowTitle();
    redoAvailable(false);
    undoAvailable(false);
    copyAvailable(false);

    //Connect MainWindow menu
    connect(ui->actionExit, SIGNAL(triggered()), this, SLOT(close()));
    connect(ui->actionUndo, SIGNAL(triggered()), this, SIGNAL(undo()));
    connect(ui->actionRedo, SIGNAL(triggered()), this, SIGNAL(redo()));
    connect(ui->actionSelect_All, SIGNAL(triggered()), this, SIGNAL(selectAll()));
    connect(ui->actionCopy, SIGNAL(triggered()), this, SIGNAL(copy()));
    connect(ui->actionPaste, SIGNAL(triggered()), this, SIGNAL(paste()));
    connect(ui->actionCut, SIGNAL(triggered()), this, SIGNAL(cut()));
    connect(ui->actionDelete, SIGNAL(triggered()), this, SIGNAL(deleteSelection()));
    connect(ui->actionNew, SIGNAL(triggered()), this, SIGNAL(newFile()));
    connect(ui->actionOpen, SIGNAL(triggered()), this, SIGNAL(open()));
    connect(ui->actionSave, SIGNAL(triggered()), this, SIGNAL(save()));
    connect(ui->actionSave_As, SIGNAL(triggered()), this, SIGNAL(saveAs()));

    //Connect InputWidget and HistoryManager
    HistoryManager* history_manager = HistoryManager::getInstance();

    connect(ui->input, SIGNAL(addToHistory(QString)),
            history_manager, SLOT(addToHistory(QString)));
    connect(history_manager, SIGNAL(wordSelected(QString)),
            ui->input, SLOT(setInput(QString)));

    //Connect HistoryWidget and HistoryManager
    connect(ui->history, SIGNAL(inputWordSelected(QString)),
            history_manager, SIGNAL(wordSelected(QString)));
    connect(ui->history, SIGNAL(removeFromHistory(QString)),
            history_manager, SLOT(removeFromHistory(QString)));
    connect(history_manager, SIGNAL(historyChanged(QVector<QString>)),
            ui->history, SLOT(historyChanged(QVector<QString>)));

    //Connect MainWindows and FileManager
    FileManager* file_manager = FileManager::getInstance();
    connect(this, SIGNAL(newFile()), file_manager, SLOT(newFile()));
    connect(this, SIGNAL(open()), file_manager, SLOT(open()));
    connect(this, SIGNAL(save()), file_manager, SLOT(save()));
    connect(this, SIGNAL(saveAs()), file_manager, SLOT(saveAs()));
    connect(file_manager, SIGNAL(hasUnsavedData(bool)),
            this, SLOT(hasUnsavedData(bool)));
    connect(file_manager, SIGNAL(fileNameChanged(QString)),
            this, SLOT(fileNameChanged(QString)));

    //Connect MainWindows and EditorWindowWidget
    connect(this, SIGNAL(undo()), ui->editorWindow, SLOT(undo()));
    connect(this, SIGNAL(redo()), ui->editorWindow, SLOT(redo()));
    connect(this, SIGNAL(selectAll()), ui->editorWindow, SLOT(selectAll()));
    connect(this, SIGNAL(copy()), ui->editorWindow, SLOT(copy()));
    connect(this, SIGNAL(paste()), ui->editorWindow, SLOT(paste()));
    connect(this, SIGNAL(cut()), ui->editorWindow, SLOT(cut()));
    connect(this, SIGNAL(deleteSelection()),
            ui->editorWindow, SLOT(deleteSelection()));

    connect(ui->editorWindow, SIGNAL(redoAvailable(bool)),
            this, SLOT(redoAvailable(bool)));
    connect(ui->editorWindow, SIGNAL(undoAvailable(bool)),
            this, SLOT(undoAvailable(bool)));
    connect(ui->editorWindow, SIGNAL(copyAvailable(bool)),
            this, SLOT(copyAvailable(bool)));

    //Connect InputWidget and MarkovRunManager
    MarkovRunManager* run_manager = MarkovRunManager::getInstance();

    connect(ui->input, SIGNAL(run(QString)),
            run_manager, SLOT(runWithoutDebug(QString)));
    connect(ui->input, SIGNAL(runWithDebug(QString)),
            run_manager, SLOT(runWithDebug(QString)));
    connect(run_manager, SIGNAL(runWithoutDebugStarted(QString)),
            ui->input, SLOT(runStarted()));
    connect(run_manager, SIGNAL(debugStarted(QString)),
            ui->input, SLOT(runStarted()));
    connect(run_manager, SIGNAL(runWithoutDebugFinishFail(QString,RunError,int)),
            ui->input, SLOT(runFinished()));
    connect(run_manager, SIGNAL(runWithoutDebugFinishSuccess(QString,QString,int)),
            ui->input, SLOT(runFinished()));
    connect(run_manager, SIGNAL(debugFinishFail(QString,RunError,int)),
            ui->input, SLOT(runFinished()));
    connect(run_manager, SIGNAL(debugFinishSuccess(QString,QString,int)),
            ui->input, SLOT(runFinished()));
    connect(run_manager, SIGNAL(canRunSourceCode(bool)),
            ui->input, SLOT(canRunAlgorithm(bool)));

    //Connect SourceCodeManager and EditorWindowWidget
    SourceCodeManager* source_manager = SourceCodeManager::getInstance();
    connect(source_manager, SIGNAL(newSourceCodeWasLoaded(QString)),
            ui->editorWindow, SLOT(newSourceCode(QString)));
    connect(ui->editorWindow, SIGNAL(sourceCodeChanged(QString)),
            source_manager, SLOT(setSourceCode(QString)));

    //Read file to open from command line
    QStringList arguments = QCoreApplication::arguments();
    if(arguments.size() >= 2)
    {
        QString file_name = arguments.at(1);
        FileManager::getInstance()->openFile(file_name);
    }
    else
    {
        source_manager->setNewSourceCodeFromFile(tr("//Alphabet\nT = {}\n\n//Rules\n//a -> b"));
    }

}

void MainWindow::updateWindowTitle()
{
    QString file = _current_file;
    if(file == "")
        file = tr("Untitiled");

    QFileInfo fileInfo(file);
    QString filename(fileInfo.fileName());

    QString saved="";
    if(_has_unsaved_data)
        saved = "*";

    QString title = tr("%1%2 - Yad Studio").arg(filename, saved);
    this->setWindowTitle(title);
}

void MainWindow::fileNameChanged(QString new_name)
{
    _current_file = new_name;
    updateWindowTitle();
}

void MainWindow::hasUnsavedData(bool has_unsaved_data)
{
    _has_unsaved_data = has_unsaved_data;
    updateWindowTitle();
}

void MainWindow::redoAvailable(bool v)
{
    ui->actionRedo->setEnabled(v);
}

void MainWindow::undoAvailable(bool v)
{
    ui->actionUndo->setEnabled(v);
}

void MainWindow::copyAvailable(bool v)
{
    ui->actionCopy->setEnabled(v);
    ui->actionCut->setEnabled(v);
    ui->actionDelete->setEnabled(v);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::closeEvent(QCloseEvent * event)
{
    if(FileManager::getInstance()->hasUnsavedData())
    {
        QMessageBox msgBox;
        msgBox.setText(tr("The document has been modified."));
        msgBox.setInformativeText(tr("Do you want to save your changes?"));
        msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
        msgBox.setDefaultButton(QMessageBox::Save);
        int ret = msgBox.exec();

        if(ret == QMessageBox::Save)
        {
            FileManager::getInstance()->save();
            QMainWindow::closeEvent(event);
        }
        else if(ret == QMessageBox::Discard)
        {
            QMainWindow::closeEvent(event);
        }
        else
        {
            event->ignore();
        }

    }
    else
    {
        QMainWindow::closeEvent(event);
    }
}
<|endoftext|>


<commit_before>/*
 * Copyright 2015 Aldebaran
 *
 * 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.
 *
*/

#ifndef BASIC_EVENT_RECORDER_HPP
#define BASIC_EVENT_RECORDER_HPP

/*
* LOCAL includes
*/
#include <alrosbridge/recorder/globalrecorder.hpp>
#include "../helpers.hpp"

/*
* STANDARD includes
*/
#include <string>

namespace alros
{
namespace recorder
{

template<class T>
class BasicEventRecorder
{

public:
  BasicEventRecorder( const std::string& topic ):
    topic_( topic ),
    buffer_duration_( helpers::bufferDefaultDuration ),
    is_initialized_( false ),
    is_subscribed_( false )
  {
    std::cout << "Size of buffer: " << buffer_.size() << std::endl;
  }

  virtual ~BasicEventRecorder() {}

  inline std::string topic() const
  {
    return topic_;
  }

  inline bool isInitialized() const
  {
    return is_initialized_;
  }

  inline void subscribe( bool state)
  {
    is_subscribed_ = state;
  }

  inline bool isSubscribed() const
  {
    return is_subscribed_;
  }

  virtual void write(const T& msg)
  {
    if (!msg.header.stamp.isZero()) {
      gr_->write(topic_, msg, msg.header.stamp);
    }
    else {
      gr_->write(topic_, msg);
    }
  }

  virtual void writeDump()
  {
    boost::mutex::scoped_lock lock_write_buffer( mutex_ );
    removeOld();
    typename std::list<T>::iterator it;
    for (it = buffer_.begin(); it != buffer_.end(); it++)
    {
      if (!it->header.stamp.isZero()) {
        gr_->write(topic_, *it, it->header.stamp);
      }
      else {
        gr_->write(topic_, *it);
      }
    }
  }

  virtual void bufferize(const T& msg)
  {
    std::cout << "In bufferize function" << std::endl;
    boost::mutex::scoped_lock lock_bufferize( mutex_ );
    typename std::list<T>::iterator it;
    removeOld();
    buffer_.push_back(msg);

  }

  virtual void reset(boost::shared_ptr<GlobalRecorder> gr, float conv_frequency)
  {
    gr_ = gr;
    is_initialized_ = true;
  }

  virtual void setBufferDuration(float duration)
  {
    boost::mutex::scoped_lock lock_bufferize( mutex_ );
    buffer_duration_ = duration;
  }

protected:
  bool isTooOld(const T& msg)
  {
    ros::Duration d( ros::Time::now() - msg.header.stamp );
    if (static_cast<float>(d.toSec()) > buffer_duration_)
    {
      std::cout << "Removing old data in buffer: "
                << d.toSec() << "s" << std::endl;
      return true;
    }
    return false;
  }

  void removeOld()
  {
    std::cout << "Size of buffer: " << buffer_.size() << std::endl;
    while (buffer_.size() > 0 && isTooOld(buffer_.front()))
    {
      buffer_.pop_front();
    }
  }

protected:
  std::string topic_;

  std::list<T> buffer_;
  float buffer_duration_;
  boost::mutex mutex_;

  bool is_initialized_;
  bool is_subscribed_;

  boost::shared_ptr<alros::recorder::GlobalRecorder> gr_;

}; // class

} // publisher
} // alros

#endif
<commit_msg>Remove spamming logs<commit_after>/*
 * Copyright 2015 Aldebaran
 *
 * 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.
 *
*/

#ifndef BASIC_EVENT_RECORDER_HPP
#define BASIC_EVENT_RECORDER_HPP

/*
* LOCAL includes
*/
#include <alrosbridge/recorder/globalrecorder.hpp>
#include "../helpers.hpp"

/*
* STANDARD includes
*/
#include <string>

namespace alros
{
namespace recorder
{

template<class T>
class BasicEventRecorder
{

public:
  BasicEventRecorder( const std::string& topic ):
    topic_( topic ),
    buffer_duration_( helpers::bufferDefaultDuration ),
    is_initialized_( false ),
    is_subscribed_( false )
  {}

  virtual ~BasicEventRecorder() {}

  inline std::string topic() const
  {
    return topic_;
  }

  inline bool isInitialized() const
  {
    return is_initialized_;
  }

  inline void subscribe( bool state)
  {
    is_subscribed_ = state;
  }

  inline bool isSubscribed() const
  {
    return is_subscribed_;
  }

  virtual void write(const T& msg)
  {
    if (!msg.header.stamp.isZero()) {
      gr_->write(topic_, msg, msg.header.stamp);
    }
    else {
      gr_->write(topic_, msg);
    }
  }

  virtual void writeDump()
  {
    boost::mutex::scoped_lock lock_write_buffer( mutex_ );
    removeOld();
    typename std::list<T>::iterator it;
    for (it = buffer_.begin(); it != buffer_.end(); it++)
    {
      if (!it->header.stamp.isZero()) {
        gr_->write(topic_, *it, it->header.stamp);
      }
      else {
        gr_->write(topic_, *it);
      }
    }
  }

  virtual void bufferize(const T& msg)
  {
    boost::mutex::scoped_lock lock_bufferize( mutex_ );
    typename std::list<T>::iterator it;
    removeOld();
    buffer_.push_back(msg);

  }

  virtual void reset(boost::shared_ptr<GlobalRecorder> gr, float conv_frequency)
  {
    gr_ = gr;
    is_initialized_ = true;
  }

  virtual void setBufferDuration(float duration)
  {
    boost::mutex::scoped_lock lock_bufferize( mutex_ );
    buffer_duration_ = duration;
  }

protected:
  bool isTooOld(const T& msg)
  {
    ros::Duration d( ros::Time::now() - msg.header.stamp );
    if (static_cast<float>(d.toSec()) > buffer_duration_)
    {
      return true;
    }
    return false;
  }

  void removeOld()
  {
    while (buffer_.size() > 0 && isTooOld(buffer_.front()))
    {
      buffer_.pop_front();
    }
  }

protected:
  std::string topic_;

  std::list<T> buffer_;
  float buffer_duration_;
  boost::mutex mutex_;

  bool is_initialized_;
  bool is_subscribed_;

  boost::shared_ptr<alros::recorder::GlobalRecorder> gr_;

}; // class

} // publisher
} // alros

#endif
<|endoftext|>


<commit_before>#include <sys/socket.h>
#include <sys/un.h>

#include "data/Event.h"
#include "ipc/server/Json.h"

namespace blitzortung {
  namespace ipc {
    namespace server {

      Json::Json(const unsigned int socket, const Process& process, const hardware::Pcb& hardware) :
	Base(socket),
	process_(process),
	hardware_(hardware),
	logger_("ipc.server.Json")
      {
	if (logger_.isDebugEnabled())
	  logger_.debugStream() << "initialize for socket " << socket;
      }

      void Json::cmdGetInfo() {
	    json_object* jsonHardware = json_object_new_object();
	    json_object_object_add(jsonHardware, "firmware", json_object_new_string(hardware_.getFirmwareVersion().c_str()));
	    json_object_object_add(jsonResponse_, "hardware", jsonHardware);

	    const hardware::gps::Base& gps = hardware_.getGps();
	    json_object* jsonGps = json_object_new_object();
	    char gpsStatus = gps.getStatus();
	    json_object_object_add(jsonGps, "longitude", json_object_new_double(gps.getLocation().getLongitude()));
	    json_object_object_add(jsonGps, "longitudeError", json_object_new_double(gps.getLocation().getLongitudeError()));
	    json_object_object_add(jsonGps, "latitude", json_object_new_double(gps.getLocation().getLatitude()));
	    json_object_object_add(jsonGps, "latitudeError", json_object_new_double(gps.getLocation().getLatitudeError()));
	    json_object_object_add(jsonGps, "altitude", json_object_new_int(gps.getLocation().getAltitude()));
	    json_object_object_add(jsonGps, "altitudeError", json_object_new_int(gps.getLocation().getAltitudeError()));
	    pt::ptime gpsTime = gps.getTime();
	    std::ostringstream oss;
	    gr::date_facet *datefacet = new gr::date_facet();
	    datefacet->format("%Y-%m-%d");
	    oss.imbue(std::locale(std::locale::classic(), datefacet));
	    oss << gpsTime.date();
	    json_object_object_add(jsonGps, "date", json_object_new_string(oss.str().c_str()));
	    oss.str("");
	    oss << gpsTime.time_of_day();
	    json_object_object_add(jsonGps, "time", json_object_new_string(oss.str().c_str()));
	    json_object_object_add(jsonGps, "ticksPerSecond", json_object_new_double(gps.getTicksPerSecond()));
	    json_object_object_add(jsonGps, "tickError", json_object_new_double(gps.getTickError()));
	    json_object_object_add(jsonGps, "status", json_object_new_string_len(&gpsStatus, 1));
	    json_object_object_add(jsonGps, "satelliteCount", json_object_new_int(gps.getSatelliteCount()));
	    json_object_object_add(jsonGps, "type", json_object_new_string(gps.getType().c_str()));
	    json_object_object_add(jsonHardware, "gps", jsonGps);

	    const hardware::comm::Base& comm = hardware_.getComm();
	    json_object* jsonComm = json_object_new_object();
	    json_object_object_add(jsonComm, "baudRate", json_object_new_int(comm.getBaudRate()));
	    json_object_object_add(jsonComm, "interfaceName", json_object_new_string(comm.getInterfaceName().c_str()));
	    json_object_object_add(jsonHardware, "comm", jsonComm);

	    json_object* jsonProcess = json_object_new_object();
	    json_object_object_add(jsonProcess, "numberOfSeconds", json_object_new_int(process_.getEventCountBuffer().getActualSize()));
	    json_object_object_add(jsonProcess, "numberOfEvents", json_object_new_int(process_.getEventCountBuffer().getSum()));
	    json_object_object_add(jsonProcess, "eventsPerSecond", json_object_new_double(process_.getEventCountBuffer().getAverage()));
	    json_object_object_add(jsonResponse_, "process", jsonProcess);
      }

      std::string Json::respond(const std::string& input) {
	jsonResponse_ = json_object_new_object();

	json_object* jsonObj = json_tokener_parse(input.c_str());
	if (jsonObj != 0) {
	  json_object* cmd_obj = json_object_object_get(jsonObj, "cmd");
	  if (cmd_obj != 0) {
	    std::string command(json_object_get_string(cmd_obj));

	    json_object_object_add(jsonResponse_, "command", json_object_new_string(command.c_str()));

	    if (command == "getInfo")
	      cmdGetInfo();
	    else if (command =="getActivity")
	      cmdGetActivity();

	    json_object_put(cmd_obj);
	  }

	  json_object_put(jsonObj);
	} else {
	  std::string result = "could not parse command '" + input + "'";
	  json_object_object_add(jsonResponse_, "error", json_object_new_string(result.c_str()));
	  logger_.warnStream() << result;
	}

	std::string jsonString(json_object_to_json_string(jsonResponse_));
	json_object_put(jsonResponse_);

	return jsonString;
      }

      void Json::cmdGetActivity() {
	    json_object* jsonActivity = json_object_new_array();

	    const unsigned int intervalSeconds = 60;
	    const int totalNumberOfSeconds = process_.getEventCountBuffer().getActualSize();
	    const int totalNumberOfIntervals = totalNumberOfSeconds / intervalSeconds;

	    for (int interval = totalNumberOfIntervals; interval > 0; interval--) {
	      int eventsPerInterval = 0;
	      for (int second = 0; second < intervalSeconds; second ++) {
		int index = (totalNumberOfIntervals - interval) * intervalSeconds + second;
		eventsPerInterval += process_.getEventCountBuffer()[index];
	      }
	      json_object_array_add(jsonActivity, json_object_new_int(eventsPerInterval));
	    }

	    json_object_object_add(jsonResponse_, "activity", jsonActivity);

	    json_object_object_add(jsonResponse_, "intervalSeconds", json_object_new_int(intervalSeconds));

	    const hardware::gps::Base& gps = hardware_.getGps();
	    pt::ptime gpsTime = gps.getTime();
	    std::ostringstream oss;
	    gr::date_facet *datefacet = new gr::date_facet();
	    datefacet->format("%Y-%m-%d");
	    oss.imbue(std::locale(std::locale::classic(), datefacet));
	    oss << gpsTime.date();
	    json_object_object_add(jsonResponse_, "date", json_object_new_string(oss.str().c_str()));
	    oss.str("");
	    oss << gpsTime.time_of_day();
	    json_object_object_add(jsonResponse_, "time", json_object_new_string(oss.str().c_str()));
      }

    }
  }
}
<commit_msg>fixed variable type<commit_after>#include <sys/socket.h>
#include <sys/un.h>

#include "data/Event.h"
#include "ipc/server/Json.h"

namespace blitzortung {
  namespace ipc {
    namespace server {

      Json::Json(const unsigned int socket, const Process& process, const hardware::Pcb& hardware) :
	Base(socket),
	process_(process),
	hardware_(hardware),
	logger_("ipc.server.Json")
      {
	if (logger_.isDebugEnabled())
	  logger_.debugStream() << "initialize for socket " << socket;
      }

      void Json::cmdGetInfo() {
	    json_object* jsonHardware = json_object_new_object();
	    json_object_object_add(jsonHardware, "firmware", json_object_new_string(hardware_.getFirmwareVersion().c_str()));
	    json_object_object_add(jsonResponse_, "hardware", jsonHardware);

	    const hardware::gps::Base& gps = hardware_.getGps();
	    json_object* jsonGps = json_object_new_object();
	    char gpsStatus = gps.getStatus();
	    json_object_object_add(jsonGps, "longitude", json_object_new_double(gps.getLocation().getLongitude()));
	    json_object_object_add(jsonGps, "longitudeError", json_object_new_double(gps.getLocation().getLongitudeError()));
	    json_object_object_add(jsonGps, "latitude", json_object_new_double(gps.getLocation().getLatitude()));
	    json_object_object_add(jsonGps, "latitudeError", json_object_new_double(gps.getLocation().getLatitudeError()));
	    json_object_object_add(jsonGps, "altitude", json_object_new_int(gps.getLocation().getAltitude()));
	    json_object_object_add(jsonGps, "altitudeError", json_object_new_int(gps.getLocation().getAltitudeError()));
	    pt::ptime gpsTime = gps.getTime();
	    std::ostringstream oss;
	    gr::date_facet *datefacet = new gr::date_facet();
	    datefacet->format("%Y-%m-%d");
	    oss.imbue(std::locale(std::locale::classic(), datefacet));
	    oss << gpsTime.date();
	    json_object_object_add(jsonGps, "date", json_object_new_string(oss.str().c_str()));
	    oss.str("");
	    oss << gpsTime.time_of_day();
	    json_object_object_add(jsonGps, "time", json_object_new_string(oss.str().c_str()));
	    json_object_object_add(jsonGps, "ticksPerSecond", json_object_new_double(gps.getTicksPerSecond()));
	    json_object_object_add(jsonGps, "tickError", json_object_new_double(gps.getTickError()));
	    json_object_object_add(jsonGps, "status", json_object_new_string_len(&gpsStatus, 1));
	    json_object_object_add(jsonGps, "satelliteCount", json_object_new_int(gps.getSatelliteCount()));
	    json_object_object_add(jsonGps, "type", json_object_new_string(gps.getType().c_str()));
	    json_object_object_add(jsonHardware, "gps", jsonGps);

	    const hardware::comm::Base& comm = hardware_.getComm();
	    json_object* jsonComm = json_object_new_object();
	    json_object_object_add(jsonComm, "baudRate", json_object_new_int(comm.getBaudRate()));
	    json_object_object_add(jsonComm, "interfaceName", json_object_new_string(comm.getInterfaceName().c_str()));
	    json_object_object_add(jsonHardware, "comm", jsonComm);

	    json_object* jsonProcess = json_object_new_object();
	    json_object_object_add(jsonProcess, "numberOfSeconds", json_object_new_int(process_.getEventCountBuffer().getActualSize()));
	    json_object_object_add(jsonProcess, "numberOfEvents", json_object_new_int(process_.getEventCountBuffer().getSum()));
	    json_object_object_add(jsonProcess, "eventsPerSecond", json_object_new_double(process_.getEventCountBuffer().getAverage()));
	    json_object_object_add(jsonResponse_, "process", jsonProcess);
      }

      std::string Json::respond(const std::string& input) {
	jsonResponse_ = json_object_new_object();

	json_object* jsonObj = json_tokener_parse(input.c_str());
	if (jsonObj != 0) {
	  json_object* cmd_obj = json_object_object_get(jsonObj, "cmd");
	  if (cmd_obj != 0) {
	    std::string command(json_object_get_string(cmd_obj));

	    json_object_object_add(jsonResponse_, "command", json_object_new_string(command.c_str()));

	    if (command == "getInfo")
	      cmdGetInfo();
	    else if (command =="getActivity")
	      cmdGetActivity();

	    json_object_put(cmd_obj);
	  }

	  json_object_put(jsonObj);
	} else {
	  std::string result = "could not parse command '" + input + "'";
	  json_object_object_add(jsonResponse_, "error", json_object_new_string(result.c_str()));
	  logger_.warnStream() << result;
	}

	std::string jsonString(json_object_to_json_string(jsonResponse_));
	json_object_put(jsonResponse_);

	return jsonString;
      }

      void Json::cmdGetActivity() {
	    json_object* jsonActivity = json_object_new_array();

	    const unsigned int intervalSeconds = 60;
	    const int totalNumberOfSeconds = process_.getEventCountBuffer().getActualSize();
	    const int totalNumberOfIntervals = totalNumberOfSeconds / intervalSeconds;

	    for (int interval = totalNumberOfIntervals; interval > 0; interval--) {
	      int eventsPerInterval = 0;
	      for (unsigned int second = 0; second < intervalSeconds; second ++) {
		int index = (totalNumberOfIntervals - interval) * intervalSeconds + second;
		eventsPerInterval += process_.getEventCountBuffer()[index];
	      }
	      json_object_array_add(jsonActivity, json_object_new_int(eventsPerInterval));
	    }

	    json_object_object_add(jsonResponse_, "activity", jsonActivity);

	    json_object_object_add(jsonResponse_, "intervalSeconds", json_object_new_int(intervalSeconds));

	    const hardware::gps::Base& gps = hardware_.getGps();
	    pt::ptime gpsTime = gps.getTime();
	    std::ostringstream oss;
	    gr::date_facet *datefacet = new gr::date_facet();
	    datefacet->format("%Y-%m-%d");
	    oss.imbue(std::locale(std::locale::classic(), datefacet));
	    oss << gpsTime.date();
	    json_object_object_add(jsonResponse_, "date", json_object_new_string(oss.str().c_str()));
	    oss.str("");
	    oss << gpsTime.time_of_day();
	    json_object_object_add(jsonResponse_, "time", json_object_new_string(oss.str().c_str()));
      }

    }
  }
}
<|endoftext|>


<commit_before>#include "calculator/cell/integrated_fission_source.h"

#include <memory>

#include "data/cross_sections.h"
#include "domain/domain_types.h"
#include "domain/tests/finite_element_mock.h"
#include "material/tests/mock_material.h"
#include "system/moments/spherical_harmonic_types.h"
#include "system/moments/tests/spherical_harmonic_mock.h"
#include "test_helpers/gmock_wrapper.h"
#include "test_helpers/dealii_test_domain.h"

namespace  {

using namespace bart;

using ::testing::Return, ::testing::ReturnRef, ::testing::DoDefault, ::testing::NiceMock;

template <typename DimensionWrapper>
class CalcCellIntegratedFissionSourceTest :
    public ::testing::Test,
    public bart::testing::DealiiTestDomain<DimensionWrapper::value> {
 protected:
  static constexpr int dim = DimensionWrapper::value;
  using FiniteElementType = typename domain::FiniteElementMock<dim>;
  using FissionSourceNormType = typename calculator::cell::IntegratedFissionSource<dim>;
  using SphericalHarmonicType = system::moments::SphericalHarmonicMock;

  // Supporting objects and mocks
  std::shared_ptr<NiceMock<FiniteElementType>> finite_element_ptr_;
  std::shared_ptr<data::CrossSections> cross_sections_ptr_;
  std::shared_ptr<SphericalHarmonicType > spherical_harmonic_ptr_;

  NiceMock<btest::MockMaterial> mock_material_;

  // test parameters
  const int quadrature_points_ = 4;

  void SetUp() override;
};

template <typename DimensionWrapper>
void CalcCellIntegratedFissionSourceTest<DimensionWrapper>::SetUp() {

  std::unordered_map<int, bool> fissile_id_map{{0, true}, {1, false}};
  std::unordered_map<int, std::vector<double>> nu_sigma_f = {
      {0, {1.0, 2.0}},
      {1, {3.0, 6.0}}
  };

  ON_CALL(mock_material_, GetFissileIDMap())
      .WillByDefault(Return(fissile_id_map));
  ON_CALL(mock_material_, GetNuSigF())
      .WillByDefault(Return(nu_sigma_f));

  finite_element_ptr_ = std::make_shared<NiceMock<FiniteElementType>>();
  cross_sections_ptr_ = std::make_shared<data::CrossSections>(mock_material_);
  spherical_harmonic_ptr_ = std::make_shared<SphericalHarmonicType>();

  ON_CALL(*finite_element_ptr_, n_cell_quad_pts())
      .WillByDefault(Return(this->quadrature_points_));

  this->SetUpDealii();
}

TYPED_TEST_CASE(CalcCellIntegratedFissionSourceTest, bart::testing::AllDimensions);

TYPED_TEST(CalcCellIntegratedFissionSourceTest, Constructor) {
  static constexpr int dim = this->dim;

  EXPECT_CALL(*this->finite_element_ptr_, n_cell_quad_pts())
      .WillOnce(DoDefault());

  calculator::cell::IntegratedFissionSource<dim> test_calculator(
      this->finite_element_ptr_,
      this->cross_sections_ptr_);

  EXPECT_EQ(this->finite_element_ptr_.use_count(), 2);
  EXPECT_EQ(this->cross_sections_ptr_.use_count(), 2);
}

TYPED_TEST(CalcCellIntegratedFissionSourceTest, CellValueNonFissileMPI) {
  static constexpr int dim = this->dim;

  for (auto cell : this->cells_) {
    // Set to the non-fissile material
    cell->set_material_id(1);

    calculator::cell::IntegratedFissionSource<dim> test_calculator(
        this->finite_element_ptr_,
        this->cross_sections_ptr_);

    double fission_norm = test_calculator.CellValue(
        cell,
        this->spherical_harmonic_ptr_.get());
    EXPECT_EQ(fission_norm, 0.0);
    break;
  }
}

TYPED_TEST(CalcCellIntegratedFissionSourceTest, CellValueMPI) {
  static constexpr int dim = this->dim;
  auto& finite_element_mock = *(this->finite_element_ptr_);
  auto& spherical_harmonic_mock = *(this->spherical_harmonic_ptr_);

  for (auto cell : this->cells_) {
    // Set to the non-fissile material
    cell->set_material_id(0);

    // EXPECTATIONS
    // Jacobian should be called for each quadrature point
    for (int q = 0; q < this->quadrature_points_; ++q) {
      EXPECT_CALL(finite_element_mock, Jacobian(q))
          .Times(2)                              // Called twice, once for each group
          .WillRepeatedly(Return(10*(q+1)));
    }
    // Number of groups should be determined by Spherical Harmonics
    EXPECT_CALL(spherical_harmonic_mock, total_groups())
        .WillOnce(Return(2));
    // Zeroth moments should be queried for each group
    std::vector<double> group_0_flux{1, 2, 3, 4};
    std::vector<double> group_1_flux{4, 3, 2, 1};

    system::moments::MomentVector group_0_flux_vector(group_0_flux.begin(),
                                                      group_0_flux.end());
    system::moments::MomentVector group_1_flux_vector(group_1_flux.begin(),
                                                      group_1_flux.end());

    system::moments::MomentIndex group_0_index{0,0,0};
    system::moments::MomentIndex group_1_index{1,0,0};

    EXPECT_CALL(spherical_harmonic_mock, GetMoment(group_0_index))
        .WillOnce(ReturnRef(group_0_flux_vector));
    EXPECT_CALL(spherical_harmonic_mock, GetMoment(group_1_index))
        .WillOnce(ReturnRef(group_1_flux_vector));
    EXPECT_CALL(finite_element_mock, ValueAtQuadrature(group_0_flux_vector))
        .WillOnce(Return(group_0_flux));
    EXPECT_CALL(finite_element_mock, ValueAtQuadrature(group_1_flux_vector))
        .WillOnce(Return(group_1_flux));

    calculator::cell::IntegratedFissionSource<dim> test_calculator(
        this->finite_element_ptr_,
        this->cross_sections_ptr_);

    double fission_norm = test_calculator.CellValue(
        cell,
        this->spherical_harmonic_ptr_.get());
    EXPECT_EQ(fission_norm, 700.0);
    break;
  }
}

} // namespace<commit_msg>fixed typo in IntegratedFissionSource test<commit_after>#include "calculator/cell/integrated_fission_source.h"

#include <memory>

#include "data/cross_sections.h"
#include "domain/domain_types.h"
#include "domain/tests/finite_element_mock.h"
#include "material/tests/mock_material.h"
#include "system/moments/spherical_harmonic_types.h"
#include "system/moments/tests/spherical_harmonic_mock.h"
#include "test_helpers/gmock_wrapper.h"
#include "test_helpers/dealii_test_domain.h"

namespace  {

using namespace bart;

using ::testing::Return, ::testing::ReturnRef, ::testing::DoDefault, ::testing::NiceMock;

template <typename DimensionWrapper>
class CalcCellIntegratedFissionSourceTest :
    public ::testing::Test,
    public bart::testing::DealiiTestDomain<DimensionWrapper::value> {
 protected:
  static constexpr int dim = DimensionWrapper::value;
  using FiniteElementType = typename domain::FiniteElementMock<dim>;
  using FissionSourceNormType = typename calculator::cell::IntegratedFissionSource<dim>;
  using SphericalHarmonicType = system::moments::SphericalHarmonicMock;

  // Supporting objects and mocks
  std::shared_ptr<NiceMock<FiniteElementType>> finite_element_ptr_;
  std::shared_ptr<data::CrossSections> cross_sections_ptr_;
  std::shared_ptr<SphericalHarmonicType > spherical_harmonic_ptr_;

  NiceMock<btest::MockMaterial> mock_material_;

  // test parameters
  const int quadrature_points_ = 4;

  void SetUp() override;
};

template <typename DimensionWrapper>
void CalcCellIntegratedFissionSourceTest<DimensionWrapper>::SetUp() {

  std::unordered_map<int, bool> fissile_id_map{{0, true}, {1, false}};
  std::unordered_map<int, std::vector<double>> nu_sigma_f = {
      {0, {1.0, 2.0}},
      {1, {3.0, 6.0}}
  };

  ON_CALL(mock_material_, GetFissileIDMap())
      .WillByDefault(Return(fissile_id_map));
  ON_CALL(mock_material_, GetNuSigF())
      .WillByDefault(Return(nu_sigma_f));

  finite_element_ptr_ = std::make_shared<NiceMock<FiniteElementType>>();
  cross_sections_ptr_ = std::make_shared<data::CrossSections>(mock_material_);
  spherical_harmonic_ptr_ = std::make_shared<SphericalHarmonicType>();

  ON_CALL(*finite_element_ptr_, n_cell_quad_pts())
      .WillByDefault(Return(this->quadrature_points_));

  this->SetUpDealii();
}

TYPED_TEST_CASE(CalcCellIntegratedFissionSourceTest, bart::testing::AllDimensions);

TYPED_TEST(CalcCellIntegratedFissionSourceTest, Constructor) {
  static constexpr int dim = this->dim;

  EXPECT_CALL(*this->finite_element_ptr_, n_cell_quad_pts())
      .WillOnce(DoDefault());

  calculator::cell::IntegratedFissionSource<dim> test_calculator(
      this->finite_element_ptr_,
      this->cross_sections_ptr_);

  EXPECT_EQ(this->finite_element_ptr_.use_count(), 2);
  EXPECT_EQ(this->cross_sections_ptr_.use_count(), 2);
}

TYPED_TEST(CalcCellIntegratedFissionSourceTest, CellValueNonFissileMPI) {
  static constexpr int dim = this->dim;

  for (auto cell : this->cells_) {
    // Set to the non-fissile material
    cell->set_material_id(1);

    calculator::cell::IntegratedFissionSource<dim> test_calculator(
        this->finite_element_ptr_,
        this->cross_sections_ptr_);

    double fission_norm = test_calculator.CellValue(
        cell,
        this->spherical_harmonic_ptr_.get());
    EXPECT_EQ(fission_norm, 0.0);
    break;
  }
}

TYPED_TEST(CalcCellIntegratedFissionSourceTest, CellValueMPI) {
  static constexpr int dim = this->dim;
  auto& finite_element_mock = *(this->finite_element_ptr_);
  auto& spherical_harmonic_mock = *(this->spherical_harmonic_ptr_);

  for (auto cell : this->cells_) {
    // Set to the fissile material
    cell->set_material_id(0);

    // EXPECTATIONS
    // Jacobian should be called for each quadrature point
    for (int q = 0; q < this->quadrature_points_; ++q) {
      EXPECT_CALL(finite_element_mock, Jacobian(q))
          .Times(2)                              // Called twice, once for each group
          .WillRepeatedly(Return(10*(q+1)));
    }
    // Number of groups should be determined by Spherical Harmonics
    EXPECT_CALL(spherical_harmonic_mock, total_groups())
        .WillOnce(Return(2));
    // Zeroth moments should be queried for each group
    std::vector<double> group_0_flux{1, 2, 3, 4};
    std::vector<double> group_1_flux{4, 3, 2, 1};

    system::moments::MomentVector group_0_flux_vector(group_0_flux.begin(),
                                                      group_0_flux.end());
    system::moments::MomentVector group_1_flux_vector(group_1_flux.begin(),
                                                      group_1_flux.end());

    system::moments::MomentIndex group_0_index{0,0,0};
    system::moments::MomentIndex group_1_index{1,0,0};

    EXPECT_CALL(spherical_harmonic_mock, GetMoment(group_0_index))
        .WillOnce(ReturnRef(group_0_flux_vector));
    EXPECT_CALL(spherical_harmonic_mock, GetMoment(group_1_index))
        .WillOnce(ReturnRef(group_1_flux_vector));
    EXPECT_CALL(finite_element_mock, ValueAtQuadrature(group_0_flux_vector))
        .WillOnce(Return(group_0_flux));
    EXPECT_CALL(finite_element_mock, ValueAtQuadrature(group_1_flux_vector))
        .WillOnce(Return(group_1_flux));

    calculator::cell::IntegratedFissionSource<dim> test_calculator(
        this->finite_element_ptr_,
        this->cross_sections_ptr_);

    double fission_norm = test_calculator.CellValue(
        cell,
        this->spherical_harmonic_ptr_.get());
    EXPECT_EQ(fission_norm, 700.0);
    break;
  }
}

} // namespace<|endoftext|>