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

// Author: kenton@google.com (Kenton Varda)
//  Based on original Protocol Buffers design by
//  Sanjay Ghemawat, Jeff Dean, and others.

#include <google/protobuf/compiler/java/java_doc_comment.h>

#include <vector>

#include <google/protobuf/io/printer.h>
#include <google/protobuf/stubs/strutil.h>

namespace google {
namespace protobuf {
namespace compiler {
namespace java {

std::string EscapeJavadoc(const std::string& input) {
  std::string result;
  result.reserve(input.size() * 2);

  char prev = '*';

  for (std::string::size_type i = 0; i < input.size(); i++) {
    char c = input[i];
    switch (c) {
      case '*':
        // Avoid "/*".
        if (prev == '/') {
          result.append("*");
        } else {
          result.push_back(c);
        }
        break;
      case '/':
        // Avoid "*/".
        if (prev == '*') {
          result.append("/");
        } else {
          result.push_back(c);
        }
        break;
      case '@':
        // '@' starts javadoc tags including the @deprecated tag, which will
        // cause a compile-time error if inserted before a declaration that
        // does not have a corresponding @Deprecated annotation.
        result.append("@");
        break;
      case '<':
        // Avoid interpretation as HTML.
        result.append("<");
        break;
      case '>':
        // Avoid interpretation as HTML.
        result.append(">");
        break;
      case '&':
        // Avoid interpretation as HTML.
        result.append("&");
        break;
      case '\\':
        // Java interprets Unicode escape sequences anywhere!
        result.append("\");
        break;
      default:
        result.push_back(c);
        break;
    }

    prev = c;
  }

  return result;
}

static void WriteDocCommentBodyForLocation(io::Printer* printer,
                                           const SourceLocation& location) {
  std::string comments = location.leading_comments.empty()
                             ? location.trailing_comments
                             : location.leading_comments;
  if (!comments.empty()) {
    // TODO(kenton):  Ideally we should parse the comment text as Markdown and
    //   write it back as HTML, but this requires a Markdown parser.  For now
    //   we just use
 to get fixed-width text formatting.

    // If the comment itself contains block comment start or end markers,
    // HTML-escape them so that they don't accidentally close the doc comment.
    comments = EscapeJavadoc(comments);

    std::vector<std::string> lines = Split(comments, "\n");
    while (!lines.empty() && lines.back().empty()) {
      lines.pop_back();
    }

    printer->Print(" *
\n");
    for (int i = 0; i < lines.size(); i++) {
      // Most lines should start with a space.  Watch out for lines that start
      // with a /, since putting that right after the leading asterisk will
      // close the comment.
      if (!lines[i].empty() && lines[i][0] == '/') {
        printer->Print(" * $line$\n", "line", lines[i]);
      } else {
        printer->Print(" *$line$\n", "line", lines[i]);
      }
    }
    printer->Print(
        " *
\n"
        " *\n");
  }
}

template <typename DescriptorType>
static void WriteDocCommentBody(io::Printer* printer,
                                const DescriptorType* descriptor) {
  SourceLocation location;
  if (descriptor->GetSourceLocation(&location)) {
    WriteDocCommentBodyForLocation(printer, location);
  }
}

static std::string FirstLineOf(const std::string& value) {
  std::string result = value;

  std::string::size_type pos = result.find_first_of('\n');
  if (pos != std::string::npos) {
    result.erase(pos);
  }

  // If line ends in an opening brace, make it "{ ... }" so it looks nice.
  if (!result.empty() && result[result.size() - 1] == '{') {
    result.append(" ... }");
  }

  return result;
}

void WriteMessageDocComment(io::Printer* printer, const Descriptor* message) {
  printer->Print("/**\n");
  WriteDocCommentBody(printer, message);
  printer->Print(
      " * Protobuf type {@code $fullname$}\n"
      " */\n",
      "fullname", EscapeJavadoc(message->full_name()));
}

void WriteFieldDocComment(io::Printer* printer, const FieldDescriptor* field) {
  // We start the comment with the main body based on the comments from the
  // .proto file (if present). We then continue with the field declaration, e.g.:
  //   optional string foo = 5;
  // And then we end with the javadoc tags if applicable.
  // If the field is a group, the debug string might end with {.
  printer->Print("/**\n");
  WriteDocCommentBody(printer, field);
  printer->Print(" * $def$\n", "def",
                 EscapeJavadoc(FirstLineOf(field->DebugString())));
  printer->Print(" */\n");
}

void WriteFieldAccessorDocComment(io::Printer* printer,
                                  const FieldDescriptor* field,
                                  const FieldAccessorType type,
                                  const bool builder) {
  printer->Print("/**\n");
  WriteDocCommentBody(printer, field);
  printer->Print(" * $def$\n", "def",
                 EscapeJavadoc(FirstLineOf(field->DebugString())));
  switch (type) {
    case HAZZER:
      printer->Print(" * @return Whether the $name$ field is set.\n", "name",
                     field->camelcase_name());
      break;
    case GETTER:
      printer->Print(" * @return The $name$.\n", "name",
                     field->camelcase_name());
      break;
    case SETTER:
      printer->Print(" * @param value The $name$ to set.\n", "name",
                     field->camelcase_name());
      break;
    case CLEARER:
      // Print nothing
      break;
    // Repeated
    case LIST_COUNT:
      printer->Print(" * @return The number of $name$(s).\n", "name",
                 field->camelcase_name());
      break;
    case LIST_GETTER:
      printer->Print(" * @return A list containing the $name$(s).\n", "name",
                     field->camelcase_name());
      break;
    case LIST_INDEXED_GETTER:
      printer->Print(" * @param index The index of the element to return.\n");
      printer->Print(" * @return The $name$(s) at the given index.\n", "name",
                     field->camelcase_name());
      break;
    case LIST_INDEXED_SETTER:
      printer->Print(" * @param index The index to set the value at.\n");
      printer->Print(" * @param value The $name$ to set.\n", "name",
                     field->camelcase_name());
      break;
    case LIST_ADDER:
      printer->Print(" * @param value The $name$ to add.\n", "name",
                     field->camelcase_name());
      break;
    case LIST_MULTI_ADDER:
      printer->Print(" * @param values The $name$(s) to add.\n", "name",
                 field->camelcase_name());
      break;
  }
  if (builder) {
    printer->Print(" * @return This builder for chaining.\n");
  }
  printer->Print(" */\n");
}

void WriteFieldEnumValueAccessorDocComment(io::Printer* printer,
                                           const FieldDescriptor* field,
                                           const FieldAccessorType type,
                                           const bool builder) {
  printer->Print("/**\n");
  WriteDocCommentBody(printer, field);
  printer->Print(" * $def$\n", "def",
                 EscapeJavadoc(FirstLineOf(field->DebugString())));
  switch (type) {
    case HAZZER:
      // Should never happen
      break;
    case GETTER:
      printer->Print(" * @return The enum value for $name$.\n", "name",
                 field->camelcase_name());
      break;
    case SETTER:
      printer->Print(" * @param value The enum value for $name$ to set.\n",
                     "name", field->camelcase_name());
      break;
    case CLEARER:
      // Print nothing
      break;
    // Repeated
    case LIST_COUNT:
      // Should never happen
      break;
    case LIST_GETTER:
      printer->Print(" * @return A list containing the enum values for $name$(s).\n",
                     "name", field->camelcase_name());
      break;
    case LIST_INDEXED_GETTER:
      printer->Print(" * @param index The index of the value to return.\n");
      printer->Print(" * @return The enum value of the $name$ at the given index.\n",
                     "name", field->camelcase_name());
      break;
    case LIST_INDEXED_SETTER:
      printer->Print(" * @param index The index to set the value at.\n");
      printer->Print(" * @param value The enum value of the $name$ to set.\n",
                     "name", field->camelcase_name());
      break;
    case LIST_ADDER:
      printer->Print(" * @param value The enum value of the $name$ to add.\n",
                     "name", field->camelcase_name());
      break;
    case LIST_MULTI_ADDER:
      printer->Print(" * @param values The enum values of the $name$(s) to add.\n",
                     "name", field->camelcase_name());
      break;
  }
  if (builder) {
    printer->Print(" * @return This builder for chaining.\n");
  }
  printer->Print(" */\n");
}

void WriteFieldStringBytesAccessorDocComment(io::Printer* printer,
                                             const FieldDescriptor* field,
                                             const FieldAccessorType type,
                                             const bool builder) {
  printer->Print("/**\n");
  WriteDocCommentBody(printer, field);
  printer->Print(" * $def$\n", "def",
                 EscapeJavadoc(FirstLineOf(field->DebugString())));
  switch (type) {
    case HAZZER:
      // Should never happen
      break;
    case GETTER:
      printer->Print(" * @return The bytes for $name$.\n", "name",
                 field->camelcase_name());
      break;
    case SETTER:
      printer->Print(" * @param value The bytes for $name$ to set.\n",
                     "name", field->camelcase_name());
      break;
    case CLEARER:
      // Print nothing
      break;
    // Repeated
    case LIST_COUNT:
      // Should never happen
      break;
    case LIST_GETTER:
      printer->Print(" * @return A list containing the bytes for $name$(s).\n",
                     "name", field->camelcase_name());
      break;
    case LIST_INDEXED_GETTER:
      printer->Print(" * @param index The index of the value to return.\n");
      printer->Print(" * @return The bytes of the $name$ at the given index.\n",
                     "name", field->camelcase_name());
      break;
    case LIST_INDEXED_SETTER:
      printer->Print(" * @param index The index to set the value at.\n");
      printer->Print(" * @param value The bytes of the $name$ to set.\n",
                     "name", field->camelcase_name());
      break;
    case LIST_ADDER:
      printer->Print(" * @param value The bytes of the $name$ to add.\n",
                     "name", field->camelcase_name());
      break;
    case LIST_MULTI_ADDER:
      printer->Print(" * @param values The bytes of the $name$(s) to add.\n",
                     "name", field->camelcase_name());
      break;
  }
  if (builder) {
    printer->Print(" * @return This builder for chaining.\n");
  }
  printer->Print(" */\n");
}

// Enum

void WriteEnumDocComment(io::Printer* printer, const EnumDescriptor* enum_) {
  printer->Print("/**\n");
  WriteDocCommentBody(printer, enum_);
  printer->Print(
      " * Protobuf enum {@code $fullname$}\n"
      " */\n",
      "fullname", EscapeJavadoc(enum_->full_name()));
}

void WriteEnumValueDocComment(io::Printer* printer,
                              const EnumValueDescriptor* value) {
  printer->Print("/**\n");
  WriteDocCommentBody(printer, value);
  printer->Print(
      " * $def$\n"
      " */\n",
      "def", EscapeJavadoc(FirstLineOf(value->DebugString())));
}

void WriteServiceDocComment(io::Printer* printer,
                            const ServiceDescriptor* service) {
  printer->Print("/**\n");
  WriteDocCommentBody(printer, service);
  printer->Print(
      " * Protobuf service {@code $fullname$}\n"
      " */\n",
      "fullname", EscapeJavadoc(service->full_name()));
}

void WriteMethodDocComment(io::Printer* printer,
                           const MethodDescriptor* method) {
  printer->Print("/**\n");
  WriteDocCommentBody(printer, method);
  printer->Print(
      " * $def$\n"
      " */\n",
      "def", EscapeJavadoc(FirstLineOf(method->DebugString())));
}

}  // namespace java
}  // namespace compiler
}  // namespace protobuf
}  // namespace google
<commit_msg>Follow line length guidelines<commit_after>// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc.  All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

// Author: kenton@google.com (Kenton Varda)
//  Based on original Protocol Buffers design by
//  Sanjay Ghemawat, Jeff Dean, and others.

#include <google/protobuf/compiler/java/java_doc_comment.h>

#include <vector>

#include <google/protobuf/io/printer.h>
#include <google/protobuf/stubs/strutil.h>

namespace google {
namespace protobuf {
namespace compiler {
namespace java {

std::string EscapeJavadoc(const std::string& input) {
  std::string result;
  result.reserve(input.size() * 2);

  char prev = '*';

  for (std::string::size_type i = 0; i < input.size(); i++) {
    char c = input[i];
    switch (c) {
      case '*':
        // Avoid "/*".
        if (prev == '/') {
          result.append("*");
        } else {
          result.push_back(c);
        }
        break;
      case '/':
        // Avoid "*/".
        if (prev == '*') {
          result.append("/");
        } else {
          result.push_back(c);
        }
        break;
      case '@':
        // '@' starts javadoc tags including the @deprecated tag, which will
        // cause a compile-time error if inserted before a declaration that
        // does not have a corresponding @Deprecated annotation.
        result.append("@");
        break;
      case '<':
        // Avoid interpretation as HTML.
        result.append("<");
        break;
      case '>':
        // Avoid interpretation as HTML.
        result.append(">");
        break;
      case '&':
        // Avoid interpretation as HTML.
        result.append("&");
        break;
      case '\\':
        // Java interprets Unicode escape sequences anywhere!
        result.append("\");
        break;
      default:
        result.push_back(c);
        break;
    }

    prev = c;
  }

  return result;
}

static void WriteDocCommentBodyForLocation(io::Printer* printer,
                                           const SourceLocation& location) {
  std::string comments = location.leading_comments.empty()
                             ? location.trailing_comments
                             : location.leading_comments;
  if (!comments.empty()) {
    // TODO(kenton):  Ideally we should parse the comment text as Markdown and
    //   write it back as HTML, but this requires a Markdown parser.  For now
    //   we just use
 to get fixed-width text formatting.

    // If the comment itself contains block comment start or end markers,
    // HTML-escape them so that they don't accidentally close the doc comment.
    comments = EscapeJavadoc(comments);

    std::vector<std::string> lines = Split(comments, "\n");
    while (!lines.empty() && lines.back().empty()) {
      lines.pop_back();
    }

    printer->Print(" *
\n");
    for (int i = 0; i < lines.size(); i++) {
      // Most lines should start with a space.  Watch out for lines that start
      // with a /, since putting that right after the leading asterisk will
      // close the comment.
      if (!lines[i].empty() && lines[i][0] == '/') {
        printer->Print(" * $line$\n", "line", lines[i]);
      } else {
        printer->Print(" *$line$\n", "line", lines[i]);
      }
    }
    printer->Print(
        " *
\n"
        " *\n");
  }
}

template <typename DescriptorType>
static void WriteDocCommentBody(io::Printer* printer,
                                const DescriptorType* descriptor) {
  SourceLocation location;
  if (descriptor->GetSourceLocation(&location)) {
    WriteDocCommentBodyForLocation(printer, location);
  }
}

static std::string FirstLineOf(const std::string& value) {
  std::string result = value;

  std::string::size_type pos = result.find_first_of('\n');
  if (pos != std::string::npos) {
    result.erase(pos);
  }

  // If line ends in an opening brace, make it "{ ... }" so it looks nice.
  if (!result.empty() && result[result.size() - 1] == '{') {
    result.append(" ... }");
  }

  return result;
}

void WriteMessageDocComment(io::Printer* printer, const Descriptor* message) {
  printer->Print("/**\n");
  WriteDocCommentBody(printer, message);
  printer->Print(
      " * Protobuf type {@code $fullname$}\n"
      " */\n",
      "fullname", EscapeJavadoc(message->full_name()));
}

void WriteFieldDocComment(io::Printer* printer, const FieldDescriptor* field) {
  // We start the comment with the main body based on the comments from the
  // .proto file (if present). We then continue with the field declaration, e.g.:
  //   optional string foo = 5;
  // And then we end with the javadoc tags if applicable.
  // If the field is a group, the debug string might end with {.
  printer->Print("/**\n");
  WriteDocCommentBody(printer, field);
  printer->Print(" * $def$\n", "def",
                 EscapeJavadoc(FirstLineOf(field->DebugString())));
  printer->Print(" */\n");
}

void WriteFieldAccessorDocComment(io::Printer* printer,
                                  const FieldDescriptor* field,
                                  const FieldAccessorType type,
                                  const bool builder) {
  printer->Print("/**\n");
  WriteDocCommentBody(printer, field);
  printer->Print(" * $def$\n", "def",
                 EscapeJavadoc(FirstLineOf(field->DebugString())));
  switch (type) {
    case HAZZER:
      printer->Print(" * @return Whether the $name$ field is set.\n", "name",
                     field->camelcase_name());
      break;
    case GETTER:
      printer->Print(" * @return The $name$.\n", "name",
                     field->camelcase_name());
      break;
    case SETTER:
      printer->Print(" * @param value The $name$ to set.\n", "name",
                     field->camelcase_name());
      break;
    case CLEARER:
      // Print nothing
      break;
    // Repeated
    case LIST_COUNT:
      printer->Print(" * @return The number of $name$(s).\n", "name",
                 field->camelcase_name());
      break;
    case LIST_GETTER:
      printer->Print(" * @return A list containing the $name$(s).\n", "name",
                     field->camelcase_name());
      break;
    case LIST_INDEXED_GETTER:
      printer->Print(" * @param index The index of the element to return.\n");
      printer->Print(" * @return The $name$(s) at the given index.\n", "name",
                     field->camelcase_name());
      break;
    case LIST_INDEXED_SETTER:
      printer->Print(" * @param index The index to set the value at.\n");
      printer->Print(" * @param value The $name$ to set.\n", "name",
                     field->camelcase_name());
      break;
    case LIST_ADDER:
      printer->Print(" * @param value The $name$ to add.\n", "name",
                     field->camelcase_name());
      break;
    case LIST_MULTI_ADDER:
      printer->Print(" * @param values The $name$(s) to add.\n", "name",
                 field->camelcase_name());
      break;
  }
  if (builder) {
    printer->Print(" * @return This builder for chaining.\n");
  }
  printer->Print(" */\n");
}

void WriteFieldEnumValueAccessorDocComment(io::Printer* printer,
                                           const FieldDescriptor* field,
                                           const FieldAccessorType type,
                                           const bool builder) {
  printer->Print("/**\n");
  WriteDocCommentBody(printer, field);
  printer->Print(" * $def$\n", "def",
                 EscapeJavadoc(FirstLineOf(field->DebugString())));
  switch (type) {
    case HAZZER:
      // Should never happen
      break;
    case GETTER:
      printer->Print(" * @return The enum value for $name$.\n", "name",
                 field->camelcase_name());
      break;
    case SETTER:
      printer->Print(" * @param value The enum value for $name$ to set.\n",
                     "name", field->camelcase_name());
      break;
    case CLEARER:
      // Print nothing
      break;
    // Repeated
    case LIST_COUNT:
      // Should never happen
      break;
    case LIST_GETTER:
      printer->Print(" * @return A list containing the enum values for "
                     "$name$(s).\n", "name", field->camelcase_name());
      break;
    case LIST_INDEXED_GETTER:
      printer->Print(" * @param index The index of the value to return.\n");
      printer->Print(" * @return The enum value of the $name$ at the given "
                     "index.\n", "name", field->camelcase_name());
      break;
    case LIST_INDEXED_SETTER:
      printer->Print(" * @param index The index to set the value at.\n");
      printer->Print(" * @param value The enum value of the $name$ to set.\n",
                     "name", field->camelcase_name());
      break;
    case LIST_ADDER:
      printer->Print(" * @param value The enum value of the $name$ to add.\n",
                     "name", field->camelcase_name());
      break;
    case LIST_MULTI_ADDER:
      printer->Print(" * @param values The enum values of the $name$(s) to "
                     "add.\n", "name", field->camelcase_name());
      break;
  }
  if (builder) {
    printer->Print(" * @return This builder for chaining.\n");
  }
  printer->Print(" */\n");
}

void WriteFieldStringBytesAccessorDocComment(io::Printer* printer,
                                             const FieldDescriptor* field,
                                             const FieldAccessorType type,
                                             const bool builder) {
  printer->Print("/**\n");
  WriteDocCommentBody(printer, field);
  printer->Print(" * $def$\n", "def",
                 EscapeJavadoc(FirstLineOf(field->DebugString())));
  switch (type) {
    case HAZZER:
      // Should never happen
      break;
    case GETTER:
      printer->Print(" * @return The bytes for $name$.\n", "name",
                 field->camelcase_name());
      break;
    case SETTER:
      printer->Print(" * @param value The bytes for $name$ to set.\n",
                     "name", field->camelcase_name());
      break;
    case CLEARER:
      // Print nothing
      break;
    // Repeated
    case LIST_COUNT:
      // Should never happen
      break;
    case LIST_GETTER:
      printer->Print(" * @return A list containing the bytes for $name$(s).\n",
                     "name", field->camelcase_name());
      break;
    case LIST_INDEXED_GETTER:
      printer->Print(" * @param index The index of the value to return.\n");
      printer->Print(" * @return The bytes of the $name$ at the given index.\n",
                     "name", field->camelcase_name());
      break;
    case LIST_INDEXED_SETTER:
      printer->Print(" * @param index The index to set the value at.\n");
      printer->Print(" * @param value The bytes of the $name$ to set.\n",
                     "name", field->camelcase_name());
      break;
    case LIST_ADDER:
      printer->Print(" * @param value The bytes of the $name$ to add.\n",
                     "name", field->camelcase_name());
      break;
    case LIST_MULTI_ADDER:
      printer->Print(" * @param values The bytes of the $name$(s) to add.\n",
                     "name", field->camelcase_name());
      break;
  }
  if (builder) {
    printer->Print(" * @return This builder for chaining.\n");
  }
  printer->Print(" */\n");
}

// Enum

void WriteEnumDocComment(io::Printer* printer, const EnumDescriptor* enum_) {
  printer->Print("/**\n");
  WriteDocCommentBody(printer, enum_);
  printer->Print(
      " * Protobuf enum {@code $fullname$}\n"
      " */\n",
      "fullname", EscapeJavadoc(enum_->full_name()));
}

void WriteEnumValueDocComment(io::Printer* printer,
                              const EnumValueDescriptor* value) {
  printer->Print("/**\n");
  WriteDocCommentBody(printer, value);
  printer->Print(
      " * $def$\n"
      " */\n",
      "def", EscapeJavadoc(FirstLineOf(value->DebugString())));
}

void WriteServiceDocComment(io::Printer* printer,
                            const ServiceDescriptor* service) {
  printer->Print("/**\n");
  WriteDocCommentBody(printer, service);
  printer->Print(
      " * Protobuf service {@code $fullname$}\n"
      " */\n",
      "fullname", EscapeJavadoc(service->full_name()));
}

void WriteMethodDocComment(io::Printer* printer,
                           const MethodDescriptor* method) {
  printer->Print("/**\n");
  WriteDocCommentBody(printer, method);
  printer->Print(
      " * $def$\n"
      " */\n",
      "def", EscapeJavadoc(FirstLineOf(method->DebugString())));
}

}  // namespace java
}  // namespace compiler
}  // namespace protobuf
}  // namespace google
<|endoftext|>


<commit_before>/*
*  Copyright 2016 Matthias Fuchs
*
*  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 <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestAssert.h>
#include <cppunit/TestFixture.h>

#include <zbar.h>

#include <stromx/runtime/ConstDataRef.h>
#include <stromx/runtime/DataContainer.h>
#include <stromx/runtime/List.h>
#include <stromx/runtime/OperatorTester.h>
#include <stromx/runtime/ReadAccess.h>
#include <stromx/runtime/String.h>
#include <stromx/cvsupport/Image.h>

#include "stromx/zbar/Scan.h"

namespace stromx
{
namespace zbar
{

class ScanTest : public CPPUNIT_NS :: TestFixture
{
    CPPUNIT_TEST_SUITE (ScanTest);
    CPPUNIT_TEST (testExecute);
    CPPUNIT_TEST (testExecuteWrongSymbolType);
    CPPUNIT_TEST (testSetSymbolType);
    CPPUNIT_TEST_SUITE_END ();

    public:
        ScanTest() : m_operator(0) {}

        void setUp();
        void tearDown();

    protected:
        void testExecute();
        void testExecuteWrongSymbolType();
        void testSetSymbolType();

    private:
        runtime::OperatorTester* m_operator;
};

CPPUNIT_TEST_SUITE_REGISTRATION (ScanTest);

void ScanTest::setUp ( void )
{
    m_operator = new runtime::OperatorTester(new Scan());
    m_operator->initialize();
    m_operator->activate();
}

void ScanTest::testExecute()
{
    runtime::DataContainer input(new cvsupport::Image("barcode.png"));
    m_operator->setParameter(Scan::SYMBOL_TYPE, runtime::Enum(::zbar::ZBAR_EAN13));
    m_operator->setInputData(Scan::INPUT, input);

    runtime::DataContainer result = m_operator->getOutputData(Scan::SYMBOLS);

    runtime::ReadAccess access(result);
    const std::vector<const runtime::Data*> & content = access.get<runtime::List>().content();
    CPPUNIT_ASSERT_EQUAL(std::size_t(1), content.size());
    const runtime::String* symbol = runtime::data_cast<runtime::String>(content[0]);
    CPPUNIT_ASSERT_EQUAL(symbol->get(), std::string("9876543210128"));
}

void ScanTest::testExecuteWrongSymbolType()
{
    runtime::DataContainer input(new cvsupport::Image("barcode.png"));
    m_operator->setParameter(Scan::SYMBOL_TYPE, runtime::Enum(::zbar::ZBAR_EAN8));
    m_operator->setInputData(Scan::INPUT, input);

    runtime::DataContainer result = m_operator->getOutputData(Scan::SYMBOLS);

    runtime::ReadAccess access(result);
    const std::vector<const runtime::Data*> & content = access.get<runtime::List>().content();
    CPPUNIT_ASSERT_EQUAL(std::size_t(0), content.size());
}

void ScanTest::testSetSymbolType()
{
    m_operator->setParameter(Scan::SYMBOL_TYPE, runtime::Enum(::zbar::ZBAR_EAN13));
    runtime::DataRef value = m_operator->getParameter(Scan::SYMBOL_TYPE);

    CPPUNIT_ASSERT_EQUAL(runtime::Enum(::zbar::ZBAR_EAN13),
                         runtime::data_cast<runtime::Enum>(value));
}

void ScanTest::tearDown ( void )
{
    delete m_operator;
}

}
}

<commit_msg>Fix scan test<commit_after>/*
*  Copyright 2016 Matthias Fuchs
*
*  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 <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestAssert.h>
#include <cppunit/TestFixture.h>

#include <zbar.h>

#include <stromx/runtime/ConstDataRef.h>
#include <stromx/runtime/DataContainer.h>
#include <stromx/runtime/List.h>
#include <stromx/runtime/OperatorTester.h>
#include <stromx/runtime/ReadAccess.h>
#include <stromx/runtime/String.h>
#include <stromx/cvsupport/Image.h>

#include "stromx/zbar/Scan.h"

namespace stromx
{
namespace zbar
{

class ScanTest : public CPPUNIT_NS :: TestFixture
{
    CPPUNIT_TEST_SUITE (ScanTest);
    CPPUNIT_TEST (testExecute);
    CPPUNIT_TEST (testExecuteWrongSymbolType);
    CPPUNIT_TEST (testSetSymbolType);
    CPPUNIT_TEST_SUITE_END ();

    public:
        ScanTest() : m_operator(0) {}

        void setUp();
        void tearDown();

    protected:
        void testExecute();
        void testExecuteWrongSymbolType();
        void testSetSymbolType();

    private:
        runtime::OperatorTester* m_operator;
};

CPPUNIT_TEST_SUITE_REGISTRATION (ScanTest);

void ScanTest::setUp ( void )
{
    m_operator = new runtime::OperatorTester(new Scan());
    m_operator->initialize();
    m_operator->activate();
}

void ScanTest::testExecute()
{
    runtime::DataContainer input(new cvsupport::Image("barcode.png", cvsupport::Image::GRAYSCALE));
    m_operator->setParameter(Scan::SYMBOL_TYPE, runtime::Enum(::zbar::ZBAR_EAN13));
    m_operator->setInputData(Scan::INPUT, input);

    runtime::DataContainer result = m_operator->getOutputData(Scan::SYMBOLS);

    runtime::ReadAccess access(result);
    const std::vector<const runtime::Data*> & content = access.get<runtime::List>().content();
    CPPUNIT_ASSERT_EQUAL(std::size_t(1), content.size());
    const runtime::String* symbol = runtime::data_cast<runtime::String>(content[0]);
    CPPUNIT_ASSERT_EQUAL(symbol->get(), std::string("9876543210128"));
}

void ScanTest::testExecuteWrongSymbolType()
{
    runtime::DataContainer input(new cvsupport::Image("barcode.png", cvsupport::Image::GRAYSCALE));
    m_operator->setParameter(Scan::SYMBOL_TYPE, runtime::Enum(::zbar::ZBAR_EAN8));
    m_operator->setInputData(Scan::INPUT, input);

    runtime::DataContainer result = m_operator->getOutputData(Scan::SYMBOLS);

    runtime::ReadAccess access(result);
    const std::vector<const runtime::Data*> & content = access.get<runtime::List>().content();
    CPPUNIT_ASSERT_EQUAL(std::size_t(0), content.size());
}

void ScanTest::testSetSymbolType()
{
    m_operator->setParameter(Scan::SYMBOL_TYPE, runtime::Enum(::zbar::ZBAR_EAN13));
    runtime::DataRef value = m_operator->getParameter(Scan::SYMBOL_TYPE);

    CPPUNIT_ASSERT_EQUAL(runtime::Enum(::zbar::ZBAR_EAN13),
                         runtime::data_cast<runtime::Enum>(value));
}

void ScanTest::tearDown ( void )
{
    delete m_operator;
}

}
}

<|endoftext|>


<commit_before>/** @file
 *
 * @ingroup dspSoundFileLib
 *
 * @brief Tests for the #TTSoundfileLoader class
 *
 * @details Tests the core functions of the TTSoundfileLoader class in order to ensure that things are working after a build. It also demostrate how to make calls to common methods within the class.@n
 * IMPORTANT NOTE: Because POSIX filepaths will be specific to your system, this test will attempt to find the path to the SoundfileLib extension using the TTFoundationBinaryPath environment variable. If you wish to test with a different sound file, you will need to place in that extension folder and change the relevant macros in the header of this class.
 *
 * @authors Nathan Wolek
 *
 * @copyright Copyright © 2013 by Nathan Wolek @n
 * This code is licensed under the terms of the "New BSD License" @n
 * http://creativecommons.org/licenses/BSD/
 */

#include "TTSoundfileLoader.h"
#include "TTUnitTest.h"

/*

 It is possible to change the target sound file for this test using the macros below.
 Both sound files are included in the Jamoma respository at the following path:
 {JAMOMA_ROOT}/Core/DSP/extensions/SoundfileLib/

 The test should look for the named TESTFILE at this path.

 */

/* */
 #define TESTFILE "geese_clip.aif"
 #define TESTNUMCHANNELS 2
 #define TESTSAMPLERATE 44100
 #define TESTDURATIONINSAMPLES 88202
 #define TESTDURATIONINSECONDS 2.00004535
 #define TESTTITLE ""
 #define TESTARTIST ""
 #define TESTDATE ""
 #define TESTANNOTATION ""
/* */

/*
#define TESTFILE "ding_b2.aiff"
#define TESTNUMCHANNELS 1
#define TESTSAMPLERATE 44100
#define TESTDURATIONINSAMPLES 39493
#define TESTDURATIONINSECONDS 0.89553288
#define TESTTITLE ""
#define TESTARTIST ""
#define TESTDATE ""
#define TESTANNOTATION ""
 */

TTErr TTSoundfileLoader::test(TTValue& returnedTestInfo)
{
    int errorCount = 0;
    int testAssertionCount = 0;

    // assemble the full path of the target sound file

    TTString testSoundPath = TTFoundationBinaryPath;
    int pos = testSoundPath.find_last_of('/');
    testSoundPath = testSoundPath.substr(0,pos+1);
    testSoundPath += TESTFILE;

    std::cout << "We will be using the following path for testing: " << testSoundPath << "\n";

    try {

		TTTestLog("\n");
		TTTestLog("Testing TTSoundfileLoader Basics...");

        // TEST 0: establish our objects & pointers
        TTObject* testTargetMatrix = new TTObject("samplematrix");
        TTObject* testNonSampleMatrix = new TTObject("delay");
        TTObjectBase* objectBasePtrToSampleMatrix;
        TTObjectBase* ptrToNonSampleMatrix;

        // TEST 1: set the filepath
        TTBoolean result1 = { this->setFilePath(TT(testSoundPath)) == kTTErrNone };

        TTTestAssertion("setFilePath operates successfully",
                        result1,
                        testAssertionCount,
                        errorCount);

        // TEST 2: set up the samplematrix first
        int channelsSend = 1;           // compiler complained about TTInt32 being ambiguous here
        int lengthSend = 22050;         // compiler complained about TTInt32 being ambiguous here
        testTargetMatrix->set("numChannels", channelsSend);
        testTargetMatrix->set("lengthInSamples", lengthSend);

        TTInt32 channelsReturn, lengthReturn;

        testTargetMatrix->get("numChannels", channelsReturn);
        testTargetMatrix->get("lengthInSamples", lengthReturn);

        // now for the actual test
        TTBoolean result2a = { channelsSend == channelsReturn };

        TTTestAssertion("numChannels attribute set successfully",
						result2a,
						testAssertionCount,
						errorCount);

        TTBoolean result2b = { lengthSend == lengthReturn };

        TTTestAssertion("lengthInSamples attribute set successfully",
						result2b,
						testAssertionCount,
						errorCount);
        //

        // TEST 3: set the target via an objectBasePtr
        objectBasePtrToSampleMatrix = testTargetMatrix->instance(); // is there a better syntax for this?

        TTBoolean result3 = { this->setTargetMatrix(objectBasePtrToSampleMatrix) == kTTErrNone };

        TTTestAssertion("setTargetMatrix via ObjectBasePtr operates successfully",
						result3,
						testAssertionCount,
						errorCount);

        // TEST 4: set the target to a non-SampleMatrix, should FAIL
        ptrToNonSampleMatrix = testNonSampleMatrix->instance();

        TTBoolean result4 = { this->setTargetMatrix(ptrToNonSampleMatrix) == kTTErrInvalidValue };

        TTTestAssertion("setTargetMatrix returns error when not a SampleMatrix",
						result4,
						testAssertionCount,
						errorCount);

        // TEST 5: copy samplevalues until samplematrix is filled

        TTBoolean result5 = { this->copyUntilFilled() == kTTErrNone };

        TTTestAssertion("copyUntilFilled operates successfully",
						result5,
						testAssertionCount,
						errorCount);

        // TEST 6: use TTSampleMatrix's load message, then compare 5 random sample values for equivalence

        // create a new TTSampleMatrix
        TTObject newTargetMatrix("samplematrix");

        // set the length and channel count
        newTargetMatrix.set("numChannels", TESTNUMCHANNELS);
        newTargetMatrix.set("lengthInSamples", TESTDURATIONINSAMPLES);

        // prepare necessary TTValues
        TTValue loadInput6 = TT(testSoundPath); // we cannot pass the naked TTString, it needs to be part of a TTValue
        TTValue aReturnWeDontCareAbout6;

        // send message
        TTBoolean result6a = { newTargetMatrix.send("load", loadInput6, aReturnWeDontCareAbout6) == kTTErrNone };

        TTTestAssertion("TTSampleMatrix load operates successfully",
                        result6a,
                        testAssertionCount,
                        errorCount);

        // now let's test some values!
        int randomIndex6;
        TTSampleValue randomValueSoundFile6;
        TTBoolean result6 = true;

        for (int i = 0; i<5; i++)
        {
            randomIndex6 = lengthReturn * TTRandom64();
            std::cout << "let's look at index " << randomIndex6 << "\n";

            TTValue peekInput6(randomIndex6);
            peekInput6.append(0);
            TTValue peekOutput6;

            this->peek(randomIndex6,0,randomValueSoundFile6);
            newTargetMatrix.send("peek",peekInput6,peekOutput6);
            std::cout << "Does " << randomValueSoundFile6 << " = " << double(peekOutput6) << " ?\n";

            if (result6) // allows test to keep variable false once it is false
                result6 = TTTestFloatEquivalence(randomValueSoundFile6, double(peekOutput6), true, 0.0000001);
        }

        TTTestAssertion("comparing 5 random values for equivalence",
                        result6,
                        testAssertionCount,
                        errorCount);

        //

        // TEST 7: now use TTBuffer's load message, and again compare 5 random sample values for equivalence

        // create a new TTBuffer
        TTObject newTargetBuffer("buffer");

        // set the length and channel count
        newTargetBuffer.set("numChannels", TESTNUMCHANNELS);
        newTargetBuffer.set("lengthInSamples", TESTDURATIONINSAMPLES);

        // prepare necessary TTValues
        TTValue loadInput7 = TT(testSoundPath); // we cannot pass the naked TTString, it needs to be part of a TTValue
        TTValue aReturnWeDontCareAbout7;

        // send message
        TTBoolean result7a = { newTargetBuffer.send("load", loadInput7, aReturnWeDontCareAbout7) == kTTErrNone };

        TTTestAssertion("TTBuffer load operates successfully",
                        result7a,
                        testAssertionCount,
                        errorCount);

        // now let's test some values!
        int randomIndex7;
        TTSampleValue randomValueSoundFile7;
        TTBoolean result7 = true;

        for (int i = 0; i<5; i++)
        {
            randomIndex7 = lengthReturn * TTRandom64();
            std::cout << "let's look at index " << randomIndex7 << "\n";

            TTValue peekInput7(randomIndex7);
            peekInput7.append(0);
            TTValue peekOutput7;

            this->peek(randomIndex7,0,randomValueSoundFile7);
            newTargetBuffer.send("peek",peekInput7,peekOutput7);
            std::cout << "Does " << randomValueSoundFile7 << " = " << double(peekOutput7) << " ?\n";

            if (result7) // allows test to keep variable false once it is false
                result7 = TTTestFloatEquivalence(randomValueSoundFile7, double(peekOutput7), true, 0.0000001);
        }

        TTTestAssertion("comparing 5 random values for equivalence",
                        result7,
                        testAssertionCount,
                        errorCount);

        //

        // releasing objects
        objectBasePtrToSampleMatrix = NULL;
        ptrToNonSampleMatrix = NULL;
        delete testTargetMatrix;
        delete testNonSampleMatrix;

    } catch (...) {
        TTTestAssertion("FAILED to run tests -- likely that necessary objects did not instantiate",
            0,
            testAssertionCount,
            errorCount);

    }

    return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo);
}
<commit_msg>TTSoundfileLoader::test() - test 7 works. resolves #176, but I don't like this goofy syntax.<commit_after>/** @file
 *
 * @ingroup dspSoundFileLib
 *
 * @brief Tests for the #TTSoundfileLoader class
 *
 * @details Tests the core functions of the TTSoundfileLoader class in order to ensure that things are working after a build. It also demostrate how to make calls to common methods within the class.@n
 * IMPORTANT NOTE: Because POSIX filepaths will be specific to your system, this test will attempt to find the path to the SoundfileLib extension using the TTFoundationBinaryPath environment variable. If you wish to test with a different sound file, you will need to place in that extension folder and change the relevant macros in the header of this class.
 *
 * @authors Nathan Wolek
 *
 * @copyright Copyright © 2013 by Nathan Wolek @n
 * This code is licensed under the terms of the "New BSD License" @n
 * http://creativecommons.org/licenses/BSD/
 */

#include "TTSoundfileLoader.h"
#include "TTUnitTest.h"
#include "TTBuffer.h"

/*

 It is possible to change the target sound file for this test using the macros below.
 Both sound files are included in the Jamoma respository at the following path:
 {JAMOMA_ROOT}/Core/DSP/extensions/SoundfileLib/

 The test should look for the named TESTFILE at this path.

 */

/* */
 #define TESTFILE "geese_clip.aif"
 #define TESTNUMCHANNELS 2
 #define TESTSAMPLERATE 44100
 #define TESTDURATIONINSAMPLES 88202
 #define TESTDURATIONINSECONDS 2.00004535
 #define TESTTITLE ""
 #define TESTARTIST ""
 #define TESTDATE ""
 #define TESTANNOTATION ""
/* */

/*
#define TESTFILE "ding_b2.aiff"
#define TESTNUMCHANNELS 1
#define TESTSAMPLERATE 44100
#define TESTDURATIONINSAMPLES 39493
#define TESTDURATIONINSECONDS 0.89553288
#define TESTTITLE ""
#define TESTARTIST ""
#define TESTDATE ""
#define TESTANNOTATION ""
 */

TTErr TTSoundfileLoader::test(TTValue& returnedTestInfo)
{
    int errorCount = 0;
    int testAssertionCount = 0;

    // assemble the full path of the target sound file

    TTString testSoundPath = TTFoundationBinaryPath;
    int pos = testSoundPath.find_last_of('/');
    testSoundPath = testSoundPath.substr(0,pos+1);
    testSoundPath += TESTFILE;

    std::cout << "We will be using the following path for testing: " << testSoundPath << "\n";

    try {

		TTTestLog("\n");
		TTTestLog("Testing TTSoundfileLoader Basics...");

        // TEST 0: establish our objects & pointers
        TTObject* testTargetMatrix = new TTObject("samplematrix");
        TTObject* testNonSampleMatrix = new TTObject("delay");
        TTObjectBase* objectBasePtrToSampleMatrix;
        TTObjectBase* ptrToNonSampleMatrix;

        // TEST 1: set the filepath
        TTBoolean result1 = { this->setFilePath(TT(testSoundPath)) == kTTErrNone };

        TTTestAssertion("setFilePath operates successfully",
                        result1,
                        testAssertionCount,
                        errorCount);

        // TEST 2: set up the samplematrix first
        int channelsSend = 1;           // compiler complained about TTInt32 being ambiguous here
        int lengthSend = 22050;         // compiler complained about TTInt32 being ambiguous here
        testTargetMatrix->set("numChannels", channelsSend);
        testTargetMatrix->set("lengthInSamples", lengthSend);

        TTInt32 channelsReturn, lengthReturn;

        testTargetMatrix->get("numChannels", channelsReturn);
        testTargetMatrix->get("lengthInSamples", lengthReturn);

        // now for the actual test
        TTBoolean result2a = { channelsSend == channelsReturn };

        TTTestAssertion("numChannels attribute set successfully",
						result2a,
						testAssertionCount,
						errorCount);

        TTBoolean result2b = { lengthSend == lengthReturn };

        TTTestAssertion("lengthInSamples attribute set successfully",
						result2b,
						testAssertionCount,
						errorCount);
        //

        // TEST 3: set the target via an objectBasePtr
        objectBasePtrToSampleMatrix = testTargetMatrix->instance(); // is there a better syntax for this?

        TTBoolean result3 = { this->setTargetMatrix(objectBasePtrToSampleMatrix) == kTTErrNone };

        TTTestAssertion("setTargetMatrix via ObjectBasePtr operates successfully",
						result3,
						testAssertionCount,
						errorCount);

        // TEST 4: set the target to a non-SampleMatrix, should FAIL
        ptrToNonSampleMatrix = testNonSampleMatrix->instance();

        TTBoolean result4 = { this->setTargetMatrix(ptrToNonSampleMatrix) == kTTErrInvalidValue };

        TTTestAssertion("setTargetMatrix returns error when not a SampleMatrix",
						result4,
						testAssertionCount,
						errorCount);

        // TEST 5: copy samplevalues until samplematrix is filled

        TTBoolean result5 = { this->copyUntilFilled() == kTTErrNone };

        TTTestAssertion("copyUntilFilled operates successfully",
						result5,
						testAssertionCount,
						errorCount);

        // TEST 6: use TTSampleMatrix's load message, then compare 5 random sample values for equivalence

        // create a new TTSampleMatrix
        TTObject newTargetMatrix("samplematrix");

        // set the length and channel count
        newTargetMatrix.set("numChannels", TESTNUMCHANNELS);
        newTargetMatrix.set("lengthInSamples", TESTDURATIONINSAMPLES);

        // prepare necessary TTValues
        TTValue loadInput6 = TT(testSoundPath); // we cannot pass the naked TTString, it needs to be part of a TTValue
        TTValue aReturnWeDontCareAbout6;

        // send message
        TTBoolean result6a = { newTargetMatrix.send("load", loadInput6, aReturnWeDontCareAbout6) == kTTErrNone };

        TTTestAssertion("TTSampleMatrix load operates successfully",
                        result6a,
                        testAssertionCount,
                        errorCount);

        // now let's test some values!
        int randomIndex6;
        TTSampleValue randomValueSoundFile6;
        TTBoolean result6 = true;

        for (int i = 0; i<5; i++)
        {
            randomIndex6 = lengthReturn * TTRandom64();
            std::cout << "let's look at index " << randomIndex6 << "\n";

            TTValue peekInput6(randomIndex6);
            peekInput6.append(0);
            TTValue peekOutput6;

            this->peek(randomIndex6,0,randomValueSoundFile6);
            newTargetMatrix.send("peek",peekInput6,peekOutput6);
            std::cout << "Does " << randomValueSoundFile6 << " = " << double(peekOutput6) << " ?\n";

            if (result6) // allows test to keep variable false once it is false
                result6 = TTTestFloatEquivalence(randomValueSoundFile6, double(peekOutput6), true, 0.0000001);
        }

        TTTestAssertion("comparing 5 random values for equivalence",
                        result6,
                        testAssertionCount,
                        errorCount);

        //

        // TEST 7: now use TTBuffer's load message, and again compare 5 random sample values for equivalence

        // create a new TTBuffer
        TTObject newTargetBuffer("buffer");

        // set the length and channel count
        newTargetBuffer.set("numChannels", TESTNUMCHANNELS);
        newTargetBuffer.set("lengthInSamples", TESTDURATIONINSAMPLES);

        // prepare necessary TTValues
        TTValue loadInput7 = TT(testSoundPath); // we cannot pass the naked TTString, it needs to be part of a TTValue
        TTValue aSendWeDontCareAbout7, aReturnWeDontCareAbout7;
        TTValue checkOutValue;

        // send message
        TTBoolean result7a = { newTargetBuffer.send("load", loadInput7, aReturnWeDontCareAbout7) == kTTErrNone };

        TTTestAssertion("TTBuffer load operates successfully",
                        result7a,
                        testAssertionCount,
                        errorCount);

        // check out samplematrix
        newTargetBuffer.send("checkOutMatrix",aSendWeDontCareAbout7,checkOutValue);
        TTObjectBase* checkedOutMatrix = checkOutValue[0];

        // now let's test some values!
        int randomIndex7;
        TTSampleValue randomValueSoundFile7;
        TTBoolean result7 = true;

        for (int i = 0; i<5; i++)
        {
            randomIndex7 = lengthReturn * TTRandom64();
            std::cout << "let's look at index " << randomIndex7 << "\n";

            TTValue peekInput7(randomIndex7);
            peekInput7.append(0);
            TTValue peekOutput7;

            this->peek(randomIndex7,0,randomValueSoundFile7);
            checkedOutMatrix->sendMessage("peek",peekInput7,peekOutput7);
            std::cout << "Does " << randomValueSoundFile7 << " = " << double(peekOutput7) << " ?\n";

            if (result7) // allows test to keep variable false once it is false
                result7 = TTTestFloatEquivalence(randomValueSoundFile7, double(peekOutput7), true, 0.0000001);
        }

        TTTestAssertion("comparing 5 random values for equivalence",
                        result7,
                        testAssertionCount,
                        errorCount);

        // check in samplematrix
        TTBoolean result7c = { newTargetBuffer.send("checkInMatrix",checkOutValue,aReturnWeDontCareAbout7) == kTTErrNone };

        TTTestAssertion("TTBuffer checks in SampleMatrix successfully",
                        result7c,
                        testAssertionCount,
                        errorCount);

        // releasing objects
        objectBasePtrToSampleMatrix = NULL;
        ptrToNonSampleMatrix = NULL;
        delete testTargetMatrix;
        delete testNonSampleMatrix;

    } catch (...) {
        TTTestAssertion("FAILED to run tests -- likely that necessary objects did not instantiate",
            0,
            testAssertionCount,
            errorCount);

    }

    return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo);
}
<|endoftext|>


<commit_before>/* File: SamplerGenMonkeyPatch.cpp
 * Author: Chris Dellin <cdellin@gmail.com>
 * Copyright: 2015 Carnegie Mellon University
 * License: BSD
 */

#include <sstream>
#include <ompl/base/StateSampler.h>
#include <ompl_multiset/SamplerGenMonkeyPatch.h>

// from Johannes Schaub - litb
// http://bloglitb.blogspot.de/2011/12/access-to-private-members-safer.html

namespace {

   // this defines a friend function
   // that can be called by ADL using the tag type
   template<typename Tag, typename Tag::type M>
   struct Rob {
     friend typename Tag::type get(Tag) {
       return M;
     }
   };

   // tag used to access StateSampler::rng_
   struct StateSampler_rng {
     typedef ompl::RNG ompl::base::StateSampler::*type;
     friend type get(StateSampler_rng);
   };
   template struct Rob<StateSampler_rng, &ompl::base::StateSampler::rng_>;

   // tag used to access RNG::generator_
   struct RNG_generator {
     typedef boost::mt19937 ompl::RNG::*type;
     friend type get(RNG_generator);
   };
   template struct Rob<RNG_generator, &ompl::RNG::generator_>;

} // anonymous namespace

boost::mt19937 & ompl_multiset::SamplerGenMonkeyPatch(
   ompl::base::StateSamplerPtr sampler)
{
   return (*sampler).*get(StateSampler_rng()).*get(RNG_generator());
}
<commit_msg>fixed up indentation<commit_after>/* File: SamplerGenMonkeyPatch.cpp
 * Author: Chris Dellin <cdellin@gmail.com>
 * Copyright: 2015 Carnegie Mellon University
 * License: BSD
 */

#include <sstream>
#include <ompl/base/StateSampler.h>
#include <ompl_multiset/SamplerGenMonkeyPatch.h>

// from Johannes Schaub - litb
// http://bloglitb.blogspot.de/2011/12/access-to-private-members-safer.html

namespace {

   // this defines a friend function
   // that can be called by ADL using the tag type
   template<typename Tag, typename Tag::type M>
   struct Rob
   {
      friend typename Tag::type get(Tag)
      {
         return M;
      }
   };

   // tag used to access StateSampler::rng_
   struct StateSampler_rng
   {
      typedef ompl::RNG ompl::base::StateSampler::*type;
      friend type get(StateSampler_rng);
   };
   template struct Rob<StateSampler_rng, &ompl::base::StateSampler::rng_>;

   // tag used to access RNG::generator_
   struct RNG_generator
   {
      typedef boost::mt19937 ompl::RNG::*type;
      friend type get(RNG_generator);
   };
   template struct Rob<RNG_generator, &ompl::RNG::generator_>;

} // anonymous namespace

boost::mt19937 & ompl_multiset::SamplerGenMonkeyPatch(
   ompl::base::StateSamplerPtr sampler)
{
   return (*sampler).*get(StateSampler_rng()).*get(RNG_generator());
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: testserver.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: hr $ $Date: 2003-03-18 19:07:10 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#include <string.h>
#include <assert.h>

#ifndef _OSL_TIME_H_
#include <osl/time.h>
#endif

#include <osl/mutex.hxx>
#include <osl/conditn.h>

#include <osl/thread.hxx>

#include <cppuhelper/servicefactory.hxx>
#include <cppuhelper/implbase1.hxx>

#include <com/sun/star/connection/XAcceptor.hpp>
#include <com/sun/star/connection/XConnection.hpp>

#include <com/sun/star/bridge/XInstanceProvider.hpp>
#include <com/sun/star/bridge/XBridgeFactory.hpp>

#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/lang/XInitialization.hpp>

#include <test/XTestFactory.hpp>

#include <cppuhelper/weak.hxx>

using namespace ::test;
using namespace ::rtl;
using namespace ::osl;
using namespace ::cppu;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::bridge;
using namespace ::com::sun::star::connection;
#include "testcomp.h"
#ifdef SAL_W32
#include <conio.h>
#endif

/*********
 *
 ********/

class MyThread :
    public Thread
{
public:
    MyThread( const Reference< XAcceptor > &r ,
              const Reference< XBridgeFactory > &rFactory,
              const Reference< XMultiServiceFactory > &rSMgr,
              const OUString &sConnectionDescription,
              const OUString &sProtocol,
              sal_Bool bReverse,
              sal_Bool bLatency ) :
        m_rAcceptor( r ),
        m_rBridgeFactory ( rFactory ),
        m_sConnectionDescription( sConnectionDescription ),
        m_sProtocol( sProtocol ),
        m_bReverse( bReverse ),
        m_bLatency( bLatency ),
        m_rSMgr( rSMgr )
        {}
    virtual void SAL_CALL run();

    void latencyTest( const Reference< XConnection > &r );

private:
    Reference < XAcceptor > m_rAcceptor;
    Reference < XBridgeFactory > m_rBridgeFactory;
    Reference < XMultiServiceFactory > m_rSMgr;
    OUString m_sConnectionDescription;
    OUString m_sProtocol;
    sal_Bool m_bReverse;
    sal_Bool m_bLatency;
};

void MyThread::latencyTest( const Reference< XConnection > &r )
{
    Sequence < sal_Int8 > s;
    while( 12 == r->read( s , 12 ) )
    {
        r->read( s , 188 );
        s = Sequence < sal_Int8 >(60);
        r->write( s );
    }
}

void MyThread::run()
{

    while ( sal_True )
    {
        try
        {
            Reference < XConnection > rConnection =
                m_rAcceptor->accept( m_sConnectionDescription );

            if( ! rConnection.is() )
            {
                break;
            }
            if( m_bLatency )
            {
                latencyTest( rConnection );
            }
            else
            {

                Reference < XBridge > rBridge =
                    m_rBridgeFactory->createBridge(
                        OUString() ,
                        m_sProtocol,
                        rConnection ,
                        (XInstanceProvider * ) new OInstanceProvider(m_rSMgr) );

                if( m_bReverse )
                {
                    printf( "doing reverse callme test (test is ok, when on each line a +- appears\n" );
                    Reference < XInterface > r = rBridge->getInstance(
                        OUString( RTL_CONSTASCII_USTRINGPARAM("blubber"  )));
                    Reference < XTestFactory > rFactory( r , UNO_QUERY );
                    Reference < XCallMe > rCallMe = rFactory->createCallMe();

                    for( sal_Int32 i = 0 ; i < 1  ; i ++ )
                    {
                        rCallMe->callOneway(
                            OUString( RTL_CONSTASCII_USTRINGPARAM("my test string")) , 2 );
                    }
                    printf( "all oneway are send\n" );
                    rCallMe->call( OUString::createFromAscii( "reverse call me test finished" ) , 0 );
                printf( "revers callme test finished\n" );
                }
            }
        }
        catch ( Exception & e )
        {
            printf( "Exception was thrown by acceptor \n" );
            OString o = OUStringToOString( e.Message , RTL_TEXTENCODING_ASCII_US );
            printf( "%s\n" , o.getStr() );
            break;
        }
        catch ( ... )
        {
            printf( "Exception was thrown by acceptor thread\n" );
            break;
        }
    }
}

int main( int argc, char *argv[] )
{
//  testserver();

    if( argc < 2 )
    {
        printf( "usage : testserver [-r] connectionstring\n"
                "        -r does a reverse test (server calls client)\n" );
        return 0;
    }

    OUString sConnectionString;
    OUString sProtocol;
    sal_Bool bReverse = sal_False;
    sal_Bool bLatency = sal_False;

    parseCommandLine( argv , &sConnectionString , &sProtocol , &bLatency , &bReverse );

    {
        Reference< XMultiServiceFactory > rSMgr = createRegistryServiceFactory(
            OUString( RTL_CONSTASCII_USTRINGPARAM( "server.rdb" )  ) );

        Reference < XBridgeFactory > rBridgeFactory ( createComponent(
            OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.bridge.BridgeFactory")),
            OUString( RTL_CONSTASCII_USTRINGPARAM("brdgfctr" )),
            rSMgr ),
                                                     UNO_QUERY );

        createComponent( OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.bridge.Bridge.iiop")),
                         OUString( RTL_CONSTASCII_USTRINGPARAM("remotebridge")),
                         rSMgr );

        Reference < XAcceptor > rAcceptor(
            createComponent( OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.connection.Acceptor")),
                             OUString( RTL_CONSTASCII_USTRINGPARAM("acceptor")),
                             rSMgr ) ,
            UNO_QUERY );

        MyThread thread( rAcceptor ,
                         rBridgeFactory,
                         rSMgr,
                         sConnectionString,
                         sProtocol,
                         bReverse,
                         bLatency);
        thread.create();

#ifdef SAL_W32
        _getch();
#elif  SOLARIS
        getchar();
#elif LINUX
        TimeValue value={360,0};
        osl_waitThread( &value );
#endif
        printf( "Closing...\n" );

        rAcceptor->stopAccepting();
        thread.join();

        printf( "Closed\n" );

        Reference < XComponent > rComp2( rBridgeFactory , UNO_QUERY );
        rComp2->dispose();
        Reference < XComponent > rComp( rSMgr, UNO_QUERY );
        rComp->dispose();
    }
    return 0;
}
<commit_msg>INTEGRATION: CWS dbgmacros1 (1.8.6); FILE MERGED 2003/04/09 10:15:49 kso 1.8.6.1: #108413# - debug macro unification.<commit_after>/*************************************************************************
 *
 *  $RCSfile: testserver.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: vg $ $Date: 2003-04-15 16:30:10 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#include <string.h>

#ifndef _OSL_TIME_H_
#include <osl/time.h>
#endif

#include <osl/mutex.hxx>
#include <osl/conditn.h>

#include <osl/thread.hxx>

#include <cppuhelper/servicefactory.hxx>
#include <cppuhelper/implbase1.hxx>

#include <com/sun/star/connection/XAcceptor.hpp>
#include <com/sun/star/connection/XConnection.hpp>

#include <com/sun/star/bridge/XInstanceProvider.hpp>
#include <com/sun/star/bridge/XBridgeFactory.hpp>

#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/lang/XInitialization.hpp>

#include <test/XTestFactory.hpp>

#include <cppuhelper/weak.hxx>

using namespace ::test;
using namespace ::rtl;
using namespace ::osl;
using namespace ::cppu;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::bridge;
using namespace ::com::sun::star::connection;
#include "testcomp.h"
#ifdef SAL_W32
#include <conio.h>
#endif

/*********
 *
 ********/

class MyThread :
    public Thread
{
public:
    MyThread( const Reference< XAcceptor > &r ,
              const Reference< XBridgeFactory > &rFactory,
              const Reference< XMultiServiceFactory > &rSMgr,
              const OUString &sConnectionDescription,
              const OUString &sProtocol,
              sal_Bool bReverse,
              sal_Bool bLatency ) :
        m_rAcceptor( r ),
        m_rBridgeFactory ( rFactory ),
        m_sConnectionDescription( sConnectionDescription ),
        m_sProtocol( sProtocol ),
        m_bReverse( bReverse ),
        m_bLatency( bLatency ),
        m_rSMgr( rSMgr )
        {}
    virtual void SAL_CALL run();

    void latencyTest( const Reference< XConnection > &r );

private:
    Reference < XAcceptor > m_rAcceptor;
    Reference < XBridgeFactory > m_rBridgeFactory;
    Reference < XMultiServiceFactory > m_rSMgr;
    OUString m_sConnectionDescription;
    OUString m_sProtocol;
    sal_Bool m_bReverse;
    sal_Bool m_bLatency;
};

void MyThread::latencyTest( const Reference< XConnection > &r )
{
    Sequence < sal_Int8 > s;
    while( 12 == r->read( s , 12 ) )
    {
        r->read( s , 188 );
        s = Sequence < sal_Int8 >(60);
        r->write( s );
    }
}

void MyThread::run()
{

    while ( sal_True )
    {
        try
        {
            Reference < XConnection > rConnection =
                m_rAcceptor->accept( m_sConnectionDescription );

            if( ! rConnection.is() )
            {
                break;
            }
            if( m_bLatency )
            {
                latencyTest( rConnection );
            }
            else
            {

                Reference < XBridge > rBridge =
                    m_rBridgeFactory->createBridge(
                        OUString() ,
                        m_sProtocol,
                        rConnection ,
                        (XInstanceProvider * ) new OInstanceProvider(m_rSMgr) );

                if( m_bReverse )
                {
                    printf( "doing reverse callme test (test is ok, when on each line a +- appears\n" );
                    Reference < XInterface > r = rBridge->getInstance(
                        OUString( RTL_CONSTASCII_USTRINGPARAM("blubber"  )));
                    Reference < XTestFactory > rFactory( r , UNO_QUERY );
                    Reference < XCallMe > rCallMe = rFactory->createCallMe();

                    for( sal_Int32 i = 0 ; i < 1  ; i ++ )
                    {
                        rCallMe->callOneway(
                            OUString( RTL_CONSTASCII_USTRINGPARAM("my test string")) , 2 );
                    }
                    printf( "all oneway are send\n" );
                    rCallMe->call( OUString::createFromAscii( "reverse call me test finished" ) , 0 );
                printf( "revers callme test finished\n" );
                }
            }
        }
        catch ( Exception & e )
        {
            printf( "Exception was thrown by acceptor \n" );
            OString o = OUStringToOString( e.Message , RTL_TEXTENCODING_ASCII_US );
            printf( "%s\n" , o.getStr() );
            break;
        }
        catch ( ... )
        {
            printf( "Exception was thrown by acceptor thread\n" );
            break;
        }
    }
}

int main( int argc, char *argv[] )
{
//  testserver();

    if( argc < 2 )
    {
        printf( "usage : testserver [-r] connectionstring\n"
                "        -r does a reverse test (server calls client)\n" );
        return 0;
    }

    OUString sConnectionString;
    OUString sProtocol;
    sal_Bool bReverse = sal_False;
    sal_Bool bLatency = sal_False;

    parseCommandLine( argv , &sConnectionString , &sProtocol , &bLatency , &bReverse );

    {
        Reference< XMultiServiceFactory > rSMgr = createRegistryServiceFactory(
            OUString( RTL_CONSTASCII_USTRINGPARAM( "server.rdb" )  ) );

        Reference < XBridgeFactory > rBridgeFactory ( createComponent(
            OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.bridge.BridgeFactory")),
            OUString( RTL_CONSTASCII_USTRINGPARAM("brdgfctr" )),
            rSMgr ),
                                                     UNO_QUERY );

        createComponent( OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.bridge.Bridge.iiop")),
                         OUString( RTL_CONSTASCII_USTRINGPARAM("remotebridge")),
                         rSMgr );

        Reference < XAcceptor > rAcceptor(
            createComponent( OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.connection.Acceptor")),
                             OUString( RTL_CONSTASCII_USTRINGPARAM("acceptor")),
                             rSMgr ) ,
            UNO_QUERY );

        MyThread thread( rAcceptor ,
                         rBridgeFactory,
                         rSMgr,
                         sConnectionString,
                         sProtocol,
                         bReverse,
                         bLatency);
        thread.create();

#ifdef SAL_W32
        _getch();
#elif  SOLARIS
        getchar();
#elif LINUX
        TimeValue value={360,0};
        osl_waitThread( &value );
#endif
        printf( "Closing...\n" );

        rAcceptor->stopAccepting();
        thread.join();

        printf( "Closed\n" );

        Reference < XComponent > rComp2( rBridgeFactory , UNO_QUERY );
        rComp2->dispose();
        Reference < XComponent > rComp( rSMgr, UNO_QUERY );
        rComp->dispose();
    }
    return 0;
}
<|endoftext|>


<commit_before>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>

using namespace View;

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

    undoButton = new QPushButton(this);
    undoButton->setText("Undo");
    undoButton->move(50, 600);
    connect(undoButton, SIGNAL(clicked()), this, SIGNAL(onUndo()));

    redoButton = new QPushButton(this);
    redoButton->setText("Redo");
    redoButton->move(150, 600);
    connect(redoButton, SIGNAL(clicked()), this, SIGNAL(onRedo()));

    loadPuzzleButton = new QPushButton(this);
    loadPuzzleButton->setText("Load Puzzle");
    loadPuzzleButton->move(250, 600);
    connect(loadPuzzleButton, SIGNAL(clicked()), this, SIGNAL(onLoadPuzzlePressed()));

    savePuzzleButton = new QPushButton(this);
    savePuzzleButton->setText("Save Puzzle");
    savePuzzleButton->move(350, 600);
    connect(savePuzzleButton, SIGNAL(clicked()), this, SIGNAL(onSavePuzzlePressed()));

    loadProgressButton = new QPushButton(this);
    loadProgressButton->setText("Load Progress");
    loadProgressButton->move(450, 600);
    connect(loadProgressButton, SIGNAL(clicked()), this, SIGNAL(onLoadProgressPressed()));

    saveProgressButton = new QPushButton(this);
    saveProgressButton->setText("Save Progress");
    saveProgressButton->move(550, 600);
    connect(saveProgressButton, SIGNAL(clicked()), this, SIGNAL(onSaveProgressPressed()));

    for (int i = 1; i < 10; i++) {
        for (int j = 1; j < 10; j++) {

            //Creating and formatting each QLineEdit field.
            fields[i][j] = new QLineEdit(" ",this);
            fields[i][j]->setInputMask("D");
            fields[i][j]->setObjectName(QString::number(i) + "_" + QString::number(j));
            fields[i][j]->setFixedHeight(31);
            fields[i][j]->setFixedWidth(41);
            fields[i][j]->setAlignment(Qt::AlignCenter);
            fields[i][j]->setStyleSheet("font: 18pt;");

            connect(fields[i][j], SIGNAL(textChanged(QString)),this,SLOT(fieldChanged(QString)));
        }
    }
    createLayout();
}

MainWindow::~MainWindow()
{
    //buttons are deleted when ui is deleted since it is parent, see Qt documentation
    delete ui;
}

void MainWindow::fieldChanged(QString text)
{
    //Will eventually parse the object name '1_1' (row 1, col 1) into a position array,
    //and pass the position and values to the Controller, for now just update label to display Value/Field.
    QLineEdit *field = (QLineEdit *)sender();
    emit onMakeMove(QString("Value: " + text + " Field: " + field->objectName()));
}

void MainWindow::createLayout()
{
    ui->gridLayout->setMargin(6);
    ui->gridLayout->setSpacing(6);

    for(int i = 1; i < 10; i++) {
        for(int j = 1; j < 10; j++) {
            ui->gridLayout->addWidget(fields[i][j], i, j);

        }
    }
}
<commit_msg>Changed input mask to QValidator<commit_after>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>

using namespace View;

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

    undoButton = new QPushButton(this);
    undoButton->setText("Undo");
    undoButton->move(50, 600);
    connect(undoButton, SIGNAL(clicked()), this, SIGNAL(onUndo()));

    redoButton = new QPushButton(this);
    redoButton->setText("Redo");
    redoButton->move(150, 600);
    connect(redoButton, SIGNAL(clicked()), this, SIGNAL(onRedo()));

    loadPuzzleButton = new QPushButton(this);
    loadPuzzleButton->setText("Load Puzzle");
    loadPuzzleButton->move(250, 600);
    connect(loadPuzzleButton, SIGNAL(clicked()), this, SIGNAL(onLoadPuzzlePressed()));

    savePuzzleButton = new QPushButton(this);
    savePuzzleButton->setText("Save Puzzle");
    savePuzzleButton->move(350, 600);
    connect(savePuzzleButton, SIGNAL(clicked()), this, SIGNAL(onSavePuzzlePressed()));

    loadProgressButton = new QPushButton(this);
    loadProgressButton->setText("Load Progress");
    loadProgressButton->move(450, 600);
    connect(loadProgressButton, SIGNAL(clicked()), this, SIGNAL(onLoadProgressPressed()));

    saveProgressButton = new QPushButton(this);
    saveProgressButton->setText("Save Progress");
    saveProgressButton->move(550, 600);
    connect(saveProgressButton, SIGNAL(clicked()), this, SIGNAL(onSaveProgressPressed()));

    for (int i = 1; i < 10; i++) {
        for (int j = 1; j < 10; j++) {

            //Creating and formatting each QLineEdit field.
            fields[i][j] = new QLineEdit();

            QValidator *val = new QIntValidator(1,9,fields[i][j]);
            fields[i][j]->setValidator(val);

//            fields[i][j]->setInputMask("D");
            fields[i][j]->setObjectName(QString::number(i) + "_" + QString::number(j));
            fields[i][j]->setFixedHeight(31);
            fields[i][j]->setFixedWidth(41);
            fields[i][j]->setAlignment(Qt::AlignCenter);
            fields[i][j]->setStyleSheet("font: 18pt;");

            connect(fields[i][j], SIGNAL(textChanged(QString)),this,SLOT(fieldChanged(QString)));
        }
    }
    createLayout();
}

MainWindow::~MainWindow()
{
    //buttons are deleted when ui is deleted since it is parent, see Qt documentation
    delete ui;
}

void MainWindow::fieldChanged(QString text)
{
    //Will eventually parse the object name '1_1' (row 1, col 1) into a position array,
    //and pass the position and values to the Controller, for now just update label to display Value/Field.
    QLineEdit *field = (QLineEdit *)sender();
    emit onMakeMove(QString("Value: " + text + " Field: " + field->objectName()));
}

void MainWindow::createLayout()
{
    ui->gridLayout->setMargin(6);
    ui->gridLayout->setSpacing(6);

    for(int i = 1; i < 10; i++) {
        for(int j = 1; j < 10; j++) {
            ui->gridLayout->addWidget(fields[i][j], i, j);

        }
    }
}
<|endoftext|>