<commit_before>// Copyright (c) 2020 The Orbit 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 "CaptureSerializer.h"

#include <fstream>
#include <memory>

#include "App.h"
#include "Callstack.h"
#include "Capture.h"
#include "Core.h"
#include "EventTracer.h"
#include "OrbitModule.h"
#include "OrbitProcess.h"
#include "Pdb.h"
#include "PrintVar.h"
#include "SamplingProfiler.h"
#include "ScopeTimer.h"
#include "Serialization.h"
#include "TextBox.h"
#include "TimeGraph.h"
#include "TimerChain.h"
#include "absl/strings/str_format.h"

//-----------------------------------------------------------------------------
CaptureSerializer::CaptureSerializer() {
  m_Version = 2;
  m_TimerVersion = Timer::Version;
  m_SizeOfTimer = sizeof(Timer);
}

//-----------------------------------------------------------------------------
outcome::result<void, std::string> CaptureSerializer::Save(
    const std::string& filename) {
  Capture::PreSave();

  std::basic_ostream<char> Stream(&GStreamCounter);
  cereal::BinaryOutputArchive CountingArchive(Stream);
  GStreamCounter.Reset();
  Save(CountingArchive);
  PRINT_VAR(GStreamCounter.Size());
  GStreamCounter.Reset();

  // Binary
  m_CaptureName = filename;
  std::ofstream file(m_CaptureName, std::ios::binary);
  if (file.fail()) {
    ERROR("Saving capture in \"%s\": %s", filename, "file.fail()");
    return outcome::failure("Error opening the file for writing");
  }

  try {
    SCOPE_TIMER_LOG(absl::StrFormat("Saving capture in \"%s\"", filename));
    cereal::BinaryOutputArchive archive(file);
    Save(archive);
    return outcome::success();
  } catch (std::exception& e) {
    ERROR("Saving capture in \"%s\": %s", filename, e.what());
    return outcome::failure("Error serializing the capture");
  }
}

//-----------------------------------------------------------------------------
template <class T>
void CaptureSerializer::Save(T& archive) {
  m_NumTimers = time_graph_->GetNumTimers();

  // Header
  archive(cereal::make_nvp("Capture", *this));

  {
    ORBIT_SIZE_SCOPE("Functions");
    std::vector<Function> functions;
    for (auto& pair : Capture::GSelectedFunctionsMap) {
      Function* func = pair.second;
      if (func != nullptr) {
        functions.push_back(*func);
      }
    }

    archive(functions);
  }

  {
    ORBIT_SIZE_SCOPE("Capture::GFunctionCountMap");
    archive(Capture::GFunctionCountMap);
  }

  {
    ORBIT_SIZE_SCOPE("Capture::GCallstacks");
    archive(Capture::GCallstacks);
  }

  {
    ORBIT_SIZE_SCOPE("Capture::GAddressInfos");
    archive(Capture::GAddressInfos);
  }

  {
    ORBIT_SIZE_SCOPE("Capture::GAddressToFunctionName");
    archive(Capture::GAddressToFunctionName);
  }

  {
    ORBIT_SIZE_SCOPE("SamplingProfiler");
    archive(Capture::GSamplingProfiler);
  }

  {
    ORBIT_SIZE_SCOPE("String manager");
    archive(*time_graph_->GetStringManager());
  }

  {
    ORBIT_SIZE_SCOPE("Event Buffer");
    archive(GEventTracer.GetEventBuffer());
  }

  // Timers
  int numWrites = 0;
  std::vector<std::shared_ptr<TimerChain>> chains =
      time_graph_->GetAllTimerChains();
  for (const std::shared_ptr<TimerChain>& chain : chains) {
    if (!chain) continue;
    for (TimerChainIterator& it = chain->begin(); it != chain->end(); ++it) {
      TimerBlock& block = *it;
      for (int k = 0; k < block.size(); ++k) {
        archive(cereal::binary_data(&(block[k].GetTimer()), sizeof(Timer)));

        if (++numWrites > m_NumTimers) {
          return;
        }
      }
    }
  }
}

//-----------------------------------------------------------------------------
outcome::result<void, std::string> CaptureSerializer::Load(
    const std::string& filename) {
  SCOPE_TIMER_LOG(absl::StrFormat("Loading capture from \"%s\"", filename));

  // Binary
  std::ifstream file(filename, std::ios::binary);
  if (file.fail()) {
    ERROR("Loading capture from \"%s\": %s", filename, "file.fail()");
    return outcome::failure("Error opening the file for reading");
  }

  try {
    // Header
    cereal::BinaryInputArchive archive(file);
    archive(*this);

    // Functions
    std::vector<Function> functions;
    archive(functions);
    Capture::GSelectedFunctions.clear();
    Capture::GSelectedFunctionsMap.clear();
    for (const auto& function : functions) {
      std::shared_ptr<Function> function_ptr =
          std::make_shared<Function>(function);
      Capture::GSelectedFunctions.push_back(function_ptr);
      Capture::GSelectedFunctionsMap[function_ptr->GetVirtualAddress()] =
          function_ptr.get();
    }
    Capture::GVisibleFunctionsMap = Capture::GSelectedFunctionsMap;

    archive(Capture::GFunctionCountMap);

    archive(Capture::GCallstacks);

    archive(Capture::GAddressInfos);

    archive(Capture::GAddressToFunctionName);

    archive(Capture::GSamplingProfiler);
    if (Capture::GSamplingProfiler == nullptr) {
      Capture::GSamplingProfiler = std::make_shared<SamplingProfiler>();
    }
    Capture::GSamplingProfiler->SortByThreadUsage();

    time_graph_->Clear();

    archive(*time_graph_->GetStringManager());

    // Event buffer
    archive(GEventTracer.GetEventBuffer());

    // Timers
    Timer timer;
    while (file.read(reinterpret_cast<char*>(&timer), sizeof(Timer))) {
      time_graph_->ProcessTimer(timer);
    }

    GOrbitApp->AddSamplingReport(Capture::GSamplingProfiler);
    GOrbitApp->FireRefreshCallbacks();
    return outcome::success();

  } catch (std::exception& e) {
    ERROR("Loading capture from \"%s\": %s", filename, e.what());
    return outcome::failure("Error parsing the capture");
  }
}

//-----------------------------------------------------------------------------
ORBIT_SERIALIZE(CaptureSerializer, 0) {
  ORBIT_NVP_VAL(0, m_CaptureName);
  ORBIT_NVP_VAL(0, m_Version);
  ORBIT_NVP_VAL(0, m_TimerVersion);
  ORBIT_NVP_VAL(0, m_NumTimers);
  ORBIT_NVP_VAL(0, m_SizeOfTimer);
}
<commit_msg>Fix build.<commit_after>// Copyright (c) 2020 The Orbit 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 "CaptureSerializer.h"

#include <fstream>
#include <memory>

#include "App.h"
#include "Callstack.h"
#include "Capture.h"
#include "Core.h"
#include "EventTracer.h"
#include "OrbitModule.h"
#include "OrbitProcess.h"
#include "Pdb.h"
#include "PrintVar.h"
#include "SamplingProfiler.h"
#include "ScopeTimer.h"
#include "Serialization.h"
#include "TextBox.h"
#include "TimeGraph.h"
#include "TimerChain.h"
#include "absl/strings/str_format.h"

//-----------------------------------------------------------------------------
CaptureSerializer::CaptureSerializer() {
  m_Version = 2;
  m_TimerVersion = Timer::Version;
  m_SizeOfTimer = sizeof(Timer);
}

//-----------------------------------------------------------------------------
outcome::result<void, std::string> CaptureSerializer::Save(
    const std::string& filename) {
  Capture::PreSave();

  std::basic_ostream<char> Stream(&GStreamCounter);
  cereal::BinaryOutputArchive CountingArchive(Stream);
  GStreamCounter.Reset();
  Save(CountingArchive);
  PRINT_VAR(GStreamCounter.Size());
  GStreamCounter.Reset();

  // Binary
  m_CaptureName = filename;
  std::ofstream file(m_CaptureName, std::ios::binary);
  if (file.fail()) {
    ERROR("Saving capture in \"%s\": %s", filename, "file.fail()");
    return outcome::failure("Error opening the file for writing");
  }

  try {
    SCOPE_TIMER_LOG(absl::StrFormat("Saving capture in \"%s\"", filename));
    cereal::BinaryOutputArchive archive(file);
    Save(archive);
    return outcome::success();
  } catch (std::exception& e) {
    ERROR("Saving capture in \"%s\": %s", filename, e.what());
    return outcome::failure("Error serializing the capture");
  }
}

//-----------------------------------------------------------------------------
template <class T>
void CaptureSerializer::Save(T& archive) {
  m_NumTimers = time_graph_->GetNumTimers();

  // Header
  archive(cereal::make_nvp("Capture", *this));

  {
    ORBIT_SIZE_SCOPE("Functions");
    std::vector<Function> functions;
    for (auto& pair : Capture::GSelectedFunctionsMap) {
      Function* func = pair.second;
      if (func != nullptr) {
        functions.push_back(*func);
      }
    }

    archive(functions);
  }

  {
    ORBIT_SIZE_SCOPE("Capture::GFunctionCountMap");
    archive(Capture::GFunctionCountMap);
  }

  {
    ORBIT_SIZE_SCOPE("Capture::GCallstacks");
    archive(Capture::GCallstacks);
  }

  {
    ORBIT_SIZE_SCOPE("Capture::GAddressInfos");
    archive(Capture::GAddressInfos);
  }

  {
    ORBIT_SIZE_SCOPE("Capture::GAddressToFunctionName");
    archive(Capture::GAddressToFunctionName);
  }

  {
    ORBIT_SIZE_SCOPE("SamplingProfiler");
    archive(Capture::GSamplingProfiler);
  }

  {
    ORBIT_SIZE_SCOPE("String manager");
    archive(*time_graph_->GetStringManager());
  }

  {
    ORBIT_SIZE_SCOPE("Event Buffer");
    archive(GEventTracer.GetEventBuffer());
  }

  // Timers
  int numWrites = 0;
  std::vector<std::shared_ptr<TimerChain>> chains =
      time_graph_->GetAllTimerChains();
  for (auto& chain : chains) {
    if (!chain) continue;
    for (TimerChainIterator& it = chain->begin(); it != chain->end(); ++it) {
      TimerBlock& block = *it;
      for (int k = 0; k < block.size(); ++k) {
        archive(cereal::binary_data(&(block[k].GetTimer()), sizeof(Timer)));

        if (++numWrites > m_NumTimers) {
          return;
        }
      }
    }
  }
}

//-----------------------------------------------------------------------------
outcome::result<void, std::string> CaptureSerializer::Load(
    const std::string& filename) {
  SCOPE_TIMER_LOG(absl::StrFormat("Loading capture from \"%s\"", filename));

  // Binary
  std::ifstream file(filename, std::ios::binary);
  if (file.fail()) {
    ERROR("Loading capture from \"%s\": %s", filename, "file.fail()");
    return outcome::failure("Error opening the file for reading");
  }

  try {
    // Header
    cereal::BinaryInputArchive archive(file);
    archive(*this);

    // Functions
    std::vector<Function> functions;
    archive(functions);
    Capture::GSelectedFunctions.clear();
    Capture::GSelectedFunctionsMap.clear();
    for (const auto& function : functions) {
      std::shared_ptr<Function> function_ptr =
          std::make_shared<Function>(function);
      Capture::GSelectedFunctions.push_back(function_ptr);
      Capture::GSelectedFunctionsMap[function_ptr->GetVirtualAddress()] =
          function_ptr.get();
    }
    Capture::GVisibleFunctionsMap = Capture::GSelectedFunctionsMap;

    archive(Capture::GFunctionCountMap);

    archive(Capture::GCallstacks);

    archive(Capture::GAddressInfos);

    archive(Capture::GAddressToFunctionName);

    archive(Capture::GSamplingProfiler);
    if (Capture::GSamplingProfiler == nullptr) {
      Capture::GSamplingProfiler = std::make_shared<SamplingProfiler>();
    }
    Capture::GSamplingProfiler->SortByThreadUsage();

    time_graph_->Clear();

    archive(*time_graph_->GetStringManager());

    // Event buffer
    archive(GEventTracer.GetEventBuffer());

    // Timers
    Timer timer;
    while (file.read(reinterpret_cast<char*>(&timer), sizeof(Timer))) {
      time_graph_->ProcessTimer(timer);
    }

    GOrbitApp->AddSamplingReport(Capture::GSamplingProfiler);
    GOrbitApp->FireRefreshCallbacks();
    return outcome::success();

  } catch (std::exception& e) {
    ERROR("Loading capture from \"%s\": %s", filename, e.what());
    return outcome::failure("Error parsing the capture");
  }
}

//-----------------------------------------------------------------------------
ORBIT_SERIALIZE(CaptureSerializer, 0) {
  ORBIT_NVP_VAL(0, m_CaptureName);
  ORBIT_NVP_VAL(0, m_Version);
  ORBIT_NVP_VAL(0, m_TimerVersion);
  ORBIT_NVP_VAL(0, m_NumTimers);
  ORBIT_NVP_VAL(0, m_SizeOfTimer);
}
<|endoftext|>


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

#include "highwayhash/arch_specific.h"

#include <stdint.h>

#if HH_ARCH_X64 && !HH_MSC_VERSION
#include <cpuid.h>
#endif

#if HH_ARCH_PPC
#include <sys/platform/ppc.h>  // __ppc_get_timebase_freq
#endif

#include <string.h>  // memcpy
#include <string>

namespace highwayhash {

const char* TargetName(const TargetBits target_bit) {
  switch (target_bit) {
    case HH_TARGET_Portable:
      return "Portable";
    case HH_TARGET_SSE41:
      return "SSE41";
    case HH_TARGET_AVX2:
      return "AVX2";
    case HH_TARGET_VSX:
      return "VSX";
    case HH_TARGET_NEON:
      return "NEON";
    default:
      return nullptr;  // zero, multiple, or unknown bits
  }
}

#if HH_ARCH_X64

namespace {

std::string BrandString() {
  char brand_string[49];
  uint32_t abcd[4];

  // Check if brand string is supported (it is on all reasonable Intel/AMD)
  Cpuid(0x80000000U, 0, abcd);
  if (abcd[0] < 0x80000004U) {
    return std::string();
  }

  for (int i = 0; i < 3; ++i) {
    Cpuid(0x80000002U + i, 0, abcd);
    memcpy(brand_string + i * 16, &abcd, sizeof(abcd));
  }
  brand_string[48] = 0;
  return brand_string;
}

}  // namespace

void Cpuid(const uint32_t level, const uint32_t count,
           uint32_t* HH_RESTRICT abcd) {
#if HH_MSC_VERSION
  int regs[4];
  __cpuidex(regs, level, count);
  for (int i = 0; i < 4; ++i) {
    abcd[i] = regs[i];
  }
#else
  uint32_t a, b, c, d;
  __cpuid_count(level, count, a, b, c, d);
  abcd[0] = a;
  abcd[1] = b;
  abcd[2] = c;
  abcd[3] = d;
#endif
}

uint32_t ApicId() {
  uint32_t abcd[4];
  Cpuid(1, 0, abcd);
  return abcd[1] >> 24;  // ebx
}

#endif  // HH_ARCH_X64

namespace {

double DetectNominalClockRate() {
#if HH_ARCH_X64
  const std::string& brand_string = BrandString();
  // Brand strings include the maximum configured frequency. These prefixes are
  // defined by Intel CPUID documentation.
  const char* prefixes[3] = {"MHz", "GHz", "THz"};
  const double multipliers[3] = {1E6, 1E9, 1E12};
  for (size_t i = 0; i < 3; ++i) {
    const size_t pos_prefix = brand_string.find(prefixes[i]);
    if (pos_prefix != std::string::npos) {
      const size_t pos_space = brand_string.rfind(' ', pos_prefix - 1);
      if (pos_space != std::string::npos) {
        const std::string digits =
            brand_string.substr(pos_space + 1, pos_prefix - pos_space - 1);
        return std::stod(digits) * multipliers[i];
      }
    }
  }
#elif HH_ARCH_PPC
  double freq = -1;
  char line[200];
  char* s;
  char* value;

  FILE* f = fopen("/proc/cpuinfo", "r");
  if (f != nullptr) {
    while (fgets(line, sizeof(line), f) != nullptr) {
      // NOTE: the ':' is the only character we can rely on
      if (!(value = strchr(line, ':'))) continue;
      // terminate the valuename
      *value++ = '\0';
      // skip any leading spaces
      while (*value == ' ') value++;
      if ((s = strchr(value, '\n'))) *s = '\0';

      if (!strncasecmp(line, "clock", strlen("clock")) &&
          sscanf(value, "%lf", &freq) == 1) {
        freq *= 1E6;
        break;
      }
    }
    fclose(f);
    return freq;
  }
#endif

  return 0.0;
}

}  // namespace

double NominalClockRate() {
  // Thread-safe caching - this is called several times.
  static const double cycles_per_second = DetectNominalClockRate();
  return cycles_per_second;
}

double InvariantTicksPerSecond() {
#if HH_ARCH_PPC
  static const double cycles_per_second = __ppc_get_timebase_freq();
  return cycles_per_second;
#else
  return NominalClockRate();
#endif
}

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

#include "highwayhash/arch_specific.h"

#include <stdint.h>

#if HH_ARCH_X64 && !HH_MSC_VERSION
#include <cpuid.h>
#endif

#if HH_ARCH_PPC
#if __GLIBC__
#include <sys/platform/ppc.h>  // __ppc_get_timebase_freq
#elif __FreeBSD__
#include <sys/types.h>
#include <sys/sysctl.h>
#endif

#include <string.h>  // memcpy
#include <string>

namespace highwayhash {

const char* TargetName(const TargetBits target_bit) {
  switch (target_bit) {
    case HH_TARGET_Portable:
      return "Portable";
    case HH_TARGET_SSE41:
      return "SSE41";
    case HH_TARGET_AVX2:
      return "AVX2";
    case HH_TARGET_VSX:
      return "VSX";
    case HH_TARGET_NEON:
      return "NEON";
    default:
      return nullptr;  // zero, multiple, or unknown bits
  }
}

#if HH_ARCH_X64

namespace {

std::string BrandString() {
  char brand_string[49];
  uint32_t abcd[4];

  // Check if brand string is supported (it is on all reasonable Intel/AMD)
  Cpuid(0x80000000U, 0, abcd);
  if (abcd[0] < 0x80000004U) {
    return std::string();
  }

  for (int i = 0; i < 3; ++i) {
    Cpuid(0x80000002U + i, 0, abcd);
    memcpy(brand_string + i * 16, &abcd, sizeof(abcd));
  }
  brand_string[48] = 0;
  return brand_string;
}

}  // namespace

void Cpuid(const uint32_t level, const uint32_t count,
           uint32_t* HH_RESTRICT abcd) {
#if HH_MSC_VERSION
  int regs[4];
  __cpuidex(regs, level, count);
  for (int i = 0; i < 4; ++i) {
    abcd[i] = regs[i];
  }
#else
  uint32_t a, b, c, d;
  __cpuid_count(level, count, a, b, c, d);
  abcd[0] = a;
  abcd[1] = b;
  abcd[2] = c;
  abcd[3] = d;
#endif
}

uint32_t ApicId() {
  uint32_t abcd[4];
  Cpuid(1, 0, abcd);
  return abcd[1] >> 24;  // ebx
}

#endif  // HH_ARCH_X64

namespace {

double DetectNominalClockRate() {
#if HH_ARCH_X64
  const std::string& brand_string = BrandString();
  // Brand strings include the maximum configured frequency. These prefixes are
  // defined by Intel CPUID documentation.
  const char* prefixes[3] = {"MHz", "GHz", "THz"};
  const double multipliers[3] = {1E6, 1E9, 1E12};
  for (size_t i = 0; i < 3; ++i) {
    const size_t pos_prefix = brand_string.find(prefixes[i]);
    if (pos_prefix != std::string::npos) {
      const size_t pos_space = brand_string.rfind(' ', pos_prefix - 1);
      if (pos_space != std::string::npos) {
        const std::string digits =
            brand_string.substr(pos_space + 1, pos_prefix - pos_space - 1);
        return std::stod(digits) * multipliers[i];
      }
    }
  }
#elif HH_ARCH_PPC
  double freq = -1;
#if __linux__
  char line[200];
  char* s;
  char* value;

  FILE* f = fopen("/proc/cpuinfo", "r");
  if (f != nullptr) {
    while (fgets(line, sizeof(line), f) != nullptr) {
      // NOTE: the ':' is the only character we can rely on
      if (!(value = strchr(line, ':'))) continue;
      // terminate the valuename
      *value++ = '\0';
      // skip any leading spaces
      while (*value == ' ') value++;
      if ((s = strchr(value, '\n'))) *s = '\0';

      if (!strncasecmp(line, "clock", strlen("clock")) &&
          sscanf(value, "%lf", &freq) == 1) {
        freq *= 1E6;
        break;
      }
    }
    fclose(f);
    return freq;
  }
 #elif __FreeBSD__
  size_t length = sizeof(freq);
  sysctlbyname("dev.cpu.0.freq"), &freq, &length, NULL, 0);
  freq *= 1E6;
  return freq;
#endif
#endif

  return 0.0;
}

}  // namespace

double NominalClockRate() {
  // Thread-safe caching - this is called several times.
  static const double cycles_per_second = DetectNominalClockRate();
  return cycles_per_second;
}

double InvariantTicksPerSecond() {
#if HH_ARCH_PPC
#if __GLIBC__
  static const double cycles_per_second = __ppc_get_timebase_freq();
#elif __FreeBSD__
  static double cycles_per_second = 0;
  size_t length = sizeof(cycles_per_second);
  sysctlbyname("kern.timecounter.tc.timebase.frequency", &cycles_per_second, &length, NULL, 0);
#endif
  return cycles_per_second;
#else
  return NominalClockRate();
#endif
}

}  // namespace highwayhash
<|endoftext|>


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

#include "browser/ui/file_dialog.h"

#include "base/callback.h"
#include "base/file_util.h"
#include "browser/native_window.h"
#include "browser/ui/gtk/gtk_util.h"
#include "ui/base/gtk/gtk_signal.h"

namespace file_dialog {

namespace {

class FileChooserDialog {
 public:
  FileChooserDialog(GtkFileChooserAction action,
                    atom::NativeWindow* parent_window,
                    const std::string& title,
                    const base::FilePath& default_path) {
    GtkWindow* window = parent_window ? parent_window->GetNativeWindow() : NULL;
    dialog_ = gtk_file_chooser_dialog_new(
        title.c_str(),
        window,
        action,
        GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
        GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT,
        NULL);

    if (action == GTK_FILE_CHOOSER_ACTION_SAVE)
      gtk_file_chooser_set_do_overwrite_confirmation(GTK_FILE_CHOOSER(dialog_),
                                                     TRUE);
    if (action != GTK_FILE_CHOOSER_ACTION_OPEN)
      gtk_file_chooser_set_create_folders(GTK_FILE_CHOOSER(dialog_), TRUE);

    // Set window-to-parent modality by adding the dialog to the same window
    // group as the parent.
    gtk_window_group_add_window(gtk_window_get_group(window),
                                GTK_WINDOW(dialog_));
    gtk_window_set_modal(GTK_WINDOW(dialog_), TRUE);

    if (!default_path.empty()) {
      if (base::DirectoryExists(default_path))
        gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog_),
                                            default_path.value().c_str());
      else
        gtk_file_chooser_set_filename(GTK_FILE_CHOOSER(dialog_),
                                      default_path.value().c_str());
    }
  }

  virtual ~FileChooserDialog() {
    gtk_widget_destroy(dialog_);
  }

  void RunSaveAsynchronous(const SaveDialogCallback& callback) {
    save_callback_ = callback;
    g_signal_connect(dialog_, "delete-event",
                     G_CALLBACK(gtk_widget_hide_on_delete), NULL);
    g_signal_connect(dialog_, "response",
                     G_CALLBACK(OnFileSaveDialogResponseThunk), this);
    gtk_widget_show_all(dialog_);
  }

  base::FilePath GetFileName() const {
    gchar* filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog_));
    base::FilePath path(filename);
    g_free(filename);
    return path;
  }

  CHROMEGTK_CALLBACK_1(FileChooserDialog, void,
                       OnFileSaveDialogResponse, int);

  GtkWidget* dialog() const { return dialog_; }

 private:
  GtkWidget* dialog_;

  SaveDialogCallback save_callback_;
  OpenDialogCallback open_callback_;

  DISALLOW_COPY_AND_ASSIGN(FileChooserDialog);
};

void FileChooserDialog::OnFileSaveDialogResponse(GtkWidget* widget,
                                                 int response) {
  gtk_widget_hide_all(dialog_);

  if (response == GTK_RESPONSE_ACCEPT)
    save_callback_.Run(true, GetFileName());
  else
    save_callback_.Run(false, base::FilePath());
  delete this;
}

}  // namespace

bool ShowOpenDialog(atom::NativeWindow* parent_window,
                    const std::string& title,
                    const base::FilePath& default_path,
                    int properties,
                    std::vector<base::FilePath>* paths) {
  return false;
}

void ShowOpenDialog(atom::NativeWindow* parent_window,
                    const std::string& title,
                    const base::FilePath& default_path,
                    int properties,
                    const OpenDialogCallback& callback) {
  callback.Run(false, std::vector<base::FilePath>());
}

bool ShowSaveDialog(atom::NativeWindow* parent_window,
                    const std::string& title,
                    const base::FilePath& default_path,
                    base::FilePath* path) {
  FileChooserDialog save_dialog(
      GTK_FILE_CHOOSER_ACTION_SAVE, parent_window, title, default_path);
  gtk_widget_show_all(save_dialog.dialog());
  int response = gtk_dialog_run(GTK_DIALOG(save_dialog.dialog()));
  if (response == GTK_RESPONSE_ACCEPT) {
    *path = save_dialog.GetFileName();
    return true;
  } else {
    return false;
  }
}

void ShowSaveDialog(atom::NativeWindow* parent_window,
                    const std::string& title,
                    const base::FilePath& default_path,
                    const SaveDialogCallback& callback) {
  FileChooserDialog* dialog = new FileChooserDialog(
      GTK_FILE_CHOOSER_ACTION_SAVE, parent_window, title, default_path);
  dialog->RunSaveAsynchronous(callback);
}

}  // namespace file_dialog
<commit_msg>gtk: Add file open dialog.<commit_after>// Copyright (c) 2014 GitHub, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "browser/ui/file_dialog.h"

#include "base/callback.h"
#include "base/file_util.h"
#include "browser/native_window.h"
#include "browser/ui/gtk/gtk_util.h"
#include "ui/base/gtk/gtk_signal.h"

namespace file_dialog {

namespace {

class FileChooserDialog {
 public:
  FileChooserDialog(GtkFileChooserAction action,
                    atom::NativeWindow* parent_window,
                    const std::string& title,
                    const base::FilePath& default_path) {
    const char* confirm_text = GTK_STOCK_OK;
    if (action == GTK_FILE_CHOOSER_ACTION_SAVE)
      confirm_text = GTK_STOCK_SAVE;
    else if (action == GTK_FILE_CHOOSER_ACTION_OPEN)
      confirm_text = GTK_STOCK_OPEN;

    GtkWindow* window = parent_window ? parent_window->GetNativeWindow() : NULL;
    dialog_ = gtk_file_chooser_dialog_new(
        title.c_str(),
        window,
        action,
        GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
        confirm_text, GTK_RESPONSE_ACCEPT,
        NULL);

    if (action == GTK_FILE_CHOOSER_ACTION_SAVE)
      gtk_file_chooser_set_do_overwrite_confirmation(GTK_FILE_CHOOSER(dialog_),
                                                     TRUE);
    if (action != GTK_FILE_CHOOSER_ACTION_OPEN)
      gtk_file_chooser_set_create_folders(GTK_FILE_CHOOSER(dialog_), TRUE);

    // Set window-to-parent modality by adding the dialog to the same window
    // group as the parent.
    gtk_window_group_add_window(gtk_window_get_group(window),
                                GTK_WINDOW(dialog_));
    gtk_window_set_modal(GTK_WINDOW(dialog_), TRUE);

    if (!default_path.empty()) {
      if (base::DirectoryExists(default_path))
        gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog_),
                                            default_path.value().c_str());
      else
        gtk_file_chooser_set_filename(GTK_FILE_CHOOSER(dialog_),
                                      default_path.value().c_str());
    }
  }

  virtual ~FileChooserDialog() {
    gtk_widget_destroy(dialog_);
  }

  void RunAsynchronous() {
    g_signal_connect(dialog_, "delete-event",
                     G_CALLBACK(gtk_widget_hide_on_delete), NULL);
    g_signal_connect(dialog_, "response",
                     G_CALLBACK(OnFileDialogResponseThunk), this);
    gtk_widget_show_all(dialog_);
  }

  void RunSaveAsynchronous(const SaveDialogCallback& callback) {
    save_callback_ = callback;
    RunAsynchronous();
  }

  void RunOpenAsynchronous(const OpenDialogCallback& callback) {
    open_callback_ = callback;
    RunAsynchronous();
  }

  base::FilePath GetFileName() const {
    gchar* filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog_));
    base::FilePath path(filename);
    g_free(filename);
    return path;
  }

  std::vector<base::FilePath> GetFileNames() const {
    std::vector<base::FilePath> paths;
    GSList* filenames = gtk_file_chooser_get_filenames(
        GTK_FILE_CHOOSER(dialog_));
    for (GSList* iter = filenames; iter != NULL; iter = g_slist_next(iter)) {
      base::FilePath path(static_cast<char*>(iter->data));
      g_free(iter->data);
      paths.push_back(path);
    }
    g_slist_free(filenames);
    return paths;
  }

  CHROMEGTK_CALLBACK_1(FileChooserDialog, void, OnFileDialogResponse, int);

  GtkWidget* dialog() const { return dialog_; }

 private:
  GtkWidget* dialog_;

  SaveDialogCallback save_callback_;
  OpenDialogCallback open_callback_;

  DISALLOW_COPY_AND_ASSIGN(FileChooserDialog);
};

void FileChooserDialog::OnFileDialogResponse(GtkWidget* widget, int response) {
  gtk_widget_hide_all(dialog_);

  if (!save_callback_.is_null()) {
    if (response == GTK_RESPONSE_ACCEPT)
      save_callback_.Run(true, GetFileName());
    else
      save_callback_.Run(false, base::FilePath());
  } else if (!open_callback_.is_null()) {
    if (response == GTK_RESPONSE_ACCEPT)
      open_callback_.Run(true, GetFileNames());
    else
      open_callback_.Run(false, std::vector<base::FilePath>());
  }
  delete this;
}

}  // namespace

bool ShowOpenDialog(atom::NativeWindow* parent_window,
                    const std::string& title,
                    const base::FilePath& default_path,
                    int properties,
                    std::vector<base::FilePath>* paths) {
  return false;
}

void ShowOpenDialog(atom::NativeWindow* parent_window,
                    const std::string& title,
                    const base::FilePath& default_path,
                    int properties,
                    const OpenDialogCallback& callback) {
  GtkFileChooserAction action = GTK_FILE_CHOOSER_ACTION_OPEN;
  if (properties & FILE_DIALOG_OPEN_DIRECTORY)
    action = GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER;
  FileChooserDialog* open_dialog = new FileChooserDialog(
      action, parent_window, title, default_path);
  if (properties & FILE_DIALOG_MULTI_SELECTIONS)
    gtk_file_chooser_set_select_multiple(
        GTK_FILE_CHOOSER(open_dialog->dialog()), TRUE);

  open_dialog->RunOpenAsynchronous(callback);
}

bool ShowSaveDialog(atom::NativeWindow* parent_window,
                    const std::string& title,
                    const base::FilePath& default_path,
                    base::FilePath* path) {
  FileChooserDialog save_dialog(
      GTK_FILE_CHOOSER_ACTION_SAVE, parent_window, title, default_path);
  gtk_widget_show_all(save_dialog.dialog());
  int response = gtk_dialog_run(GTK_DIALOG(save_dialog.dialog()));
  if (response == GTK_RESPONSE_ACCEPT) {
    *path = save_dialog.GetFileName();
    return true;
  } else {
    return false;
  }
}

void ShowSaveDialog(atom::NativeWindow* parent_window,
                    const std::string& title,
                    const base::FilePath& default_path,
                    const SaveDialogCallback& callback) {
  FileChooserDialog* save_dialog = new FileChooserDialog(
      GTK_FILE_CHOOSER_ACTION_SAVE, parent_window, title, default_path);
  save_dialog->RunSaveAsynchronous(callback);
}

}  // namespace file_dialog
<|endoftext|>


<commit_before>/***************************************************
  This is a library for the HDC1000 Humidity & Temp Sensor

  Designed specifically to work with the HDC1008 sensor from Adafruit
  ----> https://www.adafruit.com/products/2635

  These sensors use I2C to communicate, 2 pins are required to
  interface
  Adafruit invests time and resources providing this open source code,
  please support Adafruit and open-source hardware by purchasing
  products from Adafruit!

  Written by Limor Fried/Ladyada for Adafruit Industries.
  BSD license, all text above must be included in any redistribution

  Modified for Photon  needs application.h for types  RMB
 ****************************************************/
#include "application.h"
#include "Adafruit_HDC1000/Adafruit_HDC1000.h"

Adafruit_HDC1000::Adafruit_HDC1000() {
}

boolean Adafruit_HDC1000::begin(uint8_t addr) {
  _i2caddr = addr;

  Wire.begin();

  reset();
  if (read16(HDC1000_MANUFID) != 0x5449) return false;
  if (read16(HDC1000_DEVICEID) != 0x1000) return false;
  return true;
}

void Adafruit_HDC1000::reset(void) {
  // reset,combined temp/humidity measurement,and select 14 bit temp & humidity resolution
  uint16_t config = HDC1000_CONFIG_RST | HDC1000_CONFIG_MODE | HDC1000_CONFIG_TRES_14 | HDC1000_CONFIG_HRES_14;

  Wire.beginTransmission(_i2caddr);
  Wire.write(HDC1000_CONFIG);   // set pointer register to configuration register   RMB
  Wire.write(config>>8);        // now write out 2 bytes MSB first    RMB
  Wire.write(config&0xFF);
  Wire.endTransmission();
  delay(15);
}

float Adafruit_HDC1000::readTemperature(void) {

  float temp = (read32(HDC1000_TEMP, 20) >> 16);
  temp /= 65536;
  temp *= 165;
  temp -= 40;

  return temp;
}

float Adafruit_HDC1000::readHumidity(void) {
  // reads both temp and humidity but masks out temp in highest 16 bits
  // originally used hum but humidity declared in private section of class
  float humidity = (read32(HDC1000_TEMP, 20) & 0xFFFF);

  humidity /= 65536;
  humidity *= 100;

  return humidity;
}

void Adafruit_HDC1000::ReadTempHumidity(void) {
  // HDC1008 setup to measure both temperature and humidity in one conversion
  // this is a different way to access data in ONE read
  // this sets internal private variables that can be accessed by Get() functions

  uint32_t rt,rh ;  // working variables

  rt = read32(HDC1000_TEMP, 20);    // get temp and humidity reading together
  rh = rt;                          // save a copy for humidity processing

  float (temp = (rt >> 16));        // convert to temp first
  temp /= 65536;
  temp *= 165;
  temp -= 40;

  float (humidity = (rh & 0xFFFF));   // now convert to humidity
  humidity /= 65536;
  humidity *= 100;
}

float Adafruit_HDC1000::GetTemperature(void) {
  // getter function to access private temp variable

  return temp ;
}

float Adafruit_HDC1000::GetHumidity(void) {
  // getter function to access private humidity variable

  return humidity ;
}

// Add ability to test battery voltage, useful in remote monitoring, TRUE if <2.8V
// usually called after Temp/Humid reading  RMB
// Thanks to KFricke for micropython-hdc1008 example on GitHub
boolean Adafruit_HDC1000::batteryLOW(void)  {

  uint16_t battLOW = (read16(HDC1000_CONFIG_BATT, 20));

  battLOW &= HDC1000_CONFIG_BATT;   // mask off other bits, bit 11 will be 1 if voltage < 2.8V

  if (battLOW> 0) return true;
  return  false;
}

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

uint16_t Adafruit_HDC1000::read16(uint8_t a, uint8_t d) {
  Wire.beginTransmission(_i2caddr);
  Wire.write(a);
  Wire.endTransmission();
  delay(d);
  Wire.requestFrom((uint8_t)_i2caddr, (uint8_t)2);
  uint16_t r = Wire.read();
  r <<= 8;
  r |= Wire.read();
  //Serial.println(r, HEX);
  return r;
}

uint32_t Adafruit_HDC1000::read32(uint8_t a, uint8_t d) {
  Wire.beginTransmission(_i2caddr);
  Wire.write(a);
  Wire.endTransmission();
  // delay was hardcoded as 50, should use d   RMB
  delay(d);
  Wire.requestFrom((uint8_t)_i2caddr, (uint8_t)4);
  uint32_t r = Wire.read();
  // assembles temp into highest 16 bits, humidity into lowest 16 bits
  r <<= 8;
  r |= Wire.read();
  r <<= 8;
  r |= Wire.read();
  r <<= 8;
  r |= Wire.read();
  //Serial.println(r, HEX);
  return r;
}
<commit_msg>parentheses important in float cast of private var<commit_after>/***************************************************
  This is a library for the HDC1000 Humidity & Temp Sensor

  Designed specifically to work with the HDC1008 sensor from Adafruit
  ----> https://www.adafruit.com/products/2635

  These sensors use I2C to communicate, 2 pins are required to
  interface
  Adafruit invests time and resources providing this open source code,
  please support Adafruit and open-source hardware by purchasing
  products from Adafruit!

  Written by Limor Fried/Ladyada for Adafruit Industries.
  BSD license, all text above must be included in any redistribution

  Modified for Photon  needs application.h for types  RMB
 ****************************************************/
#include "application.h"
#include "Adafruit_HDC1000/Adafruit_HDC1000.h"

Adafruit_HDC1000::Adafruit_HDC1000() {
}

boolean Adafruit_HDC1000::begin(uint8_t addr) {
  _i2caddr = addr;

  Wire.begin();

  reset();
  if (read16(HDC1000_MANUFID) != 0x5449) return false;
  if (read16(HDC1000_DEVICEID) != 0x1000) return false;
  return true;
}

void Adafruit_HDC1000::reset(void) {
  // reset,combined temp/humidity measurement,and select 14 bit temp & humidity resolution
  uint16_t config = HDC1000_CONFIG_RST | HDC1000_CONFIG_MODE | HDC1000_CONFIG_TRES_14 | HDC1000_CONFIG_HRES_14;

  Wire.beginTransmission(_i2caddr);
  Wire.write(HDC1000_CONFIG);   // set pointer register to configuration register   RMB
  Wire.write(config>>8);        // now write out 2 bytes MSB first    RMB
  Wire.write(config&0xFF);
  Wire.endTransmission();
  delay(15);
}

float Adafruit_HDC1000::readTemperature(void) {

  float temp = (read32(HDC1000_TEMP, 20) >> 16);
  temp /= 65536;
  temp *= 165;
  temp -= 40;

  return temp;
}

float Adafruit_HDC1000::readHumidity(void) {
  // reads both temp and humidity but masks out temp in highest 16 bits
  // originally used hum but humidity declared in private section of class
  float humidity = (read32(HDC1000_TEMP, 20) & 0xFFFF);

  humidity /= 65536;
  humidity *= 100;

  return humidity;
}

void Adafruit_HDC1000::ReadTempHumidity(void) {
  // HDC1008 setup to measure both temperature and humidity in one conversion
  // this is a different way to access data in ONE read
  // this sets internal private variables that can be accessed by Get() functions

  uint32_t rt,rh ;  // working variables

  rt = read32(HDC1000_TEMP, 20);    // get temp and humidity reading together
  rh = rt;                          // save a copy for humidity processing

  // important to use ( ) around temp so private variable accessed and float cast done
  float (temp = (rt >> 16));        // convert to temp first
  temp /= 65536;
  temp *= 165;
  temp -= 40;

  // important to use ( ) around humidity so private variable accessed and float cast done
  float (humidity = (rh & 0xFFFF));   // now convert to humidity
  humidity /= 65536;
  humidity *= 100;
}

float Adafruit_HDC1000::GetTemperature(void) {
  // getter function to access private temp variable

  return temp ;
}

float Adafruit_HDC1000::GetHumidity(void) {
  // getter function to access private humidity variable

  return humidity ;
}

// Add ability to test battery voltage, useful in remote monitoring, TRUE if <2.8V
// usually called after Temp/Humid reading  RMB
// Thanks to KFricke for micropython-hdc1008 example on GitHub
boolean Adafruit_HDC1000::batteryLOW(void)  {

  uint16_t battLOW = (read16(HDC1000_CONFIG_BATT, 20));

  battLOW &= HDC1000_CONFIG_BATT;   // mask off other bits, bit 11 will be 1 if voltage < 2.8V

  if (battLOW> 0) return true;
  return  false;
}

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

uint16_t Adafruit_HDC1000::read16(uint8_t a, uint8_t d) {
  Wire.beginTransmission(_i2caddr);
  Wire.write(a);
  Wire.endTransmission();
  delay(d);
  Wire.requestFrom((uint8_t)_i2caddr, (uint8_t)2);
  uint16_t r = Wire.read();
  r <<= 8;
  r |= Wire.read();
  //Serial.println(r, HEX);
  return r;
}

uint32_t Adafruit_HDC1000::read32(uint8_t a, uint8_t d) {
  Wire.beginTransmission(_i2caddr);
  Wire.write(a);
  Wire.endTransmission();
  // delay was hardcoded as 50, should use d   RMB
  delay(d);
  Wire.requestFrom((uint8_t)_i2caddr, (uint8_t)4);
  uint32_t r = Wire.read();
  // assembles temp into highest 16 bits, humidity into lowest 16 bits
  r <<= 8;
  r |= Wire.read();
  r <<= 8;
  r |= Wire.read();
  r <<= 8;
  r |= Wire.read();
  //Serial.println(r, HEX);
  return r;
}
<|endoftext|>


<commit_before>#include <cassert>
#include <cstdio>
#include <memory>

#include "dxutil.h"
#include "renderer.h"
#include "camera.h"

#include <shellapi.h> // must be after windows.h
#include <ShellScalingApi.h>

#pragma comment(lib, "d3d11.lib")
#pragma comment(lib, "dxgi.lib")
#pragma comment(lib, "ninput.lib")
#pragma comment(lib, "shcore.lib")

// Constants
static const int kSwapChainBufferCount = 3;
static const DXGI_FORMAT kSwapChainFormat = DXGI_FORMAT_B8G8R8A8_UNORM;
static const int kUpdateFrequency = 60;

// Globals
HWND ghWnd;
bool gShouldClose;
ComPtr<IDXGISwapChain> gpSwapChain;
ComPtr<ID3D11Device> gpDevice;
ComPtr<ID3D11DeviceContext> gpDeviceContext;
std::unique_ptr<Renderer> gpRenderer;
OrbitCamera gCamera;
UINT64 gPerformanceFrequency;
UINT64 gLastFrameTicks;
UINT64 gAccumulatedFrameTicks;
double gRenderScale;
int gWindowWidth = 1280;
int gWindowHeight = 720;
int gRenderWidth;
int gRenderHeight;

void InitApp()
{
    LARGE_INTEGER performanceFrequency, firstFrameTicks;
    CHECK_WIN32(QueryPerformanceFrequency(&performanceFrequency));
    CHECK_WIN32(QueryPerformanceCounter(&firstFrameTicks));
    gPerformanceFrequency = performanceFrequency.QuadPart;
    gLastFrameTicks = firstFrameTicks.QuadPart;
    gAccumulatedFrameTicks = 0;

    gpRenderer = std::make_unique<Renderer>(gpDevice.Get(), gpDeviceContext.Get());
    gpRenderer->Init();

#define SIM_ORBIT_RADIUS 50.f
#define SIM_DISC_RADIUS  12.f
    auto center = DirectX::XMVectorSet(0.0f, 0.4f*SIM_DISC_RADIUS, 0.0f, 0.0f);
    auto radius = 15.0f;
    auto minRadius = SIM_ORBIT_RADIUS - 3.25f * SIM_DISC_RADIUS;
    auto maxRadius = SIM_ORBIT_RADIUS + 3.0f * SIM_DISC_RADIUS;
    auto longAngle = 4.50f;
    auto latAngle = 1.45f;
    gCamera.View(center, radius, minRadius, maxRadius, longAngle, latAngle);
}

void ResizeApp(int width, int height)
{
    CHECK_HR(gpSwapChain->ResizeBuffers(kSwapChainBufferCount, width, height, kSwapChainFormat, 0));

    gpRenderer->Resize(width, height);

    float aspect = (float)gRenderWidth / gRenderHeight;
    gCamera.Projection(DirectX::XM_PIDIV2 * 0.8f * 3 / 2, aspect);
}

void UpdateApp()
{
    gCamera.ProcessInertia();

    LARGE_INTEGER currFrameTicks;
    CHECK_WIN32(QueryPerformanceCounter(&currFrameTicks));

    UINT64 deltaTicks = currFrameTicks.QuadPart - gLastFrameTicks;
    gAccumulatedFrameTicks += deltaTicks;

    const UINT64 kMillisecondsPerUpdate = 1000 / kUpdateFrequency;
    const UINT64 kTicksPerMillisecond = gPerformanceFrequency / 1000;
    const UINT64 kTicksPerUpdate = kMillisecondsPerUpdate * kTicksPerMillisecond;

    while (gAccumulatedFrameTicks >= kTicksPerUpdate)
    {
        gpRenderer->Update(kMillisecondsPerUpdate);
        gAccumulatedFrameTicks -= kTicksPerUpdate;
    }

    gLastFrameTicks = currFrameTicks.QuadPart;
}

void RenderApp()
{
    ComPtr<ID3D11Texture2D> pBackBuffer;
    CHECK_HR(gpSwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer)));

    D3D11_RENDER_TARGET_VIEW_DESC rtvDesc{};
    rtvDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM_SRGB;
    rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
    ComPtr<ID3D11RenderTargetView> pBackBufferRTV;
    CHECK_HR(gpDevice->CreateRenderTargetView(pBackBuffer.Get(), &rtvDesc, &pBackBufferRTV));

    gpRenderer->RenderFrame(pBackBufferRTV.Get(), gCamera);
}

// Event handler
LRESULT CALLBACK MyWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
    case WM_CLOSE:
        gShouldClose = true;
        return 0;
    case WM_SIZE: {
        UINT ww = LOWORD(lParam);
        UINT wh = HIWORD(lParam);

        // Ignore resizing to minimized
        if (ww == 0 || wh == 0) return 0;

        gWindowWidth = (int)ww;
        gWindowHeight = (int)wh;
        gRenderWidth = (UINT)(double(gWindowWidth)  * gRenderScale);
        gRenderHeight = (UINT)(double(gWindowHeight) * gRenderScale);

        // Update camera projection
        float aspect = (float)gRenderWidth / (float)gRenderHeight;
        gCamera.Projection(DirectX::XM_PIDIV2 * 0.8f * 3 / 2, aspect);

        ResizeApp(gRenderWidth, gRenderHeight);

        return 0;
    }
    case WM_MOUSEWHEEL: {
        auto delta = GET_WHEEL_DELTA_WPARAM(wParam);
        gCamera.ZoomRadius(-0.07f * delta);
        return 0;
    }
    case WM_POINTERDOWN:
    case WM_POINTERUPDATE:
    case WM_POINTERUP: {
        auto pointerId = GET_POINTERID_WPARAM(wParam);
        POINTER_INFO pointerInfo;
        if (GetPointerInfo(pointerId, &pointerInfo)) {
            if (message == WM_POINTERDOWN) {

                // Compute pointer position in render units
                POINT p = pointerInfo.ptPixelLocation;
                ScreenToClient(hWnd, &p);

                RECT clientRect;
                GetClientRect(hWnd, &clientRect);
                p.x = p.x * gRenderWidth / (clientRect.right - clientRect.left);
                p.y = p.y * gRenderHeight / (clientRect.bottom - clientRect.top);

                gCamera.AddPointer(pointerId);
            }

            // Otherwise send it to the camera controls
            gCamera.ProcessPointerFrames(pointerId, &pointerInfo);
            if (message == WM_POINTERUP) gCamera.RemovePointer(pointerId);
        }
        return 0;
    }
    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
    }
}

UINT SetupDPI()
{
    // Just do system DPI awareness for now for simplicity... scale the 3D content
    SetProcessDpiAwareness(PROCESS_SYSTEM_DPI_AWARE);

    UINT dpiX = 0, dpiY;
    POINT pt = { 1, 1 };
    auto hMonitor = MonitorFromPoint(pt, MONITOR_DEFAULTTONEAREST);
    if (SUCCEEDED(GetDpiForMonitor(hMonitor, MDT_EFFECTIVE_DPI, &dpiX, &dpiY))) {
        return dpiX;
    }
    else {
        return 96; // default
    }
}

int main()
{
    UINT dpi = SetupDPI();

    gRenderScale = 96.0 / double(dpi);

    // Scale default window size based on dpi
    gWindowWidth *= dpi / 96;
    gWindowHeight *= dpi / 96;

    // Create window
    {
        WNDCLASSEX wc;
        ZeroMemory(&wc, sizeof(wc));
        wc.cbSize = sizeof(wc);
        wc.style = CS_HREDRAW | CS_VREDRAW;
        wc.lpfnWndProc = MyWndProc;
        wc.hInstance = GetModuleHandle(NULL);
        wc.hCursor = LoadCursor(NULL, IDC_ARROW);
        wc.hbrBackground = (HBRUSH)COLOR_BACKGROUND;
        wc.lpszClassName = TEXT("WindowClass");
        CHECK_WIN32(RegisterClassEx(&wc));

        RECT wr = { 0, 0, gWindowWidth, gWindowHeight };
        CHECK_WIN32(AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE));
        ghWnd = CHECK_WIN32(CreateWindowEx(
            0, TEXT("WindowClass"),
            TEXT("Spooky"), WS_OVERLAPPEDWINDOW,
            CW_USEDEFAULT, CW_USEDEFAULT, wr.right - wr.left, wr.bottom - wr.top,
            0, 0, GetModuleHandle(NULL), 0));
    }

    // Create D3D11 device and swap chain
    {
        ComPtr<IDXGIFactory> pFactory;
        CHECK_HR(CreateDXGIFactory(IID_PPV_ARGS(&pFactory)));

        UINT deviceFlags = 0;
#ifdef _DEBUG
        deviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif

        RECT clientRect;
        GetClientRect(ghWnd, &clientRect);

        DXGI_SWAP_CHAIN_DESC scd{};
        scd.BufferCount = kSwapChainBufferCount;
        scd.BufferDesc.Format = kSwapChainFormat;
        scd.BufferDesc.Width = clientRect.right - clientRect.left;
        scd.BufferDesc.Height = clientRect.bottom - clientRect.top;
        scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
        scd.OutputWindow = ghWnd;
        scd.Windowed = TRUE;
        scd.SampleDesc.Count = 1;
        scd.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;

        CHECK_HR(D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, deviceFlags, NULL, 0, D3D11_SDK_VERSION, &scd, &gpSwapChain, &gpDevice, NULL, &gpDeviceContext));
    }

    InitApp();

    ShowWindow(ghWnd, SW_SHOWNORMAL);

    while (!gShouldClose)
    {
        // Handle all events
        MSG msg;
        while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE) > 0)
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }

        UpdateApp();

        RenderApp();

        // Swap buffers
        CHECK_HR(gpSwapChain->Present(0, 0));
    }

    CHECK_HR(gpSwapChain->SetFullscreenState(FALSE, NULL));
}<commit_msg>swapchain nonsense<commit_after>#include <cassert>
#include <cstdio>
#include <memory>

#include "dxutil.h"
#include "renderer.h"
#include "camera.h"

#include <shellapi.h> // must be after windows.h
#include <ShellScalingApi.h>

#pragma comment(lib, "d3d11.lib")
#pragma comment(lib, "dxgi.lib")
#pragma comment(lib, "ninput.lib")
#pragma comment(lib, "shcore.lib")

// Constants
static const int kSwapChainBufferCount = 3;
static const DXGI_FORMAT kSwapChainFormat = DXGI_FORMAT_B8G8R8A8_UNORM;
static const int kUpdateFrequency = 60;

// Globals
HWND ghWnd;
bool gShouldClose;
ComPtr<IDXGISwapChain> gpSwapChain;
ComPtr<ID3D11Device> gpDevice;
ComPtr<ID3D11DeviceContext> gpDeviceContext;
std::unique_ptr<Renderer> gpRenderer;
OrbitCamera gCamera;
UINT64 gPerformanceFrequency;
UINT64 gLastFrameTicks;
UINT64 gAccumulatedFrameTicks;
double gRenderScale;
int gWindowWidth = 1280;
int gWindowHeight = 720;
int gRenderWidth;
int gRenderHeight;

void InitApp()
{
    LARGE_INTEGER performanceFrequency, firstFrameTicks;
    CHECK_WIN32(QueryPerformanceFrequency(&performanceFrequency));
    CHECK_WIN32(QueryPerformanceCounter(&firstFrameTicks));
    gPerformanceFrequency = performanceFrequency.QuadPart;
    gLastFrameTicks = firstFrameTicks.QuadPart;
    gAccumulatedFrameTicks = 0;

    gpRenderer = std::make_unique<Renderer>(gpDevice.Get(), gpDeviceContext.Get());
    gpRenderer->Init();

#define SIM_ORBIT_RADIUS 50.f
#define SIM_DISC_RADIUS  12.f
    auto center = DirectX::XMVectorSet(0.0f, 0.4f*SIM_DISC_RADIUS, 0.0f, 0.0f);
    auto radius = 15.0f;
    auto minRadius = SIM_ORBIT_RADIUS - 3.25f * SIM_DISC_RADIUS;
    auto maxRadius = SIM_ORBIT_RADIUS + 3.0f * SIM_DISC_RADIUS;
    auto longAngle = 4.50f;
    auto latAngle = 1.45f;
    gCamera.View(center, radius, minRadius, maxRadius, longAngle, latAngle);
}

void ResizeApp(int width, int height)
{
    CHECK_HR(gpSwapChain->ResizeBuffers(kSwapChainBufferCount, width, height, kSwapChainFormat, 0));

    gpRenderer->Resize(width, height);

    float aspect = (float)gRenderWidth / gRenderHeight;
    gCamera.Projection(DirectX::XM_PIDIV2 * 0.8f * 3 / 2, aspect);
}

void UpdateApp()
{
    gCamera.ProcessInertia();

    LARGE_INTEGER currFrameTicks;
    CHECK_WIN32(QueryPerformanceCounter(&currFrameTicks));

    UINT64 deltaTicks = currFrameTicks.QuadPart - gLastFrameTicks;
    gAccumulatedFrameTicks += deltaTicks;

    const UINT64 kMillisecondsPerUpdate = 1000 / kUpdateFrequency;
    const UINT64 kTicksPerMillisecond = gPerformanceFrequency / 1000;
    const UINT64 kTicksPerUpdate = kMillisecondsPerUpdate * kTicksPerMillisecond;

    while (gAccumulatedFrameTicks >= kTicksPerUpdate)
    {
        gpRenderer->Update(kMillisecondsPerUpdate);
        gAccumulatedFrameTicks -= kTicksPerUpdate;
    }

    gLastFrameTicks = currFrameTicks.QuadPart;
}

void RenderApp()
{
    ComPtr<ID3D11Texture2D> pBackBuffer;
    CHECK_HR(gpSwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer)));

    D3D11_RENDER_TARGET_VIEW_DESC rtvDesc{};
    rtvDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM_SRGB;
    rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
    ComPtr<ID3D11RenderTargetView> pBackBufferRTV;
    CHECK_HR(gpDevice->CreateRenderTargetView(pBackBuffer.Get(), &rtvDesc, &pBackBufferRTV));

    gpRenderer->RenderFrame(pBackBufferRTV.Get(), gCamera);
}

// Event handler
LRESULT CALLBACK MyWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
    case WM_CLOSE:
        gShouldClose = true;
        return 0;
    case WM_SIZE: {
        UINT ww = LOWORD(lParam);
        UINT wh = HIWORD(lParam);

        // Ignore resizing to minimized
        if (ww == 0 || wh == 0) return 0;

        gWindowWidth = (int)ww;
        gWindowHeight = (int)wh;
        gRenderWidth = (UINT)(double(gWindowWidth)  * gRenderScale);
        gRenderHeight = (UINT)(double(gWindowHeight) * gRenderScale);

        // Update camera projection
        float aspect = (float)gRenderWidth / (float)gRenderHeight;
        gCamera.Projection(DirectX::XM_PIDIV2 * 0.8f * 3 / 2, aspect);

        ResizeApp(gWindowWidth, gWindowHeight);

        return 0;
    }
    case WM_MOUSEWHEEL: {
        auto delta = GET_WHEEL_DELTA_WPARAM(wParam);
        gCamera.ZoomRadius(-0.07f * delta);
        return 0;
    }
    case WM_POINTERDOWN:
    case WM_POINTERUPDATE:
    case WM_POINTERUP: {
        auto pointerId = GET_POINTERID_WPARAM(wParam);
        POINTER_INFO pointerInfo;
        if (GetPointerInfo(pointerId, &pointerInfo)) {
            if (message == WM_POINTERDOWN) {

                // Compute pointer position in render units
                POINT p = pointerInfo.ptPixelLocation;
                ScreenToClient(hWnd, &p);

                RECT clientRect;
                GetClientRect(hWnd, &clientRect);
                p.x = p.x * gRenderWidth / (clientRect.right - clientRect.left);
                p.y = p.y * gRenderHeight / (clientRect.bottom - clientRect.top);

                gCamera.AddPointer(pointerId);
            }

            // Otherwise send it to the camera controls
            gCamera.ProcessPointerFrames(pointerId, &pointerInfo);
            if (message == WM_POINTERUP) gCamera.RemovePointer(pointerId);
        }
        return 0;
    }
    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
    }
}

UINT SetupDPI()
{
    // Just do system DPI awareness for now for simplicity... scale the 3D content
    SetProcessDpiAwareness(PROCESS_SYSTEM_DPI_AWARE);

    UINT dpiX = 0, dpiY;
    POINT pt = { 1, 1 };
    auto hMonitor = MonitorFromPoint(pt, MONITOR_DEFAULTTONEAREST);
    if (SUCCEEDED(GetDpiForMonitor(hMonitor, MDT_EFFECTIVE_DPI, &dpiX, &dpiY))) {
        return dpiX;
    }
    else {
        return 96; // default
    }
}

int main()
{
    UINT dpi = SetupDPI();

    gRenderScale = 96.0 / double(dpi);

    // Scale default window size based on dpi
    gWindowWidth *= dpi / 96;
    gWindowHeight *= dpi / 96;

    // Create window
    {
        WNDCLASSEX wc;
        ZeroMemory(&wc, sizeof(wc));
        wc.cbSize = sizeof(wc);
        wc.style = CS_HREDRAW | CS_VREDRAW;
        wc.lpfnWndProc = MyWndProc;
        wc.hInstance = GetModuleHandle(NULL);
        wc.hCursor = LoadCursor(NULL, IDC_ARROW);
        wc.hbrBackground = (HBRUSH)COLOR_BACKGROUND;
        wc.lpszClassName = TEXT("WindowClass");
        CHECK_WIN32(RegisterClassEx(&wc));

        RECT wr = { 0, 0, gWindowWidth, gWindowHeight };
        CHECK_WIN32(AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE));
        ghWnd = CHECK_WIN32(CreateWindowEx(
            0, TEXT("WindowClass"),
            TEXT("Spooky"), WS_OVERLAPPEDWINDOW,
            CW_USEDEFAULT, CW_USEDEFAULT, wr.right - wr.left, wr.bottom - wr.top,
            0, 0, GetModuleHandle(NULL), 0));
    }

    // Create D3D11 device and swap chain
    {
        ComPtr<IDXGIFactory> pFactory;
        CHECK_HR(CreateDXGIFactory(IID_PPV_ARGS(&pFactory)));

        UINT deviceFlags = 0;
#ifdef _DEBUG
        deviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif

        RECT clientRect;
        GetClientRect(ghWnd, &clientRect);

        DXGI_SWAP_CHAIN_DESC scd{};
        scd.BufferCount = kSwapChainBufferCount;
        scd.BufferDesc.Format = kSwapChainFormat;
        scd.BufferDesc.Width = clientRect.right - clientRect.left;
        scd.BufferDesc.Height = clientRect.bottom - clientRect.top;
        scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
        scd.OutputWindow = ghWnd;
        scd.Windowed = TRUE;
        scd.SampleDesc.Count = 1;
        scd.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;

        CHECK_HR(D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, deviceFlags, NULL, 0, D3D11_SDK_VERSION, &scd, &gpSwapChain, &gpDevice, NULL, &gpDeviceContext));
    }

    InitApp();

    ShowWindow(ghWnd, SW_SHOWNORMAL);

    while (!gShouldClose)
    {
        // Handle all events
        MSG msg;
        while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE) > 0)
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }

        UpdateApp();

        RenderApp();

        // Swap buffers
        CHECK_HR(gpSwapChain->Present(0, 0));
    }

    CHECK_HR(gpSwapChain->SetFullscreenState(FALSE, NULL));
}<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////////////////
//
// File: Accumulator.hpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// Description:
//
///////////////////////////////////////////////////////////////////////////////

#ifndef NEKTAR_LIB_UTILITIES_EXPRESSION_TEMPLATES_ACCUMULATOR_HPP
#define NEKTAR_LIB_UTILITIES_EXPRESSION_TEMPLATES_ACCUMULATOR_HPP

#include <boost/call_traits.hpp>

namespace Nektar
{
    template<typename DataType>
    class Accumulator
    {
        public:
            explicit Accumulator(typename boost::call_traits<DataType>::reference data) :
                m_isInitialized(false),
                m_data(data)
            {
            }

            void operator=(typename boost::call_traits<DataType>::const_reference rhs)
            {
                m_isInitialized = true;
                m_data = rhs;
            }

            bool IsInitialized() const
            {
                return m_isInitialized;
            }

            typename boost::call_traits<DataType>::reference GetData() const
            {
                m_isInitialized = true;
                return m_data;
            }

            typename boost::call_traits<DataType>::reference operator*() const
            {
                m_isInitialized = true;
                return m_data;
            }

        private:
            Accumulator(const Accumulator<DataType>& rhs);
            Accumulator<DataType>& operator=(const Accumulator<DataType>& rhs);

            mutable bool m_isInitialized;
            typename boost::call_traits<DataType>::reference m_data;
    };
}

#endif //NEKTAR_LIB_UTILITIES_EXPRESSION_TEMPLATES_ACCUMULATOR_HPP

/**
    $Log: Accumulator.hpp,v $
    Revision 1.2  2007/01/16 17:37:55  bnelson
    Wrapped everything with #ifdef NEKTAR_USE_EXPRESSION_TEMPLATES

    Revision 1.1  2007/01/16 05:29:49  bnelson
    Major improvements for expression templates.

 **/

<commit_msg>Added comments and removed some unused code.<commit_after>///////////////////////////////////////////////////////////////////////////////
//
// File: Accumulator.hpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// Description:
//
///////////////////////////////////////////////////////////////////////////////

#ifndef NEKTAR_LIB_UTILITIES_EXPRESSION_TEMPLATES_ACCUMULATOR_HPP
#define NEKTAR_LIB_UTILITIES_EXPRESSION_TEMPLATES_ACCUMULATOR_HPP

#include <boost/call_traits.hpp>

namespace Nektar
{

    /// \brief A wrapper for a piece of data to be passed through the expression templates.
    template<typename DataType>
    class Accumulator
    {
        public:
            explicit Accumulator(typename boost::call_traits<DataType>::reference data) :
                m_isInitialized(false),
                m_data(data)
            {
            }

            /// \brief Returns true if the accumulator contains valid data, false otherwise.
            ///
            /// When starting an expression evaluation, the accumulator starts out in an uninitialized
            /// state and this method will return false.  At some point the accumulator will obtain
            /// valid values, and after this point this method will return true.
            bool IsInitialized() const
            {
                return m_isInitialized;
            }

            /// \brief Returns the data held by the accumulator.
            ///
            /// Without a little more infrastructure, it is impossible to determine
            /// if the data has been modified after this call is made.  Therefore,
            /// pessimistically, we will assume that it will be modified so all
            /// subsequent calls to IsInitialized will return true.
            typename boost::call_traits<DataType>::reference operator*() const
            {
                m_isInitialized = true;
                return m_data;
            }

        private:
            /// By definition an accumulator stores a particular value and updates
            /// it as the expression is being evaluated.  So a copy constructor and
            /// assignment operator don't really make much sense.
            Accumulator(const Accumulator<DataType>& rhs);
            Accumulator<DataType>& operator=(const Accumulator<DataType>& rhs);

            mutable bool m_isInitialized;
            typename boost::call_traits<DataType>::reference m_data;
    };
}

#endif //NEKTAR_LIB_UTILITIES_EXPRESSION_TEMPLATES_ACCUMULATOR_HPP

/**
    $Log: Accumulator.hpp,v $
    Revision 1.3  2007/01/30 23:37:15  bnelson
    *** empty log message ***

    Revision 1.2  2007/01/16 17:37:55  bnelson
    Wrapped everything with #ifdef NEKTAR_USE_EXPRESSION_TEMPLATES

    Revision 1.1  2007/01/16 05:29:49  bnelson
    Major improvements for expression templates.

 **/

<|endoftext|>


<commit_before>#include "CommandsConfigReader.h"

#include <algorithm>
#include <map>
#include <memory>
#include <string>

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>

#include "Command.h"
#include "CommandMetadata.h"
#include "XPLMDataAccess.h"

using namespace xcopilot;
namespace pt = boost::property_tree;

static std::map<std::string, CommandType> commandTypeProvider = {
    { "int", CommandType::INT },
    { "float", CommandType::FLOAT },
    { "double", CommandType::DOUBLE },
    { "boolean", CommandType::BOOLEAN }
};

std::vector<XPLMDataRef> readDataRefs(const pt::ptree& node, XPlaneDataRefSDK* xPlaneSDK) {
    // TODO: make this iteration only once
    std::vector<std::string> dataRefs;
    std::transform(std::begin(node), std::end(node), std::back_inserter(dataRefs),
                   [](const pt::ptree::value_type& value) { return value.second.get<std::string>(""); });
    std::vector<XPLMDataRef> dataRefsIds;
    std::transform(dataRefs.begin(), dataRefs.end(), std::back_inserter(dataRefsIds),
                   [xPlaneSDK](const std::string &dataRef) { return xPlaneSDK->findDataRef(dataRef); });
    return dataRefsIds;
}

std::vector<std::shared_ptr<Command>> CommandsConfigReader::getCommandsForAircraft(const std::string configFilePath) {
    pt::ptree root;
    pt::read_json(configFilePath, root);
    std::vector<std::shared_ptr<Command>> commands;

    for (auto& node : root) {
        auto name = node.first;
        auto type = node.second.get<std::string>("type");
        auto regex = node.second.get<std::string>("regex");
        auto dataRefs = readDataRefs(node.second.get_child("dataRefs"), xPlaneSDK);
        CommandMetadata commandMetadata(name, commandTypeProvider[type], regex, dataRefs);
        commands.push_back(std::make_shared<Command>(commandMetadata));
        std::cout << "Command: " << name << " - Regex: " << regex << std::endl;
    }

    return commands;
}
<commit_msg>implement TODO (remove double iteration over datarefs list)<commit_after>#include "CommandsConfigReader.h"

#include <algorithm>
#include <map>
#include <memory>
#include <string>

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>

#include "Command.h"
#include "CommandMetadata.h"
#include "XPLMDataAccess.h"

using namespace xcopilot;
namespace pt = boost::property_tree;

static std::map<std::string, CommandType> commandTypeProvider = {
    { "int", CommandType::INT },
    { "float", CommandType::FLOAT },
    { "double", CommandType::DOUBLE },
    { "boolean", CommandType::BOOLEAN }
};

std::vector<XPLMDataRef> readDataRefs(const pt::ptree& node, XPlaneDataRefSDK* xPlaneSDK) {
    std::vector<XPLMDataRef> dataRefsIds;
    std::transform(std::begin(node), std::end(node), std::back_inserter(dataRefsIds),
                   [xPlaneSDK](const pt::ptree::value_type& value) {
        auto dataRef = value.second.get<std::string>("");
        return xPlaneSDK->findDataRef(dataRef);
    });
    return dataRefsIds;
}

std::vector<std::shared_ptr<Command>> CommandsConfigReader::getCommandsForAircraft(const std::string configFilePath) {
    pt::ptree root;
    pt::read_json(configFilePath, root);
    std::vector<std::shared_ptr<Command>> commands;

    for (auto& node : root) {
        auto name = node.first;
        auto type = node.second.get<std::string>("type");
        auto regex = node.second.get<std::string>("regex");
        auto dataRefs = readDataRefs(node.second.get_child("dataRefs"), xPlaneSDK);
        CommandMetadata commandMetadata(name, commandTypeProvider[type], regex, dataRefs);
        commands.push_back(std::make_shared<Command>(commandMetadata));
        std::cout << "Command: " << name << " - Regex: " << regex << std::endl;
    }

    return commands;
}
<|endoftext|>


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

#include "HTMLImageElementImp.h"

#include <boost/bind.hpp>

#include "DocumentImp.h"
#include "css/Box.h"

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

HTMLImageElementImp::HTMLImageElementImp(DocumentImp* ownerDocument) :
    ObjectMixin(ownerDocument, u"img")
{
}

HTMLImageElementImp::HTMLImageElementImp(HTMLImageElementImp* org, bool deep) :
    ObjectMixin(org, deep)
{
}

void HTMLImageElementImp::eval()
{
    HTMLElementImp::eval();
    HTMLElementImp::evalBorder(this);
    HTMLElementImp::evalHeight(this);
    HTMLElementImp::evalWidth(this);
    HTMLElementImp::evalHspace(this);
    HTMLElementImp::evalVspace(this);

    DocumentImp* document = getOwnerDocumentImp();
    request = new(std::nothrow) HttpRequest(document->getDocumentURI());
    if (request) {
        request->open(u"GET", getSrc());
        request->setHanndler(boost::bind(&HTMLImageElementImp::notify, this));
        document->incrementLoadEventDelayCount();
        request->send();
    } else
        active = false;
}

void HTMLImageElementImp::notify()
{
    if (request->getStatus() != 200)
        active = false;
    else {
        // TODO: Check type
        image = new(std::nothrow) BoxImage();
        if (!image)
            active = false;
        else {
            if (FILE* file = request->openFile()) {
                image->open(file);
                fclose(file);
            }
            if (image->getState() != BoxImage::CompletelyAvailable) {
                active = false;
                delete image;
                image = 0;
            }
        }
    }
    if (Box* box = getBox())
        box->setFlags(1);
    DocumentImp* document = getOwnerDocumentImp();
    document->decrementLoadEventDelayCount();
}

// Node
Node HTMLImageElementImp::cloneNode(bool deep)
{
    return new(std::nothrow) HTMLImageElementImp(this, deep);
}

// HTMLImageElement
std::u16string HTMLImageElementImp::getAlt()
{
    // TODO: implement me!
    return u"";
}

void HTMLImageElementImp::setAlt(std::u16string alt)
{
    // TODO: implement me!
}

std::u16string HTMLImageElementImp::getSrc()
{
    return getAttribute(u"src");
}

void HTMLImageElementImp::setSrc(std::u16string src)
{
    setAttribute(u"src", src);
}

std::u16string HTMLImageElementImp::getCrossOrigin()
{
    // TODO: implement me!
    return u"";
}

void HTMLImageElementImp::setCrossOrigin(std::u16string crossOrigin)
{
    // TODO: implement me!
}

std::u16string HTMLImageElementImp::getUseMap()
{
    // TODO: implement me!
    return u"";
}

void HTMLImageElementImp::setUseMap(std::u16string useMap)
{
    // TODO: implement me!
}

bool HTMLImageElementImp::getIsMap()
{
    // TODO: implement me!
    return 0;
}

void HTMLImageElementImp::setIsMap(bool isMap)
{
    // TODO: implement me!
}

unsigned int HTMLImageElementImp::getWidth()
{
    // TODO: implement me!
    return 0;
}

void HTMLImageElementImp::setWidth(unsigned int width)
{
    // TODO: implement me!
}

unsigned int HTMLImageElementImp::getHeight()
{
    // TODO: implement me!
    return 0;
}

void HTMLImageElementImp::setHeight(unsigned int height)
{
    // TODO: implement me!
}

unsigned int HTMLImageElementImp::getNaturalWidth()
{
    // TODO: implement me!
    return 0;
}

unsigned int HTMLImageElementImp::getNaturalHeight()
{
    // TODO: implement me!
    return 0;
}

bool HTMLImageElementImp::getComplete()
{
    // TODO: implement me!
    return 0;
}

std::u16string HTMLImageElementImp::getName()
{
    // TODO: implement me!
    return u"";
}

void HTMLImageElementImp::setName(std::u16string name)
{
    // TODO: implement me!
}

std::u16string HTMLImageElementImp::getAlign()
{
    // TODO: implement me!
    return u"";
}

void HTMLImageElementImp::setAlign(std::u16string align)
{
    // TODO: implement me!
}

std::u16string HTMLImageElementImp::getBorder()
{
    // TODO: implement me!
    return u"";
}

void HTMLImageElementImp::setBorder(std::u16string border)
{
    // TODO: implement me!
}

unsigned int HTMLImageElementImp::getHspace()
{
    // TODO: implement me!
    return 0;
}

void HTMLImageElementImp::setHspace(unsigned int hspace)
{
    // TODO: implement me!
}

std::u16string HTMLImageElementImp::getLongDesc()
{
    // TODO: implement me!
    return u"";
}

void HTMLImageElementImp::setLongDesc(std::u16string longDesc)
{
    // TODO: implement me!
}

unsigned int HTMLImageElementImp::getVspace()
{
    // TODO: implement me!
    return 0;
}

void HTMLImageElementImp::setVspace(unsigned int vspace)
{
    // TODO: implement me!
}

}  // org::w3c::dom::bootstrap

namespace html {

namespace {

class Constructor : public Object
{
public:
    // Object
    virtual Any message_(uint32_t selector, const char* id, int argc, Any* argv) {
        bootstrap::HTMLImageElementImp* img = 0;
        switch (argc) {
        case 0:
            img = new(std::nothrow) bootstrap::HTMLImageElementImp(0);
            break;
        case 1:
            img = new(std::nothrow) bootstrap::HTMLImageElementImp(0);
            if (img)
                img->setWidth(argv[0]);
            break;
        case 2:
            img = new(std::nothrow) bootstrap::HTMLImageElementImp(0);
            if (img) {
                img->setWidth(argv[0]);
                img->setHeight(argv[1]);
            }
            break;
        default:
            break;
        }
        return img;
    }
    Constructor() :
        Object(this) {
    }
};

}  // namespace

Object HTMLImageElement::getConstructor()
{
    static Constructor constructor;
    return constructor.self();
}

}

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

#include "HTMLImageElementImp.h"

#include <boost/bind.hpp>

#include "DocumentImp.h"
#include "css/Box.h"

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

HTMLImageElementImp::HTMLImageElementImp(DocumentImp* ownerDocument) :
    ObjectMixin(ownerDocument, u"img")
{
}

HTMLImageElementImp::HTMLImageElementImp(HTMLImageElementImp* org, bool deep) :
    ObjectMixin(org, deep)
{
}

void HTMLImageElementImp::eval()
{
    HTMLElementImp::eval();
    HTMLElementImp::evalBorder(this);
    HTMLElementImp::evalHeight(this);
    HTMLElementImp::evalWidth(this);
    HTMLElementImp::evalHspace(this);
    HTMLElementImp::evalVspace(this);

    DocumentImp* document = getOwnerDocumentImp();
    request = new(std::nothrow) HttpRequest(document->getDocumentURI());
    if (request) {
        request->open(u"GET", getSrc());
        request->setHanndler(boost::bind(&HTMLImageElementImp::notify, this));
        document->incrementLoadEventDelayCount();
        request->send();
    } else
        active = false;
}

void HTMLImageElementImp::notify()
{
    if (request->getStatus() != 200)
        active = false;
    else {
        // TODO: Check type
        delete image;
        image = new(std::nothrow) BoxImage();
        if (!image)
            active = false;
        else {
            if (FILE* file = request->openFile()) {
                image->open(file);
                fclose(file);
            }
            if (image->getState() != BoxImage::CompletelyAvailable) {
                active = false;
                delete image;
                image = 0;
            }
        }
    }
    if (Box* box = getBox())
        box->setFlags(1);
    DocumentImp* document = getOwnerDocumentImp();
    document->decrementLoadEventDelayCount();
}

// Node
Node HTMLImageElementImp::cloneNode(bool deep)
{
    return new(std::nothrow) HTMLImageElementImp(this, deep);
}

// HTMLImageElement
std::u16string HTMLImageElementImp::getAlt()
{
    // TODO: implement me!
    return u"";
}

void HTMLImageElementImp::setAlt(std::u16string alt)
{
    // TODO: implement me!
}

std::u16string HTMLImageElementImp::getSrc()
{
    return getAttribute(u"src");
}

void HTMLImageElementImp::setSrc(std::u16string src)
{
    setAttribute(u"src", src);
    DocumentImp* document = getOwnerDocumentImp();
    if (request)
        request->abort();
    else
        request = new(std::nothrow) HttpRequest(document->getDocumentURI());
    if (request) {
        request->open(u"GET", getSrc());
        request->setHanndler(boost::bind(&HTMLImageElementImp::notify, this));
        document->incrementLoadEventDelayCount();
        request->send();
    }
}

std::u16string HTMLImageElementImp::getCrossOrigin()
{
    // TODO: implement me!
    return u"";
}

void HTMLImageElementImp::setCrossOrigin(std::u16string crossOrigin)
{
    // TODO: implement me!
}

std::u16string HTMLImageElementImp::getUseMap()
{
    // TODO: implement me!
    return u"";
}

void HTMLImageElementImp::setUseMap(std::u16string useMap)
{
    // TODO: implement me!
}

bool HTMLImageElementImp::getIsMap()
{
    // TODO: implement me!
    return 0;
}

void HTMLImageElementImp::setIsMap(bool isMap)
{
    // TODO: implement me!
}

unsigned int HTMLImageElementImp::getWidth()
{
    // TODO: implement me!
    return 0;
}

void HTMLImageElementImp::setWidth(unsigned int width)
{
    // TODO: implement me!
}

unsigned int HTMLImageElementImp::getHeight()
{
    // TODO: implement me!
    return 0;
}

void HTMLImageElementImp::setHeight(unsigned int height)
{
    // TODO: implement me!
}

unsigned int HTMLImageElementImp::getNaturalWidth()
{
    // TODO: implement me!
    return 0;
}

unsigned int HTMLImageElementImp::getNaturalHeight()
{
    // TODO: implement me!
    return 0;
}

bool HTMLImageElementImp::getComplete()
{
    // TODO: implement me!
    return 0;
}

std::u16string HTMLImageElementImp::getName()
{
    // TODO: implement me!
    return u"";
}

void HTMLImageElementImp::setName(std::u16string name)
{
    // TODO: implement me!
}

std::u16string HTMLImageElementImp::getAlign()
{
    // TODO: implement me!
    return u"";
}

void HTMLImageElementImp::setAlign(std::u16string align)
{
    // TODO: implement me!
}

std::u16string HTMLImageElementImp::getBorder()
{
    // TODO: implement me!
    return u"";
}

void HTMLImageElementImp::setBorder(std::u16string border)
{
    // TODO: implement me!
}

unsigned int HTMLImageElementImp::getHspace()
{
    // TODO: implement me!
    return 0;
}

void HTMLImageElementImp::setHspace(unsigned int hspace)
{
    // TODO: implement me!
}

std::u16string HTMLImageElementImp::getLongDesc()
{
    // TODO: implement me!
    return u"";
}

void HTMLImageElementImp::setLongDesc(std::u16string longDesc)
{
    // TODO: implement me!
}

unsigned int HTMLImageElementImp::getVspace()
{
    // TODO: implement me!
    return 0;
}

void HTMLImageElementImp::setVspace(unsigned int vspace)
{
    // TODO: implement me!
}

}  // org::w3c::dom::bootstrap

namespace html {

namespace {

class Constructor : public Object
{
public:
    // Object
    virtual Any message_(uint32_t selector, const char* id, int argc, Any* argv) {
        bootstrap::HTMLImageElementImp* img = 0;
        switch (argc) {
        case 0:
            img = new(std::nothrow) bootstrap::HTMLImageElementImp(0);
            break;
        case 1:
            img = new(std::nothrow) bootstrap::HTMLImageElementImp(0);
            if (img)
                img->setWidth(argv[0]);
            break;
        case 2:
            img = new(std::nothrow) bootstrap::HTMLImageElementImp(0);
            if (img) {
                img->setWidth(argv[0]);
                img->setHeight(argv[1]);
            }
            break;
        default:
            break;
        }
        return img;
    }
    Constructor() :
        Object(this) {
    }
};

}  // namespace

Object HTMLImageElement::getConstructor()
{
    static Constructor constructor;
    return constructor.self();
}

}

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


<commit_before>/*************************************************************************
 *
 *  $RCSfile: txtstyle.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: mtg $ $Date: 2001-03-22 15:30:20 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _TOOLS_DEBUG_HXX
//#include <tools/debug.hxx>
#endif

#ifndef _COM_SUN_STAR_STYLE_PARAGRAPHSTYLECATEGORY_HPP_
#include <com/sun/star/style/ParagraphStyleCategory.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSETINFO_HPP_
#include <com/sun/star/beans/XPropertySetInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSTATE_HPP_
#include <com/sun/star/beans/XPropertyState.hpp>
#endif

#ifndef _XMLOFF_XMLKYWD_HXX
#include "xmlkywd.hxx"
#endif

#ifndef _XMLOFF_PROPERTYSETMAPPER_HXX
//#include "xmlprmap.hxx"
#endif
#ifndef _XMLOFF_XMLSMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_FAMILIES_HXX
#include "families.hxx"
#endif
#ifndef _XMLOFF_TXTPRMAP_HXX
//#include "txtprmap.hxx"
#endif
#ifndef _XMLOFF_TXTPARAE_HXX
#include "txtparae.hxx"
#endif
#ifndef _XMLOFF_XMLNUME_HXX
#include "xmlnume.hxx"
#endif
#ifndef _XMLOFF_XMLEXP_HXX
#include "xmlexp.hxx"
#endif
#ifndef _XMLOFF_XMLSECTIONEXPORT_HXX
#include "XMLSectionExport.hxx"
#endif
#ifndef _XMLOFF_XMLLINENUMBERINGEXPORT_HXX_
#include "XMLLineNumberingExport.hxx"
#endif

#ifndef _XMLOFF_STYLEEXP_HXX
//#include "styleexp.hxx"
#endif

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::style;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::beans;

void XMLTextParagraphExport::exportStyleAttributes(
        const ::com::sun::star::uno::Reference<
                ::com::sun::star::style::XStyle > & rStyle )
{
    Any aAny;
    Reference< XPropertySet > xPropSet( rStyle, UNO_QUERY );
    Reference< XPropertySetInfo > xPropSetInfo =
            xPropSet->getPropertySetInfo();
    if( xPropSetInfo->hasPropertyByName( sCategory ) )
    {
        aAny = xPropSet->getPropertyValue( sCategory );
        sal_Int16 nCategory;
        aAny >>= nCategory;
        const sal_Char *pValue = 0;
        if( -1 != nCategory )
        {
            switch( nCategory )
            {
            case ParagraphStyleCategory::TEXT:
                pValue = sXML_text;
                break;
            case ParagraphStyleCategory::CHAPTER:
                pValue = sXML_chapter;
                break;
            case ParagraphStyleCategory::LIST:
                pValue = sXML_list;
                break;
            case ParagraphStyleCategory::INDEX:
                pValue = sXML_index;
                break;
            case ParagraphStyleCategory::EXTRA:
                pValue = sXML_extra;
                break;
            case ParagraphStyleCategory::HTML:
                pValue = sXML_html;
                break;
            }
        }
        if( pValue )
            GetExport().AddAttributeASCII( XML_NAMESPACE_STYLE, sXML_class,
                                                pValue );
    }
    if( xPropSetInfo->hasPropertyByName( sPageDescName ) )
    {
        Reference< XPropertyState > xPropState( xPropSet, uno::UNO_QUERY );
        if( PropertyState_DIRECT_VALUE ==
                xPropState->getPropertyState( sPageDescName  ) )
        {
            aAny = xPropSet->getPropertyValue( sPageDescName );
            OUString sName;
            aAny >>= sName;
            GetExport().AddAttribute( XML_NAMESPACE_STYLE,
                                      sXML_master_page_name,
                                      sName );
        }
    }
}

void XMLTextParagraphExport::exportNumStyles( sal_Bool bUsed )
{
    SvxXMLNumRuleExport aNumRuleExport( GetExport() );
    aNumRuleExport.exportStyles( bUsed, pListAutoPool, !IsBlockMode() );
}

void XMLTextParagraphExport::exportTextStyles( sal_Bool bUsed )
{
    Reference < lang::XMultiServiceFactory > xFactory (GetExport().GetModel(), UNO_QUERY);
    if (xFactory.is())
    {
        Reference < XInterface > xInt = xFactory->createInstance (
                                            OUString( RTL_CONSTASCII_USTRINGPARAM (
                                                "com.sun.star.text.Defaults") ) );
        if ( xInt.is() )
        {
            Reference < XPropertySet > xPropSet (xInt, UNO_QUERY);
            if (xPropSet.is())
                exportDefaultStyle( xPropSet, sXML_text, GetParaPropMapper());
        }
    }
    exportStyleFamily( "ParagraphStyles", sXML_paragraph, GetParaPropMapper(),
                       bUsed, XML_STYLE_FAMILY_TEXT_PARAGRAPH, 0);
    exportStyleFamily( "CharacterStyles", sXML_text, GetTextPropMapper(),
                       bUsed, XML_STYLE_FAMILY_TEXT_TEXT );
    // get shape export to make sure the the frame family is added correctly.
    GetExport().GetShapeExport();
    exportStyleFamily( "FrameStyles", XML_STYLE_FAMILY_SD_GRAPHICS_NAME, GetFramePropMapper(),
                       bUsed, XML_STYLE_FAMILY_TEXT_FRAME, 0);
    exportNumStyles( bUsed );
    if( !IsBlockMode() )
    {
        exportTextFootnoteConfiguration();
        XMLSectionExport::ExportBibliographyConfiguration(GetExport());
        XMLLineNumberingExport aLineNumberingExport(GetExport());
        aLineNumberingExport.Export();
    }
}
<commit_msg>export default style as family: paragraph and not text<commit_after>/*************************************************************************
 *
 *  $RCSfile: txtstyle.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: mtg $ $Date: 2001-03-22 21:02:27 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _TOOLS_DEBUG_HXX
//#include <tools/debug.hxx>
#endif

#ifndef _COM_SUN_STAR_STYLE_PARAGRAPHSTYLECATEGORY_HPP_
#include <com/sun/star/style/ParagraphStyleCategory.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSETINFO_HPP_
#include <com/sun/star/beans/XPropertySetInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSTATE_HPP_
#include <com/sun/star/beans/XPropertyState.hpp>
#endif

#ifndef _XMLOFF_XMLKYWD_HXX
#include "xmlkywd.hxx"
#endif

#ifndef _XMLOFF_PROPERTYSETMAPPER_HXX
//#include "xmlprmap.hxx"
#endif
#ifndef _XMLOFF_XMLSMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_FAMILIES_HXX
#include "families.hxx"
#endif
#ifndef _XMLOFF_TXTPRMAP_HXX
//#include "txtprmap.hxx"
#endif
#ifndef _XMLOFF_TXTPARAE_HXX
#include "txtparae.hxx"
#endif
#ifndef _XMLOFF_XMLNUME_HXX
#include "xmlnume.hxx"
#endif
#ifndef _XMLOFF_XMLEXP_HXX
#include "xmlexp.hxx"
#endif
#ifndef _XMLOFF_XMLSECTIONEXPORT_HXX
#include "XMLSectionExport.hxx"
#endif
#ifndef _XMLOFF_XMLLINENUMBERINGEXPORT_HXX_
#include "XMLLineNumberingExport.hxx"
#endif

#ifndef _XMLOFF_STYLEEXP_HXX
//#include "styleexp.hxx"
#endif

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::style;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::beans;

void XMLTextParagraphExport::exportStyleAttributes(
        const ::com::sun::star::uno::Reference<
                ::com::sun::star::style::XStyle > & rStyle )
{
    Any aAny;
    Reference< XPropertySet > xPropSet( rStyle, UNO_QUERY );
    Reference< XPropertySetInfo > xPropSetInfo =
            xPropSet->getPropertySetInfo();
    if( xPropSetInfo->hasPropertyByName( sCategory ) )
    {
        aAny = xPropSet->getPropertyValue( sCategory );
        sal_Int16 nCategory;
        aAny >>= nCategory;
        const sal_Char *pValue = 0;
        if( -1 != nCategory )
        {
            switch( nCategory )
            {
            case ParagraphStyleCategory::TEXT:
                pValue = sXML_text;
                break;
            case ParagraphStyleCategory::CHAPTER:
                pValue = sXML_chapter;
                break;
            case ParagraphStyleCategory::LIST:
                pValue = sXML_list;
                break;
            case ParagraphStyleCategory::INDEX:
                pValue = sXML_index;
                break;
            case ParagraphStyleCategory::EXTRA:
                pValue = sXML_extra;
                break;
            case ParagraphStyleCategory::HTML:
                pValue = sXML_html;
                break;
            }
        }
        if( pValue )
            GetExport().AddAttributeASCII( XML_NAMESPACE_STYLE, sXML_class,
                                                pValue );
    }
    if( xPropSetInfo->hasPropertyByName( sPageDescName ) )
    {
        Reference< XPropertyState > xPropState( xPropSet, uno::UNO_QUERY );
        if( PropertyState_DIRECT_VALUE ==
                xPropState->getPropertyState( sPageDescName  ) )
        {
            aAny = xPropSet->getPropertyValue( sPageDescName );
            OUString sName;
            aAny >>= sName;
            GetExport().AddAttribute( XML_NAMESPACE_STYLE,
                                      sXML_master_page_name,
                                      sName );
        }
    }
}

void XMLTextParagraphExport::exportNumStyles( sal_Bool bUsed )
{
    SvxXMLNumRuleExport aNumRuleExport( GetExport() );
    aNumRuleExport.exportStyles( bUsed, pListAutoPool, !IsBlockMode() );
}

void XMLTextParagraphExport::exportTextStyles( sal_Bool bUsed )
{
    Reference < lang::XMultiServiceFactory > xFactory (GetExport().GetModel(), UNO_QUERY);
    if (xFactory.is())
    {
        Reference < XInterface > xInt = xFactory->createInstance (
                                            OUString( RTL_CONSTASCII_USTRINGPARAM (
                                                "com.sun.star.text.Defaults") ) );
        if ( xInt.is() )
        {
            Reference < XPropertySet > xPropSet (xInt, UNO_QUERY);
            if (xPropSet.is())
                exportDefaultStyle( xPropSet, sXML_paragraph, GetParaPropMapper());
        }
    }
    exportStyleFamily( "ParagraphStyles", sXML_paragraph, GetParaPropMapper(),
                       bUsed, XML_STYLE_FAMILY_TEXT_PARAGRAPH, 0);
    exportStyleFamily( "CharacterStyles", sXML_text, GetTextPropMapper(),
                       bUsed, XML_STYLE_FAMILY_TEXT_TEXT );
    // get shape export to make sure the the frame family is added correctly.
    GetExport().GetShapeExport();
    exportStyleFamily( "FrameStyles", XML_STYLE_FAMILY_SD_GRAPHICS_NAME, GetFramePropMapper(),
                       bUsed, XML_STYLE_FAMILY_TEXT_FRAME, 0);
    exportNumStyles( bUsed );
    if( !IsBlockMode() )
    {
        exportTextFootnoteConfiguration();
        XMLSectionExport::ExportBibliographyConfiguration(GetExport());
        XMLLineNumberingExport aLineNumberingExport(GetExport());
        aLineNumberingExport.Export();
    }
}
<|endoftext|>