<commit_before>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/lite/delegates/external/external_delegate.h"

#include <string>
#include <locale>
#include <vector>

#include "tensorflow/lite/minimal_logging.h"
#include "tensorflow/lite/shared_library.h"

namespace tflite {
namespace {

// External delegate library construct
struct ExternalLib {
  using CreateDelegatePtr = std::add_pointer<TfLiteDelegate*(
      const char**, const char**, size_t,
      void (*report_error)(const char*))>::type;
  using DestroyDelegatePtr = std::add_pointer<void(TfLiteDelegate*)>::type;
  struct wchar_codecvt : public std::codecvt<wchar_t, char, std::mbstate_t> {};
  std::wstring_convert<wchar_codecvt> converter;

  // Open a given delegate library and load the create/destroy symbols
  bool load(const std::string library) {
    void* handle = SharedLibrary::LoadLibrary(converter.from_bytes(library.c_str()).c_str());
    if (handle == nullptr) {
      TFLITE_LOG(TFLITE_LOG_INFO, "Unable to load external delegate from : %s",
                 library.c_str());
    } else {
      create =
          reinterpret_cast<decltype(create)>(SharedLibrary::GetLibrarySymbol(
              handle, "tflite_plugin_create_delegate"));
      destroy =
          reinterpret_cast<decltype(destroy)>(SharedLibrary::GetLibrarySymbol(
              handle, "tflite_plugin_destroy_delegate"));
      return create && destroy;
    }
    return false;
  }

  CreateDelegatePtr create{nullptr};
  DestroyDelegatePtr destroy{nullptr};
};

// An ExternalDelegateWrapper is responsibile to manage a TFLite delegate
// initialized from a shared library. It creates a delegate from the given
// option and storages it to external_delegate_ member variable. On the
// destruction, it conducts necessary clean up process.
class ExternalDelegateWrapper {
 public:
  explicit ExternalDelegateWrapper(
      const TfLiteExternalDelegateOptions* options);
  ~ExternalDelegateWrapper();

  // Return a TfLiteDelegate which is created from
  // tflite_plugin_create_delegate() of an external delegate logic.
  TfLiteDelegate* tflite_external_delegate() { return external_delegate_; }

  // Return a TfLiteDelegate which is convertibile to this class.
  TfLiteDelegate* tflite_wrapper_delegate() { return &wrapper_delegate_; }

 private:
  ExternalLib external_lib_;

  // external delegate instance owned by external delegate logic.
  // It's created by "tflite_plugin_destroy_delegate()" function in the external
  // delegate logic And it should be released by
  // "tflite_plugin_destroy_delegate()" function.
  TfLiteDelegate* external_delegate_;

  // TfLiteDelegate representation of this ExternalDelegateWrapper object.
  TfLiteDelegate wrapper_delegate_;
};

// Converts the given TfLiteDelegate to an ExternalDelegateWrapper instance.
inline ExternalDelegateWrapper* GetExternalDelegateWrapper(
    TfLiteDelegate* delegate) {
  return reinterpret_cast<ExternalDelegateWrapper*>(delegate->data_);
}

// Relay Prepare() call to the associated external TfLiteDelegate object.
TfLiteStatus DelegatePrepare(TfLiteContext* context, TfLiteDelegate* delegate) {
  auto external_delegate_wrapper = GetExternalDelegateWrapper(delegate);
  TfLiteDelegate* external_delegate =
      external_delegate_wrapper->tflite_external_delegate();
  return external_delegate->Prepare(context, external_delegate);
}

// Relay CopyFromBufferHandle() call to the associated external TfLiteDelegate
// object.
TfLiteStatus DelegateCopyFromBufferHandle(TfLiteContext* context,
                                          struct TfLiteDelegate* delegate,
                                          TfLiteBufferHandle buffer_handle,
                                          TfLiteTensor* tensor) {
  auto external_delegate_wrapper = GetExternalDelegateWrapper(delegate);
  TfLiteDelegate* external_delegate =
      external_delegate_wrapper->tflite_external_delegate();
  return external_delegate->CopyFromBufferHandle(context, delegate,
                                                 buffer_handle, tensor);
}

// Relay CopyToBufferHandle() call to the associated external TfLiteDelegate
// object.
TfLiteStatus DelegateCopyToBufferHandle(TfLiteContext* context,
                                        struct TfLiteDelegate* delegate,
                                        TfLiteBufferHandle buffer_handle,
                                        TfLiteTensor* tensor) {
  auto external_delegate_wrapper = GetExternalDelegateWrapper(delegate);
  TfLiteDelegate* external_delegate =
      external_delegate_wrapper->tflite_external_delegate();
  return external_delegate->CopyToBufferHandle(context, delegate, buffer_handle,
                                               tensor);
}

// Relay FreeBufferHandle() call to the associated external TfLiteDelegate
// object.
void DelegateFreeBufferHandle(TfLiteContext* context,
                              struct TfLiteDelegate* delegate,
                              TfLiteBufferHandle* handle) {
  auto external_delegate_wrapper = GetExternalDelegateWrapper(delegate);
  TfLiteDelegate* external_delegate =
      external_delegate_wrapper->tflite_external_delegate();
  return external_delegate->FreeBufferHandle(context, delegate, handle);
}

ExternalDelegateWrapper::ExternalDelegateWrapper(
    const TfLiteExternalDelegateOptions* options) {
  external_delegate_ = nullptr;
  if (external_lib_.load(options->lib_path)) {
    std::vector<const char*> ckeys, cvalues;
    for (int i = 0; i < options->count; i++) {
      ckeys.push_back(options->keys[i]);
      cvalues.push_back(options->values[i]);
    }

    external_delegate_ = external_lib_.create(ckeys.data(), cvalues.data(),
                                              ckeys.size(), nullptr);
    if (external_delegate_) {
      wrapper_delegate_ = {
          .data_ = reinterpret_cast<void*>(this),
          .Prepare = DelegatePrepare,
          .CopyFromBufferHandle = nullptr,
          .CopyToBufferHandle = nullptr,
          .FreeBufferHandle = nullptr,
          .flags = external_delegate_->flags,
      };
      if (external_delegate_->CopyFromBufferHandle) {
        wrapper_delegate_.CopyFromBufferHandle = DelegateCopyFromBufferHandle;
      }
      if (external_delegate_->CopyToBufferHandle) {
        wrapper_delegate_.CopyToBufferHandle = DelegateCopyToBufferHandle;
      }
      if (external_delegate_->FreeBufferHandle) {
        wrapper_delegate_.FreeBufferHandle = DelegateFreeBufferHandle;
      }
    }
  }
}

ExternalDelegateWrapper::~ExternalDelegateWrapper() {
  if (external_delegate_ != nullptr) {
    external_lib_.destroy(external_delegate_);
  }
}

}  // namespace
}  // namespace tflite

// TfLiteExternalDelegateOptionsInsert adds key/value to the given
// TfLiteExternalDelegateOptions instance.
TfLiteStatus TfLiteExternalDelegateOptionsInsert(
    TfLiteExternalDelegateOptions* options, const char* key,
    const char* value) {
  if (options->count >= kMaxOptions) {
    return kTfLiteError;
  }
  options->keys[options->count] = key;
  options->values[options->count] = value;
  options->count++;
  return kTfLiteOk;
}

TfLiteExternalDelegateOptions TfLiteExternalDelegateOptionsDefault(
    const char* lib_path) {
  // As 'keys' and 'values' don't need to be set here, using designated
  // initializers may cause a compiling error as "non-trivial designated
  // initializers not supported" by some compiler.
  TfLiteExternalDelegateOptions options;
  options.lib_path = lib_path;
  options.count = 0;
  options.insert = TfLiteExternalDelegateOptionsInsert;
  return options;
}

TfLiteDelegate* TfLiteExternalDelegateCreate(
    const TfLiteExternalDelegateOptions* options) {
  auto* external_delegate_wrapper =
      new tflite::ExternalDelegateWrapper(options);
  if (external_delegate_wrapper) {
    return external_delegate_wrapper->tflite_wrapper_delegate();
  }
  return nullptr;
}

void TfLiteExternalDelegateDelete(TfLiteDelegate* delegate) {
  delete tflite::GetExternalDelegateWrapper(delegate);
}
<commit_msg>Convert string only for Windows<commit_after>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/lite/delegates/external/external_delegate.h"

#include <string>
#include <locale>
#include <vector>

#include "tensorflow/lite/minimal_logging.h"
#include "tensorflow/lite/shared_library.h"

namespace tflite {
namespace {

// External delegate library construct
struct ExternalLib {
  using CreateDelegatePtr = std::add_pointer<TfLiteDelegate*(
      const char**, const char**, size_t,
      void (*report_error)(const char*))>::type;
  using DestroyDelegatePtr = std::add_pointer<void(TfLiteDelegate*)>::type;
  struct wchar_codecvt : public std::codecvt<wchar_t, char, std::mbstate_t> {};
  std::wstring_convert<wchar_codecvt> converter;

  // Open a given delegate library and load the create/destroy symbols
  bool load(const std::string library) {
#if defined(_WIN32)
    void* handle = SharedLibrary::LoadLibrary(converter.from_bytes(library.c_str()).c_str());
#else
    void* handle = SharedLibrary::LoadLibrary(library.c_str());
#endif // defined(_WIN32)
    if (handle == nullptr) {
      TFLITE_LOG(TFLITE_LOG_INFO, "Unable to load external delegate from : %s",
                 library.c_str());
    } else {
      create =
          reinterpret_cast<decltype(create)>(SharedLibrary::GetLibrarySymbol(
              handle, "tflite_plugin_create_delegate"));
      destroy =
          reinterpret_cast<decltype(destroy)>(SharedLibrary::GetLibrarySymbol(
              handle, "tflite_plugin_destroy_delegate"));
      return create && destroy;
    }
    return false;
  }

  CreateDelegatePtr create{nullptr};
  DestroyDelegatePtr destroy{nullptr};
};

// An ExternalDelegateWrapper is responsibile to manage a TFLite delegate
// initialized from a shared library. It creates a delegate from the given
// option and storages it to external_delegate_ member variable. On the
// destruction, it conducts necessary clean up process.
class ExternalDelegateWrapper {
 public:
  explicit ExternalDelegateWrapper(
      const TfLiteExternalDelegateOptions* options);
  ~ExternalDelegateWrapper();

  // Return a TfLiteDelegate which is created from
  // tflite_plugin_create_delegate() of an external delegate logic.
  TfLiteDelegate* tflite_external_delegate() { return external_delegate_; }

  // Return a TfLiteDelegate which is convertibile to this class.
  TfLiteDelegate* tflite_wrapper_delegate() { return &wrapper_delegate_; }

 private:
  ExternalLib external_lib_;

  // external delegate instance owned by external delegate logic.
  // It's created by "tflite_plugin_destroy_delegate()" function in the external
  // delegate logic And it should be released by
  // "tflite_plugin_destroy_delegate()" function.
  TfLiteDelegate* external_delegate_;

  // TfLiteDelegate representation of this ExternalDelegateWrapper object.
  TfLiteDelegate wrapper_delegate_;
};

// Converts the given TfLiteDelegate to an ExternalDelegateWrapper instance.
inline ExternalDelegateWrapper* GetExternalDelegateWrapper(
    TfLiteDelegate* delegate) {
  return reinterpret_cast<ExternalDelegateWrapper*>(delegate->data_);
}

// Relay Prepare() call to the associated external TfLiteDelegate object.
TfLiteStatus DelegatePrepare(TfLiteContext* context, TfLiteDelegate* delegate) {
  auto external_delegate_wrapper = GetExternalDelegateWrapper(delegate);
  TfLiteDelegate* external_delegate =
      external_delegate_wrapper->tflite_external_delegate();
  return external_delegate->Prepare(context, external_delegate);
}

// Relay CopyFromBufferHandle() call to the associated external TfLiteDelegate
// object.
TfLiteStatus DelegateCopyFromBufferHandle(TfLiteContext* context,
                                          struct TfLiteDelegate* delegate,
                                          TfLiteBufferHandle buffer_handle,
                                          TfLiteTensor* tensor) {
  auto external_delegate_wrapper = GetExternalDelegateWrapper(delegate);
  TfLiteDelegate* external_delegate =
      external_delegate_wrapper->tflite_external_delegate();
  return external_delegate->CopyFromBufferHandle(context, delegate,
                                                 buffer_handle, tensor);
}

// Relay CopyToBufferHandle() call to the associated external TfLiteDelegate
// object.
TfLiteStatus DelegateCopyToBufferHandle(TfLiteContext* context,
                                        struct TfLiteDelegate* delegate,
                                        TfLiteBufferHandle buffer_handle,
                                        TfLiteTensor* tensor) {
  auto external_delegate_wrapper = GetExternalDelegateWrapper(delegate);
  TfLiteDelegate* external_delegate =
      external_delegate_wrapper->tflite_external_delegate();
  return external_delegate->CopyToBufferHandle(context, delegate, buffer_handle,
                                               tensor);
}

// Relay FreeBufferHandle() call to the associated external TfLiteDelegate
// object.
void DelegateFreeBufferHandle(TfLiteContext* context,
                              struct TfLiteDelegate* delegate,
                              TfLiteBufferHandle* handle) {
  auto external_delegate_wrapper = GetExternalDelegateWrapper(delegate);
  TfLiteDelegate* external_delegate =
      external_delegate_wrapper->tflite_external_delegate();
  return external_delegate->FreeBufferHandle(context, delegate, handle);
}

ExternalDelegateWrapper::ExternalDelegateWrapper(
    const TfLiteExternalDelegateOptions* options) {
  external_delegate_ = nullptr;
  if (external_lib_.load(options->lib_path)) {
    std::vector<const char*> ckeys, cvalues;
    for (int i = 0; i < options->count; i++) {
      ckeys.push_back(options->keys[i]);
      cvalues.push_back(options->values[i]);
    }

    external_delegate_ = external_lib_.create(ckeys.data(), cvalues.data(),
                                              ckeys.size(), nullptr);
    if (external_delegate_) {
      wrapper_delegate_ = {
          .data_ = reinterpret_cast<void*>(this),
          .Prepare = DelegatePrepare,
          .CopyFromBufferHandle = nullptr,
          .CopyToBufferHandle = nullptr,
          .FreeBufferHandle = nullptr,
          .flags = external_delegate_->flags,
      };
      if (external_delegate_->CopyFromBufferHandle) {
        wrapper_delegate_.CopyFromBufferHandle = DelegateCopyFromBufferHandle;
      }
      if (external_delegate_->CopyToBufferHandle) {
        wrapper_delegate_.CopyToBufferHandle = DelegateCopyToBufferHandle;
      }
      if (external_delegate_->FreeBufferHandle) {
        wrapper_delegate_.FreeBufferHandle = DelegateFreeBufferHandle;
      }
    }
  }
}

ExternalDelegateWrapper::~ExternalDelegateWrapper() {
  if (external_delegate_ != nullptr) {
    external_lib_.destroy(external_delegate_);
  }
}

}  // namespace
}  // namespace tflite

// TfLiteExternalDelegateOptionsInsert adds key/value to the given
// TfLiteExternalDelegateOptions instance.
TfLiteStatus TfLiteExternalDelegateOptionsInsert(
    TfLiteExternalDelegateOptions* options, const char* key,
    const char* value) {
  if (options->count >= kMaxOptions) {
    return kTfLiteError;
  }
  options->keys[options->count] = key;
  options->values[options->count] = value;
  options->count++;
  return kTfLiteOk;
}

TfLiteExternalDelegateOptions TfLiteExternalDelegateOptionsDefault(
    const char* lib_path) {
  // As 'keys' and 'values' don't need to be set here, using designated
  // initializers may cause a compiling error as "non-trivial designated
  // initializers not supported" by some compiler.
  TfLiteExternalDelegateOptions options;
  options.lib_path = lib_path;
  options.count = 0;
  options.insert = TfLiteExternalDelegateOptionsInsert;
  return options;
}

TfLiteDelegate* TfLiteExternalDelegateCreate(
    const TfLiteExternalDelegateOptions* options) {
  auto* external_delegate_wrapper =
      new tflite::ExternalDelegateWrapper(options);
  if (external_delegate_wrapper) {
    return external_delegate_wrapper->tflite_wrapper_delegate();
  }
  return nullptr;
}

void TfLiteExternalDelegateDelete(TfLiteDelegate* delegate) {
  delete tflite::GetExternalDelegateWrapper(delegate);
}
<|endoftext|>


<commit_before>#ifndef TOPPRA_CONST_ACCEL_HPP
#define TOPPRA_CONST_ACCEL_HPP

#include <toppra/parametrizer.hpp>
#include <toppra/toppra.hpp>

namespace toppra {

namespace parametrizer {

/** \brief A path parametrizer with constant acceleration assumption.
 *
 * We assume that in each segment, the path acceleration is constant.
 */
class ConstAccel : public Parametrizer {
 public:
  ConstAccel(GeometricPathPtr path, const Vector &gridpoints, const Vector &vsquared);

  const Vector get_m_ts() {return m_ts;}

 private:
  /** Return joint derivatives at specified times. */
  Vectors eval_impl(const Vector &times, int order = 0) const override;
  bool validate_impl() const override;
  Bound pathInterval_impl() const override;

  /** \brief Evaluate path variables ss, vs, and us at the input time instances.
   *
   * For each t, a starting gridpoint will be selected. The selected
   * path position, velocity and acceleration is then used to compute
   * the corresponding output quantities.
   *
   * \param[in] ts Time instances to be evaluated, starting from zero seconds.
   * \param[out] ss Path positions at the given time instances.
   * \param[out] vs Path velocities at the given time instances.
   * \param[out] us Path accelerations at the given time instances.
   *
   */
  bool evalParams(const Vector &ts, Vector &ss, Vector &vs, Vector &us) const;
  // Compute times and acclerations from given data (path, velocities)
  void process_internals();
  // Vector of time instances (corresponded to gridpoints)
  Vector m_ts;
  // Vector of accelerations (corresponded to gridpoints). Should have size
  // shorter than m_ts and m_vs by 1.
  Vector m_us;
};
}  // namespace parametrizer

}  // namespace toppra

#endif
<commit_msg>Fixed function name, made return reference.<commit_after>#ifndef TOPPRA_CONST_ACCEL_HPP
#define TOPPRA_CONST_ACCEL_HPP

#include <toppra/parametrizer.hpp>
#include <toppra/toppra.hpp>

namespace toppra {

namespace parametrizer {

/** \brief A path parametrizer with constant acceleration assumption.
 *
 * We assume that in each segment, the path acceleration is constant.
 */
class ConstAccel : public Parametrizer {
 public:
  ConstAccel(GeometricPathPtr path, const Vector &gridpoints, const Vector &vsquared);

  const Vector& getTs() { return m_ts; }

 private:
  /** Return joint derivatives at specified times. */
  Vectors eval_impl(const Vector &times, int order = 0) const override;
  bool validate_impl() const override;
  Bound pathInterval_impl() const override;

  /** \brief Evaluate path variables ss, vs, and us at the input time instances.
   *
   * For each t, a starting gridpoint will be selected. The selected
   * path position, velocity and acceleration is then used to compute
   * the corresponding output quantities.
   *
   * \param[in] ts Time instances to be evaluated, starting from zero seconds.
   * \param[out] ss Path positions at the given time instances.
   * \param[out] vs Path velocities at the given time instances.
   * \param[out] us Path accelerations at the given time instances.
   *
   */
  bool evalParams(const Vector &ts, Vector &ss, Vector &vs, Vector &us) const;
  // Compute times and acclerations from given data (path, velocities)
  void process_internals();
  // Vector of time instances (corresponded to gridpoints)
  Vector m_ts;
  // Vector of accelerations (corresponded to gridpoints). Should have size
  // shorter than m_ts and m_vs by 1.
  Vector m_us;
};
}  // namespace parametrizer

}  // namespace toppra

#endif
<|endoftext|>


<commit_before>/*
 * Copyright 2006-2008 The FLWOR Foundation.
 *
 * 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 <iostream>
#include <sstream>
#include <fstream>
#include <vector>
#include <string>
#include <cstring>
#include <stdio.h>
#include <stdlib.h>
#include <cstring>

#include "testdriverconfig.h" // SRC and BIN dir definitions
#include "testuriresolver.h"
#include "specification.h" // parsing spec files
#include "common/common.h"

#include <zorba/zorba.h>
#include <zorba/error_handler.h>
#include <zorba/exception.h>
#include <zorba/zorbastring.h>
#include <zorba/util/file.h>
#include <zorba/static_context_consts.h>

#include <zorbautils/strutil.h>

#include <simplestore/simplestore.h>

#include "util/properties.h"
#include "testdriver_comparator.h"

bool isErrorExpected(zorba::ZorbaException& e, State* aState) {
  if ( aState->hasErrors) {
    std::vector<std::string>::const_iterator lIter = aState->theErrors.begin();
    std::vector<std::string>::const_iterator lEnd  = aState->theErrors.end();
    zorba::String lError = zorba::ZorbaException::getErrorCodeAsString(e.getErrorCode());
    for(;lIter!=lEnd;++lIter)
    {
      zorba::String lSpecError = *lIter;
      if (lError.compare(lSpecError) == 0) {
        return true;
      }
    }
  }
  return false;
}

Zorba_CompilerHints
getCompilerHints()
{
  Zorba_CompilerHints lHints;

  // ZORBA_OPTLEVEL=O0 | O1
  char* lOptLevel = getenv("ZORBA_OPTLEVEL");
  if ( lOptLevel != NULL && strcmp(lOptLevel, "O0") == 0 ) {
    lHints.opt_level = ZORBA_OPT_LEVEL_O0;
    std::cout << "testdriver is using optimization level O0" << std::endl;
  } else {
    lHints.opt_level = ZORBA_OPT_LEVEL_O1;
    std::cout << "testdriver is using optimization level O1" << std::endl;
  }
  return lHints;
}

// set a variable in the dynamic context
// inlineFile specifies whether the given parameter is a file and it's value should
// be inlined or not
void
set_var (bool inlineFile, std::string name, std::string val, zorba::DynamicContext* dctx)
{
  zorba::str_replace_all(val, "$UPDATE_SRC_DIR", zorba::UPDATE_SRC_DIR);

  zorba::ItemFactory* lFactory = zorba::Zorba::getInstance(NULL)->getItemFactory();

  if (!inlineFile)
  {
    zorba::Item lItem = lFactory->createString(val);
		if(name != ".")
			dctx->setVariable (name, lItem);
		else
			dctx->setContextItem (lItem);
  }
  else
  {
    std::ifstream* is = new std::ifstream(val.c_str ());

    if ( *is==NULL )
      std::cout << "Error: Location not found: " << val.c_str() << std::endl;

    assert (*is);

    if(name != ".")
    {
      dctx->setVariableAsDocument(name,
                                  val.c_str(),
                                  std::auto_ptr<std::istream>(is),
                                  validate_lax);
    }
    else
    {
      dctx->setContextItemAsDocument (val.c_str(), std::auto_ptr<std::istream>(is));
    }
  }
}

int
#ifdef _WIN32_WCE
_tmain(int argc, _TCHAR* argv[])
#else
main(int argc, char** argv)
#endif
{
  if (argc != 2)
  {
    std::cout << "\nusage:   testdriver [testfile]" << std::endl;
    return 1;
  }

  zorba::Properties::load (NULL, NULL);

  zorba::Zorba* engine = zorba::Zorba::getInstance(zorba::simplestore::SimpleStoreManager::getStore());

  Specification lSpec;
  int flags = zorba::file::CONVERT_SLASHES | zorba::file::RESOLVE;

  std::string srcDir = zorba::UPDATE_SRC_DIR;
  std::string binDir = zorba::UPDATE_BINARY_DIR;

  std::string argString = std::string(argv[1]);
  std::string lSpecNoSuffix = argString.substr(0, argString.size()-5);

  std::string lSpecFileString  = srcDir + "/Queries/" + argv[1];
  zorba::file lSpecFile(lSpecFileString, flags);
  zorba::filesystem_path lSpecPath(lSpecFile.branch_path());

  if ( (! lSpecFile.exists ()) || lSpecFile.is_directory () )
  {
    std::cout << "\n spec file " << lSpecFile.get_path()
              << " does not exist or is not a file" << std::endl;
    return 2;
  }

  std::cout << "test " << lSpecNoSuffix << std::endl;

  std::string lResultFileString = binDir+"/QueryResults/"+lSpecNoSuffix+".res";
  zorba::file lResultFile(lResultFileString, flags);
  if (!lResultFile.exists())
    zorba::file(lResultFile.branch_path()).deep_mkdir();

  std::string lRefFileString = srcDir+"/ExpectedTestResults/"+lSpecNoSuffix+".xml.res";
  zorba::file lRefFile(lRefFileString, flags);
  zorba::filesystem_path lRefPath(lRefFile.branch_path());

  // read the xargs and errors if the spec file exists
  lSpec.parseFile(lSpecFile.get_path());

  Zorba_SerializerOptions lSerOptions;
  lSerOptions.omit_xml_declaration = ZORBA_OMIT_XML_DECLARATION_YES;

  int lRun = 0;
  std::vector<State*>::const_iterator lIter = lSpec.statesBegin();
  std::vector<State*>::const_iterator lEnd = lSpec.statesEnd();

  std::vector<zorba::XQuery_t> lQueries;

  for(; lIter != lEnd; ++lIter)
  {
    State* lState = *lIter;

    std::string   qname_str;
    if(lSpecPath.get_path().find("XQueryX") == std::string::npos)
      qname_str = (*lIter)->theName + ".xq";
    else
      qname_str = (*lIter)->theName + ".xqx";
    std::cout << "qname_str " << qname_str << std::endl;

    zorba::filesystem_path lQueryName(qname_str,
                                      zorba::file::CONVERT_SLASHES);
    zorba::filesystem_path lQueryFile(lSpecPath, lQueryName);

    std::cout << std::endl << "Query (Run " << ++lRun << "):" << std::endl;
    std::cout << "Query file " << lQueryFile << ": " << std::endl;
    zorba::printFile(std::cout, lQueryFile);
    std::cout << std::endl;
    std::ifstream lQueryStream(lQueryFile.c_str());

    try
    {
      zorba::StaticContext_t lContext = engine->createStaticContext();
      std::string path = lQueryFile.get_path();

      std::auto_ptr<zorba::TestSchemaURIResolver> resolver;
      if ( path.find ( "w3c_update_testsuite" ) != std::string::npos )
      {
        std::string uri_map_file = srcDir + "/Queries/w3c_update_testsuite/TestSources/uri.txt";
        resolver.reset(new zorba::TestSchemaURIResolver ( uri_map_file.c_str() ));
        lContext->setSchemaURIResolver ( resolver.get() );

        if (path.find("ValSkip") != std::string::npos ||
            path.find("ValLax") != std::string::npos)
          lContext->setBoundarySpacePolicy(preserve_space);

      	zorba::String lProlog = zorba::String(std::string("import schema 'http://www.w3.org/XML/1998/namespace';\n"));

        lContext->loadProlog(lProlog, getCompilerHints());
      }

      zorba::XQuery_t lQuery = engine->createQuery();
      lQuery->setFileName (lQueryFile.c_str());
      lQuery->compile(lQueryStream, lContext, getCompilerHints());
      lQueries.push_back(lQuery);
    }
    catch (zorba::ZorbaException &e)
    {
      if (isErrorExpected(e, lState))
      {
        std::cout << "Expected compiler error:\n" << e << std::endl;
        std::cout << "updtestdriver: success" << std::endl;
        return 0;
      }
      else
      {
        std::cout << "Unexpected compiler error:\n" << e << std::endl;
        return 3;
      }
    }

    try
    {
      zorba::DynamicContext* lDynCtx = lQueries.back()->getDynamicContext();
      if (lState->hasDate)
      {
        std::string lDateTime = lState->theDate;
        if (lDateTime.find("T") == std::string::npos) {
          lDateTime += "T00:00:00";
        }
        lDynCtx->setCurrentDateTime(engine->getItemFactory()->createDateTime(lDateTime));
      }

      std::vector<Variable*>::const_iterator lVarIter = (*lIter)->varsBegin();
      std::vector<Variable*>::const_iterator lVarEnd = (*lIter)->varsEnd();

      for(; lVarIter != lVarEnd; ++lVarIter)
      {
        Variable* lVar = *lVarIter;
        set_var(lVar->theInline, lVar->theName, lVar->theValue, lDynCtx);
      }
    }
    catch (zorba::ZorbaException &e)
    {
      if (isErrorExpected(e, lState)) {
        std::cout << "Expected execution error:\n" << e << std::endl;
        continue;
      } else {
        std::cout << "Unexpected execution error:\n" << e << std::endl;
        return 6;
      }
    }

    try
    {
      if (lQueries.back()->isUpdateQuery())
      {
        zorba::XQuery_t query = lQueries.back();
        query->applyUpdates();

        std::cout << "Updating Query -> no Result" << std::endl;
      }
      else
      {
        if ( lResultFile.exists ())
          lResultFile.remove();

        std::ofstream lResFileStream(lResultFile.get_path().c_str());
        lQueries.back()->serialize(lResFileStream, &lSerOptions);
        lResFileStream.flush();

        if (lState->hasCompare)
        {
          bool lRes = false;
          bool anyMatch = false;
          ulong numRefs = lState->theCompares.size();
          for (ulong i = 0; i < numRefs && !lRes; i++)
          {
            std::string lRefFileTmpString = lRefPath;

            // the ref file is the same for xqueryx and xquery tests
            // hence, we remove the string xqueryx or xquery from the path
            size_t lPosOfW3C = lRefPath.get_path().find("w3c_update_testsuite");
            if (lPosOfW3C != std::string::npos)
            {
              if (lRefPath.get_path().find("XQueryX", lPosOfW3C) != std::string::npos)
                lRefFileTmpString = lRefFileTmpString.erase(lPosOfW3C + 21, 8);
              else
                lRefFileTmpString = lRefFileTmpString.erase(lPosOfW3C + 21, 7);
            }

            zorba::filesystem_path lRefFile(lRefFileTmpString,
                                            zorba::filesystem_path(lState->theCompares[i],
                                                                   zorba::file::CONVERT_SLASHES));
            std::cout << std::endl << "Ref " << lRefFile.get_path()  << std::endl;

            int lLine, lCol, lPos;
            std::string lRefLine, lResultLine;
            lRes = zorba::fileEquals(lRefFile.get_path().c_str(),
                                     lResultFile.get_path().c_str(),
                                     lLine, lCol, lPos, lRefLine, lResultLine);

            // if the simple comparison doesn't work, we do the full-fledged
            // xml canonical comparison
            if (lRes)
            {
              std::cout << "updtestdriver: success (non-canonical result matches)"
                        << std::endl;
              anyMatch = true;
              break;
            }
            else
            {
              std::cout << "Actual and Reference results are not identical"
                        << std::endl << std::endl
                        << "Actual Result " << lResultFile.get_path() << ": "
                        << std::endl << std::endl;

              zorba::printFile(std::cout, lResultFile.get_path());

              std::cout << "Reference Result " << lRefFile.get_path() << ": "
                        << std::endl << std::endl;

              zorba::printFile(std::cout, lRefFile.get_path());

              std::cout << std::endl << std::endl;

              int lCanonicalRes =
              zorba::canonicalizeAndCompare(State::compareTypeStr(lState->theCompareTypes[i]),
                                            lRefFile.get_path().c_str(),
                                            lResultFile.get_path().c_str(),
                                            zorba::UPDATE_BINARY_DIR.c_str());
              if (lCanonicalRes == 0)
              {
                anyMatch = true;
                break;
              }
            }
          } // multiple compare possible

          if (!anyMatch)
          {
            return 4;
          }

        }
        else if (lState->hasErrors)
        {
          std::cout << "Query must throw an error!" << std::endl;
          return 5;
        }
        else
        {
          std::cout << "Query returns result but no expected result defined!"
                    << std::endl;
        }
      } // if non-updating query
    }
    catch (zorba::ZorbaException &e)
    {
      if (isErrorExpected(e, lState)) {
        std::cout << "Expected execution error:\n" << e << std::endl;
        continue;
      } else {
        std::cout << "Unexpected execution error:\n" << e << std::endl;
        return 6;
      }
    }
  } // for each query described in the spec file

  std::cout << "updtestdriver: success" << std::endl;
  return 0;
}
<commit_msg>temporarily disabled the loadProlog to make CDash tests pass<commit_after>/*
 * Copyright 2006-2008 The FLWOR Foundation.
 *
 * 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 <iostream>
#include <sstream>
#include <fstream>
#include <vector>
#include <string>
#include <cstring>
#include <stdio.h>
#include <stdlib.h>
#include <cstring>

#include "testdriverconfig.h" // SRC and BIN dir definitions
#include "testuriresolver.h"
#include "specification.h" // parsing spec files
#include "common/common.h"

#include <zorba/zorba.h>
#include <zorba/error_handler.h>
#include <zorba/exception.h>
#include <zorba/zorbastring.h>
#include <zorba/util/file.h>
#include <zorba/static_context_consts.h>

#include <zorbautils/strutil.h>

#include <simplestore/simplestore.h>

#include "util/properties.h"
#include "testdriver_comparator.h"

bool isErrorExpected(zorba::ZorbaException& e, State* aState) {
  if ( aState->hasErrors) {
    std::vector<std::string>::const_iterator lIter = aState->theErrors.begin();
    std::vector<std::string>::const_iterator lEnd  = aState->theErrors.end();
    zorba::String lError = zorba::ZorbaException::getErrorCodeAsString(e.getErrorCode());
    for(;lIter!=lEnd;++lIter)
    {
      zorba::String lSpecError = *lIter;
      if (lError.compare(lSpecError) == 0) {
        return true;
      }
    }
  }
  return false;
}

Zorba_CompilerHints
getCompilerHints()
{
  Zorba_CompilerHints lHints;

  // ZORBA_OPTLEVEL=O0 | O1
  char* lOptLevel = getenv("ZORBA_OPTLEVEL");
  if ( lOptLevel != NULL && strcmp(lOptLevel, "O0") == 0 ) {
    lHints.opt_level = ZORBA_OPT_LEVEL_O0;
    std::cout << "testdriver is using optimization level O0" << std::endl;
  } else {
    lHints.opt_level = ZORBA_OPT_LEVEL_O1;
    std::cout << "testdriver is using optimization level O1" << std::endl;
  }
  return lHints;
}

// set a variable in the dynamic context
// inlineFile specifies whether the given parameter is a file and it's value should
// be inlined or not
void
set_var (bool inlineFile, std::string name, std::string val, zorba::DynamicContext* dctx)
{
  zorba::str_replace_all(val, "$UPDATE_SRC_DIR", zorba::UPDATE_SRC_DIR);

  zorba::ItemFactory* lFactory = zorba::Zorba::getInstance(NULL)->getItemFactory();

  if (!inlineFile)
  {
    zorba::Item lItem = lFactory->createString(val);
		if(name != ".")
			dctx->setVariable (name, lItem);
		else
			dctx->setContextItem (lItem);
  }
  else
  {
    std::ifstream* is = new std::ifstream(val.c_str ());

    if ( *is==NULL )
      std::cout << "Error: Location not found: " << val.c_str() << std::endl;

    assert (*is);

    if(name != ".")
    {
      dctx->setVariableAsDocument(name,
                                  val.c_str(),
                                  std::auto_ptr<std::istream>(is),
                                  validate_lax);
    }
    else
    {
      dctx->setContextItemAsDocument (val.c_str(), std::auto_ptr<std::istream>(is));
    }
  }
}

int
#ifdef _WIN32_WCE
_tmain(int argc, _TCHAR* argv[])
#else
main(int argc, char** argv)
#endif
{
  if (argc != 2)
  {
    std::cout << "\nusage:   testdriver [testfile]" << std::endl;
    return 1;
  }

  zorba::Properties::load (NULL, NULL);

  zorba::Zorba* engine = zorba::Zorba::getInstance(zorba::simplestore::SimpleStoreManager::getStore());

  Specification lSpec;
  int flags = zorba::file::CONVERT_SLASHES | zorba::file::RESOLVE;

  std::string srcDir = zorba::UPDATE_SRC_DIR;
  std::string binDir = zorba::UPDATE_BINARY_DIR;

  std::string argString = std::string(argv[1]);
  std::string lSpecNoSuffix = argString.substr(0, argString.size()-5);

  std::string lSpecFileString  = srcDir + "/Queries/" + argv[1];
  zorba::file lSpecFile(lSpecFileString, flags);
  zorba::filesystem_path lSpecPath(lSpecFile.branch_path());

  if ( (! lSpecFile.exists ()) || lSpecFile.is_directory () )
  {
    std::cout << "\n spec file " << lSpecFile.get_path()
              << " does not exist or is not a file" << std::endl;
    return 2;
  }

  std::cout << "test " << lSpecNoSuffix << std::endl;

  std::string lResultFileString = binDir+"/QueryResults/"+lSpecNoSuffix+".res";
  zorba::file lResultFile(lResultFileString, flags);
  if (!lResultFile.exists())
    zorba::file(lResultFile.branch_path()).deep_mkdir();

  std::string lRefFileString = srcDir+"/ExpectedTestResults/"+lSpecNoSuffix+".xml.res";
  zorba::file lRefFile(lRefFileString, flags);
  zorba::filesystem_path lRefPath(lRefFile.branch_path());

  // read the xargs and errors if the spec file exists
  lSpec.parseFile(lSpecFile.get_path());

  Zorba_SerializerOptions lSerOptions;
  lSerOptions.omit_xml_declaration = ZORBA_OMIT_XML_DECLARATION_YES;

  int lRun = 0;
  std::vector<State*>::const_iterator lIter = lSpec.statesBegin();
  std::vector<State*>::const_iterator lEnd = lSpec.statesEnd();

  std::vector<zorba::XQuery_t> lQueries;

  for(; lIter != lEnd; ++lIter)
  {
    State* lState = *lIter;

    std::string   qname_str;
    if(lSpecPath.get_path().find("XQueryX") == std::string::npos)
      qname_str = (*lIter)->theName + ".xq";
    else
      qname_str = (*lIter)->theName + ".xqx";
    std::cout << "qname_str " << qname_str << std::endl;

    zorba::filesystem_path lQueryName(qname_str,
                                      zorba::file::CONVERT_SLASHES);
    zorba::filesystem_path lQueryFile(lSpecPath, lQueryName);

    std::cout << std::endl << "Query (Run " << ++lRun << "):" << std::endl;
    std::cout << "Query file " << lQueryFile << ": " << std::endl;
    zorba::printFile(std::cout, lQueryFile);
    std::cout << std::endl;
    std::ifstream lQueryStream(lQueryFile.c_str());

    try
    {
      zorba::StaticContext_t lContext = engine->createStaticContext();
      std::string path = lQueryFile.get_path();

      std::auto_ptr<zorba::TestSchemaURIResolver> resolver;
      if ( path.find ( "w3c_update_testsuite" ) != std::string::npos )
      {
        std::string uri_map_file = srcDir + "/Queries/w3c_update_testsuite/TestSources/uri.txt";
        resolver.reset(new zorba::TestSchemaURIResolver ( uri_map_file.c_str() ));
        lContext->setSchemaURIResolver ( resolver.get() );

        if (path.find("ValSkip") != std::string::npos ||
            path.find("ValLax") != std::string::npos)
          lContext->setBoundarySpacePolicy(preserve_space);
#if 0
      	zorba::String lProlog = zorba::String(std::string("import schema 'http://www.w3.org/XML/1998/namespace';\n"));

        lContext->loadProlog(lProlog, getCompilerHints());
#endif
      }

      zorba::XQuery_t lQuery = engine->createQuery();
      lQuery->setFileName (lQueryFile.c_str());
      lQuery->compile(lQueryStream, lContext, getCompilerHints());
      lQueries.push_back(lQuery);
    }
    catch (zorba::ZorbaException &e)
    {
      if (isErrorExpected(e, lState))
      {
        std::cout << "Expected compiler error:\n" << e << std::endl;
        std::cout << "updtestdriver: success" << std::endl;
        return 0;
      }
      else
      {
        std::cout << "Unexpected compiler error:\n" << e << std::endl;
        return 3;
      }
    }

    try
    {
      zorba::DynamicContext* lDynCtx = lQueries.back()->getDynamicContext();
      if (lState->hasDate)
      {
        std::string lDateTime = lState->theDate;
        if (lDateTime.find("T") == std::string::npos) {
          lDateTime += "T00:00:00";
        }
        lDynCtx->setCurrentDateTime(engine->getItemFactory()->createDateTime(lDateTime));
      }

      std::vector<Variable*>::const_iterator lVarIter = (*lIter)->varsBegin();
      std::vector<Variable*>::const_iterator lVarEnd = (*lIter)->varsEnd();

      for(; lVarIter != lVarEnd; ++lVarIter)
      {
        Variable* lVar = *lVarIter;
        set_var(lVar->theInline, lVar->theName, lVar->theValue, lDynCtx);
      }
    }
    catch (zorba::ZorbaException &e)
    {
      if (isErrorExpected(e, lState)) {
        std::cout << "Expected execution error:\n" << e << std::endl;
        continue;
      } else {
        std::cout << "Unexpected execution error:\n" << e << std::endl;
        return 6;
      }
    }

    try
    {
      if (lQueries.back()->isUpdateQuery())
      {
        zorba::XQuery_t query = lQueries.back();
        query->applyUpdates();

        std::cout << "Updating Query -> no Result" << std::endl;
      }
      else
      {
        if ( lResultFile.exists ())
          lResultFile.remove();

        std::ofstream lResFileStream(lResultFile.get_path().c_str());
        lQueries.back()->serialize(lResFileStream, &lSerOptions);
        lResFileStream.flush();

        if (lState->hasCompare)
        {
          bool lRes = false;
          bool anyMatch = false;
          ulong numRefs = lState->theCompares.size();
          for (ulong i = 0; i < numRefs && !lRes; i++)
          {
            std::string lRefFileTmpString = lRefPath;

            // the ref file is the same for xqueryx and xquery tests
            // hence, we remove the string xqueryx or xquery from the path
            size_t lPosOfW3C = lRefPath.get_path().find("w3c_update_testsuite");
            if (lPosOfW3C != std::string::npos)
            {
              if (lRefPath.get_path().find("XQueryX", lPosOfW3C) != std::string::npos)
                lRefFileTmpString = lRefFileTmpString.erase(lPosOfW3C + 21, 8);
              else
                lRefFileTmpString = lRefFileTmpString.erase(lPosOfW3C + 21, 7);
            }

            zorba::filesystem_path lRefFile(lRefFileTmpString,
                                            zorba::filesystem_path(lState->theCompares[i],
                                                                   zorba::file::CONVERT_SLASHES));
            std::cout << std::endl << "Ref " << lRefFile.get_path()  << std::endl;

            int lLine, lCol, lPos;
            std::string lRefLine, lResultLine;
            lRes = zorba::fileEquals(lRefFile.get_path().c_str(),
                                     lResultFile.get_path().c_str(),
                                     lLine, lCol, lPos, lRefLine, lResultLine);

            // if the simple comparison doesn't work, we do the full-fledged
            // xml canonical comparison
            if (lRes)
            {
              std::cout << "updtestdriver: success (non-canonical result matches)"
                        << std::endl;
              anyMatch = true;
              break;
            }
            else
            {
              std::cout << "Actual and Reference results are not identical"
                        << std::endl << std::endl
                        << "Actual Result " << lResultFile.get_path() << ": "
                        << std::endl << std::endl;

              zorba::printFile(std::cout, lResultFile.get_path());

              std::cout << "Reference Result " << lRefFile.get_path() << ": "
                        << std::endl << std::endl;

              zorba::printFile(std::cout, lRefFile.get_path());

              std::cout << std::endl << std::endl;

              int lCanonicalRes =
              zorba::canonicalizeAndCompare(State::compareTypeStr(lState->theCompareTypes[i]),
                                            lRefFile.get_path().c_str(),
                                            lResultFile.get_path().c_str(),
                                            zorba::UPDATE_BINARY_DIR.c_str());
              if (lCanonicalRes == 0)
              {
                anyMatch = true;
                break;
              }
            }
          } // multiple compare possible

          if (!anyMatch)
          {
            return 4;
          }

        }
        else if (lState->hasErrors)
        {
          std::cout << "Query must throw an error!" << std::endl;
          return 5;
        }
        else
        {
          std::cout << "Query returns result but no expected result defined!"
                    << std::endl;
        }
      } // if non-updating query
    }
    catch (zorba::ZorbaException &e)
    {
      if (isErrorExpected(e, lState)) {
        std::cout << "Expected execution error:\n" << e << std::endl;
        continue;
      } else {
        std::cout << "Unexpected execution error:\n" << e << std::endl;
        return 6;
      }
    }
  } // for each query described in the spec file

  std::cout << "updtestdriver: success" << std::endl;
  return 0;
}
<|endoftext|>


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

using namespace View;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        }
    }
}
<commit_msg>Forgot to uncomment some stuff.<commit_after>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>

using namespace View;

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

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

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

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

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

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

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

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

            //Creating and formatting each QLineEdit field.
            fields[i][j] = new QLineEdit();
            QValidator *val = new QIntValidator(1,9,fields[i][j]);
            fields[i][j]->setValidator(val);
            fields[i][j]->setObjectName(QString::number(i) + "_" + QString::number(j));
            fields[i][j]->setFixedHeight(31);
            fields[i][j]->setFixedWidth(41);
            fields[i][j]->setAlignment(Qt::AlignCenter);
            fields[i][j]->setStyleSheet("font: 18pt;");

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

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

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

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

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

        }
    }
}
<|endoftext|>


<commit_before>#include <bits/stdc++.h>
using namespace std;

// ---- Start ----
template<typename T, typename Cmp=less<T> >
void quick_sort(T *beg, T *end, const Cmp &cmp = Cmp()){
    if(beg == end || beg+1==end)return;
    T mid = *beg;
    T *l = beg+1, *r = end-1;
    while(l != r+1){
        if(cmp(mid, *r))r--;
        else if(cmp(*l, mid))l++;
        else swap(*l,*r);
    }
    swap(*beg, *r);
    quick_sort(beg,r,cmp);
    quick_sort(r+1,end,cmp);
}
// ---- End ----

// ---- Demo ----
const int N = 10;
int A[N];
void print(){
    cout<<"A: ";
    for(int i=0;i<N;i++){
        cout<<A[i]<<' ';
    }
    cout<<endl;
}

int main(){
    for(int i=0;i<N;i++){
        A[i] = i;
    }
    random_shuffle(A,A+N);
    print();
    quick_sort(A,A+N);
    print();
    while(1);
}<commit_msg>fix quick sort bug<commit_after>#include <bits/stdc++.h>
using namespace std;

// ---- Start ----
template<typename T, typename Cmp=less<T> >
void quick_sort(T *beg, T *end, const Cmp &cmp = Cmp()){
    if(beg == end || beg+1==end)return;
    T mid = *beg;
    T *l = beg+1, *r = end-1;
    while(l != r+1){
        if(cmp(mid, *r))r--;
        else if(!cmp(mid, *l))l++;
        else swap(*l,*r);
    }
    swap(*beg, *r);
    quick_sort(beg,r,cmp);
    quick_sort(r+1,end,cmp);
}
// ---- End ----

// ---- Demo ----
const int N = 10;
int A[N];
void print(){
    cout<<"A: ";
    for(int i=0;i<N;i++){
        cout<<A[i]<<' ';
    }
    cout<<endl;
}

int main(){
    for(int i=0;i<N;i++){
        A[i] = rand()%(i+1);
    }
    random_shuffle(A,A+N);
    print();
    quick_sort(A,A+N);
    print();
    while(1);
}<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: optupdt.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: ihi $ $Date: 2006-08-04 09:48:19 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifdef SVX_DLLIMPLEMENTATION
#undef SVX_DLLIMPLEMENTATION
#endif

// include ---------------------------------------------------------------

#ifndef _FILEDLGHELPER_HXX
#include <sfx2/filedlghelper.hxx>
#endif

#include "optupdt.hxx"
#include "optupdt.hrc"

#include "dialmgr.hxx"
#include "dialogs.hrc"

#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif

#ifndef  _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

#ifndef  _COM_SUN_STAR_UI_DIALOGS_XFOLDERPICKER_HPP_
#include <com/sun/star/ui/dialogs/XFolderPicker.hpp>
#endif

#ifndef  _COM_SUN_STAR_UI_DIALOGS_EXECUTABLEDIALOGRESULTS_HPP_
#include <com/sun/star/ui/dialogs/ExecutableDialogResults.hpp>
#endif

#ifndef  _COM_SUN_STAR_FRAME_XDESKTOP_HPP_
#include <com/sun/star/frame/XDesktop.hpp>
#endif

#ifndef  _COM_SUN_STAR_FRAME_XDISPATCHPROVIDER_HPP_
#include <com/sun/star/frame/XDispatchProvider.hpp>
#endif

#ifndef _COM_SUN_STAR_UTIL_XCHANGESBATCH_HPP_
#include <com/sun/star/util/XChangesBatch.hpp>
#endif

#ifndef _COM_SUN_STAR_UTIL_XURLTRANSFORMER_HPP_
#include <com/sun/star/util/XURLTransformer.hpp>
#endif

#include <osl/file.hxx>
#include <osl/security.hxx>

namespace beans = ::com::sun::star::beans;
namespace container = ::com::sun::star::container;
namespace dialogs = ::com::sun::star::ui::dialogs;
namespace frame = ::com::sun::star::frame;
namespace lang = ::com::sun::star::lang;
namespace uno = ::com::sun::star::uno;
namespace util = ::com::sun::star::util;

// define ----------------------------------------------------------------

#define UNISTRING(s) rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(s))

// class SvxOnlineUpdateTabPage --------------------------------------------------

SvxOnlineUpdateTabPage::SvxOnlineUpdateTabPage( Window* pParent, const SfxItemSet& rSet ) :

    SfxTabPage( pParent, SVX_RES( RID_SVXPAGE_ONLINEUPDATE ), rSet ),
        m_aOptionsLine( this, ResId( FL_OPTIONS ) ),
        m_aAutoCheckCheckBox( this, ResId( CB_AUTOCHECK ) ),
        m_aEveryDayButton( this, ResId( RB_EVERYDAY ) ),
        m_aEveryWeekButton( this, ResId( RB_EVERYWEEK ) ),
        m_aEveryMonthButton( this, ResId( RB_EVERYMONTH ) ),
        m_aCheckNowButton( this, ResId( PB_CHECKNOW ) ),
        m_aAutoDownloadCheckBox( this, ResId( CB_AUTODOWNLOAD ) ),
        m_aDestPathLabel( this, ResId( FT_DESTPATHLABEL ) ),
        m_aDestPath( this, ResId( FT_DESTPATH ) ),
        m_aChangePathButton( this, ResId( PB_CHANGEPATH ) )
{
    FreeResource();

    m_aAutoCheckCheckBox.SetClickHdl( LINK( this, SvxOnlineUpdateTabPage, AutoCheckHdl_Impl ) );
    m_aCheckNowButton.SetClickHdl( LINK( this, SvxOnlineUpdateTabPage, CheckNowHdl_Impl ) );
    m_aAutoDownloadCheckBox.SetClickHdl( LINK( this, SvxOnlineUpdateTabPage, AutoDownloadHdl_Impl ) );
    m_aChangePathButton.SetClickHdl( LINK( this, SvxOnlineUpdateTabPage, FileDialogHdl_Impl ) );

    uno::Reference < lang::XMultiServiceFactory > xFactory( ::comphelper::getProcessServiceFactory() );

    m_xUpdateAccess = uno::Reference < container::XNameReplace >(
        xFactory->createInstance( UNISTRING( "com.sun.star.setup.UpdateCheckConfig" ) ),
        uno::UNO_QUERY_THROW );

    sal_Bool bDownloadSupported;
    m_xUpdateAccess->getByName( UNISTRING( "DownloadSupported") ) >>= bDownloadSupported;

    WinBits nStyle = m_aDestPath.GetStyle();
    nStyle |= WB_PATHELLIPSIS;
    m_aDestPath.SetStyle(nStyle);

    m_aAutoDownloadCheckBox.Show(bDownloadSupported);
    m_aDestPathLabel.Show(bDownloadSupported);
    m_aDestPath.Show(bDownloadSupported);
    m_aChangePathButton.Show(bDownloadSupported);
}

// -----------------------------------------------------------------------

SvxOnlineUpdateTabPage::~SvxOnlineUpdateTabPage()
{
}

// -----------------------------------------------------------------------

SfxTabPage*
SvxOnlineUpdateTabPage::Create( Window* pParent, const SfxItemSet& rAttrSet )
{
    return new SvxOnlineUpdateTabPage( pParent, rAttrSet );
}

// -----------------------------------------------------------------------

BOOL SvxOnlineUpdateTabPage::FillItemSet( SfxItemSet& )
{
    BOOL bModified = FALSE;

    sal_Bool bValue;
    sal_Int64 nValue;

    if( m_aAutoCheckCheckBox.GetSavedValue() != m_aAutoCheckCheckBox.IsChecked() )
    {
        bValue = (TRUE == m_aAutoCheckCheckBox.IsChecked());
        m_xUpdateAccess->replaceByName( UNISTRING("AutoCheckEnabled"), uno::makeAny( bValue ) );
        bModified = TRUE;
    }

    nValue = 0;
    if( TRUE == m_aEveryDayButton.IsChecked() )
    {
        if( FALSE == m_aEveryDayButton.GetSavedValue() )
            nValue = 86400;
    }
    else if( TRUE == m_aEveryWeekButton.IsChecked() )
    {
        if( FALSE == m_aEveryWeekButton.GetSavedValue() )
            nValue = 604800;
    }
    else if( TRUE == m_aEveryMonthButton.IsChecked() )
    {
        if( FALSE == m_aEveryMonthButton.GetSavedValue() )
            nValue = 2592000;
    }

    if( nValue > 0 )
    {
        m_xUpdateAccess->replaceByName( UNISTRING("CheckInterval"), uno::makeAny( nValue ) );
        bModified = TRUE;
    }

    if( m_aAutoDownloadCheckBox.GetSavedValue() != m_aAutoDownloadCheckBox.IsChecked() )
    {
        bValue = (TRUE == m_aAutoDownloadCheckBox.IsChecked());
        m_xUpdateAccess->replaceByName( UNISTRING("AutoDownloadEnabled"), uno::makeAny( bValue ) );
        bModified = TRUE;
    }

    rtl::OUString sValue, aURL;
    m_xUpdateAccess->getByName( UNISTRING("DownloadDestination") ) >>= sValue;

    if( ( osl::FileBase::E_None == osl::FileBase::getFileURLFromSystemPath(m_aDestPath.GetText(), aURL) ) &&
        ( ! aURL.equals( sValue ) ) )
    {
        m_xUpdateAccess->replaceByName( UNISTRING("DownloadDestination"), uno::makeAny( aURL ) );
        bModified = TRUE;
    }

    uno::Reference< util::XChangesBatch > xChangesBatch(m_xUpdateAccess, uno::UNO_QUERY);
    if( xChangesBatch.is() && xChangesBatch->hasPendingChanges() )
        xChangesBatch->commitChanges();

    return bModified;
}

// -----------------------------------------------------------------------

void SvxOnlineUpdateTabPage::Reset( const SfxItemSet& )
{
    sal_Bool bValue;
    m_xUpdateAccess->getByName( UNISTRING("AutoCheckEnabled") ) >>= bValue;

    m_aAutoCheckCheckBox.Check(bValue);
    m_aEveryDayButton.Enable(bValue);
    m_aEveryWeekButton.Enable(bValue);
    m_aEveryMonthButton.Enable(bValue);

    sal_Int64 nValue;
    m_xUpdateAccess->getByName( UNISTRING("CheckInterval") ) >>= nValue;

    if( nValue == 86400 )
        m_aEveryDayButton.Check();
    else if( nValue == 604800 )
        m_aEveryWeekButton.Check();
    else
        m_aEveryMonthButton.Check();

    m_aAutoCheckCheckBox.SaveValue();
    m_aEveryDayButton.SaveValue();
    m_aEveryWeekButton.SaveValue();
    m_aEveryMonthButton.SaveValue();

    m_xUpdateAccess->getByName( UNISTRING("AutoDownloadEnabled") ) >>= bValue;
    m_aAutoDownloadCheckBox.Check(bValue);
    m_aDestPathLabel.Enable(bValue);
    m_aDestPath.Enable(bValue);
    m_aChangePathButton.Enable(bValue);

    rtl::OUString sValue, aPath;
    m_xUpdateAccess->getByName( UNISTRING("DownloadDestination") ) >>= sValue;

    if( osl::FileBase::E_None == osl::FileBase::getSystemPathFromFileURL(sValue, aPath) )
        m_aDestPath.SetText(aPath);

    m_aAutoDownloadCheckBox.SaveValue();
}

// -----------------------------------------------------------------------

void SvxOnlineUpdateTabPage::FillUserData()
{
}

// -----------------------------------------------------------------------

IMPL_LINK( SvxOnlineUpdateTabPage, AutoCheckHdl_Impl, CheckBox *, pBox )
{
    BOOL bEnabled = pBox->IsChecked();

    m_aEveryDayButton.Enable(bEnabled);
    m_aEveryWeekButton.Enable(bEnabled);
    m_aEveryMonthButton.Enable(bEnabled);

    return 0;
}

// -----------------------------------------------------------------------

IMPL_LINK( SvxOnlineUpdateTabPage, AutoDownloadHdl_Impl, CheckBox *, pBox )
{
    BOOL bEnabled = pBox->IsChecked();

    m_aDestPathLabel.Enable(bEnabled);
    m_aDestPath.Enable(bEnabled);
    m_aChangePathButton.Enable(bEnabled);

    return 0;
}

// -----------------------------------------------------------------------

IMPL_LINK( SvxOnlineUpdateTabPage, FileDialogHdl_Impl, PushButton *, EMPTYARG )
{
    uno::Reference < lang::XMultiServiceFactory > xFactory( ::comphelper::getProcessServiceFactory() );
    uno::Reference < dialogs::XFolderPicker > xFolderPicker(
        xFactory->createInstance( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( FOLDER_PICKER_SERVICE_NAME ) ) ),
        uno::UNO_QUERY );

    rtl::OUString aURL;
    if( osl::FileBase::E_None != osl::FileBase::getFileURLFromSystemPath(m_aDestPath.GetText(), aURL) )
        osl::Security().getHomeDir(aURL);

    xFolderPicker->setDisplayDirectory( aURL );
    sal_Int16 nRet = xFolderPicker->execute();

    if ( dialogs::ExecutableDialogResults::OK == nRet )
    {
        rtl::OUString aFolder;
        if( osl::FileBase::E_None == osl::FileBase::getSystemPathFromFileURL(xFolderPicker->getDirectory(), aFolder))
            m_aDestPath.SetText( aFolder );
    }

    return 0;
}

// -----------------------------------------------------------------------

IMPL_LINK( SvxOnlineUpdateTabPage, CheckNowHdl_Impl, PushButton *, EMPTYARG )
{
    uno::Reference < lang::XMultiServiceFactory > xFactory( ::comphelper::getProcessServiceFactory() );

    try
    {
        uno::Reference< lang::XMultiServiceFactory > xConfigProvider(
            xFactory->createInstance( UNISTRING( "com.sun.star.configuration.ConfigurationProvider" )),
            uno::UNO_QUERY_THROW);

        beans::PropertyValue aProperty;
        aProperty.Name  = UNISTRING( "nodepath" );
        aProperty.Value = uno::makeAny( UNISTRING("org.openoffice.Office.Addons/AddonUI/OfficeHelp/UpdateCheckJob") );

        uno::Sequence< uno::Any > aArgumentList( 1 );
        aArgumentList[0] = uno::makeAny( aProperty );

        uno::Reference< container::XNameAccess > xNameAccess(
            xConfigProvider->createInstanceWithArguments(
                UNISTRING("com.sun.star.configuration.ConfigurationAccess"), aArgumentList ),
            uno::UNO_QUERY_THROW );

        util::URL aURL;
        xNameAccess->getByName(UNISTRING("URL")) >>= aURL.Complete;

        uno::Reference < util::XURLTransformer > xTransformer(
            xFactory->createInstance(  UNISTRING( "com.sun.star.util.URLTransformer" ) ),
            uno::UNO_QUERY_THROW );

        xTransformer->parseStrict(aURL);

        uno::Reference < frame::XDesktop > xDesktop(
            xFactory->createInstance(  UNISTRING( "com.sun.star.frame.Desktop" ) ),
            uno::UNO_QUERY_THROW );

        uno::Reference< frame::XDispatchProvider > xDispatchProvider(
            xDesktop->getCurrentFrame(), uno::UNO_QUERY );

        uno::Reference< frame::XDispatch > xDispatch = xDispatchProvider->queryDispatch(aURL, rtl::OUString(), 0);

        if( xDispatch.is() )
            xDispatch->dispatch(aURL, uno::Sequence< beans::PropertyValue > ());

    }
    catch( const uno::Exception& e )
    {
         OSL_TRACE( "Caught exception: %s\n thread terminated.\n",
            rtl::OUStringToOString(e.Message, RTL_TEXTENCODING_UTF8).getStr());
    }

    return 0;
}

<commit_msg>INTEGRATION: CWS pchfix02 (1.2.16); FILE MERGED 2006/09/01 17:46:20 kaib 1.2.16.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: optupdt.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 04:32:48 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"

#ifdef SVX_DLLIMPLEMENTATION
#undef SVX_DLLIMPLEMENTATION
#endif

// include ---------------------------------------------------------------

#ifndef _FILEDLGHELPER_HXX
#include <sfx2/filedlghelper.hxx>
#endif

#include "optupdt.hxx"
#include "optupdt.hrc"

#include "dialmgr.hxx"
#include "dialogs.hrc"

#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif

#ifndef  _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

#ifndef  _COM_SUN_STAR_UI_DIALOGS_XFOLDERPICKER_HPP_
#include <com/sun/star/ui/dialogs/XFolderPicker.hpp>
#endif

#ifndef  _COM_SUN_STAR_UI_DIALOGS_EXECUTABLEDIALOGRESULTS_HPP_
#include <com/sun/star/ui/dialogs/ExecutableDialogResults.hpp>
#endif

#ifndef  _COM_SUN_STAR_FRAME_XDESKTOP_HPP_
#include <com/sun/star/frame/XDesktop.hpp>
#endif

#ifndef  _COM_SUN_STAR_FRAME_XDISPATCHPROVIDER_HPP_
#include <com/sun/star/frame/XDispatchProvider.hpp>
#endif

#ifndef _COM_SUN_STAR_UTIL_XCHANGESBATCH_HPP_
#include <com/sun/star/util/XChangesBatch.hpp>
#endif

#ifndef _COM_SUN_STAR_UTIL_XURLTRANSFORMER_HPP_
#include <com/sun/star/util/XURLTransformer.hpp>
#endif

#include <osl/file.hxx>
#include <osl/security.hxx>

namespace beans = ::com::sun::star::beans;
namespace container = ::com::sun::star::container;
namespace dialogs = ::com::sun::star::ui::dialogs;
namespace frame = ::com::sun::star::frame;
namespace lang = ::com::sun::star::lang;
namespace uno = ::com::sun::star::uno;
namespace util = ::com::sun::star::util;

// define ----------------------------------------------------------------

#define UNISTRING(s) rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(s))

// class SvxOnlineUpdateTabPage --------------------------------------------------

SvxOnlineUpdateTabPage::SvxOnlineUpdateTabPage( Window* pParent, const SfxItemSet& rSet ) :

    SfxTabPage( pParent, SVX_RES( RID_SVXPAGE_ONLINEUPDATE ), rSet ),
        m_aOptionsLine( this, ResId( FL_OPTIONS ) ),
        m_aAutoCheckCheckBox( this, ResId( CB_AUTOCHECK ) ),
        m_aEveryDayButton( this, ResId( RB_EVERYDAY ) ),
        m_aEveryWeekButton( this, ResId( RB_EVERYWEEK ) ),
        m_aEveryMonthButton( this, ResId( RB_EVERYMONTH ) ),
        m_aCheckNowButton( this, ResId( PB_CHECKNOW ) ),
        m_aAutoDownloadCheckBox( this, ResId( CB_AUTODOWNLOAD ) ),
        m_aDestPathLabel( this, ResId( FT_DESTPATHLABEL ) ),
        m_aDestPath( this, ResId( FT_DESTPATH ) ),
        m_aChangePathButton( this, ResId( PB_CHANGEPATH ) )
{
    FreeResource();

    m_aAutoCheckCheckBox.SetClickHdl( LINK( this, SvxOnlineUpdateTabPage, AutoCheckHdl_Impl ) );
    m_aCheckNowButton.SetClickHdl( LINK( this, SvxOnlineUpdateTabPage, CheckNowHdl_Impl ) );
    m_aAutoDownloadCheckBox.SetClickHdl( LINK( this, SvxOnlineUpdateTabPage, AutoDownloadHdl_Impl ) );
    m_aChangePathButton.SetClickHdl( LINK( this, SvxOnlineUpdateTabPage, FileDialogHdl_Impl ) );

    uno::Reference < lang::XMultiServiceFactory > xFactory( ::comphelper::getProcessServiceFactory() );

    m_xUpdateAccess = uno::Reference < container::XNameReplace >(
        xFactory->createInstance( UNISTRING( "com.sun.star.setup.UpdateCheckConfig" ) ),
        uno::UNO_QUERY_THROW );

    sal_Bool bDownloadSupported;
    m_xUpdateAccess->getByName( UNISTRING( "DownloadSupported") ) >>= bDownloadSupported;

    WinBits nStyle = m_aDestPath.GetStyle();
    nStyle |= WB_PATHELLIPSIS;
    m_aDestPath.SetStyle(nStyle);

    m_aAutoDownloadCheckBox.Show(bDownloadSupported);
    m_aDestPathLabel.Show(bDownloadSupported);
    m_aDestPath.Show(bDownloadSupported);
    m_aChangePathButton.Show(bDownloadSupported);
}

// -----------------------------------------------------------------------

SvxOnlineUpdateTabPage::~SvxOnlineUpdateTabPage()
{
}

// -----------------------------------------------------------------------

SfxTabPage*
SvxOnlineUpdateTabPage::Create( Window* pParent, const SfxItemSet& rAttrSet )
{
    return new SvxOnlineUpdateTabPage( pParent, rAttrSet );
}

// -----------------------------------------------------------------------

BOOL SvxOnlineUpdateTabPage::FillItemSet( SfxItemSet& )
{
    BOOL bModified = FALSE;

    sal_Bool bValue;
    sal_Int64 nValue;

    if( m_aAutoCheckCheckBox.GetSavedValue() != m_aAutoCheckCheckBox.IsChecked() )
    {
        bValue = (TRUE == m_aAutoCheckCheckBox.IsChecked());
        m_xUpdateAccess->replaceByName( UNISTRING("AutoCheckEnabled"), uno::makeAny( bValue ) );
        bModified = TRUE;
    }

    nValue = 0;
    if( TRUE == m_aEveryDayButton.IsChecked() )
    {
        if( FALSE == m_aEveryDayButton.GetSavedValue() )
            nValue = 86400;
    }
    else if( TRUE == m_aEveryWeekButton.IsChecked() )
    {
        if( FALSE == m_aEveryWeekButton.GetSavedValue() )
            nValue = 604800;
    }
    else if( TRUE == m_aEveryMonthButton.IsChecked() )
    {
        if( FALSE == m_aEveryMonthButton.GetSavedValue() )
            nValue = 2592000;
    }

    if( nValue > 0 )
    {
        m_xUpdateAccess->replaceByName( UNISTRING("CheckInterval"), uno::makeAny( nValue ) );
        bModified = TRUE;
    }

    if( m_aAutoDownloadCheckBox.GetSavedValue() != m_aAutoDownloadCheckBox.IsChecked() )
    {
        bValue = (TRUE == m_aAutoDownloadCheckBox.IsChecked());
        m_xUpdateAccess->replaceByName( UNISTRING("AutoDownloadEnabled"), uno::makeAny( bValue ) );
        bModified = TRUE;
    }

    rtl::OUString sValue, aURL;
    m_xUpdateAccess->getByName( UNISTRING("DownloadDestination") ) >>= sValue;

    if( ( osl::FileBase::E_None == osl::FileBase::getFileURLFromSystemPath(m_aDestPath.GetText(), aURL) ) &&
        ( ! aURL.equals( sValue ) ) )
    {
        m_xUpdateAccess->replaceByName( UNISTRING("DownloadDestination"), uno::makeAny( aURL ) );
        bModified = TRUE;
    }

    uno::Reference< util::XChangesBatch > xChangesBatch(m_xUpdateAccess, uno::UNO_QUERY);
    if( xChangesBatch.is() && xChangesBatch->hasPendingChanges() )
        xChangesBatch->commitChanges();

    return bModified;
}

// -----------------------------------------------------------------------

void SvxOnlineUpdateTabPage::Reset( const SfxItemSet& )
{
    sal_Bool bValue;
    m_xUpdateAccess->getByName( UNISTRING("AutoCheckEnabled") ) >>= bValue;

    m_aAutoCheckCheckBox.Check(bValue);
    m_aEveryDayButton.Enable(bValue);
    m_aEveryWeekButton.Enable(bValue);
    m_aEveryMonthButton.Enable(bValue);

    sal_Int64 nValue;
    m_xUpdateAccess->getByName( UNISTRING("CheckInterval") ) >>= nValue;

    if( nValue == 86400 )
        m_aEveryDayButton.Check();
    else if( nValue == 604800 )
        m_aEveryWeekButton.Check();
    else
        m_aEveryMonthButton.Check();

    m_aAutoCheckCheckBox.SaveValue();
    m_aEveryDayButton.SaveValue();
    m_aEveryWeekButton.SaveValue();
    m_aEveryMonthButton.SaveValue();

    m_xUpdateAccess->getByName( UNISTRING("AutoDownloadEnabled") ) >>= bValue;
    m_aAutoDownloadCheckBox.Check(bValue);
    m_aDestPathLabel.Enable(bValue);
    m_aDestPath.Enable(bValue);
    m_aChangePathButton.Enable(bValue);

    rtl::OUString sValue, aPath;
    m_xUpdateAccess->getByName( UNISTRING("DownloadDestination") ) >>= sValue;

    if( osl::FileBase::E_None == osl::FileBase::getSystemPathFromFileURL(sValue, aPath) )
        m_aDestPath.SetText(aPath);

    m_aAutoDownloadCheckBox.SaveValue();
}

// -----------------------------------------------------------------------

void SvxOnlineUpdateTabPage::FillUserData()
{
}

// -----------------------------------------------------------------------

IMPL_LINK( SvxOnlineUpdateTabPage, AutoCheckHdl_Impl, CheckBox *, pBox )
{
    BOOL bEnabled = pBox->IsChecked();

    m_aEveryDayButton.Enable(bEnabled);
    m_aEveryWeekButton.Enable(bEnabled);
    m_aEveryMonthButton.Enable(bEnabled);

    return 0;
}

// -----------------------------------------------------------------------

IMPL_LINK( SvxOnlineUpdateTabPage, AutoDownloadHdl_Impl, CheckBox *, pBox )
{
    BOOL bEnabled = pBox->IsChecked();

    m_aDestPathLabel.Enable(bEnabled);
    m_aDestPath.Enable(bEnabled);
    m_aChangePathButton.Enable(bEnabled);

    return 0;
}

// -----------------------------------------------------------------------

IMPL_LINK( SvxOnlineUpdateTabPage, FileDialogHdl_Impl, PushButton *, EMPTYARG )
{
    uno::Reference < lang::XMultiServiceFactory > xFactory( ::comphelper::getProcessServiceFactory() );
    uno::Reference < dialogs::XFolderPicker > xFolderPicker(
        xFactory->createInstance( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( FOLDER_PICKER_SERVICE_NAME ) ) ),
        uno::UNO_QUERY );

    rtl::OUString aURL;
    if( osl::FileBase::E_None != osl::FileBase::getFileURLFromSystemPath(m_aDestPath.GetText(), aURL) )
        osl::Security().getHomeDir(aURL);

    xFolderPicker->setDisplayDirectory( aURL );
    sal_Int16 nRet = xFolderPicker->execute();

    if ( dialogs::ExecutableDialogResults::OK == nRet )
    {
        rtl::OUString aFolder;
        if( osl::FileBase::E_None == osl::FileBase::getSystemPathFromFileURL(xFolderPicker->getDirectory(), aFolder))
            m_aDestPath.SetText( aFolder );
    }

    return 0;
}

// -----------------------------------------------------------------------

IMPL_LINK( SvxOnlineUpdateTabPage, CheckNowHdl_Impl, PushButton *, EMPTYARG )
{
    uno::Reference < lang::XMultiServiceFactory > xFactory( ::comphelper::getProcessServiceFactory() );

    try
    {
        uno::Reference< lang::XMultiServiceFactory > xConfigProvider(
            xFactory->createInstance( UNISTRING( "com.sun.star.configuration.ConfigurationProvider" )),
            uno::UNO_QUERY_THROW);

        beans::PropertyValue aProperty;
        aProperty.Name  = UNISTRING( "nodepath" );
        aProperty.Value = uno::makeAny( UNISTRING("org.openoffice.Office.Addons/AddonUI/OfficeHelp/UpdateCheckJob") );

        uno::Sequence< uno::Any > aArgumentList( 1 );
        aArgumentList[0] = uno::makeAny( aProperty );

        uno::Reference< container::XNameAccess > xNameAccess(
            xConfigProvider->createInstanceWithArguments(
                UNISTRING("com.sun.star.configuration.ConfigurationAccess"), aArgumentList ),
            uno::UNO_QUERY_THROW );

        util::URL aURL;
        xNameAccess->getByName(UNISTRING("URL")) >>= aURL.Complete;

        uno::Reference < util::XURLTransformer > xTransformer(
            xFactory->createInstance(  UNISTRING( "com.sun.star.util.URLTransformer" ) ),
            uno::UNO_QUERY_THROW );

        xTransformer->parseStrict(aURL);

        uno::Reference < frame::XDesktop > xDesktop(
            xFactory->createInstance(  UNISTRING( "com.sun.star.frame.Desktop" ) ),
            uno::UNO_QUERY_THROW );

        uno::Reference< frame::XDispatchProvider > xDispatchProvider(
            xDesktop->getCurrentFrame(), uno::UNO_QUERY );

        uno::Reference< frame::XDispatch > xDispatch = xDispatchProvider->queryDispatch(aURL, rtl::OUString(), 0);

        if( xDispatch.is() )
            xDispatch->dispatch(aURL, uno::Sequence< beans::PropertyValue > ());

    }
    catch( const uno::Exception& e )
    {
         OSL_TRACE( "Caught exception: %s\n thread terminated.\n",
            rtl::OUStringToOString(e.Message, RTL_TEXTENCODING_UTF8).getStr());
    }

    return 0;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: tabline.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: pb $ $Date: 2000-09-26 06:37: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): _______________________________________
 *
 *
 ************************************************************************/

// include ---------------------------------------------------------------

#ifndef _SHL_HXX
#include <tools/shl.hxx>
#endif
#ifndef _MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX
#include <svtools/pathoptions.hxx>
#endif
#ifndef _SFXAPP_HXX
#include <sfx2/app.hxx>
#endif
#ifndef _SFX_OBJSH_HXX //autogen
#include <sfx2/objsh.hxx>
#endif
#pragma hdrstop

#define _SVX_TABLINE_CXX
#include "dialogs.hrc"
#include "tabline.hrc"
#include "dlgname.hrc"

#define ITEMID_COLOR_TABLE      SID_COLOR_TABLE
#define ITEMID_DASH_LIST        SID_DASH_LIST
#define ITEMID_LINEEND_LIST     SID_LINEEND_LIST

#include "tabline.hxx"
#include "dlgname.hxx"
#include "dialmgr.hxx"
#include "svdmodel.hxx"
#include "xtable.hxx"
#include "drawitem.hxx"

#define DLGWIN this->GetParent()->GetParent()

#define BITMAP_WIDTH   32
#define BITMAP_HEIGHT  12
#define XOUT_WIDTH    150

/*************************************************************************
|*
|* Konstruktor des Tab-Dialogs: Fuegt die Seiten zum Dialog hinzu
|*
\************************************************************************/

SvxLineTabDialog::SvxLineTabDialog
(
    Window* pParent,
    const SfxItemSet* pAttr,
    SdrModel* pModel,
    const SdrObject* pSdrObj,
    BOOL bHasObj
) :

    SfxTabDialog    ( pParent, SVX_RES( RID_SVXDLG_LINE ), pAttr ),
    pDrawModel      ( pModel ),
    pObj            ( pSdrObj ),
    bObjSelected    ( bHasObj ),
    pColorTab       ( pModel->GetColorTable() ),
    pDashList       ( pModel->GetDashList() ),
    pLineEndList    ( pModel->GetLineEndList() ),
    pNewDashList    ( pModel->GetDashList() ),
    pNewLineEndList ( pModel->GetLineEndList() ),
    rOutAttrs       ( *pAttr )

{
    FreeResource();

    AddTabPage( RID_SVXPAGE_LINE, SvxLineTabPage::Create, 0);
    AddTabPage( RID_SVXPAGE_LINE_DEF, SvxLineDefTabPage::Create, 0);
    AddTabPage( RID_SVXPAGE_LINEEND_DEF, SvxLineEndDefTabPage::Create, 0);

    nLineEndListState = CT_NONE;
    nDashListState = CT_NONE;

    nDlgType = 0;
    nPageType = 0; // wird hier in erster Linie benutzt, um mit FillItemSet
                   // die richtigen Attribute zu erhalten ( noch Fragen? )
    nPosDashLb = 0;
    nPosLineEndLb = 0;

    SetCurPageId( RID_SVXPAGE_LINE );

    CancelButton& rBtnCancel = GetCancelButton();
    rBtnCancel.SetClickHdl( LINK( this, SvxLineTabDialog, CancelHdl ) );
//! rBtnCancel.SetText( SVX_RESSTR( RID_SVXSTR_CLOSE ) );
}

// -----------------------------------------------------------------------

SvxLineTabDialog::~SvxLineTabDialog()
{
}

// -----------------------------------------------------------------------

void SvxLineTabDialog::SavePalettes()
{
    if( pNewDashList != pDrawModel->GetDashList() )
    {
        delete pDrawModel->GetDashList();
        pDrawModel->SetDashList( pNewDashList );
        SfxObjectShell::Current()->PutItem( SvxDashListItem( pNewDashList ) );
        pDashList = pDrawModel->GetDashList();
    }
    if( pNewLineEndList != pDrawModel->GetLineEndList() )
    {
        delete pDrawModel->GetLineEndList();
        pDrawModel->SetLineEndList( pNewLineEndList );
        SfxObjectShell::Current()->PutItem( SvxLineEndListItem( pNewLineEndList ) );
        pLineEndList = pDrawModel->GetLineEndList();
    }

    // Speichern der Tabellen, wenn sie geaendert wurden.

    const String aPath( SvtPathOptions().GetPalettePath() );

    if( nDashListState & CT_MODIFIED )
    {
        pDashList->SetPath( aPath );
        pDashList->Save();

        // ToolBoxControls werden benachrichtigt:
        SfxObjectShell::Current()->PutItem( SvxDashListItem( pDashList ) );
    }

    if( nLineEndListState & CT_MODIFIED )
    {
        pLineEndList->SetPath( aPath );
        pLineEndList->Save();

        // ToolBoxControls werden benachrichtigt:
        SfxObjectShell::Current()->PutItem( SvxLineEndListItem( pLineEndList ) );
    }
}

// -----------------------------------------------------------------------

short SvxLineTabDialog::Ok()
{
    SavePalettes();

    // Es wird RET_OK zurueckgeliefert, wenn wenigstens eine
    // TabPage in FillItemSet() TRUE zurueckliefert. Dieses
    // geschieht z.Z. standardmaessig.
    return( SfxTabDialog::Ok() );
}

// -----------------------------------------------------------------------

IMPL_LINK_INLINE_START( SvxLineTabDialog, CancelHdl, void *, p )
{
    SavePalettes();

    EndDialog( RET_CANCEL );
    return 0;
}
IMPL_LINK_INLINE_END( SvxLineTabDialog, CancelHdl, void *, p )

// -----------------------------------------------------------------------

void SvxLineTabDialog::PageCreated( USHORT nId, SfxTabPage &rPage )
{
    switch( nId )
    {
        case RID_SVXPAGE_LINE:
            ( (SvxLineTabPage&) rPage ).SetColorTable( pColorTab );
            ( (SvxLineTabPage&) rPage ).SetDashList( pDashList );
            ( (SvxLineTabPage&) rPage ).SetLineEndList( pLineEndList );
            ( (SvxLineTabPage&) rPage ).SetDlgType( &nDlgType );
            ( (SvxLineTabPage&) rPage ).SetPageType( &nPageType );
            ( (SvxLineTabPage&) rPage ).SetPosDashLb( &nPosDashLb );
            ( (SvxLineTabPage&) rPage ).SetPosLineEndLb( &nPosLineEndLb );
            ( (SvxLineTabPage&) rPage ).SetDashChgd( &nDashListState );
            ( (SvxLineTabPage&) rPage ).SetLineEndChgd( &nLineEndListState );
            ( (SvxLineTabPage&) rPage ).SetObjSelected( bObjSelected );
            ( (SvxLineTabPage&) rPage ).Construct();
            // ActivatePage() wird das erste mal nicht gerufen
            ( (SvxLineTabPage&) rPage ).ActivatePage( rOutAttrs );
        break;

        case RID_SVXPAGE_LINE_DEF:
            ( (SvxLineDefTabPage&) rPage ).SetDashList( pDashList );
            ( (SvxLineDefTabPage&) rPage ).SetDlgType( &nDlgType );
            ( (SvxLineDefTabPage&) rPage ).SetPageType( &nPageType );
            ( (SvxLineDefTabPage&) rPage ).SetPosDashLb( &nPosDashLb );
            ( (SvxLineDefTabPage&) rPage ).SetDashChgd( &nDashListState );
            ( (SvxLineDefTabPage&) rPage ).SetObjSelected( bObjSelected );
            ( (SvxLineDefTabPage&) rPage ).Construct();
        break;

        case RID_SVXPAGE_LINEEND_DEF:
            ( (SvxLineEndDefTabPage&) rPage ).SetLineEndList( pLineEndList );
            ( (SvxLineEndDefTabPage&) rPage ).SetPolyObj( pObj );
            ( (SvxLineEndDefTabPage&) rPage ).SetDlgType( &nDlgType );
            ( (SvxLineEndDefTabPage&) rPage ).SetPageType( &nPageType );
            ( (SvxLineEndDefTabPage&) rPage ).SetPosLineEndLb( &nPosLineEndLb );
            ( (SvxLineEndDefTabPage&) rPage ).SetLineEndChgd( &nLineEndListState );
            ( (SvxLineEndDefTabPage&) rPage ).SetObjSelected( bObjSelected );
            ( (SvxLineEndDefTabPage&) rPage ).Construct();
        break;
    }
}

<commit_msg>INTEGRATION: CWS dialogdiet (1.2.528); FILE MERGED 2004/01/17 01:45:18 mwu 1.2.528.1: DialogDiet 2004_01_17<commit_after>/*************************************************************************
 *
 *  $RCSfile: tabline.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: hr $ $Date: 2004-02-03 18:53:05 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

// include ---------------------------------------------------------------

#ifndef _SHL_HXX
#include <tools/shl.hxx>
#endif
#ifndef _MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX
#include <svtools/pathoptions.hxx>
#endif
#ifndef _SFXAPP_HXX
#include <sfx2/app.hxx>
#endif
#ifndef _SFX_OBJSH_HXX //autogen
#include <sfx2/objsh.hxx>
#endif
#pragma hdrstop

#define _SVX_TABLINE_CXX
#include "dialogs.hrc"
#include "tabline.hrc"
#include "dlgname.hrc"

#define ITEMID_COLOR_TABLE      SID_COLOR_TABLE
#define ITEMID_DASH_LIST        SID_DASH_LIST
#define ITEMID_LINEEND_LIST     SID_LINEEND_LIST

#include "cuitabline.hxx"
#include "dlgname.hxx"
#include "dialmgr.hxx"
#include "svdmodel.hxx"
#include "xtable.hxx"
#include "drawitem.hxx"

#define DLGWIN this->GetParent()->GetParent()

#define BITMAP_WIDTH   32
#define BITMAP_HEIGHT  12
#define XOUT_WIDTH    150

/*************************************************************************
|*
|* Konstruktor des Tab-Dialogs: Fuegt die Seiten zum Dialog hinzu
|*
\************************************************************************/

SvxLineTabDialog::SvxLineTabDialog
(
    Window* pParent,
    const SfxItemSet* pAttr,
    SdrModel* pModel,
    const SdrObject* pSdrObj,
    BOOL bHasObj
) :

    SfxTabDialog    ( pParent, SVX_RES( RID_SVXDLG_LINE ), pAttr ),
    pDrawModel      ( pModel ),
    pObj            ( pSdrObj ),
    bObjSelected    ( bHasObj ),
    pColorTab       ( pModel->GetColorTable() ),
    pDashList       ( pModel->GetDashList() ),
    pLineEndList    ( pModel->GetLineEndList() ),
    pNewDashList    ( pModel->GetDashList() ),
    pNewLineEndList ( pModel->GetLineEndList() ),
    rOutAttrs       ( *pAttr )

{
    FreeResource();

    AddTabPage( RID_SVXPAGE_LINE, SvxLineTabPage::Create, 0);
    AddTabPage( RID_SVXPAGE_LINE_DEF, SvxLineDefTabPage::Create, 0);
    AddTabPage( RID_SVXPAGE_LINEEND_DEF, SvxLineEndDefTabPage::Create, 0);

    nLineEndListState = CT_NONE;
    nDashListState = CT_NONE;

    nDlgType = 0;
    nPageType = 0; // wird hier in erster Linie benutzt, um mit FillItemSet
                   // die richtigen Attribute zu erhalten ( noch Fragen? )
    nPosDashLb = 0;
    nPosLineEndLb = 0;

    SetCurPageId( RID_SVXPAGE_LINE );

    CancelButton& rBtnCancel = GetCancelButton();
    rBtnCancel.SetClickHdl( LINK( this, SvxLineTabDialog, CancelHdl ) );
//! rBtnCancel.SetText( SVX_RESSTR( RID_SVXSTR_CLOSE ) );
}

// -----------------------------------------------------------------------

SvxLineTabDialog::~SvxLineTabDialog()
{
}

// -----------------------------------------------------------------------

void SvxLineTabDialog::SavePalettes()
{
    if( pNewDashList != pDrawModel->GetDashList() )
    {
        delete pDrawModel->GetDashList();
        pDrawModel->SetDashList( pNewDashList );
        SfxObjectShell::Current()->PutItem( SvxDashListItem( pNewDashList ) );
        pDashList = pDrawModel->GetDashList();
    }
    if( pNewLineEndList != pDrawModel->GetLineEndList() )
    {
        delete pDrawModel->GetLineEndList();
        pDrawModel->SetLineEndList( pNewLineEndList );
        SfxObjectShell::Current()->PutItem( SvxLineEndListItem( pNewLineEndList ) );
        pLineEndList = pDrawModel->GetLineEndList();
    }

    // Speichern der Tabellen, wenn sie geaendert wurden.

    const String aPath( SvtPathOptions().GetPalettePath() );

    if( nDashListState & CT_MODIFIED )
    {
        pDashList->SetPath( aPath );
        pDashList->Save();

        // ToolBoxControls werden benachrichtigt:
        SfxObjectShell::Current()->PutItem( SvxDashListItem( pDashList ) );
    }

    if( nLineEndListState & CT_MODIFIED )
    {
        pLineEndList->SetPath( aPath );
        pLineEndList->Save();

        // ToolBoxControls werden benachrichtigt:
        SfxObjectShell::Current()->PutItem( SvxLineEndListItem( pLineEndList ) );
    }
}

// -----------------------------------------------------------------------

short SvxLineTabDialog::Ok()
{
    SavePalettes();

    // Es wird RET_OK zurueckgeliefert, wenn wenigstens eine
    // TabPage in FillItemSet() TRUE zurueckliefert. Dieses
    // geschieht z.Z. standardmaessig.
    return( SfxTabDialog::Ok() );
}

// -----------------------------------------------------------------------

IMPL_LINK_INLINE_START( SvxLineTabDialog, CancelHdl, void *, p )
{
    SavePalettes();

    EndDialog( RET_CANCEL );
    return 0;
}
IMPL_LINK_INLINE_END( SvxLineTabDialog, CancelHdl, void *, p )

// -----------------------------------------------------------------------

void SvxLineTabDialog::PageCreated( USHORT nId, SfxTabPage &rPage )
{
    switch( nId )
    {
        case RID_SVXPAGE_LINE:
            ( (SvxLineTabPage&) rPage ).SetColorTable( pColorTab );
            ( (SvxLineTabPage&) rPage ).SetDashList( pDashList );
            ( (SvxLineTabPage&) rPage ).SetLineEndList( pLineEndList );
            ( (SvxLineTabPage&) rPage ).SetDlgType( nDlgType );//CHINA001 ( (SvxLineTabPage&) rPage ).SetDlgType( &nDlgType );
            ( (SvxLineTabPage&) rPage ).SetPageType( nPageType );//CHINA001 ( (SvxLineTabPage&) rPage ).SetPageType( &nPageType );
            ( (SvxLineTabPage&) rPage ).SetPosDashLb( &nPosDashLb );
            ( (SvxLineTabPage&) rPage ).SetPosLineEndLb( &nPosLineEndLb );
            ( (SvxLineTabPage&) rPage ).SetDashChgd( &nDashListState );
            ( (SvxLineTabPage&) rPage ).SetLineEndChgd( &nLineEndListState );
            ( (SvxLineTabPage&) rPage ).SetObjSelected( bObjSelected );
            ( (SvxLineTabPage&) rPage ).Construct();
            // ActivatePage() wird das erste mal nicht gerufen
            ( (SvxLineTabPage&) rPage ).ActivatePage( rOutAttrs );
        break;

        case RID_SVXPAGE_LINE_DEF:
            ( (SvxLineDefTabPage&) rPage ).SetDashList( pDashList );
            ( (SvxLineDefTabPage&) rPage ).SetDlgType( &nDlgType );
            ( (SvxLineDefTabPage&) rPage ).SetPageType( &nPageType );
            ( (SvxLineDefTabPage&) rPage ).SetPosDashLb( &nPosDashLb );
            ( (SvxLineDefTabPage&) rPage ).SetDashChgd( &nDashListState );
            ( (SvxLineDefTabPage&) rPage ).SetObjSelected( bObjSelected );
            ( (SvxLineDefTabPage&) rPage ).Construct();
        break;

        case RID_SVXPAGE_LINEEND_DEF:
            ( (SvxLineEndDefTabPage&) rPage ).SetLineEndList( pLineEndList );
            ( (SvxLineEndDefTabPage&) rPage ).SetPolyObj( pObj );
            ( (SvxLineEndDefTabPage&) rPage ).SetDlgType( &nDlgType );
            ( (SvxLineEndDefTabPage&) rPage ).SetPageType( &nPageType );
            ( (SvxLineEndDefTabPage&) rPage ).SetPosLineEndLb( &nPosLineEndLb );
            ( (SvxLineEndDefTabPage&) rPage ).SetLineEndChgd( &nLineEndListState );
            ( (SvxLineEndDefTabPage&) rPage ).SetObjSelected( bObjSelected );
            ( (SvxLineEndDefTabPage&) rPage ).Construct();
        break;
    }
}

<|endoftext|>