<commit_before>#pragma once

#include "manipulator/details/base.hpp"
#include "manipulator/details/types.hpp"
#include <json/json.hpp>
#include <unordered_set>
#include <vector>

namespace krbn {
namespace manipulator {
namespace details {
class basic final : public base {
public:
  class manipulated_original_event final {
  public:
    manipulated_original_event(device_id device_id,
                               const event_queue::queued_event::event& original_event,
                               const std::unordered_set<modifier_flag> from_modifiers) : device_id_(device_id),
                                                                                original_event_(original_event),
                                                                                from_modifiers_(from_modifiers) {
    }

    device_id get_device_id(void) const {
      return device_id_;
    }

    const event_queue::queued_event::event& get_original_event(void) const {
      return original_event_;
    }

    const std::unordered_set<modifier_flag>& get_from_modifiers(void) const {
      return from_modifiers_;
    }

    bool operator==(const manipulated_original_event& other) const {
      // Do not compare `from_modifiers_`.
      return get_device_id() == other.get_device_id() &&
             get_original_event() == other.get_original_event();
    }

  private:
    device_id device_id_;
    event_queue::queued_event::event original_event_;
    std::unordered_set<modifier_flag> from_modifiers_;
  };

  basic(const nlohmann::json& json) : base(),
                                      from_(json.find("from") != std::end(json) ? json["from"] : nlohmann::json()) {
    {
      const std::string key = "to";
      if (json.find(key) != std::end(json) && json[key].is_array()) {
        for (const auto& j : json[key]) {
          to_.emplace_back(j);
        }
      }
    }
  }

  basic(const from_event_definition& from,
        const to_event_definition& to) : from_(from),
                                         to_({to}) {
  }

  virtual ~basic(void) {
  }

  virtual void manipulate(event_queue::queued_event& front_input_event,
                          const event_queue& input_event_queue,
                          event_queue& output_event_queue,
                          uint64_t time_stamp) {
    if (!front_input_event.get_valid()) {
      return;
    }

    bool is_target = false;

    if (auto key_code = front_input_event.get_event().get_key_code()) {
      if (from_.get_key_code() == key_code) {
        is_target = true;
      }
    }
    if (auto pointing_button = front_input_event.get_event().get_pointing_button()) {
      if (from_.get_pointing_button() == pointing_button) {
        is_target = true;
      }
    }

    if (is_target) {
      std::unordered_set<modifier_flag> from_modifiers;

      if (front_input_event.get_event_type() == event_type::key_down) {

        if (!valid_) {
          is_target = false;
        }

        if (auto modifiers = from_.test_modifiers(output_event_queue.get_modifier_flag_manager())) {
          from_modifiers = *modifiers;
        } else {
          is_target = false;
        }

        if (is_target) {
          manipulated_original_events_.emplace_back(front_input_event.get_device_id(),
                                                    front_input_event.get_original_event(),
                                                    from_modifiers);
        }

      } else {
        // event_type::key_up

        // Check original_event in order to determine the correspond key_down is manipulated.

        auto it = std::find_if(std::begin(manipulated_original_events_),
                               std::end(manipulated_original_events_),
                               [&](const auto& manipulated_original_event) {
                                 return manipulated_original_event.get_device_id() == front_input_event.get_device_id() &&
                                        manipulated_original_event.get_original_event() == front_input_event.get_original_event();
                               });
        if (it != std::end(manipulated_original_events_)) {
          from_modifiers = it->get_from_modifiers();
          manipulated_original_events_.erase(it);
        } else {
          is_target = false;
        }
      }

      if (is_target) {
        front_input_event.set_valid(false);

        uint64_t time_stamp_delay = 0;
        bool persist_from_modifier_manipulation = false;

        // Release from_modifiers

        if (front_input_event.get_event_type() == event_type::key_down) {
          for (const auto& m : from_modifiers) {
            if (auto key_code = types::get_key_code(m)) {
              event_queue::queued_event event(front_input_event.get_device_id(),
                                              front_input_event.get_time_stamp() + time_stamp_delay++,
                                              event_queue::queued_event::event(*key_code),
                                              event_type::key_up,
                                              front_input_event.get_original_event(),
                                              true);
              output_event_queue.push_back_event(event);
            }
          }
        }

        // Send events

        for (size_t i = 0; i < to_.size(); ++i) {
          if (auto event = to_[i].to_event()) {
            if (front_input_event.get_event_type() == event_type::key_down) {
              enqueue_to_modifiers(to_[i],
                                   event_type::key_down,
                                   front_input_event,
                                   time_stamp_delay,
                                   output_event_queue);

              output_event_queue.emplace_back_event(front_input_event.get_device_id(),
                                                    front_input_event.get_time_stamp() + time_stamp_delay++,
                                                    *event,
                                                    event_type::key_down,
                                                    front_input_event.get_original_event());

              if (i != to_.size() - 1) {
                output_event_queue.emplace_back_event(front_input_event.get_device_id(),
                                                      front_input_event.get_time_stamp() + time_stamp_delay++,
                                                      *event,
                                                      event_type::key_up,
                                                      front_input_event.get_original_event());

                if (auto key_code = event->get_key_code()) {
                  if (types::get_modifier_flag(*key_code) != modifier_flag::zero) {
                    persist_from_modifier_manipulation = true;
                  }
                }
              }

              enqueue_to_modifiers(to_[i],
                                   event_type::key_up,
                                   front_input_event,
                                   time_stamp_delay,
                                   output_event_queue);

            } else {
              // event_type::key_up

              if (i == to_.size() - 1) {
                output_event_queue.emplace_back_event(front_input_event.get_device_id(),
                                                      front_input_event.get_time_stamp() + time_stamp_delay++,
                                                      *event,
                                                      event_type::key_up,
                                                      front_input_event.get_original_event());
              }
            }
          }
        }

        // Restore from_modifiers

        if ((front_input_event.get_event_type() == event_type::key_down) ||
            (front_input_event.get_event_type() == event_type::key_up && persist_from_modifier_manipulation)) {
          for (const auto& m : from_modifiers) {
            if (auto key_code = types::get_key_code(m)) {
              event_queue::queued_event event(front_input_event.get_device_id(),
                                              front_input_event.get_time_stamp() + time_stamp_delay++,
                                              event_queue::queued_event::event(*key_code),
                                              event_type::key_down,
                                              front_input_event.get_original_event(),
                                              !persist_from_modifier_manipulation);
              output_event_queue.push_back_event(event);
            }
          }
        }

        output_event_queue.increase_time_stamp_delay(time_stamp_delay - 1);
      }
    }
  }

  virtual bool active(void) const {
    return !manipulated_original_events_.empty();
  }

  virtual void handle_device_ungrabbed_event(device_id device_id,
                                             const event_queue& output_event_queue,
                                             uint64_t time_stamp) {
    manipulated_original_events_.erase(std::remove_if(std::begin(manipulated_original_events_),
                                                      std::end(manipulated_original_events_),
                                                      [&](const auto& e) {
                                                        return e.get_device_id() == device_id;
                                                      }),
                                       std::end(manipulated_original_events_));
  }

  const from_event_definition& get_from(void) const {
    return from_;
  }

  const std::vector<to_event_definition>& get_to(void) const {
    return to_;
  }

  void enqueue_to_modifiers(const to_event_definition& to,
                            event_type event_type,
                            const event_queue::queued_event& front_input_event,
                            uint64_t& time_stamp_delay,
                            event_queue& output_event_queue) {
    for (const auto& modifier : to.get_modifiers()) {
      // `event_definition::get_modifiers` might return two modifier_flags.
      // (eg. `modifier_flag::left_shift` and `modifier_flag::right_shift` for `modifier::shift`.)
      // We use the first modifier_flag.

      auto modifier_flags = event_definition::get_modifier_flags(modifier);
      if (!modifier_flags.empty()) {
        auto modifier_flag = modifier_flags.front();
        if (auto key_code = types::get_key_code(modifier_flag)) {
          output_event_queue.emplace_back_event(front_input_event.get_device_id(),
                                                front_input_event.get_time_stamp() + time_stamp_delay++,
                                                event_queue::queued_event::event(*key_code),
                                                event_type,
                                                front_input_event.get_original_event(),
                                                true);
        }
      }
    }
  }

private:
  from_event_definition from_;
  std::vector<to_event_definition> to_;

  std::vector<manipulated_original_event> manipulated_original_events_;
};
} // namespace details
} // namespace manipulator
} // namespace krbn
<commit_msg>call increase_time_stamp_delay only when time_stamp_delay > 0<commit_after>#pragma once

#include "manipulator/details/base.hpp"
#include "manipulator/details/types.hpp"
#include <json/json.hpp>
#include <unordered_set>
#include <vector>

namespace krbn {
namespace manipulator {
namespace details {
class basic final : public base {
public:
  class manipulated_original_event final {
  public:
    manipulated_original_event(device_id device_id,
                               const event_queue::queued_event::event& original_event,
                               const std::unordered_set<modifier_flag> from_modifiers) : device_id_(device_id),
                                                                                original_event_(original_event),
                                                                                from_modifiers_(from_modifiers) {
    }

    device_id get_device_id(void) const {
      return device_id_;
    }

    const event_queue::queued_event::event& get_original_event(void) const {
      return original_event_;
    }

    const std::unordered_set<modifier_flag>& get_from_modifiers(void) const {
      return from_modifiers_;
    }

    bool operator==(const manipulated_original_event& other) const {
      // Do not compare `from_modifiers_`.
      return get_device_id() == other.get_device_id() &&
             get_original_event() == other.get_original_event();
    }

  private:
    device_id device_id_;
    event_queue::queued_event::event original_event_;
    std::unordered_set<modifier_flag> from_modifiers_;
  };

  basic(const nlohmann::json& json) : base(),
                                      from_(json.find("from") != std::end(json) ? json["from"] : nlohmann::json()) {
    {
      const std::string key = "to";
      if (json.find(key) != std::end(json) && json[key].is_array()) {
        for (const auto& j : json[key]) {
          to_.emplace_back(j);
        }
      }
    }
  }

  basic(const from_event_definition& from,
        const to_event_definition& to) : from_(from),
                                         to_({to}) {
  }

  virtual ~basic(void) {
  }

  virtual void manipulate(event_queue::queued_event& front_input_event,
                          const event_queue& input_event_queue,
                          event_queue& output_event_queue,
                          uint64_t time_stamp) {
    if (!front_input_event.get_valid()) {
      return;
    }

    bool is_target = false;

    if (auto key_code = front_input_event.get_event().get_key_code()) {
      if (from_.get_key_code() == key_code) {
        is_target = true;
      }
    }
    if (auto pointing_button = front_input_event.get_event().get_pointing_button()) {
      if (from_.get_pointing_button() == pointing_button) {
        is_target = true;
      }
    }

    if (is_target) {
      std::unordered_set<modifier_flag> from_modifiers;

      if (front_input_event.get_event_type() == event_type::key_down) {

        if (!valid_) {
          is_target = false;
        }

        if (auto modifiers = from_.test_modifiers(output_event_queue.get_modifier_flag_manager())) {
          from_modifiers = *modifiers;
        } else {
          is_target = false;
        }

        if (is_target) {
          manipulated_original_events_.emplace_back(front_input_event.get_device_id(),
                                                    front_input_event.get_original_event(),
                                                    from_modifiers);
        }

      } else {
        // event_type::key_up

        // Check original_event in order to determine the correspond key_down is manipulated.

        auto it = std::find_if(std::begin(manipulated_original_events_),
                               std::end(manipulated_original_events_),
                               [&](const auto& manipulated_original_event) {
                                 return manipulated_original_event.get_device_id() == front_input_event.get_device_id() &&
                                        manipulated_original_event.get_original_event() == front_input_event.get_original_event();
                               });
        if (it != std::end(manipulated_original_events_)) {
          from_modifiers = it->get_from_modifiers();
          manipulated_original_events_.erase(it);
        } else {
          is_target = false;
        }
      }

      if (is_target) {
        front_input_event.set_valid(false);

        uint64_t time_stamp_delay = 0;
        bool persist_from_modifier_manipulation = false;

        // Release from_modifiers

        if (front_input_event.get_event_type() == event_type::key_down) {
          for (const auto& m : from_modifiers) {
            if (auto key_code = types::get_key_code(m)) {
              event_queue::queued_event event(front_input_event.get_device_id(),
                                              front_input_event.get_time_stamp() + time_stamp_delay++,
                                              event_queue::queued_event::event(*key_code),
                                              event_type::key_up,
                                              front_input_event.get_original_event(),
                                              true);
              output_event_queue.push_back_event(event);
            }
          }
        }

        // Send events

        for (size_t i = 0; i < to_.size(); ++i) {
          if (auto event = to_[i].to_event()) {
            if (front_input_event.get_event_type() == event_type::key_down) {
              enqueue_to_modifiers(to_[i],
                                   event_type::key_down,
                                   front_input_event,
                                   time_stamp_delay,
                                   output_event_queue);

              output_event_queue.emplace_back_event(front_input_event.get_device_id(),
                                                    front_input_event.get_time_stamp() + time_stamp_delay++,
                                                    *event,
                                                    event_type::key_down,
                                                    front_input_event.get_original_event());

              if (i != to_.size() - 1) {
                output_event_queue.emplace_back_event(front_input_event.get_device_id(),
                                                      front_input_event.get_time_stamp() + time_stamp_delay++,
                                                      *event,
                                                      event_type::key_up,
                                                      front_input_event.get_original_event());

                if (auto key_code = event->get_key_code()) {
                  if (types::get_modifier_flag(*key_code) != modifier_flag::zero) {
                    persist_from_modifier_manipulation = true;
                  }
                }
              }

              enqueue_to_modifiers(to_[i],
                                   event_type::key_up,
                                   front_input_event,
                                   time_stamp_delay,
                                   output_event_queue);

            } else {
              // event_type::key_up

              if (i == to_.size() - 1) {
                output_event_queue.emplace_back_event(front_input_event.get_device_id(),
                                                      front_input_event.get_time_stamp() + time_stamp_delay++,
                                                      *event,
                                                      event_type::key_up,
                                                      front_input_event.get_original_event());
              }
            }
          }
        }

        // Restore from_modifiers

        if ((front_input_event.get_event_type() == event_type::key_down) ||
            (front_input_event.get_event_type() == event_type::key_up && persist_from_modifier_manipulation)) {
          for (const auto& m : from_modifiers) {
            if (auto key_code = types::get_key_code(m)) {
              event_queue::queued_event event(front_input_event.get_device_id(),
                                              front_input_event.get_time_stamp() + time_stamp_delay++,
                                              event_queue::queued_event::event(*key_code),
                                              event_type::key_down,
                                              front_input_event.get_original_event(),
                                              !persist_from_modifier_manipulation);
              output_event_queue.push_back_event(event);
            }
          }
        }

        if (time_stamp_delay > 0) {
          output_event_queue.increase_time_stamp_delay(time_stamp_delay - 1);
        }
      }
    }
  }

  virtual bool active(void) const {
    return !manipulated_original_events_.empty();
  }

  virtual void handle_device_ungrabbed_event(device_id device_id,
                                             const event_queue& output_event_queue,
                                             uint64_t time_stamp) {
    manipulated_original_events_.erase(std::remove_if(std::begin(manipulated_original_events_),
                                                      std::end(manipulated_original_events_),
                                                      [&](const auto& e) {
                                                        return e.get_device_id() == device_id;
                                                      }),
                                       std::end(manipulated_original_events_));
  }

  const from_event_definition& get_from(void) const {
    return from_;
  }

  const std::vector<to_event_definition>& get_to(void) const {
    return to_;
  }

  void enqueue_to_modifiers(const to_event_definition& to,
                            event_type event_type,
                            const event_queue::queued_event& front_input_event,
                            uint64_t& time_stamp_delay,
                            event_queue& output_event_queue) {
    for (const auto& modifier : to.get_modifiers()) {
      // `event_definition::get_modifiers` might return two modifier_flags.
      // (eg. `modifier_flag::left_shift` and `modifier_flag::right_shift` for `modifier::shift`.)
      // We use the first modifier_flag.

      auto modifier_flags = event_definition::get_modifier_flags(modifier);
      if (!modifier_flags.empty()) {
        auto modifier_flag = modifier_flags.front();
        if (auto key_code = types::get_key_code(modifier_flag)) {
          output_event_queue.emplace_back_event(front_input_event.get_device_id(),
                                                front_input_event.get_time_stamp() + time_stamp_delay++,
                                                event_queue::queued_event::event(*key_code),
                                                event_type,
                                                front_input_event.get_original_event(),
                                                true);
        }
      }
    }
  }

private:
  from_event_definition from_;
  std::vector<to_event_definition> to_;

  std::vector<manipulated_original_event> manipulated_original_events_;
};
} // namespace details
} // namespace manipulator
} // namespace krbn
<|endoftext|>


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

#include "modules/canbus/vehicle/lincoln/protocol/brakeinfo_74.h"

#include "gtest/gtest.h"

namespace apollo {
namespace canbus {
namespace lincoln {

class Brakeinfo74Test : public ::testing::Test {
 public:
  virtual void SetUp() {}
};

TEST_F(Brakeinfo74Test, simple) {
  Brakeinfo74 brakeinfo;
  uint8_t data[8] = {0x64U};
  int32_t length = 8;
  ChassisDetail cd;
  brakeinfo.Parse(data, length, &cd);

  EXPECT_FALSE(cd.esp().is_abs_active());
  EXPECT_FALSE(cd.esp().is_abs_enabled());
  EXPECT_FALSE(cd.esp().is_stab_active());
  EXPECT_FALSE(cd.esp().is_stab_enabled());
  EXPECT_FALSE(cd.esp().is_trac_active());
  EXPECT_FALSE(cd.esp().is_trac_enabled());

  EXPECT_EQ(cd.epb().parking_brake_status(), Epb::PBRAKE_OFF);
  EXPECT_DOUBLE_EQ(cd.brake().brake_torque_req(), 400.0);
  EXPECT_EQ(cd.brake().hsa_status(), Brake::HSA_INACTIVE);
  EXPECT_DOUBLE_EQ(cd.brake().brake_torque_act(), 0.0);
  EXPECT_EQ(cd.brake().hsa_status(), Brake::HSA_OFF);
  EXPECT_DOUBLE_EQ(cd.brake().wheel_torque_act(), 0.0);
  EXPECT_FALSE(cd.vehicle_spd().is_vehicle_standstill());
  EXPECT_DOUBLE_EQ(cd.vehicle_spd().acc_est(), 0.0);
}

}  // namespace lincoln
}  // namespace apollo
}  // namespace canbus
<commit_msg>Use full length test data in brakeinfo_74_test<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "modules/canbus/vehicle/lincoln/protocol/brakeinfo_74.h"

#include "gtest/gtest.h"

namespace apollo {
namespace canbus {
namespace lincoln {

class Brakeinfo74Test : public ::testing::Test {
 public:
  virtual void SetUp() {}
};

TEST_F(Brakeinfo74Test, simple) {
  Brakeinfo74 brakeinfo;
  uint8_t data[8] = {0x64U, 0x02, 0x03, 0x04, 0x11, 0x12, 0x13, 0x14};
  int32_t length = 8;
  ChassisDetail cd;
  brakeinfo.Parse(data, length, &cd);

  EXPECT_TRUE(cd.esp().is_abs_active());
  EXPECT_FALSE(cd.esp().is_abs_enabled());
  EXPECT_TRUE(cd.esp().is_stab_active());
  EXPECT_FALSE(cd.esp().is_stab_enabled());
  EXPECT_FALSE(cd.esp().is_trac_active());
  EXPECT_FALSE(cd.esp().is_trac_enabled());

  EXPECT_EQ(cd.epb().parking_brake_status(), Epb::PBRAKE_OFF);
  EXPECT_DOUBLE_EQ(cd.brake().brake_torque_req(), 2448.0);
  EXPECT_EQ(cd.brake().hsa_status(), Brake::HSA_INACTIVE);
  EXPECT_DOUBLE_EQ(cd.brake().brake_torque_act(), 4108.0);
  EXPECT_EQ(cd.brake().hsa_status(), Brake::HSA_OFF);
  EXPECT_DOUBLE_EQ(cd.brake().wheel_torque_act(), 18500.0);
  EXPECT_FALSE(cd.vehicle_spd().is_vehicle_standstill());
  EXPECT_DOUBLE_EQ(cd.vehicle_spd().acc_est(), 0.665);
}

}  // namespace lincoln
}  // namespace apollo
}  // namespace canbus
<|endoftext|>


<commit_before><commit_msg>Bugfix: pass variables of correct type to `VariableStruct` constructor.<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/base/x509_util.h"
#include "net/base/x509_util_nss.h"

#include <cert.h>
#include <secoid.h>

#include "base/memory/scoped_ptr.h"
#include "base/memory/ref_counted.h"
#include "crypto/ec_private_key.h"
#include "crypto/rsa_private_key.h"
#include "crypto/scoped_nss_types.h"
#include "crypto/signature_verifier.h"
#include "net/base/x509_certificate.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace net {

namespace {

CERTCertificate* CreateNSSCertHandleFromBytes(const char* data, size_t length) {
  SECItem der_cert;
  der_cert.data = reinterpret_cast<unsigned char*>(const_cast<char*>(data));
  der_cert.len  = length;
  der_cert.type = siDERCertBuffer;

  // Parse into a certificate structure.
  return CERT_NewTempCertificate(CERT_GetDefaultCertDB(), &der_cert, NULL,
                                 PR_FALSE, PR_TRUE);
}

void VerifyCertificateSignature(const std::string& der_cert,
                                const std::vector<uint8>& der_spki) {
  crypto::ScopedPLArenaPool arena;

  CERTSignedData sd;
  memset(&sd, 0, sizeof(sd));

  SECItem der_cert_item = {
    siDERCertBuffer,
    reinterpret_cast<unsigned char*>(const_cast<char*>(der_cert.data())),
    der_cert.size()
  };
  SECStatus rv = SEC_ASN1DecodeItem(arena.get(), &sd,
                                    SEC_ASN1_GET(CERT_SignedDataTemplate),
                                    &der_cert_item);
  ASSERT_EQ(SECSuccess, rv);

  // The CERTSignedData.signatureAlgorithm is decoded, but SignatureVerifier
  // wants the DER encoded form, so re-encode it again.
  SECItem* signature_algorithm = SEC_ASN1EncodeItem(
      arena.get(),
      NULL,
      &sd.signatureAlgorithm,
      SEC_ASN1_GET(SECOID_AlgorithmIDTemplate));
  ASSERT_TRUE(signature_algorithm);

  crypto::SignatureVerifier verifier;
  bool ok = verifier.VerifyInit(
      signature_algorithm->data,
      signature_algorithm->len,
      sd.signature.data,
      sd.signature.len / 8,  // Signature is a BIT STRING, convert to bytes.
      &der_spki[0],
      der_spki.size());

  ASSERT_TRUE(ok);
  verifier.VerifyUpdate(sd.data.data,
                        sd.data.len);

  ok = verifier.VerifyFinal();
  EXPECT_TRUE(ok);
}

void VerifyOriginBoundCert(const std::string& origin,
                           const std::string& der_cert) {
  // Origin Bound Cert OID.
  static const char oid_string[] = "1.3.6.1.4.1.11129.2.1.6";

  // Create object neccessary for extension lookup call.
  SECItem extension_object = {
    siAsciiString,
    (unsigned char*)origin.data(),
    origin.size()
  };

  scoped_refptr<X509Certificate> cert = X509Certificate::CreateFromBytes(
      der_cert.data(), der_cert.size());

  ASSERT_TRUE(cert);

  EXPECT_EQ("anonymous.invalid", cert->subject().GetDisplayName());
  EXPECT_FALSE(cert->HasExpired());

  // IA5Encode and arena allocate SECItem.
  PLArenaPool* arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
  SECItem* expected = SEC_ASN1EncodeItem(arena,
                                         NULL,
                                         &extension_object,
                                         SEC_ASN1_GET(SEC_IA5StringTemplate));

  ASSERT_NE(static_cast<SECItem*>(NULL), expected);

  // Create OID SECItem.
  SECItem ob_cert_oid = { siDEROID, NULL, 0 };
  SECStatus ok = SEC_StringToOID(arena, &ob_cert_oid,
                                 oid_string, 0);

  ASSERT_EQ(SECSuccess, ok);

  SECOidTag ob_cert_oid_tag = SECOID_FindOIDTag(&ob_cert_oid);

  ASSERT_NE(SEC_OID_UNKNOWN, ob_cert_oid_tag);

  // This test is run on Mac and Win where X509Certificate::os_cert_handle isn't
  // an NSS type, so we have to manually create a NSS certificate object so we
  // can use CERT_FindCertExtension.
  CERTCertificate* nss_cert = CreateNSSCertHandleFromBytes(
      der_cert.data(), der_cert.size());
  // Lookup Origin Bound Cert extension in generated cert.
  SECItem actual = { siBuffer, NULL, 0 };
  ok = CERT_FindCertExtension(nss_cert,
                              ob_cert_oid_tag,
                              &actual);
  CERT_DestroyCertificate(nss_cert);
  ASSERT_EQ(SECSuccess, ok);

  // Compare expected and actual extension values.
  PRBool result = SECITEM_ItemsAreEqual(expected, &actual);
  ASSERT_TRUE(result);

  // Do Cleanup.
  SECITEM_FreeItem(&actual, PR_FALSE);
  PORT_FreeArena(arena, PR_FALSE);
}

}  // namespace

// This test creates an origin-bound cert from a RSA private key and
// then verifies the content of the certificate.
TEST(X509UtilNSSTest, CreateOriginBoundCertRSA) {
  // Create a sample ASCII weborigin.
  std::string origin = "http://weborigin.com:443";

  scoped_ptr<crypto::RSAPrivateKey> private_key(
      crypto::RSAPrivateKey::Create(1024));
  std::string der_cert;
  ASSERT_TRUE(x509_util::CreateOriginBoundCertRSA(private_key.get(),
                                                  origin, 1,
                                                  base::TimeDelta::FromDays(1),
                                                  &der_cert));

  VerifyOriginBoundCert(origin, der_cert);

  std::vector<uint8> spki;
  ASSERT_TRUE(private_key->ExportPublicKey(&spki));
  VerifyCertificateSignature(der_cert, spki);
}

// This test creates an origin-bound cert from an EC private key and
// then verifies the content of the certificate.
TEST(X509UtilNSSTest, CreateOriginBoundCertEC) {
  // Create a sample ASCII weborigin.
  std::string origin = "http://weborigin.com:443";

  scoped_ptr<crypto::ECPrivateKey> private_key(
      crypto::ECPrivateKey::Create());
  std::string der_cert;
  ASSERT_TRUE(x509_util::CreateOriginBoundCertEC(private_key.get(),
                                                 origin, 1,
                                                 base::TimeDelta::FromDays(1),
                                                 &der_cert));

  VerifyOriginBoundCert(origin, der_cert);

#if !defined(OS_WIN) && !defined(OS_MACOSX)
  // signature_verifier_win and signature_verifier_mac can't handle EC certs.
  std::vector<uint8> spki;
  ASSERT_TRUE(private_key->ExportPublicKey(&spki));
  VerifyCertificateSignature(der_cert, spki);
#endif
}

}  // namespace net
<commit_msg>Fix leak in X509UtilNSSTest VerifyCertificateSignature.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/base/x509_util.h"
#include "net/base/x509_util_nss.h"

#include <cert.h>
#include <secoid.h>

#include "base/memory/scoped_ptr.h"
#include "base/memory/ref_counted.h"
#include "crypto/ec_private_key.h"
#include "crypto/rsa_private_key.h"
#include "crypto/scoped_nss_types.h"
#include "crypto/signature_verifier.h"
#include "net/base/x509_certificate.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace net {

namespace {

CERTCertificate* CreateNSSCertHandleFromBytes(const char* data, size_t length) {
  SECItem der_cert;
  der_cert.data = reinterpret_cast<unsigned char*>(const_cast<char*>(data));
  der_cert.len  = length;
  der_cert.type = siDERCertBuffer;

  // Parse into a certificate structure.
  return CERT_NewTempCertificate(CERT_GetDefaultCertDB(), &der_cert, NULL,
                                 PR_FALSE, PR_TRUE);
}

void VerifyCertificateSignature(const std::string& der_cert,
                                const std::vector<uint8>& der_spki) {
  crypto::ScopedPLArenaPool arena(PORT_NewArena(DER_DEFAULT_CHUNKSIZE));

  CERTSignedData sd;
  memset(&sd, 0, sizeof(sd));

  SECItem der_cert_item = {
    siDERCertBuffer,
    reinterpret_cast<unsigned char*>(const_cast<char*>(der_cert.data())),
    der_cert.size()
  };
  SECStatus rv = SEC_ASN1DecodeItem(arena.get(), &sd,
                                    SEC_ASN1_GET(CERT_SignedDataTemplate),
                                    &der_cert_item);
  ASSERT_EQ(SECSuccess, rv);

  // The CERTSignedData.signatureAlgorithm is decoded, but SignatureVerifier
  // wants the DER encoded form, so re-encode it again.
  SECItem* signature_algorithm = SEC_ASN1EncodeItem(
      arena.get(),
      NULL,
      &sd.signatureAlgorithm,
      SEC_ASN1_GET(SECOID_AlgorithmIDTemplate));
  ASSERT_TRUE(signature_algorithm);

  crypto::SignatureVerifier verifier;
  bool ok = verifier.VerifyInit(
      signature_algorithm->data,
      signature_algorithm->len,
      sd.signature.data,
      sd.signature.len / 8,  // Signature is a BIT STRING, convert to bytes.
      &der_spki[0],
      der_spki.size());

  ASSERT_TRUE(ok);
  verifier.VerifyUpdate(sd.data.data,
                        sd.data.len);

  ok = verifier.VerifyFinal();
  EXPECT_TRUE(ok);
}

void VerifyOriginBoundCert(const std::string& origin,
                           const std::string& der_cert) {
  // Origin Bound Cert OID.
  static const char oid_string[] = "1.3.6.1.4.1.11129.2.1.6";

  // Create object neccessary for extension lookup call.
  SECItem extension_object = {
    siAsciiString,
    (unsigned char*)origin.data(),
    origin.size()
  };

  scoped_refptr<X509Certificate> cert = X509Certificate::CreateFromBytes(
      der_cert.data(), der_cert.size());

  ASSERT_TRUE(cert);

  EXPECT_EQ("anonymous.invalid", cert->subject().GetDisplayName());
  EXPECT_FALSE(cert->HasExpired());

  // IA5Encode and arena allocate SECItem.
  PLArenaPool* arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
  SECItem* expected = SEC_ASN1EncodeItem(arena,
                                         NULL,
                                         &extension_object,
                                         SEC_ASN1_GET(SEC_IA5StringTemplate));

  ASSERT_NE(static_cast<SECItem*>(NULL), expected);

  // Create OID SECItem.
  SECItem ob_cert_oid = { siDEROID, NULL, 0 };
  SECStatus ok = SEC_StringToOID(arena, &ob_cert_oid,
                                 oid_string, 0);

  ASSERT_EQ(SECSuccess, ok);

  SECOidTag ob_cert_oid_tag = SECOID_FindOIDTag(&ob_cert_oid);

  ASSERT_NE(SEC_OID_UNKNOWN, ob_cert_oid_tag);

  // This test is run on Mac and Win where X509Certificate::os_cert_handle isn't
  // an NSS type, so we have to manually create a NSS certificate object so we
  // can use CERT_FindCertExtension.
  CERTCertificate* nss_cert = CreateNSSCertHandleFromBytes(
      der_cert.data(), der_cert.size());
  // Lookup Origin Bound Cert extension in generated cert.
  SECItem actual = { siBuffer, NULL, 0 };
  ok = CERT_FindCertExtension(nss_cert,
                              ob_cert_oid_tag,
                              &actual);
  CERT_DestroyCertificate(nss_cert);
  ASSERT_EQ(SECSuccess, ok);

  // Compare expected and actual extension values.
  PRBool result = SECITEM_ItemsAreEqual(expected, &actual);
  ASSERT_TRUE(result);

  // Do Cleanup.
  SECITEM_FreeItem(&actual, PR_FALSE);
  PORT_FreeArena(arena, PR_FALSE);
}

}  // namespace

// This test creates an origin-bound cert from a RSA private key and
// then verifies the content of the certificate.
TEST(X509UtilNSSTest, CreateOriginBoundCertRSA) {
  // Create a sample ASCII weborigin.
  std::string origin = "http://weborigin.com:443";

  scoped_ptr<crypto::RSAPrivateKey> private_key(
      crypto::RSAPrivateKey::Create(1024));
  std::string der_cert;
  ASSERT_TRUE(x509_util::CreateOriginBoundCertRSA(private_key.get(),
                                                  origin, 1,
                                                  base::TimeDelta::FromDays(1),
                                                  &der_cert));

  VerifyOriginBoundCert(origin, der_cert);

  std::vector<uint8> spki;
  ASSERT_TRUE(private_key->ExportPublicKey(&spki));
  VerifyCertificateSignature(der_cert, spki);
}

// This test creates an origin-bound cert from an EC private key and
// then verifies the content of the certificate.
TEST(X509UtilNSSTest, CreateOriginBoundCertEC) {
  // Create a sample ASCII weborigin.
  std::string origin = "http://weborigin.com:443";

  scoped_ptr<crypto::ECPrivateKey> private_key(
      crypto::ECPrivateKey::Create());
  std::string der_cert;
  ASSERT_TRUE(x509_util::CreateOriginBoundCertEC(private_key.get(),
                                                 origin, 1,
                                                 base::TimeDelta::FromDays(1),
                                                 &der_cert));

  VerifyOriginBoundCert(origin, der_cert);

#if !defined(OS_WIN) && !defined(OS_MACOSX)
  // signature_verifier_win and signature_verifier_mac can't handle EC certs.
  std::vector<uint8> spki;
  ASSERT_TRUE(private_key->ExportPublicKey(&spki));
  VerifyCertificateSignature(der_cert, spki);
#endif
}

}  // namespace net
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: bootstrap.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: kr $ $Date: 2001-10-05 08:00:21 $
 *
 *  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 <list>
#include <stdio.h>

#include <osl/process.h>
#include <osl/file.h>
#include <osl/diagnose.h>
#include <osl/mutex.hxx>
#include <osl/file.hxx>

#include <rtl/bootstrap.h>
#include <rtl/ustring.hxx>
#include <rtl/ustrbuf.hxx>
#include <rtl/byteseq.hxx>

#include "macro.hxx"

// I need C++ for static variables and for lists (stl) !
// If we don't want C++, we need another solution for static vars !
using namespace ::rtl;
using namespace ::osl;

struct rtl_bootstrap_NameValue
{
    ::rtl::OUString sName;
    ::rtl::OUString sValue;
};

typedef ::std::list< struct rtl_bootstrap_NameValue > NameValueList;

static sal_Bool getFromCommandLineArgs( rtl_uString **ppValue , rtl_uString *pName )
{
    static NameValueList *pNameValueList = 0;
    if( ! pNameValueList )
    {
        static NameValueList nameValueList;

        sal_Int32 nArgCount = osl_getCommandArgCount();
        for(sal_Int32 i = 0; i < nArgCount; ++ i)
        {
            rtl_uString *pArg = 0;
            osl_getCommandArg( i, &pArg );
            if( ('-' == pArg->buffer[0] || '/' == pArg->buffer[0] ) &&
                'e' == pArg->buffer[1] &&
                'n' == pArg->buffer[2] &&
                'v' == pArg->buffer[3] &&
                ':' == pArg->buffer[4] )
            {
                sal_Int32 nIndex = rtl_ustr_indexOfChar( pArg->buffer, '=' );
                if( nIndex >= 0 )
                {

                    struct rtl_bootstrap_NameValue nameValue;
                    nameValue.sName = OUString( &(pArg->buffer[5]), nIndex - 5  );
                    nameValue.sValue = OUString( &(pArg->buffer[nIndex+1]) );
                    if( i == nArgCount-1 &&
                        nameValue.sValue.getLength() &&
                        nameValue.sValue[nameValue.sValue.getLength()-1] == 13 )
                    {
                        // avoid the 13 linefeed for the last argument,
                        // when the executable is started from a script,
                        // that was edited on windows
                        nameValue.sValue = nameValue.sValue.copy(0,nameValue.sValue.getLength()-1);
                    }
                    nameValueList.push_back( nameValue );
                }
            }
            rtl_uString_release( pArg );
        }
        pNameValueList = &nameValueList;
    }

    sal_Bool found = sal_False;

    OUString name( pName );
    for( NameValueList::iterator ii = pNameValueList->begin() ;
         ii != pNameValueList->end() ;
         ++ii )
    {
        if( (*ii).sName.equals(name) )
        {
            rtl_uString_assign( ppValue, (*ii).sValue.pData );
            found = sal_True;
            break;
        }
    }

    return found;
}

static ::rtl::OUString &getIniFileNameImpl()
{
    static OUString *pStaticName = 0;
    if( ! pStaticName )
    {
        OUString fileName;

        OUString sVarName(RTL_CONSTASCII_USTRINGPARAM("INIFILENAME"));
        if(!getFromCommandLineArgs(&fileName.pData, sVarName.pData))
        {
            osl_getExecutableFile(&fileName.pData);

            // get rid of a potential executable extension
            OUString progExt = OUString::createFromAscii(".bin");
            if(fileName.getLength() > progExt.getLength()
            && fileName.copy(fileName.getLength() - progExt.getLength()).equalsIgnoreAsciiCase(progExt))
                fileName = fileName.copy(0, fileName.getLength() - progExt.getLength());

            progExt = OUString::createFromAscii(".exe");
            if(fileName.getLength() > progExt.getLength()
            && fileName.copy(fileName.getLength() - progExt.getLength()).equalsIgnoreAsciiCase(progExt))
                fileName = fileName.copy(0, fileName.getLength() - progExt.getLength());

            // append config file suffix
            fileName += OUString(RTL_CONSTASCII_USTRINGPARAM(SAL_CONFIGFILE("")));
        }

        static OUString theFileName;
        if(fileName.getLength())
            theFileName = fileName;

        pStaticName = &theFileName;
    }

    return *pStaticName;
}

static void getFileSize( oslFileHandle handle, sal_uInt64 *pSize )
{
    sal_uInt64 nOldPos=0;
    OSL_VERIFY( osl_File_E_None == osl_getFilePos( handle, &nOldPos ) &&
                osl_File_E_None == osl_setFilePos( handle, osl_Pos_End , 0 ) &&
                osl_File_E_None == osl_getFilePos( handle, pSize ) &&
                osl_File_E_None == osl_setFilePos( handle, osl_Pos_Absolut, nOldPos ) );
}

static void getFromEnvironment( rtl_uString **ppValue, rtl_uString *pName )
{
    if( osl_Process_E_None != osl_getEnvironment( pName , ppValue ) )
    {
        // osl behaves different on win or unx.
        if( *ppValue )
        {
            rtl_uString_release( *ppValue );
            *ppValue = 0;
        }
    }

}

static void getFromList(NameValueList *pNameValueList, rtl_uString **ppValue, rtl_uString *pName)
{
    OUString name(pName);

    for(NameValueList::iterator ii = pNameValueList->begin();
        ii != pNameValueList->end();
        ++ii)
    {
        if( (*ii).sName.equals(name) )
        {
            rtl_uString_assign( ppValue, (*ii).sValue.pData );
            break;
        }
    }
}

static sal_Bool getValue(NameValueList *pNameValueList, rtl_uString * pName, rtl_uString ** ppValue, rtl_uString * pDefault)
{
    static const OUString sysUserConfig(RTL_CONSTASCII_USTRINGPARAM("SYSUSERCONFIG"));
    static const OUString sysUserHome(RTL_CONSTASCII_USTRINGPARAM("SYSUSERHOME"));
    sal_Bool result = sal_True;

    // we have build ins:
    if(!rtl_ustr_compare_WithLength(pName->buffer, pName->length, sysUserConfig.pData->buffer, sysUserConfig.pData->length))
    {
        oslSecurity security = osl_getCurrentSecurity();
        osl_getConfigDir(security, ppValue);
        osl_freeSecurityHandle(security);
    }
    else if(!rtl_ustr_compare_WithLength(pName->buffer, pName->length, sysUserHome.pData->buffer, sysUserHome.pData->length))
    {
        oslSecurity security = osl_getCurrentSecurity();
        osl_getHomeDir(security, ppValue);
        osl_freeSecurityHandle(security);
    }
    else
    {
        getFromCommandLineArgs(ppValue, pName);
        if(!*ppValue)
        {
            getFromList(pNameValueList, ppValue, pName);
            if( ! *ppValue )
            {
                getFromEnvironment( ppValue, pName );
                if( ! *ppValue )
                {
                    result = sal_False;

                    if(pDefault)
                        rtl_uString_assign( ppValue , pDefault );
                }
            }
        }
    }

#ifdef DEBUG
    OString sName = OUStringToOString(OUString(pName), RTL_TEXTENCODING_ASCII_US);
    OString sValue;
    if(*ppValue)
        sValue = OUStringToOString(OUString(*ppValue), RTL_TEXTENCODING_ASCII_US);
    OSL_TRACE("bootstrap.cxx::getValue - name:%s value:%s\n", sName.getStr(), sValue.getStr());
#endif

    return result;
}

typedef struct Bootstrap_Impl {
    NameValueList _nameValueList;
    OUString      _iniName;
} Bootstrap_Impl;

static void fillFromIniFile(Bootstrap_Impl * pBootstrap_Impl)
{
    OUString iniName = pBootstrap_Impl->_iniName;

#ifdef DEBUG
    OString sFile = OUStringToOString(iniName, RTL_TEXTENCODING_ASCII_US);
    OSL_TRACE("bootstrap.cxx::fillFromIniFile - %s\n", sFile.getStr());
#endif

    oslFileHandle handle;
    if(iniName.getLength()
    && osl_File_E_None == osl_openFile(iniName.pData, &handle, osl_File_OpenFlag_Read))
    {
        ByteSequence seq;
        sal_uInt64 nSize = 0;

        getFileSize(handle, &nSize);
        while( sal_True )
        {
            sal_uInt64 nPos;
            if(osl_File_E_None != osl_getFilePos(handle, &nPos)
            || nPos >= nSize)
                break;

            if(osl_File_E_None != osl_readLine(handle , (sal_Sequence ** ) &seq))
                break;

            OString line((const sal_Char *)seq.getConstArray(), seq.getLength());
            sal_Int32 nIndex = line.indexOf('=');
            struct rtl_bootstrap_NameValue nameValue;
            if(nIndex >= 1 && nIndex +1 < line.getLength())
            {
                nameValue.sName = OStringToOUString(line.copy(0,nIndex).trim(),
                                                    RTL_TEXTENCODING_ASCII_US);
                nameValue.sValue = OStringToOUString(line.copy(nIndex+1).trim(),
                                                     RTL_TEXTENCODING_UTF8);

                OString name_tmp = OUStringToOString(nameValue.sName, RTL_TEXTENCODING_ASCII_US);
                OString value_tmp = OUStringToOString(nameValue.sValue, RTL_TEXTENCODING_UTF8);
                OSL_TRACE("bootstrap.cxx: pushing: name=%s value=%s\n", name_tmp.getStr(), value_tmp.getStr());

                pBootstrap_Impl->_nameValueList.push_back(nameValue);
            }
        }
        osl_closeFile(handle);
    }
#ifdef DEBUG
    else
    {
        OString file_tmp = OUStringToOString(iniName, RTL_TEXTENCODING_ASCII_US);
        OSL_TRACE("bootstrap.cxx: couldn't open file: %s", file_tmp.getStr());
    }
#endif
}

extern "C"
{

rtlBootstrapHandle SAL_CALL rtl_bootstrap_args_open(rtl_uString * pIniName)
{
    OUString workDir;
    OUString iniName = OUString(pIniName);

    osl_getProcessWorkingDir(&workDir.pData);
    FileBase::getAbsoluteFileURL(workDir, iniName, iniName);

    Bootstrap_Impl * pBootstrap_Impl = new Bootstrap_Impl;

    pBootstrap_Impl->_iniName = iniName;
    fillFromIniFile(pBootstrap_Impl);

    return pBootstrap_Impl;
}

void SAL_CALL rtl_bootstrap_args_close(rtlBootstrapHandle handle)
{
    delete (Bootstrap_Impl *)handle;
}

sal_Bool SAL_CALL rtl_bootstrap_get_from_handle(rtlBootstrapHandle handle, rtl_uString *pName, rtl_uString **ppValue, rtl_uString *pDefault)
{
    MutexGuard guard(Mutex::getGlobalMutex());

    sal_Bool found = sal_False;
    if(ppValue && pName)
    {
        if(handle) {
            if(*ppValue) {
                rtl_uString_release(*ppValue);
                *ppValue = 0;
            }

            found = getValue(&((Bootstrap_Impl *)handle)->_nameValueList, pName, ppValue, pDefault);

            if(*ppValue)
            {
                OUString result = expandMacros(&((Bootstrap_Impl *)handle)->_nameValueList, OUString(*ppValue));

                rtl_uString_assign(ppValue, result.pData );
            }

            if(!found) {
                // fall back to executable rc
                  if(((Bootstrap_Impl *)handle)->_iniName != getIniFileNameImpl())
                    found = rtl_bootstrap_get(pName, ppValue, pDefault);
            }

            if(!*ppValue)
                rtl_uString_new(ppValue);

        }
        else
            found = rtl_bootstrap_get(pName, ppValue, pDefault);
    }

    return found;
}

void SAL_CALL rtl_bootstrap_get_iniName_from_handle(rtlBootstrapHandle handle, rtl_uString ** ppIniName)
{
    if(ppIniName)
        if(handle)
            rtl_uString_assign(ppIniName, ((Bootstrap_Impl *)handle)->_iniName.pData);

        else {
            const OUString & iniName = getIniFileNameImpl();

            rtl_uString_assign(ppIniName, iniName.pData);
        }
}

void SAL_CALL rtl_bootstrap_setIniFileName( rtl_uString *pName )
{
    MutexGuard guard( Mutex::getGlobalMutex() );
    OUString & file = getIniFileNameImpl();
    file = pName;
}

sal_Bool SAL_CALL rtl_bootstrap_get( rtl_uString *pName, rtl_uString **ppValue , rtl_uString *pDefault )
{
    MutexGuard guard( Mutex::getGlobalMutex() );

    static Bootstrap_Impl * pBootstrap_Impl = 0;

    if(!pBootstrap_Impl)
    {
        static Bootstrap_Impl bootstrap_Impl;

        bootstrap_Impl._iniName = getIniFileNameImpl();
        fillFromIniFile(&bootstrap_Impl);

        pBootstrap_Impl = &bootstrap_Impl;
    }

    return rtl_bootstrap_get_from_handle(pBootstrap_Impl, pName, ppValue, pDefault);
}

}
<commit_msg>added SYSBINDIR as predefined macro (#88338#)<commit_after>/*************************************************************************
 *
 *  $RCSfile: bootstrap.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: kr $ $Date: 2001-10-11 12:56:45 $
 *
 *  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 <list>
#include <stdio.h>

#include <osl/process.h>
#include <osl/file.h>
#include <osl/diagnose.h>
#include <osl/mutex.hxx>
#include <osl/file.hxx>

#include <rtl/bootstrap.h>
#include <rtl/ustring.hxx>
#include <rtl/ustrbuf.hxx>
#include <rtl/byteseq.hxx>

#include "macro.hxx"

// I need C++ for static variables and for lists (stl) !
// If we don't want C++, we need another solution for static vars !
using namespace ::rtl;
using namespace ::osl;

struct rtl_bootstrap_NameValue
{
    ::rtl::OUString sName;
    ::rtl::OUString sValue;
};

typedef ::std::list< struct rtl_bootstrap_NameValue > NameValueList;

static sal_Bool getFromCommandLineArgs( rtl_uString **ppValue , rtl_uString *pName )
{
    static NameValueList *pNameValueList = 0;
    if( ! pNameValueList )
    {
        static NameValueList nameValueList;

        sal_Int32 nArgCount = osl_getCommandArgCount();
        for(sal_Int32 i = 0; i < nArgCount; ++ i)
        {
            rtl_uString *pArg = 0;
            osl_getCommandArg( i, &pArg );
            if( ('-' == pArg->buffer[0] || '/' == pArg->buffer[0] ) &&
                'e' == pArg->buffer[1] &&
                'n' == pArg->buffer[2] &&
                'v' == pArg->buffer[3] &&
                ':' == pArg->buffer[4] )
            {
                sal_Int32 nIndex = rtl_ustr_indexOfChar( pArg->buffer, '=' );
                if( nIndex >= 0 )
                {

                    struct rtl_bootstrap_NameValue nameValue;
                    nameValue.sName = OUString( &(pArg->buffer[5]), nIndex - 5  );
                    nameValue.sValue = OUString( &(pArg->buffer[nIndex+1]) );
                    if( i == nArgCount-1 &&
                        nameValue.sValue.getLength() &&
                        nameValue.sValue[nameValue.sValue.getLength()-1] == 13 )
                    {
                        // avoid the 13 linefeed for the last argument,
                        // when the executable is started from a script,
                        // that was edited on windows
                        nameValue.sValue = nameValue.sValue.copy(0,nameValue.sValue.getLength()-1);
                    }
                    nameValueList.push_back( nameValue );
                }
            }
            rtl_uString_release( pArg );
        }
        pNameValueList = &nameValueList;
    }

    sal_Bool found = sal_False;

    OUString name( pName );
    for( NameValueList::iterator ii = pNameValueList->begin() ;
         ii != pNameValueList->end() ;
         ++ii )
    {
        if( (*ii).sName.equals(name) )
        {
            rtl_uString_assign( ppValue, (*ii).sValue.pData );
            found = sal_True;
            break;
        }
    }

    return found;
}

static ::rtl::OUString &getIniFileNameImpl()
{
    static OUString *pStaticName = 0;
    if( ! pStaticName )
    {
        OUString fileName;

        OUString sVarName(RTL_CONSTASCII_USTRINGPARAM("INIFILENAME"));
        if(!getFromCommandLineArgs(&fileName.pData, sVarName.pData))
        {
            osl_getExecutableFile(&fileName.pData);

            // get rid of a potential executable extension
            OUString progExt = OUString::createFromAscii(".bin");
            if(fileName.getLength() > progExt.getLength()
            && fileName.copy(fileName.getLength() - progExt.getLength()).equalsIgnoreAsciiCase(progExt))
                fileName = fileName.copy(0, fileName.getLength() - progExt.getLength());

            progExt = OUString::createFromAscii(".exe");
            if(fileName.getLength() > progExt.getLength()
            && fileName.copy(fileName.getLength() - progExt.getLength()).equalsIgnoreAsciiCase(progExt))
                fileName = fileName.copy(0, fileName.getLength() - progExt.getLength());

            // append config file suffix
            fileName += OUString(RTL_CONSTASCII_USTRINGPARAM(SAL_CONFIGFILE("")));
        }

        static OUString theFileName;
        if(fileName.getLength())
            theFileName = fileName;

        pStaticName = &theFileName;
    }

    return *pStaticName;
}

static void getFileSize( oslFileHandle handle, sal_uInt64 *pSize )
{
    sal_uInt64 nOldPos=0;
    OSL_VERIFY( osl_File_E_None == osl_getFilePos( handle, &nOldPos ) &&
                osl_File_E_None == osl_setFilePos( handle, osl_Pos_End , 0 ) &&
                osl_File_E_None == osl_getFilePos( handle, pSize ) &&
                osl_File_E_None == osl_setFilePos( handle, osl_Pos_Absolut, nOldPos ) );
}

static void getFromEnvironment( rtl_uString **ppValue, rtl_uString *pName )
{
    if( osl_Process_E_None != osl_getEnvironment( pName , ppValue ) )
    {
        // osl behaves different on win or unx.
        if( *ppValue )
        {
            rtl_uString_release( *ppValue );
            *ppValue = 0;
        }
    }

}

static void getFromList(NameValueList *pNameValueList, rtl_uString **ppValue, rtl_uString *pName)
{
    OUString name(pName);

    for(NameValueList::iterator ii = pNameValueList->begin();
        ii != pNameValueList->end();
        ++ii)
    {
        if( (*ii).sName.equals(name) )
        {
            rtl_uString_assign( ppValue, (*ii).sValue.pData );
            break;
        }
    }
}

static sal_Bool getValue(NameValueList *pNameValueList, rtl_uString * pName, rtl_uString ** ppValue, rtl_uString * pDefault)
{
    static const OUString sysUserConfig(RTL_CONSTASCII_USTRINGPARAM("SYSUSERCONFIG"));
    static const OUString sysUserHome  (RTL_CONSTASCII_USTRINGPARAM("SYSUSERHOME"));
    static const OUString sysBinDir    (RTL_CONSTASCII_USTRINGPARAM("SYSBINDIR"));

    sal_Bool result = sal_True;

    // we have build ins:
    if(!rtl_ustr_compare_WithLength(pName->buffer, pName->length, sysUserConfig.pData->buffer, sysUserConfig.pData->length))
    {
        oslSecurity security = osl_getCurrentSecurity();
        osl_getConfigDir(security, ppValue);
        osl_freeSecurityHandle(security);
    }
    else if(!rtl_ustr_compare_WithLength(pName->buffer, pName->length, sysUserHome.pData->buffer, sysUserHome.pData->length))
    {
        oslSecurity security = osl_getCurrentSecurity();
        osl_getHomeDir(security, ppValue);
        osl_freeSecurityHandle(security);
    }
    else if(!rtl_ustr_compare_WithLength(pName->buffer, pName->length, sysBinDir.pData->buffer, sysBinDir.pData->length))
        osl_getProcessWorkingDir(ppValue);

    else
    {
        getFromCommandLineArgs(ppValue, pName);
        if(!*ppValue)
        {
            getFromList(pNameValueList, ppValue, pName);
            if( ! *ppValue )
            {
                getFromEnvironment( ppValue, pName );
                if( ! *ppValue )
                {
                    result = sal_False;

                    if(pDefault)
                        rtl_uString_assign( ppValue , pDefault );
                }
            }
        }
    }

#ifdef DEBUG
    OString sName = OUStringToOString(OUString(pName), RTL_TEXTENCODING_ASCII_US);
    OString sValue;
    if(*ppValue)
        sValue = OUStringToOString(OUString(*ppValue), RTL_TEXTENCODING_ASCII_US);
    OSL_TRACE("bootstrap.cxx::getValue - name:%s value:%s\n", sName.getStr(), sValue.getStr());
#endif

    return result;
}

typedef struct Bootstrap_Impl {
    NameValueList _nameValueList;
    OUString      _iniName;
} Bootstrap_Impl;

static void fillFromIniFile(Bootstrap_Impl * pBootstrap_Impl)
{
    OUString iniName = pBootstrap_Impl->_iniName;

#ifdef DEBUG
    OString sFile = OUStringToOString(iniName, RTL_TEXTENCODING_ASCII_US);
    OSL_TRACE("bootstrap.cxx::fillFromIniFile - %s\n", sFile.getStr());
#endif

    oslFileHandle handle;
    if(iniName.getLength()
    && osl_File_E_None == osl_openFile(iniName.pData, &handle, osl_File_OpenFlag_Read))
    {
        ByteSequence seq;
        sal_uInt64 nSize = 0;

        getFileSize(handle, &nSize);
        while( sal_True )
        {
            sal_uInt64 nPos;
            if(osl_File_E_None != osl_getFilePos(handle, &nPos)
            || nPos >= nSize)
                break;

            if(osl_File_E_None != osl_readLine(handle , (sal_Sequence ** ) &seq))
                break;

            OString line((const sal_Char *)seq.getConstArray(), seq.getLength());
            sal_Int32 nIndex = line.indexOf('=');
            struct rtl_bootstrap_NameValue nameValue;
            if(nIndex >= 1 && nIndex +1 < line.getLength())
            {
                nameValue.sName = OStringToOUString(line.copy(0,nIndex).trim(),
                                                    RTL_TEXTENCODING_ASCII_US);
                nameValue.sValue = OStringToOUString(line.copy(nIndex+1).trim(),
                                                     RTL_TEXTENCODING_UTF8);

                OString name_tmp = OUStringToOString(nameValue.sName, RTL_TEXTENCODING_ASCII_US);
                OString value_tmp = OUStringToOString(nameValue.sValue, RTL_TEXTENCODING_UTF8);
                OSL_TRACE("bootstrap.cxx: pushing: name=%s value=%s\n", name_tmp.getStr(), value_tmp.getStr());

                pBootstrap_Impl->_nameValueList.push_back(nameValue);
            }
        }
        osl_closeFile(handle);
    }
#ifdef DEBUG
    else
    {
        OString file_tmp = OUStringToOString(iniName, RTL_TEXTENCODING_ASCII_US);
        OSL_TRACE("bootstrap.cxx: couldn't open file: %s", file_tmp.getStr());
    }
#endif
}

extern "C"
{

rtlBootstrapHandle SAL_CALL rtl_bootstrap_args_open(rtl_uString * pIniName)
{
    OUString workDir;
    OUString iniName = OUString(pIniName);

    osl_getProcessWorkingDir(&workDir.pData);
    FileBase::getAbsoluteFileURL(workDir, iniName, iniName);

    Bootstrap_Impl * pBootstrap_Impl = new Bootstrap_Impl;

    pBootstrap_Impl->_iniName = iniName;
    fillFromIniFile(pBootstrap_Impl);

    return pBootstrap_Impl;
}

void SAL_CALL rtl_bootstrap_args_close(rtlBootstrapHandle handle)
{
    delete (Bootstrap_Impl *)handle;
}

sal_Bool SAL_CALL rtl_bootstrap_get_from_handle(rtlBootstrapHandle handle, rtl_uString *pName, rtl_uString **ppValue, rtl_uString *pDefault)
{
    MutexGuard guard(Mutex::getGlobalMutex());

    sal_Bool found = sal_False;
    if(ppValue && pName)
    {
        if(handle) {
            if(*ppValue) {
                rtl_uString_release(*ppValue);
                *ppValue = 0;
            }

            found = getValue(&((Bootstrap_Impl *)handle)->_nameValueList, pName, ppValue, pDefault);

            if(*ppValue)
            {
                OUString result = expandMacros(&((Bootstrap_Impl *)handle)->_nameValueList, OUString(*ppValue));

                rtl_uString_assign(ppValue, result.pData );
            }

            if(!found) {
                // fall back to executable rc
                  if(((Bootstrap_Impl *)handle)->_iniName != getIniFileNameImpl())
                    found = rtl_bootstrap_get(pName, ppValue, pDefault);
            }

            if(!*ppValue)
                rtl_uString_new(ppValue);

        }
        else
            found = rtl_bootstrap_get(pName, ppValue, pDefault);
    }

    return found;
}

void SAL_CALL rtl_bootstrap_get_iniName_from_handle(rtlBootstrapHandle handle, rtl_uString ** ppIniName)
{
    if(ppIniName)
        if(handle)
            rtl_uString_assign(ppIniName, ((Bootstrap_Impl *)handle)->_iniName.pData);

        else {
            const OUString & iniName = getIniFileNameImpl();

            rtl_uString_assign(ppIniName, iniName.pData);
        }
}

void SAL_CALL rtl_bootstrap_setIniFileName( rtl_uString *pName )
{
    MutexGuard guard( Mutex::getGlobalMutex() );
    OUString & file = getIniFileNameImpl();
    file = pName;
}

sal_Bool SAL_CALL rtl_bootstrap_get( rtl_uString *pName, rtl_uString **ppValue , rtl_uString *pDefault )
{
    MutexGuard guard( Mutex::getGlobalMutex() );

    static Bootstrap_Impl * pBootstrap_Impl = 0;

    if(!pBootstrap_Impl)
    {
        static Bootstrap_Impl bootstrap_Impl;

        bootstrap_Impl._iniName = getIniFileNameImpl();
        fillFromIniFile(&bootstrap_Impl);

        pBootstrap_Impl = &bootstrap_Impl;
    }

    return rtl_bootstrap_get_from_handle(pBootstrap_Impl, pName, ppValue, pDefault);
}

}
<|endoftext|>


<commit_before>#include "dock.h"
#include "mainwindow.h"
#include "connection.h"
#include "dockmanagerconfig.h"
#include "dockdelegates.h"
#include "controlbar_dockmanager.h"
#include "serialize.h"
#include <ui_controlbarcommon.h>
#include <QScrollBar>
/*#include <ui_controlbarlogs.h>
#include <ui_controlbarplots.h>
#include <ui_controlbartables.h>
#include <ui_controlbargantts.h>*/

DockManager::DockManager (MainWindow * mw, QStringList const & path)
	: DockManagerView(mw), ActionAble(path)
	, m_main_window(mw)
	, m_dockwidget(0)
	, m_control_bar(0)
	, m_model(0)
	, m_config(g_traceServerName)
{
	qDebug("%s", __FUNCTION__);
	resizeColumnToContents(0);

	QString const name = path.join("/");
	DockWidget * const dock = new DockWidget(*this, name, m_main_window);
	dock->setObjectName(name);
	dock->setWindowTitle(name);
	dock->setAllowedAreas(Qt::AllDockWidgetAreas);
	m_main_window->addDockWidget(Qt::BottomDockWidgetArea, dock);
	dock->setAttribute(Qt::WA_DeleteOnClose, false);
	dock->setWidget(this);

	//if (visible)
	//	m_main_window->restoreDockWidget(dock);
	m_dockwidget = dock;

	connect(m_dockwidget, SIGNAL(widgetVisibilityChanged()), m_main_window, SLOT(onDockManagerVisibilityChanged(bool)));
	m_control_bar = new ControlBarCommon();

	connect(header(), SIGNAL(sectionResized(int, int, int)), this, SLOT(onColumnResized(int, int, int)));
	connect(m_dockwidget, SIGNAL(dockClosed()), mw, SLOT(onDockManagerClosed()));
	setAllColumnsShowFocus(false);
	setExpandsOnDoubleClick(false);
	//setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
	//setSizeAdjustPolicy(QAbstractScrollArea::AdjustIgnored);
	//header()->setSectionResizeMode(0, QHeaderView::Interactive);
	header()->setStretchLastSection(false);
	setEditTriggers(QAbstractItemView::NoEditTriggers);
	//setItemDelegateForColumn(e_Column_Close, new CloseButtonDelegate(*this, this));
	setItemDelegateForColumn(e_Column_Close, new CloseButtonDelegate(*this, this));
	setItemDelegateForColumn(e_Column_ControlWidget, new ControlWidgetDelegate(*this, this));
	setStyleSheet("QTreeView::item{ selection-background-color: #FFE7BA } QTreeView::item{ selection-color: #000000 }");
	//horizontalScrollBar()->setStyleSheet("QScrollBar:horizontal { border: 1px solid grey; height: 15px; } QScrollBar::handle:horizontal { background: white; min-width: 10px; }");
	/*
	setStyleSheet(QString::fromUtf8("QScrollBar:vertical {
		"    border: 1px solid #999999;"
		"    background:white;"
		"    width:10px;    "
		"    margin: 0px 0px 0px 0px;"
		"}"
		"QScrollBar::handle:vertical {"
		"    background: qlineargradient(x1:0, y1:0, x2:1, y2:0,"
		"    stop: 0  rgb(32, 47, 130), stop: 0.5 rgb(32, 47, 130),  stop:1 rgb(32, 47, 130));"
		"    min-height: 0px;"
		""
		"}"
		"QScrollBar::add-line:vertical {"
		"    background: qlineargradient(x1:0, y1:0, x2:1, y2:0,"
		"    stop: 0  rgb(32, 47, 130), stop: 0.5 rgb(32, 47, 130),  stop:1 rgb(32, 47, 130));"
		"    height: px;"
		"    subcontrol-position: bottom;"
		"    subcontrol-origin: margin;"
		"}"
		"QScrollBar::sub-line:vertical {"
		"    background: qlineargradient(x1:0, y1:0, x2:1, y2:0,"
		"    stop: 0  rgb(32, 47, 130), stop: 0.5 rgb(32, 47, 130),  stop:1 rgb(32, 47, 130));"
		"    height: 0px;"
		"    subcontrol-position: top;"
		"    subcontrol-origin: margin;"
		"}"
		""));
*/
}

void DockManager::loadConfig (QString const & cfgpath)
{
	QString const fname = cfgpath + "/" + g_dockManagerTag;
	DockManagerConfig config2(g_traceServerName);
	if (!::loadConfigTemplate(config2, fname))
	{
		m_config.defaultConfig();
	}
	else
	{
		m_config = config2;
		config2.m_data.root = 0; // @TODO: promyslet.. takle na to urcite zapomenu
	}

	m_model = new DockManagerModel(*this, this, &m_config.m_data);
	setModel(m_model);
	bool const on = true;
	addActionAble(*this, on, false, true);
}

void DockManager::applyConfig ()
{
	for (size_t i = 0, ie = m_config.m_columns_sizes.size(); i < ie; ++i)
		header()->resizeSection(static_cast<int>(i), m_config.m_columns_sizes[i]);

	if (m_model)
		m_model->syncExpandState(this);
}

void DockManager::saveConfig (QString const & path)
{
	QString const fname = path + "/" + g_dockManagerTag;
	::saveConfigTemplate(m_config, fname);
}

DockManager::~DockManager ()
{
	removeActionAble(*this);
}

DockWidget * DockManager::mkDockWidget (DockedWidgetBase & dwb, bool visible)
{
	return mkDockWidget(dwb, visible, Qt::BottomDockWidgetArea);
}

DockWidget * DockManager::mkDockWidget (ActionAble & aa, bool visible, Qt::DockWidgetArea area)
{
	qDebug("%s", __FUNCTION__);
	Q_ASSERT(aa.path().size() > 0);

	QString const name = aa.path().join("/");
	DockWidget * const dock = new DockWidget(*this, name, m_main_window);
	dock->setObjectName(name);
	dock->setWindowTitle(name);
	dock->setAllowedAreas(Qt::AllDockWidgetAreas);
	//dock->setWidget(docked_widget); // @NOTE: commented, it is set by caller
	m_main_window->addDockWidget(area, dock);
	dock->setAttribute(Qt::WA_DeleteOnClose, false);

	if (visible)
		m_main_window->restoreDockWidget(dock);
	return dock;
}

void DockManager::onWidgetClosed (DockWidget * w)
{
	qDebug("%s w=%08x", __FUNCTION__, w);
}

QModelIndex DockManager::addActionAble (ActionAble & aa, bool on, bool close_button, bool control_widget)
{
	qDebug("%s aa=%s show=%i", __FUNCTION__, aa.joinedPath().toStdString().c_str(), on);
	QModelIndex const idx = m_model->insertItemWithPath(aa.path(), on);
	QString const & name = aa.joinedPath();
	m_actionables.insert(name, &aa);
	m_model->initData(idx, QVariant(on ? Qt::Checked : Qt::Unchecked), Qt::CheckStateRole);

	if (close_button)
	{
		QModelIndex const jdx = m_model->index(idx.row(), e_Column_Close, idx.parent());
		openPersistentEditor(jdx);
	}
	if (control_widget)
	{
		QModelIndex const kdx = m_model->index(idx.row(), e_Column_ControlWidget, idx.parent());
		openPersistentEditor(kdx);
	}
	return idx;

}

QModelIndex DockManager::addActionAble (ActionAble & aa, bool on)
{
	return addActionAble(aa, on, true, true);
}

ActionAble const * DockManager::findActionAble (QString const & dst_joined) const
{
	actionables_t::const_iterator it = m_actionables.find(dst_joined);
	if (it != m_actionables.end() && it.key() == dst_joined)
		return *it;
	return 0;
}
ActionAble * DockManager::findActionAble (QString const & dst_joined)
{
	actionables_t::iterator it = m_actionables.find(dst_joined);
	if (it != m_actionables.end() && it.key() == dst_joined)
		return *it;
	return 0;
}

void DockManager::removeActionAble (ActionAble & aa)
{
	qDebug("%s aa=%s", __FUNCTION__, aa.joinedPath().toStdString().c_str());
	actionables_t::iterator it = m_actionables.find(aa.joinedPath());
	if (it != m_actionables.end() && it.key() == aa.joinedPath())
	{
		QModelIndex const idx = m_model->testItemWithPath(aa.path());
		if (idx.isValid())
			for (int j = 1; j < e_max_dockmgr_column; ++j)
				closePersistentEditor(m_model->index(idx.row(), j, idx.parent()));
		m_actionables.erase(it);
	}
}

void DockManager::onColumnResized (int idx, int , int new_size)
{
	if (idx < 0) return;
	size_t const curr_sz = m_config.m_columns_sizes.size();
	if (idx < curr_sz)
	{
		//qDebug("%s this=0x%08x hsize[%i]=%i", __FUNCTION__, this, idx, new_size);
	}
	else
	{
		m_config.m_columns_sizes.resize(idx + 1);
		for (size_t i = curr_sz; i < idx + 1; ++i)
			m_config.m_columns_sizes[i] = 32;
	}
	m_config.m_columns_sizes[idx] = new_size;
}

bool DockManager::handleAction (Action * a, E_ActionHandleType sync)
{
	QStringList const & src_path = a->m_src_path;
	QStringList const & dst_path = a->m_dst_path;
	QStringList const & my_addr = path();

	if (dst_path.size() == 0)
	{
		qWarning("DockManager::handleAction empty dst");
		return false;
	}

	Q_ASSERT(my_addr.size() == 1);
	int const lvl = dst_path.indexOf(my_addr.at(0), a->m_dst_curr_level);
	if (lvl == -1)
	{
		qWarning("DockManager::handleAction message not for me");
		return false;
	}
	else if (lvl == dst_path.size() - 1)
	{
		// message just for me! gr8!
		a->m_dst_curr_level = lvl;
		a->m_dst = this;
		return true;
	}
	else
	{
		// message for my children
		a->m_dst_curr_level = lvl + 1;

		if (a->m_dst_curr_level >= 0 && a->m_dst_curr_level < dst_path.size())
		{
			QString const dst_joined = dst_path.join("/");
			actionables_t::iterator it = m_actionables.find(dst_joined);
			if (it != m_actionables.end() && it.key() == dst_joined)
			{
				qDebug("delivering action to: %s", dst_joined.toStdString().c_str());
				ActionAble * const next_hop =  it.value();
				next_hop->handleAction(a, sync); //@NOTE: e_Close can invalidate iterator
			}
			else
			{
				//@TODO: find least common subpath
			}
		}
		else
		{
			qWarning("DockManager::handleAction hmm? what?");
		}
	}
	return false;
}

void DockManager::onCloseButton ()
{
	QVariant v = QObject::sender()->property("idx");
	if (v.canConvert<QModelIndex>())
	{
		QModelIndex const idx = v.value<QModelIndex>();
		if (TreeModel<DockedInfo>::node_t * const n = m_model->getItemFromIndex(idx))
		{
			QStringList const & dst_path = n->data.m_path;
			Action a;
			a.m_type = e_Close;
			a.m_src_path = path();
			a.m_src = this;
			a.m_dst_path = dst_path;
			handleAction(&a, e_Sync);
		}
	}
}

<commit_msg>* fixed destruction of dockmanager<commit_after>#include "dock.h"
#include "mainwindow.h"
#include "connection.h"
#include "dockmanagerconfig.h"
#include "dockdelegates.h"
#include "controlbar_dockmanager.h"
#include "serialize.h"
#include <ui_controlbarcommon.h>
#include <QScrollBar>
/*#include <ui_controlbarlogs.h>
#include <ui_controlbarplots.h>
#include <ui_controlbartables.h>
#include <ui_controlbargantts.h>*/

DockManager::DockManager (MainWindow * mw, QStringList const & path)
	: DockManagerView(mw), ActionAble(path)
	, m_main_window(mw)
	, m_dockwidget(0)
	, m_control_bar(0)
	, m_model(0)
	, m_config(g_traceServerName)
{
	qDebug("%s", __FUNCTION__);
	resizeColumnToContents(0);

	QString const name = path.join("/");
	DockWidget * const dock = new DockWidget(*this, name, m_main_window);
	dock->setObjectName(name);
	dock->setWindowTitle(name);
	dock->setAllowedAreas(Qt::AllDockWidgetAreas);
	m_main_window->addDockWidget(Qt::BottomDockWidgetArea, dock);
	dock->setAttribute(Qt::WA_DeleteOnClose, false);
	dock->setWidget(this);

	//if (visible)
	//	m_main_window->restoreDockWidget(dock);
	m_dockwidget = dock;

	connect(m_dockwidget, SIGNAL(widgetVisibilityChanged()), m_main_window, SLOT(onDockManagerVisibilityChanged(bool)));
	m_control_bar = new ControlBarCommon();

	connect(header(), SIGNAL(sectionResized(int, int, int)), this, SLOT(onColumnResized(int, int, int)));
	connect(m_dockwidget, SIGNAL(dockClosed()), mw, SLOT(onDockManagerClosed()));
	setAllColumnsShowFocus(false);
	setExpandsOnDoubleClick(false);
	//setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
	//setSizeAdjustPolicy(QAbstractScrollArea::AdjustIgnored);
	//header()->setSectionResizeMode(0, QHeaderView::Interactive);
	header()->setStretchLastSection(false);
	setEditTriggers(QAbstractItemView::NoEditTriggers);
	//setItemDelegateForColumn(e_Column_Close, new CloseButtonDelegate(*this, this));
	setItemDelegateForColumn(e_Column_Close, new CloseButtonDelegate(*this, this));
	setItemDelegateForColumn(e_Column_ControlWidget, new ControlWidgetDelegate(*this, this));
	setStyleSheet("QTreeView::item{ selection-background-color: #FFE7BA } QTreeView::item{ selection-color: #000000 }");
	//horizontalScrollBar()->setStyleSheet("QScrollBar:horizontal { border: 1px solid grey; height: 15px; } QScrollBar::handle:horizontal { background: white; min-width: 10px; }");
	/*
	setStyleSheet(QString::fromUtf8("QScrollBar:vertical {
		"    border: 1px solid #999999;"
		"    background:white;"
		"    width:10px;    "
		"    margin: 0px 0px 0px 0px;"
		"}"
		"QScrollBar::handle:vertical {"
		"    background: qlineargradient(x1:0, y1:0, x2:1, y2:0,"
		"    stop: 0  rgb(32, 47, 130), stop: 0.5 rgb(32, 47, 130),  stop:1 rgb(32, 47, 130));"
		"    min-height: 0px;"
		""
		"}"
		"QScrollBar::add-line:vertical {"
		"    background: qlineargradient(x1:0, y1:0, x2:1, y2:0,"
		"    stop: 0  rgb(32, 47, 130), stop: 0.5 rgb(32, 47, 130),  stop:1 rgb(32, 47, 130));"
		"    height: px;"
		"    subcontrol-position: bottom;"
		"    subcontrol-origin: margin;"
		"}"
		"QScrollBar::sub-line:vertical {"
		"    background: qlineargradient(x1:0, y1:0, x2:1, y2:0,"
		"    stop: 0  rgb(32, 47, 130), stop: 0.5 rgb(32, 47, 130),  stop:1 rgb(32, 47, 130));"
		"    height: 0px;"
		"    subcontrol-position: top;"
		"    subcontrol-origin: margin;"
		"}"
		""));
*/
}

void DockManager::loadConfig (QString const & cfgpath)
{
	QString const fname = cfgpath + "/" + g_dockManagerTag;
	DockManagerConfig config2(g_traceServerName);
	if (!::loadConfigTemplate(config2, fname))
	{
		m_config.defaultConfig();
	}
	else
	{
		m_config = config2;
		config2.m_data.root = 0; // @TODO: promyslet.. takle na to urcite zapomenu
	}

	m_model = new DockManagerModel(*this, this, &m_config.m_data);
	setModel(m_model);
	bool const on = true;
	addActionAble(*this, on, false, true);
}

void DockManager::applyConfig ()
{
	for (size_t i = 0, ie = m_config.m_columns_sizes.size(); i < ie; ++i)
		header()->resizeSection(static_cast<int>(i), m_config.m_columns_sizes[i]);

	if (m_model)
		m_model->syncExpandState(this);
}

void DockManager::saveConfig (QString const & path)
{
	QString const fname = path + "/" + g_dockManagerTag;
	::saveConfigTemplate(m_config, fname);
}

DockManager::~DockManager ()
{
	setParent(0);
	m_dockwidget->setWidget(0);
	delete m_dockwidget;
	m_dockwidget= 0;
	removeActionAble(*this);
}

DockWidget * DockManager::mkDockWidget (DockedWidgetBase & dwb, bool visible)
{
	return mkDockWidget(dwb, visible, Qt::BottomDockWidgetArea);
}

DockWidget * DockManager::mkDockWidget (ActionAble & aa, bool visible, Qt::DockWidgetArea area)
{
	qDebug("%s", __FUNCTION__);
	Q_ASSERT(aa.path().size() > 0);

	QString const name = aa.path().join("/");
	DockWidget * const dock = new DockWidget(*this, name, m_main_window);
	dock->setObjectName(name);
	dock->setWindowTitle(name);
	dock->setAllowedAreas(Qt::AllDockWidgetAreas);
	//dock->setWidget(docked_widget); // @NOTE: commented, it is set by caller
	m_main_window->addDockWidget(area, dock);
	dock->setAttribute(Qt::WA_DeleteOnClose, false);

	if (visible)
		m_main_window->restoreDockWidget(dock);
	return dock;
}

void DockManager::onWidgetClosed (DockWidget * w)
{
	qDebug("%s w=%08x", __FUNCTION__, w);
}

QModelIndex DockManager::addActionAble (ActionAble & aa, bool on, bool close_button, bool control_widget)
{
	qDebug("%s aa=%s show=%i", __FUNCTION__, aa.joinedPath().toStdString().c_str(), on);
	QModelIndex const idx = m_model->insertItemWithPath(aa.path(), on);
	QString const & name = aa.joinedPath();
	m_actionables.insert(name, &aa);
	m_model->initData(idx, QVariant(on ? Qt::Checked : Qt::Unchecked), Qt::CheckStateRole);

	if (close_button)
	{
		QModelIndex const jdx = m_model->index(idx.row(), e_Column_Close, idx.parent());
		openPersistentEditor(jdx);
	}
	if (control_widget)
	{
		QModelIndex const kdx = m_model->index(idx.row(), e_Column_ControlWidget, idx.parent());
		openPersistentEditor(kdx);
	}
	return idx;

}

QModelIndex DockManager::addActionAble (ActionAble & aa, bool on)
{
	return addActionAble(aa, on, true, true);
}

ActionAble const * DockManager::findActionAble (QString const & dst_joined) const
{
	actionables_t::const_iterator it = m_actionables.find(dst_joined);
	if (it != m_actionables.end() && it.key() == dst_joined)
		return *it;
	return 0;
}
ActionAble * DockManager::findActionAble (QString const & dst_joined)
{
	actionables_t::iterator it = m_actionables.find(dst_joined);
	if (it != m_actionables.end() && it.key() == dst_joined)
		return *it;
	return 0;
}

void DockManager::removeActionAble (ActionAble & aa)
{
	qDebug("%s aa=%s", __FUNCTION__, aa.joinedPath().toStdString().c_str());
	actionables_t::iterator it = m_actionables.find(aa.joinedPath());
	if (it != m_actionables.end() && it.key() == aa.joinedPath())
	{
		QModelIndex const idx = m_model->testItemWithPath(aa.path());
		if (idx.isValid())
			for (int j = 1; j < e_max_dockmgr_column; ++j)
				closePersistentEditor(m_model->index(idx.row(), j, idx.parent()));
		m_actionables.erase(it);
	}
}

void DockManager::onColumnResized (int idx, int , int new_size)
{
	if (idx < 0) return;
	size_t const curr_sz = m_config.m_columns_sizes.size();
	if (idx < curr_sz)
	{
		//qDebug("%s this=0x%08x hsize[%i]=%i", __FUNCTION__, this, idx, new_size);
	}
	else
	{
		m_config.m_columns_sizes.resize(idx + 1);
		for (size_t i = curr_sz; i < idx + 1; ++i)
			m_config.m_columns_sizes[i] = 32;
	}
	m_config.m_columns_sizes[idx] = new_size;
}

bool DockManager::handleAction (Action * a, E_ActionHandleType sync)
{
	QStringList const & src_path = a->m_src_path;
	QStringList const & dst_path = a->m_dst_path;
	QStringList const & my_addr = path();

	if (dst_path.size() == 0)
	{
		qWarning("DockManager::handleAction empty dst");
		return false;
	}

	Q_ASSERT(my_addr.size() == 1);
	int const lvl = dst_path.indexOf(my_addr.at(0), a->m_dst_curr_level);
	if (lvl == -1)
	{
		qWarning("DockManager::handleAction message not for me");
		return false;
	}
	else if (lvl == dst_path.size() - 1)
	{
		// message just for me! gr8!
		a->m_dst_curr_level = lvl;
		a->m_dst = this;
		return true;
	}
	else
	{
		// message for my children
		a->m_dst_curr_level = lvl + 1;

		if (a->m_dst_curr_level >= 0 && a->m_dst_curr_level < dst_path.size())
		{
			QString const dst_joined = dst_path.join("/");
			actionables_t::iterator it = m_actionables.find(dst_joined);
			if (it != m_actionables.end() && it.key() == dst_joined)
			{
				qDebug("delivering action to: %s", dst_joined.toStdString().c_str());
				ActionAble * const next_hop =  it.value();
				next_hop->handleAction(a, sync); //@NOTE: e_Close can invalidate iterator
			}
			else
			{
				//@TODO: find least common subpath
			}
		}
		else
		{
			qWarning("DockManager::handleAction hmm? what?");
		}
	}
	return false;
}

void DockManager::onCloseButton ()
{
	QVariant v = QObject::sender()->property("idx");
	if (v.canConvert<QModelIndex>())
	{
		QModelIndex const idx = v.value<QModelIndex>();
		if (TreeModel<DockedInfo>::node_t * const n = m_model->getItemFromIndex(idx))
		{
			QStringList const & dst_path = n->data.m_path;
			Action a;
			a.m_type = e_Close;
			a.m_src_path = path();
			a.m_src = this;
			a.m_dst_path = dst_path;
			handleAction(&a, e_Sync);
		}
	}
}

<|endoftext|>


<commit_before>#include <ncurses.h>

int main()
{
	initscr();
	endwin();
	return 0;
}

<commit_msg>NCusrses igh<commit_after>#include <ncurses.h>

int main()
{
	initscr();
	endwin();
	// end

	return 0;
}

<|endoftext|>


<commit_before>#include "bot/InputOutput.hxx"
#include "bot/HypothesisSpace.hxx"
#include "bot/ObjectFeatureExtractor.hxx"
#include "bot/AverageObject.hxx"
#include "bot/SingletsGenerator.hxx"
#include "bot/MultipletsGenerator.hxx"
#include "bot/CPLEXSolverSystem.hxx"
#include "bot/TrackingPredictor.hxx"
#include "vigra/hdf5impex.hxx"
#include "bot/SolutionCoder.hxx"
#include "bot/TrainingData.hxx"
#include "bot/TrackingTrainer.hxx"
#include "bot/HDF5ReaderWriter.hxx"

using namespace bot;

int main()
{
    std::string filename("dcelliq-sequence-training.h5");
    // load the image sequence
    std::vector<Matrix2D > images, segmentations;
    TrainingData training;
    HDF5ReaderWriter::load(filename, images, segmentations);
    std::cout << "****Loading the images/segmentations****" << std::endl;
    HDF5ReaderWriter::load(filename, training);
    std::cout << "****Loading the training data****" << std::endl;

    // get the context
    Context context(images);
    std::cout << "****Computing the Context****" << std::endl << context << std::endl << std::endl;

    // load the configuration
    HypothesisSpace space("../data/event-configuration-cell.ini");
    EventConfiguration conf = space.configuration();

    // create singlets/muliplets and extract object features
    std::cout << "****Extracting singlets and multiplets****" << std::endl;
    SingletsSequence singlets_vec;
    SingletsSequence avg_singlet_vec;
    MultipletsSequence multiplets_vec;
    SingletsGenerator singletsGenerator;
    MultipletsGenerator multipletsGenerator(conf.k(), conf.d_max());
    ObjectFeatureExtractor extractor(conf.get_feature_names(), context);
    for (int32 indT = 0; indT < images.size(); indT ++) {
        // generate singlets and multiplets
        Singlets singlets = singletsGenerator(images[indT], segmentations[indT]);
        Multiplets multiplets = multipletsGenerator(images[indT], segmentations[indT], singlets);

        // extract features for them
        extractor(singlets);
        extractor(multiplets);
        // save
        singlets_vec.push_back(singlets);
        avg_singlet_vec.push_back(AverageObject::average(singlets));
        multiplets_vec.push_back(multiplets);

        std::cout << "#T = " << indT
            << ": #singlets = " << singlets.size()
            << ": #multiplets = " << multiplets.size() << std::endl;

    }

    // generate hypotheses and extract joint features
    space(singlets_vec, avg_singlet_vec, multiplets_vec);
    const std::vector<FramePair >& framepairs = space.framepairs();

    // parse the training data
    std::cout << "****Parsing the training data****" << std::endl;
    SolutionCoder coder;
    int32 nTr = training.times().size();
    for (int32 ind = 0; ind < nTr; ind ++) {
        int32 time = training.times()[ind];
        std::cout << "****time = " << time << "****" << std::endl;
        const LabelAssociations& association = training.associations()[ind];

        const std::vector<Event >& events = framepairs[time].events();
        const Singlets& singlets1 = singlets_vec[time];
        const Singlets& singlets2 = singlets_vec[time+1];
        const Multiplets& multiplets1 = multiplets_vec[time];
        const Multiplets& multiplets2 = multiplets_vec[time+1];

        Solution solution;
        coder.decode(
            association,
            events,
            singlets1, singlets2,
            multiplets1, multiplets2,
            solution);
        training.solutions().push_back(solution);
    }

    // start the training
    TrackingTrainer trainer;
    const std::vector<Matrix2D > null_vector;
    std::vector<Matrix2D > weights = conf.weights(0.5);
    std::string msg = trainer(training, framepairs, weights, true);
    std::cout << "Training returns: " << msg << std::endl;
    conf.weights() = weights;

    // print the final weights
    std::cout << "Learned weights: " << std::endl;
    conf.print();

    // printe intermediate results: weights, epsilons, losses
    std::cout << "Weights: " << std::endl << trainer.weights() << std::endl << std::endl;
    std::cout << "Epsilons: " << std::endl << trainer.epsilons() << std::endl << std::endl;
    std::cout << "Losses: " << std::endl << trainer.losses() << std::endl << std::endl;

    return 0;
}
<commit_msg>Silenced compiler warning<commit_after>#include "bot/InputOutput.hxx"
#include "bot/HypothesisSpace.hxx"
#include "bot/ObjectFeatureExtractor.hxx"
#include "bot/AverageObject.hxx"
#include "bot/SingletsGenerator.hxx"
#include "bot/MultipletsGenerator.hxx"
#include "bot/CPLEXSolverSystem.hxx"
#include "bot/TrackingPredictor.hxx"
#include "vigra/hdf5impex.hxx"
#include "bot/SolutionCoder.hxx"
#include "bot/TrainingData.hxx"
#include "bot/TrackingTrainer.hxx"
#include "bot/HDF5ReaderWriter.hxx"

using namespace bot;

int main()
{
    std::string filename("dcelliq-sequence-training.h5");
    // load the image sequence
    std::vector<Matrix2D > images, segmentations;
    TrainingData training;
    HDF5ReaderWriter::load(filename, images, segmentations);
    std::cout << "****Loading the images/segmentations****" << std::endl;
    HDF5ReaderWriter::load(filename, training);
    std::cout << "****Loading the training data****" << std::endl;

    // get the context
    Context context(images);
    std::cout << "****Computing the Context****" << std::endl << context << std::endl << std::endl;

    // load the configuration
    HypothesisSpace space("event-configuration-cell.ini");
    EventConfiguration conf = space.configuration();

    // create singlets/muliplets and extract object features
    std::cout << "****Extracting singlets and multiplets****" << std::endl;
    SingletsSequence singlets_vec;
    SingletsSequence avg_singlet_vec;
    MultipletsSequence multiplets_vec;
    SingletsGenerator singletsGenerator;
    MultipletsGenerator multipletsGenerator(conf.k(), conf.d_max());
    ObjectFeatureExtractor extractor(conf.get_feature_names(), context);
    for (int32 indT = 0; indT < static_cast<int32>(images.size()); indT ++) {
        // generate singlets and multiplets
        Singlets singlets = singletsGenerator(images[indT], segmentations[indT]);
        Multiplets multiplets = multipletsGenerator(images[indT], segmentations[indT], singlets);

        // extract features for them
        extractor(singlets);
        extractor(multiplets);
        // save
        singlets_vec.push_back(singlets);
        avg_singlet_vec.push_back(AverageObject::average(singlets));
        multiplets_vec.push_back(multiplets);

        std::cout << "#T = " << indT
            << ": #singlets = " << singlets.size()
            << ": #multiplets = " << multiplets.size() << std::endl;

    }

    // generate hypotheses and extract joint features
    space(singlets_vec, avg_singlet_vec, multiplets_vec);
    const std::vector<FramePair >& framepairs = space.framepairs();

    // parse the training data
    std::cout << "****Parsing the training data****" << std::endl;
    SolutionCoder coder;
    int32 nTr = training.times().size();
    for (int32 ind = 0; ind < nTr; ind ++) {
        int32 time = training.times()[ind];
        std::cout << "****time = " << time << "****" << std::endl;
        const LabelAssociations& association = training.associations()[ind];

        const std::vector<Event >& events = framepairs[time].events();
        const Singlets& singlets1 = singlets_vec[time];
        const Singlets& singlets2 = singlets_vec[time+1];
        const Multiplets& multiplets1 = multiplets_vec[time];
        const Multiplets& multiplets2 = multiplets_vec[time+1];

        Solution solution;
        coder.decode(
            association,
            events,
            singlets1, singlets2,
            multiplets1, multiplets2,
            solution);
        training.solutions().push_back(solution);
    }

    // start the training
    TrackingTrainer trainer;
    const std::vector<Matrix2D > null_vector;
    std::vector<Matrix2D > weights = conf.weights(0.5);
    std::string msg = trainer(training, framepairs, weights, true);
    std::cout << "Training returns: " << msg << std::endl;
    conf.weights() = weights;

    // print the final weights
    std::cout << "Learned weights: " << std::endl;
    conf.print();

    // printe intermediate results: weights, epsilons, losses
    std::cout << "Weights: " << std::endl << trainer.weights() << std::endl << std::endl;
    std::cout << "Epsilons: " << std::endl << trainer.epsilons() << std::endl << std::endl;
    std::cout << "Losses: " << std::endl << trainer.losses() << std::endl << std::endl;

    return 0;
}
<|endoftext|>