<commit_before>/*
Copyright (c) 2015 - present Advanced Micro Devices, Inc. All rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include <hip/hip_runtime.h>
#include "hip_internal.hpp"
#include "platform/runtime.hpp"
#include "utils/flags.hpp"
#include "utils/versions.hpp"

std::vector<amd::Context*> g_devices;

namespace hip {

thread_local amd::Context* g_context = nullptr;
thread_local std::stack<amd::Context*> g_ctxtStack;
thread_local hipError_t g_lastError = hipSuccess;
std::once_flag g_ihipInitialized;
amd::Context* host_context = nullptr;

std::map<amd::Context*, amd::HostQueue*> g_nullStreams;

void init() {
  if (!amd::Runtime::initialized()) {
    amd::IS_HIP = true;
    amd::Runtime::init();
  }

  const std::vector<amd::Device*>& devices = amd::Device::getDevices(CL_DEVICE_TYPE_GPU, false);

  for (unsigned int i=0; i<devices.size(); i++) {
    const std::vector<amd::Device*> device(1, devices[i]);
    amd::Context* context = new amd::Context(device, amd::Context::Info());
    if (!context) return;

    if (context && CL_SUCCESS != context->create(nullptr)) {
      context->release();
    } else {
      g_devices.push_back(context);
    }
  }

  host_context = new amd::Context(devices, amd::Context::Info());
  if (!host_context) return;

  if (host_context && CL_SUCCESS != host_context->create(nullptr)) {
    host_context->release();
  }
}

amd::Context* getCurrentContext() {
  return g_context;
}

void setCurrentContext(unsigned int index) {
  assert(index<g_devices.size());
  g_context = g_devices[index];
}

amd::HostQueue* getQueue(hipStream_t stream) {
 if (stream == nullptr) {
    syncStreams();
    return getNullStream();
  } else {
    hip::Stream* s = reinterpret_cast<hip::Stream*>(stream);
    if ((s->flags & hipStreamNonBlocking) == 0) {
      getNullStream()->finish();
    }
    return s->asHostQueue();
  }
}

amd::HostQueue* getNullStream(amd::Context& context) {
  auto stream = g_nullStreams.find(&context);
  if (stream == g_nullStreams.end()) {
    amd::Device* device = context.devices()[0];
    cl_command_queue_properties properties = CL_QUEUE_PROFILING_ENABLE;
    amd::HostQueue* queue = new amd::HostQueue(context, *device, properties,
                                               amd::CommandQueue::RealTimeDisabled,
                                               amd::CommandQueue::Priority::Normal);
    g_nullStreams[&context] = queue;
    return queue;
  }
  return stream->second;
}

amd::HostQueue* getNullStream() {
  return getNullStream(*getCurrentContext());
}

};

using namespace hip;

hipError_t hipInit(unsigned int flags) {
  HIP_INIT_API(flags);

  HIP_RETURN(hipSuccess);
}

hipError_t hipCtxCreate(hipCtx_t *ctx, unsigned int flags,  hipDevice_t device) {
  HIP_INIT_API(ctx, flags, device);

  if (static_cast<size_t>(device) >= g_devices.size()) {
    HIP_RETURN(hipErrorInvalidValue);
  }

  *ctx = reinterpret_cast<hipCtx_t>(g_devices[device]);

  // Increment ref count for device primary context
  g_devices[device]->retain();
  g_ctxtStack.push(g_devices[device]);

  HIP_RETURN(hipSuccess);
}

hipError_t hipCtxSetCurrent(hipCtx_t ctx) {
  HIP_INIT_API(ctx);

  if (ctx == nullptr) {
    if(!g_ctxtStack.empty()) {
      g_ctxtStack.pop();
    }
  } else {
    hip::g_context = reinterpret_cast<amd::Context*>(as_amd(ctx));
    if(!g_ctxtStack.empty()) {
      g_ctxtStack.pop();
    }
    g_ctxtStack.push(hip::getCurrentContext());
  }

  HIP_RETURN(hipSuccess);
}

hipError_t hipCtxGetCurrent(hipCtx_t* ctx) {
  HIP_INIT_API(ctx);

  *ctx = reinterpret_cast<hipCtx_t>(hip::getCurrentContext());

  HIP_RETURN(hipSuccess);
}

hipError_t hipCtxGetSharedMemConfig(hipSharedMemConfig* pConfig) {
  HIP_INIT_API(pConfig);

  *pConfig = hipSharedMemBankSizeFourByte;

  HIP_RETURN(hipSuccess);
}

hipError_t hipRuntimeGetVersion(int *runtimeVersion) {
  HIP_INIT_API(runtimeVersion);

  if (!runtimeVersion) {
    HIP_RETURN(hipErrorInvalidValue);
  }

  *runtimeVersion = AMD_PLATFORM_BUILD_NUMBER;

  HIP_RETURN(hipSuccess);
}

hipError_t hipCtxDestroy(hipCtx_t ctx) {
  HIP_INIT_API(ctx);

  amd::Context* amdContext = reinterpret_cast<amd::Context*>(as_amd(ctx));
  if (amdContext == nullptr) {
    HIP_RETURN(hipErrorInvalidValue);
  }

  // Release last tracked command
  hip::getNullStream()->setLastQueuedCommand(nullptr);

  // Need to remove the ctx of calling thread if its the top one
  if (!g_ctxtStack.empty() && g_ctxtStack.top() == amdContext) {
    g_ctxtStack.pop();
  }

  // Remove context from global context list
  for (unsigned int i = 0; i < g_devices.size(); i++) {
    if (g_devices[i] == amdContext) {
      // Decrement ref count for device primary context
      amdContext->release();
    }
  }

  HIP_RETURN(hipSuccess);
}

hipError_t hipCtxPopCurrent(hipCtx_t* ctx) {
  HIP_INIT_API(ctx);

  amd::Context* amdContext = reinterpret_cast<amd::Context*>(as_amd(ctx));
  if (amdContext == nullptr) {
    HIP_RETURN(hipErrorInvalidContext);
  }

  if (!g_ctxtStack.empty()) {
    amdContext = g_ctxtStack.top();
    g_ctxtStack.pop();
  } else {
    HIP_RETURN(hipErrorInvalidContext);
  }

  HIP_RETURN(hipSuccess);
}

hipError_t hipCtxPushCurrent(hipCtx_t ctx) {
  HIP_INIT_API(ctx);

  amd::Context* amdContext = reinterpret_cast<amd::Context*>(as_amd(ctx));
  if (amdContext == nullptr) {
    HIP_RETURN(hipErrorInvalidContext);
  }

  hip::g_context = amdContext;
  g_ctxtStack.push(hip::getCurrentContext());

  HIP_RETURN(hipSuccess);
}

hipError_t hipDriverGetVersion(int* driverVersion) {
  HIP_INIT_API(driverVersion);

  auto* deviceHandle = g_devices[0]->devices()[0];
  const auto& info = deviceHandle->info();

  if (driverVersion) {
    *driverVersion = AMD_PLATFORM_BUILD_NUMBER * 100 +
                     AMD_PLATFORM_REVISION_NUMBER;
  } else {
    HIP_RETURN(hipErrorInvalidValue);
  }

  HIP_RETURN(hipSuccess);
}

hipError_t hipCtxGetDevice(hipDevice_t* device) {
  HIP_INIT_API(device);

  if (device != nullptr) {
    for (unsigned int i = 0; i < g_devices.size(); i++) {
      if (g_devices[i] == hip::getCurrentContext()) {
        *device = static_cast<hipDevice_t>(i);
        HIP_RETURN(hipSuccess);
      }
    }
  } else {
    HIP_RETURN(hipErrorInvalidValue);
  }

  HIP_RETURN(hipErrorUnknown);
}

hipError_t hipCtxGetApiVersion(hipCtx_t ctx, int* apiVersion) {
  HIP_INIT_API(apiVersion);

  assert(0 && "Unimplemented");

  HIP_RETURN(hipErrorUnknown);
}

hipError_t hipCtxGetCacheConfig(hipFuncCache_t* cacheConfig) {
  HIP_INIT_API(cacheConfig);

  assert(0 && "Unimplemented");

  HIP_RETURN(hipErrorUnknown);
}

hipError_t hipCtxSetCacheConfig(hipFuncCache_t cacheConfig) {
  HIP_INIT_API(cacheConfig);

  assert(0 && "Unimplemented");

  HIP_RETURN(hipErrorUnknown);
}

hipError_t hipCtxSetSharedMemConfig(hipSharedMemConfig config) {
  HIP_INIT_API(config);

  assert(0 && "Unimplemented");

  HIP_RETURN(hipErrorUnknown);
}

hipError_t hipCtxSynchronize(void) {
  HIP_INIT_API(1);

  assert(0 && "Unimplemented");

  HIP_RETURN(hipErrorUnknown);
}

hipError_t hipCtxGetFlags(unsigned int* flags) {
  HIP_INIT_API(flags);

  assert(0 && "Unimplemented");

  HIP_RETURN(hipErrorUnknown);
}

hipError_t hipDevicePrimaryCtxGetState(hipDevice_t dev, unsigned int* flags, int* active) {
  HIP_INIT_API(dev, flags, active);

  if (static_cast<unsigned int>(dev) >= g_devices.size()) {
    HIP_RETURN(hipErrorInvalidDevice);
  }

  if (flags != nullptr) {
    *flags = 0;
  }

  if (active != nullptr) {
    *active = (g_devices[dev] == hip::getCurrentContext())? 1 : 0;
  }

  HIP_RETURN(hipSuccess);
}

hipError_t hipDevicePrimaryCtxRelease(hipDevice_t dev) {
  HIP_INIT_API(dev);

  if (static_cast<unsigned int>(dev) >= g_devices.size()) {
    HIP_RETURN(hipErrorInvalidDevice);
  }

  HIP_RETURN(hipSuccess);
}

hipError_t hipDevicePrimaryCtxRetain(hipCtx_t* pctx, hipDevice_t dev) {
  HIP_INIT_API(pctx, dev);

  if (static_cast<unsigned int>(dev) >= g_devices.size()) {
    HIP_RETURN(hipErrorInvalidDevice);
  }
  if (pctx == nullptr) {
    HIP_RETURN(hipErrorInvalidValue);
  }

  *pctx = reinterpret_cast<hipCtx_t>(g_devices[dev]);

  HIP_RETURN(hipSuccess);
}

hipError_t hipDevicePrimaryCtxReset(hipDevice_t dev) {
  HIP_INIT_API(dev);

  HIP_RETURN(hipSuccess);
}

hipError_t hipDevicePrimaryCtxSetFlags(hipDevice_t dev, unsigned int flags) {
  HIP_INIT_API(dev, flags);

  if (static_cast<unsigned int>(dev) >= g_devices.size()) {
    HIP_RETURN(hipErrorInvalidDevice);
  } else {
    HIP_RETURN(hipErrorContextAlreadyInUse);
  }
}
<commit_msg>P4 to Git Change 1999915 by cpaquot@cpaquot-ocl-lc-lnx on 2019/09/17 19:43:34<commit_after>/*
Copyright (c) 2015 - present Advanced Micro Devices, Inc. All rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include <hip/hip_runtime.h>
#include "hip_internal.hpp"
#include "platform/runtime.hpp"
#include "utils/flags.hpp"
#include "utils/versions.hpp"

std::vector<amd::Context*> g_devices;

namespace hip {

thread_local amd::Context* g_context = nullptr;
thread_local std::stack<amd::Context*> g_ctxtStack;
thread_local hipError_t g_lastError = hipSuccess;
std::once_flag g_ihipInitialized;
amd::Context* host_context = nullptr;

std::map<amd::Context*, amd::HostQueue*> g_nullStreams;

void init() {
  if (!amd::Runtime::initialized()) {
    amd::IS_HIP = true;
    GPU_NUM_MEM_DEPENDENCY = 0;
    amd::Runtime::init();
  }

  const std::vector<amd::Device*>& devices = amd::Device::getDevices(CL_DEVICE_TYPE_GPU, false);

  for (unsigned int i=0; i<devices.size(); i++) {
    const std::vector<amd::Device*> device(1, devices[i]);
    amd::Context* context = new amd::Context(device, amd::Context::Info());
    if (!context) return;

    if (context && CL_SUCCESS != context->create(nullptr)) {
      context->release();
    } else {
      g_devices.push_back(context);
    }
  }

  host_context = new amd::Context(devices, amd::Context::Info());
  if (!host_context) return;

  if (host_context && CL_SUCCESS != host_context->create(nullptr)) {
    host_context->release();
  }
}

amd::Context* getCurrentContext() {
  return g_context;
}

void setCurrentContext(unsigned int index) {
  assert(index<g_devices.size());
  g_context = g_devices[index];
}

amd::HostQueue* getQueue(hipStream_t stream) {
 if (stream == nullptr) {
    syncStreams();
    return getNullStream();
  } else {
    hip::Stream* s = reinterpret_cast<hip::Stream*>(stream);
    if ((s->flags & hipStreamNonBlocking) == 0) {
      getNullStream()->finish();
    }
    return s->asHostQueue();
  }
}

amd::HostQueue* getNullStream(amd::Context& context) {
  auto stream = g_nullStreams.find(&context);
  if (stream == g_nullStreams.end()) {
    amd::Device* device = context.devices()[0];
    cl_command_queue_properties properties = CL_QUEUE_PROFILING_ENABLE;
    amd::HostQueue* queue = new amd::HostQueue(context, *device, properties,
                                               amd::CommandQueue::RealTimeDisabled,
                                               amd::CommandQueue::Priority::Normal);
    g_nullStreams[&context] = queue;
    return queue;
  }
  return stream->second;
}

amd::HostQueue* getNullStream() {
  return getNullStream(*getCurrentContext());
}

};

using namespace hip;

hipError_t hipInit(unsigned int flags) {
  HIP_INIT_API(flags);

  HIP_RETURN(hipSuccess);
}

hipError_t hipCtxCreate(hipCtx_t *ctx, unsigned int flags,  hipDevice_t device) {
  HIP_INIT_API(ctx, flags, device);

  if (static_cast<size_t>(device) >= g_devices.size()) {
    HIP_RETURN(hipErrorInvalidValue);
  }

  *ctx = reinterpret_cast<hipCtx_t>(g_devices[device]);

  // Increment ref count for device primary context
  g_devices[device]->retain();
  g_ctxtStack.push(g_devices[device]);

  HIP_RETURN(hipSuccess);
}

hipError_t hipCtxSetCurrent(hipCtx_t ctx) {
  HIP_INIT_API(ctx);

  if (ctx == nullptr) {
    if(!g_ctxtStack.empty()) {
      g_ctxtStack.pop();
    }
  } else {
    hip::g_context = reinterpret_cast<amd::Context*>(as_amd(ctx));
    if(!g_ctxtStack.empty()) {
      g_ctxtStack.pop();
    }
    g_ctxtStack.push(hip::getCurrentContext());
  }

  HIP_RETURN(hipSuccess);
}

hipError_t hipCtxGetCurrent(hipCtx_t* ctx) {
  HIP_INIT_API(ctx);

  *ctx = reinterpret_cast<hipCtx_t>(hip::getCurrentContext());

  HIP_RETURN(hipSuccess);
}

hipError_t hipCtxGetSharedMemConfig(hipSharedMemConfig* pConfig) {
  HIP_INIT_API(pConfig);

  *pConfig = hipSharedMemBankSizeFourByte;

  HIP_RETURN(hipSuccess);
}

hipError_t hipRuntimeGetVersion(int *runtimeVersion) {
  HIP_INIT_API(runtimeVersion);

  if (!runtimeVersion) {
    HIP_RETURN(hipErrorInvalidValue);
  }

  *runtimeVersion = AMD_PLATFORM_BUILD_NUMBER;

  HIP_RETURN(hipSuccess);
}

hipError_t hipCtxDestroy(hipCtx_t ctx) {
  HIP_INIT_API(ctx);

  amd::Context* amdContext = reinterpret_cast<amd::Context*>(as_amd(ctx));
  if (amdContext == nullptr) {
    HIP_RETURN(hipErrorInvalidValue);
  }

  // Release last tracked command
  hip::getNullStream()->setLastQueuedCommand(nullptr);

  // Need to remove the ctx of calling thread if its the top one
  if (!g_ctxtStack.empty() && g_ctxtStack.top() == amdContext) {
    g_ctxtStack.pop();
  }

  // Remove context from global context list
  for (unsigned int i = 0; i < g_devices.size(); i++) {
    if (g_devices[i] == amdContext) {
      // Decrement ref count for device primary context
      amdContext->release();
    }
  }

  HIP_RETURN(hipSuccess);
}

hipError_t hipCtxPopCurrent(hipCtx_t* ctx) {
  HIP_INIT_API(ctx);

  amd::Context* amdContext = reinterpret_cast<amd::Context*>(as_amd(ctx));
  if (amdContext == nullptr) {
    HIP_RETURN(hipErrorInvalidContext);
  }

  if (!g_ctxtStack.empty()) {
    amdContext = g_ctxtStack.top();
    g_ctxtStack.pop();
  } else {
    HIP_RETURN(hipErrorInvalidContext);
  }

  HIP_RETURN(hipSuccess);
}

hipError_t hipCtxPushCurrent(hipCtx_t ctx) {
  HIP_INIT_API(ctx);

  amd::Context* amdContext = reinterpret_cast<amd::Context*>(as_amd(ctx));
  if (amdContext == nullptr) {
    HIP_RETURN(hipErrorInvalidContext);
  }

  hip::g_context = amdContext;
  g_ctxtStack.push(hip::getCurrentContext());

  HIP_RETURN(hipSuccess);
}

hipError_t hipDriverGetVersion(int* driverVersion) {
  HIP_INIT_API(driverVersion);

  auto* deviceHandle = g_devices[0]->devices()[0];
  const auto& info = deviceHandle->info();

  if (driverVersion) {
    *driverVersion = AMD_PLATFORM_BUILD_NUMBER * 100 +
                     AMD_PLATFORM_REVISION_NUMBER;
  } else {
    HIP_RETURN(hipErrorInvalidValue);
  }

  HIP_RETURN(hipSuccess);
}

hipError_t hipCtxGetDevice(hipDevice_t* device) {
  HIP_INIT_API(device);

  if (device != nullptr) {
    for (unsigned int i = 0; i < g_devices.size(); i++) {
      if (g_devices[i] == hip::getCurrentContext()) {
        *device = static_cast<hipDevice_t>(i);
        HIP_RETURN(hipSuccess);
      }
    }
  } else {
    HIP_RETURN(hipErrorInvalidValue);
  }

  HIP_RETURN(hipErrorUnknown);
}

hipError_t hipCtxGetApiVersion(hipCtx_t ctx, int* apiVersion) {
  HIP_INIT_API(apiVersion);

  assert(0 && "Unimplemented");

  HIP_RETURN(hipErrorUnknown);
}

hipError_t hipCtxGetCacheConfig(hipFuncCache_t* cacheConfig) {
  HIP_INIT_API(cacheConfig);

  assert(0 && "Unimplemented");

  HIP_RETURN(hipErrorUnknown);
}

hipError_t hipCtxSetCacheConfig(hipFuncCache_t cacheConfig) {
  HIP_INIT_API(cacheConfig);

  assert(0 && "Unimplemented");

  HIP_RETURN(hipErrorUnknown);
}

hipError_t hipCtxSetSharedMemConfig(hipSharedMemConfig config) {
  HIP_INIT_API(config);

  assert(0 && "Unimplemented");

  HIP_RETURN(hipErrorUnknown);
}

hipError_t hipCtxSynchronize(void) {
  HIP_INIT_API(1);

  assert(0 && "Unimplemented");

  HIP_RETURN(hipErrorUnknown);
}

hipError_t hipCtxGetFlags(unsigned int* flags) {
  HIP_INIT_API(flags);

  assert(0 && "Unimplemented");

  HIP_RETURN(hipErrorUnknown);
}

hipError_t hipDevicePrimaryCtxGetState(hipDevice_t dev, unsigned int* flags, int* active) {
  HIP_INIT_API(dev, flags, active);

  if (static_cast<unsigned int>(dev) >= g_devices.size()) {
    HIP_RETURN(hipErrorInvalidDevice);
  }

  if (flags != nullptr) {
    *flags = 0;
  }

  if (active != nullptr) {
    *active = (g_devices[dev] == hip::getCurrentContext())? 1 : 0;
  }

  HIP_RETURN(hipSuccess);
}

hipError_t hipDevicePrimaryCtxRelease(hipDevice_t dev) {
  HIP_INIT_API(dev);

  if (static_cast<unsigned int>(dev) >= g_devices.size()) {
    HIP_RETURN(hipErrorInvalidDevice);
  }

  HIP_RETURN(hipSuccess);
}

hipError_t hipDevicePrimaryCtxRetain(hipCtx_t* pctx, hipDevice_t dev) {
  HIP_INIT_API(pctx, dev);

  if (static_cast<unsigned int>(dev) >= g_devices.size()) {
    HIP_RETURN(hipErrorInvalidDevice);
  }
  if (pctx == nullptr) {
    HIP_RETURN(hipErrorInvalidValue);
  }

  *pctx = reinterpret_cast<hipCtx_t>(g_devices[dev]);

  HIP_RETURN(hipSuccess);
}

hipError_t hipDevicePrimaryCtxReset(hipDevice_t dev) {
  HIP_INIT_API(dev);

  HIP_RETURN(hipSuccess);
}

hipError_t hipDevicePrimaryCtxSetFlags(hipDevice_t dev, unsigned int flags) {
  HIP_INIT_API(dev, flags);

  if (static_cast<unsigned int>(dev) >= g_devices.size()) {
    HIP_RETURN(hipErrorInvalidDevice);
  } else {
    HIP_RETURN(hipErrorContextAlreadyInUse);
  }
}
<|endoftext|>


<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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 <hw/pci_device.hpp>
#include <net/link_layer.hpp>
#include <net/ethernet/ethernet.hpp>
#include <vector>
struct vmxnet3_dma;
struct vmxnet3_rx_desc;
struct vmxnet3_rx_comp;

class vmxnet3 : public net::Link_layer<net::Ethernet>
{
public:
  using Link          = net::Link_layer<net::Ethernet>;
  using Link_protocol = Link::Protocol;
  static const int ETH_FRAME_LEN = 1514;
  static const int NUM_RX_QUEUES = 1;
  static const int NUM_TX_DESC   = 256;
  static const int NUM_RX_DESC   = 256;

  static std::unique_ptr<Nic> new_instance(hw::PCI_Device& d)
  { return std::make_unique<vmxnet3>(d); }

  /** Human readable name. */
  const char* driver_name() const override {
    return "vmxnet3";
  }

  /** Mac address. */
  const MAC::Addr& mac() const noexcept override
  {
    return this->hw_addr;
  }

  uint16_t MTU() const noexcept override {
    return 1500;
  }

  uint16_t packet_len() const noexcept
  {
    return sizeof(net::ethernet::Header) + MTU();
  }

  net::downstream create_physical_downstream()
  { return {this, &vmxnet3::transmit}; }

  net::Packet_ptr create_packet(int) override;

  /** Linklayer input. Hooks into IP-stack bottom, w.DOWNSTREAM data.*/
  void transmit(net::Packet_ptr pckt);

  /** Constructor. @param pcidev an initialized PCI device. */
  vmxnet3(hw::PCI_Device& pcidev);

  /** Space available in the transmit queue, in packets */
  size_t transmit_queue_available() override {
    return tx_tokens_free();
  }

  void flush() override;

  void deactivate() override;

  void move_to_this_cpu() override;

  void poll() override {}

private:
  void msix_evt_handler();
  void msix_xmit_handler();
  void msix_recv_handler();
  void enable_intr(uint8_t idx) noexcept;
  void disable_intr(uint8_t idx) noexcept;

  inline int  tx_tokens_free() const noexcept;
  inline bool can_transmit() const noexcept;
  void transmit_data(uint8_t* data, uint16_t);
  net::Packet_ptr recv_packet(uint8_t* data, uint16_t);

  // tx/rx ring state
  struct ring_stuff {
    uint8_t* buffers[NUM_TX_DESC];
    uint32_t producers  = 0;
    uint32_t prod_count = 0;
    uint32_t consumers  = 0;
  };
  struct rxring_state {
    uint8_t* buffers[NUM_RX_DESC];
    vmxnet3_rx_desc* desc0 = nullptr;
    vmxnet3_rx_desc* desc1 = nullptr;
    vmxnet3_rx_comp* comp  = nullptr;
    int index = 0;
    uint32_t producers  = 0;
    uint32_t prod_count = 0;
    uint32_t consumers  = 0;
  };
  void refill(rxring_state&);

  bool     check_version();
  uint16_t check_link();
  bool     reset();
  uint32_t command(uint32_t cmd);
  void     retrieve_hwaddr();
  void     set_hwaddr(MAC::Addr&);

  hw::PCI_Device& pcidev;
  std::vector<uint8_t> irqs;
  uintptr_t     iobase;
  uintptr_t     ptbase;
  MAC::Addr     hw_addr;
  vmxnet3_dma*  dma;

  ring_stuff tx;
  rxring_state rx[NUM_RX_QUEUES];
  // deferred transmit dma
  int      transmit_idx = -1;
  uint8_t  deferred_irq  = 0;
  bool     deferred_kick = false;
  static void handle_deferred();
  // sendq as packet chain
  net::Packet_ptr sendq = nullptr;
};
<commit_msg>vmxnet3: Use 128 buffers to reduce TCP writeq pressure<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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 <hw/pci_device.hpp>
#include <net/link_layer.hpp>
#include <net/ethernet/ethernet.hpp>
#include <vector>
struct vmxnet3_dma;
struct vmxnet3_rx_desc;
struct vmxnet3_rx_comp;

class vmxnet3 : public net::Link_layer<net::Ethernet>
{
public:
  using Link          = net::Link_layer<net::Ethernet>;
  using Link_protocol = Link::Protocol;
  static const int ETH_FRAME_LEN = 1514;
  static const int NUM_RX_QUEUES = 1;
  static const int NUM_TX_DESC   = 128;
  static const int NUM_RX_DESC   = 128;

  static std::unique_ptr<Nic> new_instance(hw::PCI_Device& d)
  { return std::make_unique<vmxnet3>(d); }

  /** Human readable name. */
  const char* driver_name() const override {
    return "vmxnet3";
  }

  /** Mac address. */
  const MAC::Addr& mac() const noexcept override
  {
    return this->hw_addr;
  }

  uint16_t MTU() const noexcept override {
    return 1500;
  }

  uint16_t packet_len() const noexcept
  {
    return sizeof(net::ethernet::Header) + MTU();
  }

  net::downstream create_physical_downstream()
  { return {this, &vmxnet3::transmit}; }

  net::Packet_ptr create_packet(int) override;

  /** Linklayer input. Hooks into IP-stack bottom, w.DOWNSTREAM data.*/
  void transmit(net::Packet_ptr pckt);

  /** Constructor. @param pcidev an initialized PCI device. */
  vmxnet3(hw::PCI_Device& pcidev);

  /** Space available in the transmit queue, in packets */
  size_t transmit_queue_available() override {
    return tx_tokens_free();
  }

  void flush() override;

  void deactivate() override;

  void move_to_this_cpu() override;

  void poll() override {}

private:
  void msix_evt_handler();
  void msix_xmit_handler();
  void msix_recv_handler();
  void enable_intr(uint8_t idx) noexcept;
  void disable_intr(uint8_t idx) noexcept;

  inline int  tx_tokens_free() const noexcept;
  inline bool can_transmit() const noexcept;
  void transmit_data(uint8_t* data, uint16_t);
  net::Packet_ptr recv_packet(uint8_t* data, uint16_t);

  // tx/rx ring state
  struct ring_stuff {
    uint8_t* buffers[NUM_TX_DESC];
    uint32_t producers  = 0;
    uint32_t prod_count = 0;
    uint32_t consumers  = 0;
  };
  struct rxring_state {
    uint8_t* buffers[NUM_RX_DESC];
    vmxnet3_rx_desc* desc0 = nullptr;
    vmxnet3_rx_desc* desc1 = nullptr;
    vmxnet3_rx_comp* comp  = nullptr;
    int index = 0;
    uint32_t producers  = 0;
    uint32_t prod_count = 0;
    uint32_t consumers  = 0;
  };
  void refill(rxring_state&);

  bool     check_version();
  uint16_t check_link();
  bool     reset();
  uint32_t command(uint32_t cmd);
  void     retrieve_hwaddr();
  void     set_hwaddr(MAC::Addr&);

  hw::PCI_Device& pcidev;
  std::vector<uint8_t> irqs;
  uintptr_t     iobase;
  uintptr_t     ptbase;
  MAC::Addr     hw_addr;
  vmxnet3_dma*  dma;

  ring_stuff tx;
  rxring_state rx[NUM_RX_QUEUES];
  // deferred transmit dma
  int      transmit_idx = -1;
  uint8_t  deferred_irq  = 0;
  bool     deferred_kick = false;
  static void handle_deferred();
  // sendq as packet chain
  net::Packet_ptr sendq = nullptr;
};
<|endoftext|>


<commit_before>#include <BST.hpp>
#include <catch.hpp>
#include <fstream>

SCENARIO ("init", "[init]")

{

  BST<int> test;

  REQUIRE(test.getroot() == nullptr);
  REQUIRE(test.getcount() == 0);

}

SCENARIO("insert", "[init]")

{

  BST<int> test;

  test.add(10);

  REQUIRE(test.search(10, test.getroot()) != 0);

}

SCENARIO("find_node", "[init]")

{

  BST<int> test;

  test.add(10);

  REQUIRE(test.search(10, test.getroot()) != 0);

  REQUIRE(test.search(10, test.getroot()) != 0);

}

SCENARIO("get root", "[init]")

{

  BST<int> test;

  test.add(10);

  REQUIRE(test.getcount() == 1);

  REQUIRE(test.getroot() != 0);

}

SCENARIO ("test1", "[init]")
{
	BST<int> test;
	ofstream testfile("testfile.txt");
	testfile << "2 1 9";
	testfile.close();
	test.input("testfile.txt");
	REQUIRE(test.getcount() == 3);

}

/*

SCENARIO("del", "[init]")

{

  BST<int> test;

  test.add(1);

  test.add(2);

  test.add(3);

  test.del(test.getroot(), 1);

  test.del(test.getroot(), 2);

  REQUIRE(test.search(1, test.getroot()) != 0);
  REQUIRE(test.search(2, test.getroot()) == 0);

  REQUIRE(test.search(3, test.getroot())!= 0);

}

*/

<commit_msg>Create init.cpp<commit_after>#include <BST.hpp>
#include <catch.hpp>
#include <fstream>

SCENARIO ("init", "[init]")

{

  BST<int> test;

  REQUIRE(test.getroot() == nullptr);
  REQUIRE(test.getcount() == 0);

}

SCENARIO("insert", "[init]")

{

  BST<int> test;

  test.add(10);

  REQUIRE(test.search(10, test.getroot()) != 0);

}

SCENARIO("find_node", "[init]")

{

  BST<int> test;

  test.add(10);

  REQUIRE(test.search(10, test.getroot()) != 0);

  REQUIRE(test.search(10, test.getroot()) != 0);

}

SCENARIO("get root", "[init]")

{

  BST<int> test;

  test.add(10);

  REQUIRE(test.getcount() == 1);

  REQUIRE(test.getroot() != 0);

}

SCENARIO ("test1", "[init]")
{
	BST<int> test;
	ofstream testfile("testfile.txt");
	testfile << "2 1 9 5";
	testfile.close();
	test.input("testfile.txt");
	REQUIRE(test.getcount() == 3);

}

/*

SCENARIO("del", "[init]")

{

  BST<int> test;

  test.add(1);

  test.add(2);

  test.add(3);

  test.del(test.getroot(), 1);

  test.del(test.getroot(), 2);

  REQUIRE(test.search(1, test.getroot()) != 0);
  REQUIRE(test.search(2, test.getroot()) == 0);

  REQUIRE(test.search(3, test.getroot())!= 0);

}

*/

<|endoftext|>


<commit_before>// Simple starting example to illustrate the "strategy design pattern"
// ** Variability **

#include <string>
#include <vector>
#include <iostream>

// greeter class: configured with a list of names, outputs a greeting for each name
class Greeter {
private:
	std::vector<std::string> names; // the list of names that the greeter must greet

public:
	// adds a name to the list of names that this Greeter object must greet
	void addName(std::string name) {
		names.push_back(name);
	}

	// greeting everyone:
	void greet() {
		for (std::vector<std::string>::iterator it=names.begin(); it != names.end(); it++) {
			std::cout << "Hello " << *it << "!" << std::endl;
		}
	}
};

// example of using the class

int main() {
	Greeter john;
	john.addName("Mark");
	john.addName("Sophie");
	john.addName("Lilly");
	john.greet();
}

<commit_msg>added comment in main file<commit_after>// Simple starting example to illustrate the "strategy design pattern"
// ** Variability **

#include <string>
#include <vector>
#include <iostream>

// greeter class: configured with a list of names, outputs a greeting for each name
class Greeter {
private:
	std::vector<std::string> names; // the list of names that the greeter must greet

public:
	// adds a name to the list of names that this Greeter object must greet
	void addName(std::string name) {
		names.push_back(name);
	}

	// greeting everyone:
	void greet() {
		for (std::vector<std::string>::iterator it=names.begin(); it != names.end(); it++) {
			std::cout << "Hello " << *it << "!" << std::endl;
		}
	}
};

// example of using the class

int main() {
	Greeter john;
	john.addName("Mark");
	john.addName("Sophie");
	john.addName("Lilly");
	john.greet();
	// outputs
	// Hello Mark!
  // Hello Sophie!
	// Hello Lilly!
	return 0;
}

<|endoftext|>


<commit_before>#include <drivers/serial.h>
#include <arch/reboot.h>
#include <pointer.h>
#include <lib/ctype.h>
#include <stdarg.h>
#include <lib/cstring.h>
#include <kernel/allocator.h>
#include <kernel/heap_allocator.h>
#include "tests.h"

asmlinkage char _end[];

int vsprintf(char *buf, const char *fmt, va_list args);

namespace tests {

int printf(const char *fmt, ...) {
    char printf_buf[512];
    va_list args;
    int printed;
    va_start(args, fmt);
    printed = vsprintf(printf_buf, fmt, args);
    va_end(args);
    serial_print(printf_buf);
    return printed;
}

char testMap[1024*1024];

TEST(allocator, can_allocate) {
    kernel::allocator<kernel::heap_allocator, 32> testAllocator1(testMap);
    for (auto i = 0; i < 1024; ++i) {
        auto result = testAllocator1.allocate(10);
        REQUIRE(static_cast<void *>(result) == reinterpret_cast<void *>(static_cast<char *>(testMap) + 32 + 64*i));
    }
}

TEST(allocator, can_divide_blocks) {
    kernel::allocator<kernel::heap_allocator, 32> testAllocator1(testMap);
    auto expected = testMap + 32;
    auto data1 = testAllocator1.allocate(120);
    REQUIRE(static_cast<void *>(data1) == static_cast<void *>(expected));
    testAllocator1.free(data1);
    auto data2 = testAllocator1.allocate(2);
    REQUIRE(static_cast<void *>(data2) == static_cast<void *>(expected));
    auto data3 = testAllocator1.allocate(2);
    expected += 32 + 32;
    REQUIRE(static_cast<void *>(data3) == static_cast<void *>(expected));
    auto data4 = testAllocator1.allocate(2);
    expected += 32 + 32 + 32; // dead memory area
    REQUIRE(static_cast<void *>(data4) == static_cast<void *>(expected));
}

TEST(kernel_allocator, can_allocate_and_free) {
    for (int i = 0; i < 1024; i++) {
        auto a = yacppl::make_shared<int>(1);
        REQUIRE(*a == 1);
        auto b = yacppl::make_unique<char>(2);
        REQUIRE(*b == 2);
        REQUIRE(reinterpret_cast<unsigned int>(b.get()) != reinterpret_cast<unsigned int>(a.get()));
        auto c = new int{498};
        REQUIRE(*c == 498);
        REQUIRE(reinterpret_cast<unsigned int>(c) != reinterpret_cast<unsigned int>(a.get()));
        REQUIRE(reinterpret_cast<unsigned int>(c) != reinterpret_cast<unsigned int>(b.get()));
        REQUIRE(*a == 1);
        REQUIRE(*b == 2);
        delete c;
        auto d = new int(5);
        delete d;
        REQUIRE(c == d);
        REQUIRE(reinterpret_cast<unsigned int>(c) > reinterpret_cast<unsigned int>(b.get()));
        REQUIRE(reinterpret_cast<unsigned int>(b.get()) > reinterpret_cast<unsigned int>(a.get()));
    }
}

asmlinkage __noreturn void main() {
    serial_init();
    TEST_RUN(allocator, can_allocate);
    TEST_RUN(allocator, can_divide_blocks);
    TEST_RUN(kernel_allocator, can_allocate_and_free);
    reboot();
    while (1);
}

} // namespace tests

<commit_msg>Minor changes in tests<commit_after>#include <drivers/serial.h>
#include <arch/reboot.h>
#include <pointer.h>
#include <lib/ctype.h>
#include <stdarg.h>
#include <lib/cstring.h>
#include <kernel/allocator.h>
#include <kernel/heap_allocator.h>
#include "tests.h"

int vsprintf(char *buf, const char *fmt, va_list args);

namespace tests {

int printf(const char *fmt, ...) {
    char printf_buf[512];
    va_list args;
    int printed;
    va_start(args, fmt);
    printed = vsprintf(printf_buf, fmt, args);
    va_end(args);
    serial_print(printf_buf);
    return printed;
}

char testMap[1024*1024];

TEST(allocator, can_allocate) {
    constexpr size_t memory_block_size = 32;
    kernel::allocator<kernel::heap_allocator, memory_block_size> testAllocator1(testMap);
    for (auto i = 0; i < 1024; ++i) {
        auto result = testAllocator1.allocate(10);
        REQUIRE(static_cast<void *>(result) == static_cast<void *>(static_cast<char *>(testMap) + memory_block_size + memory_block_size * 2 * i));
    }
}

TEST(allocator, can_divide_blocks) {
    constexpr size_t memory_block_size = 32;
    kernel::allocator<kernel::heap_allocator, memory_block_size> testAllocator1(testMap);
    auto data1 = testAllocator1.allocate(120);
    auto expected = testMap + memory_block_size;
    REQUIRE(static_cast<void *>(data1) == static_cast<void *>(expected));
    testAllocator1.free(data1);
    auto data2 = testAllocator1.allocate(2);
    REQUIRE(static_cast<void *>(data2) == static_cast<void *>(expected));
    auto data3 = testAllocator1.allocate(2);
    expected += memory_block_size * 2;
    REQUIRE(static_cast<void *>(data3) == static_cast<void *>(expected));
    auto data4 = testAllocator1.allocate(2);
    expected += memory_block_size * 3; // dead memory area
    REQUIRE(static_cast<void *>(data4) == static_cast<void *>(expected));
    auto data5 = testAllocator1.allocate(2);
    expected += memory_block_size * 2;
    REQUIRE(static_cast<void *>(data5) == static_cast<void *>(expected));
}

TEST(kernel_allocator, can_allocate_and_free) {
    for (int i = 0; i < 1024; i++) {
        auto a = yacppl::make_shared<int>(1);
        REQUIRE(*a == 1);
        auto b = yacppl::make_unique<char>(2);
        REQUIRE(*b == 2);
        REQUIRE(reinterpret_cast<unsigned int>(b.get()) != reinterpret_cast<unsigned int>(a.get()));
        auto c = new int{498};
        REQUIRE(*c == 498);
        REQUIRE(reinterpret_cast<unsigned int>(c) != reinterpret_cast<unsigned int>(a.get()));
        REQUIRE(reinterpret_cast<unsigned int>(c) != reinterpret_cast<unsigned int>(b.get()));
        REQUIRE(*a == 1);
        REQUIRE(*b == 2);
        delete c;
        auto d = new int(5);
        delete d;
        REQUIRE(c == d);
        REQUIRE(reinterpret_cast<unsigned int>(c) > reinterpret_cast<unsigned int>(b.get()));
        REQUIRE(reinterpret_cast<unsigned int>(b.get()) > reinterpret_cast<unsigned int>(a.get()));
    }
}

asmlinkage __noreturn void main() {
    serial_init();
    TEST_RUN(allocator, can_allocate);
    TEST_RUN(allocator, can_divide_blocks);
    TEST_RUN(kernel_allocator, can_allocate_and_free);
    reboot();
    while (1);
}

} // namespace tests

<|endoftext|>


<commit_before>/*  This file is part of the Vc library.

    Copyright (C) 2009-2011 Matthias Kretz <kretz@kde.org>

    Vc is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as
    published by the Free Software Foundation, either version 3 of
    the License, or (at your option) any later version.

    Vc 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 Vc.  If not, see <http://www.gnu.org/licenses/>.

*/

#include "unittest.h"
#include <iostream>
#include "vectormemoryhelper.h"
#include <cmath>

using namespace Vc;

template<typename Vec> void testInc()
{
    VectorMemoryHelper<Vec> mem(2);
    typedef typename Vec::EntryType T;
    typedef typename Vec::Mask Mask;
    T *data = mem;
    for (int borderI = 0; borderI < Vec::Size; ++borderI) {
        const T border = static_cast<T>(borderI);
        for (int i = 0; i < Vec::Size; ++i) {
            data[i] = static_cast<T>(i);
            data[i + Vec::Size] = data[i] + static_cast<T>(data[i] < border ? 1 : 0);
        }
        Vec a(&data[0]);
        Vec b(&data[Vec::Size]);
        Mask m = a < border;
        Vec aa(a);
        COMPARE(aa(m)++, a) << ", border: " << border << ", m: " << m;
        COMPARE(aa, b) << ", border: " << border << ", m: " << m;
        COMPARE(++a(m), b) << ", border: " << border << ", m: " << m;
        COMPARE(a, b) << ", border: " << border << ", m: " << m;
    }
}

template<typename Vec> void testDec()
{
    VectorMemoryHelper<Vec> mem(2);
    typedef typename Vec::EntryType T;
    typedef typename Vec::Mask Mask;
    T *data = mem;
    for (int borderI = 0; borderI < Vec::Size; ++borderI) {
        const T border = static_cast<T>(borderI);
        for (int i = 0; i < Vec::Size; ++i) {
            data[i] = static_cast<T>(i + 1);
            data[i + Vec::Size] = data[i] - static_cast<T>(data[i] < border ? 1 : 0);
        }
        Vec a(&data[0]);
        Vec b(&data[Vec::Size]);
        Mask m = a < border;
        Vec aa(a);
        COMPARE(aa(m)--, a);
        COMPARE(--a(m), b);
        COMPARE(a, b);
        COMPARE(aa, b);
    }
}

template<typename Vec> void testPlusEq()
{
    VectorMemoryHelper<Vec> mem(2);
    typedef typename Vec::EntryType T;
    typedef typename Vec::Mask Mask;
    T *data = mem;
    for (int borderI = 0; borderI < Vec::Size; ++borderI) {
        const T border = static_cast<T>(borderI);
        for (int i = 0; i < Vec::Size; ++i) {
            data[i] = static_cast<T>(i + 1);
            data[i + Vec::Size] = data[i] + static_cast<T>(data[i] < border ? 2 : 0);
        }
        Vec a(&data[0]);
        Vec b(&data[Vec::Size]);
        Mask m = a < border;
        COMPARE(a(m) += static_cast<T>(2), b);
        COMPARE(a, b);
    }
}

template<typename Vec> void testMinusEq()
{
    VectorMemoryHelper<Vec> mem(2);
    typedef typename Vec::EntryType T;
    typedef typename Vec::Mask Mask;
    T *data = mem;
    for (int borderI = 0; borderI < Vec::Size; ++borderI) {
        const T border = static_cast<T>(borderI);
        for (int i = 0; i < Vec::Size; ++i) {
            data[i] = static_cast<T>(i + 2);
            data[i + Vec::Size] = data[i] - static_cast<T>(data[i] < border ? 2 : 0);
        }
        Vec a(&data[0]);
        Vec b(&data[Vec::Size]);
        Mask m = a < border;
        COMPARE(a(m) -= static_cast<T>(2), b);
        COMPARE(a, b);
    }
}

template<typename Vec> void testTimesEq()
{
    VectorMemoryHelper<Vec> mem(2);
    typedef typename Vec::EntryType T;
    typedef typename Vec::Mask Mask;
    T *data = mem;
    for (int borderI = 0; borderI < Vec::Size; ++borderI) {
        const T border = static_cast<T>(borderI);
        for (int i = 0; i < Vec::Size; ++i) {
            data[i] = static_cast<T>(i);
            data[i + Vec::Size] = data[i] * static_cast<T>(data[i] < border ? 2 : 1);
        }
        Vec a(&data[0]);
        Vec b(&data[Vec::Size]);
        Mask m = a < border;
        COMPARE(a(m) *= static_cast<T>(2), b);
        COMPARE(a, b);
    }
}

template<typename Vec> void testDivEq()
{
    VectorMemoryHelper<Vec> mem(2);
    typedef typename Vec::EntryType T;
    typedef typename Vec::Mask Mask;
    T *data = mem;
    for (int borderI = 0; borderI < Vec::Size; ++borderI) {
        const T border = static_cast<T>(borderI);
        for (int i = 0; i < Vec::Size; ++i) {
            data[i] = static_cast<T>(5 * i);
            data[i + Vec::Size] = data[i] / static_cast<T>(data[i] < border ? 3 : 1);
        }
        Vec a(&data[0]);
        Vec b(&data[Vec::Size]);
        Mask m = a < border;
        COMPARE(a(m) /= static_cast<T>(3), b);
        COMPARE(a, b);
    }
}

template<typename Vec> void testAssign()
{
    VectorMemoryHelper<Vec> mem(2);
    typedef typename Vec::EntryType T;
    typedef typename Vec::Mask Mask;
    T *data = mem;
    for (int borderI = 0; borderI < Vec::Size; ++borderI) {
        const T border = static_cast<T>(borderI);
        for (int i = 0; i < Vec::Size; ++i) {
            data[i] = static_cast<T>(i);
            data[i + Vec::Size] = data[i] + static_cast<T>(data[i] < border ? 2 : 0);
        }
        Vec a(&data[0]);
        Vec b(&data[Vec::Size]);
        Mask m = a < border;
        COMPARE(a(m) = b, b);
        COMPARE(a, b);
    }
}

template<typename Vec> void testZero()
{
    typedef typename Vec::EntryType T;
    typedef typename Vec::Mask Mask;
    typedef typename Vec::IndexType I;

    for (int cut = 0; cut < Vec::Size; ++cut) {
        const Mask mask(I(Vc::IndexesFromZero) < cut);
        //std::cout << mask << std::endl;

        const T aa = 4;
        Vec a(aa);
        Vec b(Vc::Zero);

        b(!mask) = a;
        a.setZero(mask);

        COMPARE(a, b);
    }
}

template<typename Vec> void testCount()
{
    typedef typename Vec::EntryType T;
    typedef typename Vec::IndexType I;
    typedef typename Vec::Mask M;

    for_all_masks(Vec, m) {
        unsigned int count = 0;
        for (int i = 0; i < Vec::Size; ++i) {
            if (m[i]) {
                ++count;
            }
        }
        COMPARE(m.count(), count) << ", m = " << m;
    }
}

template<typename Vec> void testFirstOne()
{
    typedef typename Vec::EntryType T;
    typedef typename Vec::IndexType I;
    typedef typename Vec::Mask M;

    for (unsigned int i = 0; i < Vec::Size; ++i) {
        const M mask(I(Vc::IndexesFromZero) == i);
        COMPARE(mask.firstOne(), i);
    }
}

#ifdef VC_IMPL_SSE
void testFloat8GatherMask()
{
    Memory<short_v, short_v::Size * 256> data;
    short_v::Memory andMemory;
    for (int i = 0; i < short_v::Size; ++i) {
        andMemory[i] = 1 << i;
    }
    const short_v andMask(andMemory);

    for (unsigned int i = 0; i < data.vectorsCount(); ++i) {
        data.vector(i) = andMask & i;
    }

    for (unsigned int i = 0; i < data.vectorsCount(); ++i) {
        const short_m mask = data.vector(i) == short_v::Zero();

        SSE::Float8GatherMask
            gatherMaskA(mask),
            gatherMaskB(static_cast<sfloat_m>(mask));
        COMPARE(gatherMaskA.toInt(), gatherMaskB.toInt());
    }
}
#endif

template<typename V> void maskInit()
{
    typedef typename V::Mask M;
    COMPARE(M(Vc::One), M(true));
    COMPARE(M(Vc::Zero), M(false));
}

int main(int argc, char **argv)
{
    initTest(argc, argv);

    testAllTypes(maskInit);
    testAllTypes(testInc);
    testAllTypes(testDec);
    testAllTypes(testPlusEq);
    testAllTypes(testMinusEq);
    testAllTypes(testTimesEq);
    testAllTypes(testDivEq);
    testAllTypes(testAssign);
    testAllTypes(testZero);
    testAllTypes(testCount);
    testAllTypes(testFirstOne);

#ifdef VC_IMPL_SSE
    runTest(testFloat8GatherMask);
#endif

    return 0;
}
<commit_msg>add foldmarkers<commit_after>/*  This file is part of the Vc library. {{{

    Copyright (C) 2009-2013 Matthias Kretz <kretz@kde.org>

    Vc is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as
    published by the Free Software Foundation, either version 3 of
    the License, or (at your option) any later version.

    Vc 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 Vc.  If not, see <http://www.gnu.org/licenses/>.

}}}*/

#include "unittest.h"
#include <iostream>
#include "vectormemoryhelper.h"
#include <cmath>

using namespace Vc;

template<typename Vec> void testInc()/*{{{*/
{
    VectorMemoryHelper<Vec> mem(2);
    typedef typename Vec::EntryType T;
    typedef typename Vec::Mask Mask;
    T *data = mem;
    for (int borderI = 0; borderI < Vec::Size; ++borderI) {
        const T border = static_cast<T>(borderI);
        for (int i = 0; i < Vec::Size; ++i) {
            data[i] = static_cast<T>(i);
            data[i + Vec::Size] = data[i] + static_cast<T>(data[i] < border ? 1 : 0);
        }
        Vec a(&data[0]);
        Vec b(&data[Vec::Size]);
        Mask m = a < border;
        Vec aa(a);
        COMPARE(aa(m)++, a) << ", border: " << border << ", m: " << m;
        COMPARE(aa, b) << ", border: " << border << ", m: " << m;
        COMPARE(++a(m), b) << ", border: " << border << ", m: " << m;
        COMPARE(a, b) << ", border: " << border << ", m: " << m;
    }
}

/*}}}*/
template<typename Vec> void testDec()/*{{{*/
{
    VectorMemoryHelper<Vec> mem(2);
    typedef typename Vec::EntryType T;
    typedef typename Vec::Mask Mask;
    T *data = mem;
    for (int borderI = 0; borderI < Vec::Size; ++borderI) {
        const T border = static_cast<T>(borderI);
        for (int i = 0; i < Vec::Size; ++i) {
            data[i] = static_cast<T>(i + 1);
            data[i + Vec::Size] = data[i] - static_cast<T>(data[i] < border ? 1 : 0);
        }
        Vec a(&data[0]);
        Vec b(&data[Vec::Size]);
        Mask m = a < border;
        Vec aa(a);
        COMPARE(aa(m)--, a);
        COMPARE(--a(m), b);
        COMPARE(a, b);
        COMPARE(aa, b);
    }
}
/*}}}*/
template<typename Vec> void testPlusEq()/*{{{*/
{
    VectorMemoryHelper<Vec> mem(2);
    typedef typename Vec::EntryType T;
    typedef typename Vec::Mask Mask;
    T *data = mem;
    for (int borderI = 0; borderI < Vec::Size; ++borderI) {
        const T border = static_cast<T>(borderI);
        for (int i = 0; i < Vec::Size; ++i) {
            data[i] = static_cast<T>(i + 1);
            data[i + Vec::Size] = data[i] + static_cast<T>(data[i] < border ? 2 : 0);
        }
        Vec a(&data[0]);
        Vec b(&data[Vec::Size]);
        Mask m = a < border;
        COMPARE(a(m) += static_cast<T>(2), b);
        COMPARE(a, b);
    }
}
/*}}}*/
template<typename Vec> void testMinusEq()/*{{{*/
{
    VectorMemoryHelper<Vec> mem(2);
    typedef typename Vec::EntryType T;
    typedef typename Vec::Mask Mask;
    T *data = mem;
    for (int borderI = 0; borderI < Vec::Size; ++borderI) {
        const T border = static_cast<T>(borderI);
        for (int i = 0; i < Vec::Size; ++i) {
            data[i] = static_cast<T>(i + 2);
            data[i + Vec::Size] = data[i] - static_cast<T>(data[i] < border ? 2 : 0);
        }
        Vec a(&data[0]);
        Vec b(&data[Vec::Size]);
        Mask m = a < border;
        COMPARE(a(m) -= static_cast<T>(2), b);
        COMPARE(a, b);
    }
}
/*}}}*/
template<typename Vec> void testTimesEq()/*{{{*/
{
    VectorMemoryHelper<Vec> mem(2);
    typedef typename Vec::EntryType T;
    typedef typename Vec::Mask Mask;
    T *data = mem;
    for (int borderI = 0; borderI < Vec::Size; ++borderI) {
        const T border = static_cast<T>(borderI);
        for (int i = 0; i < Vec::Size; ++i) {
            data[i] = static_cast<T>(i);
            data[i + Vec::Size] = data[i] * static_cast<T>(data[i] < border ? 2 : 1);
        }
        Vec a(&data[0]);
        Vec b(&data[Vec::Size]);
        Mask m = a < border;
        COMPARE(a(m) *= static_cast<T>(2), b);
        COMPARE(a, b);
    }
}
/*}}}*/
template<typename Vec> void testDivEq()/*{{{*/
{
    VectorMemoryHelper<Vec> mem(2);
    typedef typename Vec::EntryType T;
    typedef typename Vec::Mask Mask;
    T *data = mem;
    for (int borderI = 0; borderI < Vec::Size; ++borderI) {
        const T border = static_cast<T>(borderI);
        for (int i = 0; i < Vec::Size; ++i) {
            data[i] = static_cast<T>(5 * i);
            data[i + Vec::Size] = data[i] / static_cast<T>(data[i] < border ? 3 : 1);
        }
        Vec a(&data[0]);
        Vec b(&data[Vec::Size]);
        Mask m = a < border;
        COMPARE(a(m) /= static_cast<T>(3), b);
        COMPARE(a, b);
    }
}
/*}}}*/
template<typename Vec> void testAssign()/*{{{*/
{
    VectorMemoryHelper<Vec> mem(2);
    typedef typename Vec::EntryType T;
    typedef typename Vec::Mask Mask;
    T *data = mem;
    for (int borderI = 0; borderI < Vec::Size; ++borderI) {
        const T border = static_cast<T>(borderI);
        for (int i = 0; i < Vec::Size; ++i) {
            data[i] = static_cast<T>(i);
            data[i + Vec::Size] = data[i] + static_cast<T>(data[i] < border ? 2 : 0);
        }
        Vec a(&data[0]);
        Vec b(&data[Vec::Size]);
        Mask m = a < border;
        COMPARE(a(m) = b, b);
        COMPARE(a, b);
    }
}
/*}}}*/
template<typename Vec> void testZero()/*{{{*/
{
    typedef typename Vec::EntryType T;
    typedef typename Vec::Mask Mask;
    typedef typename Vec::IndexType I;

    for (int cut = 0; cut < Vec::Size; ++cut) {
        const Mask mask(I(Vc::IndexesFromZero) < cut);
        //std::cout << mask << std::endl;

        const T aa = 4;
        Vec a(aa);
        Vec b(Vc::Zero);

        b(!mask) = a;
        a.setZero(mask);

        COMPARE(a, b);
    }
}
/*}}}*/
template<typename Vec> void testCount()/*{{{*/
{
    typedef typename Vec::EntryType T;
    typedef typename Vec::IndexType I;
    typedef typename Vec::Mask M;

    for_all_masks(Vec, m) {
        unsigned int count = 0;
        for (int i = 0; i < Vec::Size; ++i) {
            if (m[i]) {
                ++count;
            }
        }
        COMPARE(m.count(), count) << ", m = " << m;
    }
}
/*}}}*/
template<typename Vec> void testFirstOne()/*{{{*/
{
    typedef typename Vec::EntryType T;
    typedef typename Vec::IndexType I;
    typedef typename Vec::Mask M;

    for (unsigned int i = 0; i < Vec::Size; ++i) {
        const M mask(I(Vc::IndexesFromZero) == i);
        COMPARE(mask.firstOne(), i);
    }
}
/*}}}*/
#ifdef VC_IMPL_SSE
void testFloat8GatherMask()/*{{{*/
{
    Memory<short_v, short_v::Size * 256> data;
    short_v::Memory andMemory;
    for (int i = 0; i < short_v::Size; ++i) {
        andMemory[i] = 1 << i;
    }
    const short_v andMask(andMemory);

    for (unsigned int i = 0; i < data.vectorsCount(); ++i) {
        data.vector(i) = andMask & i;
    }

    for (unsigned int i = 0; i < data.vectorsCount(); ++i) {
        const short_m mask = data.vector(i) == short_v::Zero();

        SSE::Float8GatherMask
            gatherMaskA(mask),
            gatherMaskB(static_cast<sfloat_m>(mask));
        COMPARE(gatherMaskA.toInt(), gatherMaskB.toInt());
    }
}/*}}}*/
#endif

template<typename V> void maskInit()/*{{{*/
{
    typedef typename V::Mask M;
    COMPARE(M(Vc::One), M(true));
    COMPARE(M(Vc::Zero), M(false));
}
/*}}}*/
int main(int argc, char **argv)/*{{{*/
{
    initTest(argc, argv);

    testAllTypes(maskInit);
    testAllTypes(testInc);
    testAllTypes(testDec);
    testAllTypes(testPlusEq);
    testAllTypes(testMinusEq);
    testAllTypes(testTimesEq);
    testAllTypes(testDivEq);
    testAllTypes(testAssign);
    testAllTypes(testZero);
    testAllTypes(testCount);
    testAllTypes(testFirstOne);

#ifdef VC_IMPL_SSE
    runTest(testFloat8GatherMask);
#endif

    return 0;
}/*}}}*/

// vim: foldmethod=marker
<|endoftext|>


<commit_before>// $Id$

#include <qdir.h>

#include "koprefs.h"

#include <kconfig.h>
#include <ksimpleconfig.h>
#include <kstddirs.h>
#include <klocale.h>
#include <kdebug.h>
#include <kemailsettings.h>

KOPrefs *KOPrefs::mInstance = 0;

KOPrefs::KOPrefs() :
  KPrefs("korganizerrc")
{
  mCategoryColors.setAutoDelete(true);

  mDefaultCategoryColor           = QColor(196,196,196);
  QColor defaultHolidayColor      = QColor("red");
  QColor defaultHighlightColor    = QColor("blue");
  QColor defaultAgendaBgColor     = QColor(128,128,128);
  QColor defaultWorkingHoursColor = QColor(160,160,160);

  mDefaultTimeBarFont = QFont("helvetica",12,QFont::Bold);
  mDefaultViewFont = QFont("helvetica",12);

  KPrefsItem::setCurrentGroup("General");

  addPrefsItem(new KPrefsItemBool("Enable Group Scheduling",
                                  &mEnableGroupScheduling,false));
  addPrefsItem(new KPrefsItemBool("Enable Project View",
                                  &mEnableProjectView,false));

  KPrefsItem::setCurrentGroup("Personal Settings");

  addPrefsItem(new KPrefsItemInt("Mail Client",&mMailClient,
                                 MailClientKMail));
  addPrefsItem(new KPrefsItemBool("Use Control Center Email",
                                  &mEmailControlCenter,false));

  KPrefsItem::setCurrentGroup("AlarmDaemon");

  addPrefsItem(new KPrefsItemBool("Autostart",&mAlarmdAutostart,false));

  KPrefsItem::setCurrentGroup("Calendar");

  addPrefsItem(new KPrefsItemInt("Default Calendar Format",&mDefaultFormat,
                                 FormatICalendar));

  KPrefsItem::setCurrentGroup("Colors");

  addPrefsItem(new KPrefsItemColor("Holiday Color",&mHolidayColor,
                                   defaultHolidayColor));
  addPrefsItem(new KPrefsItemColor("Highlight Color",&mHighlightColor,
                                   defaultHighlightColor));
  addPrefsItem(new KPrefsItemColor("Event Color",&mEventColor,
                                   mDefaultCategoryColor));
  addPrefsItem(new KPrefsItemColor("Agenda Background Color",&mAgendaBgColor,
                                   defaultAgendaBgColor));
  addPrefsItem(new KPrefsItemColor("WorkingHours Color",&mWorkingHoursColor,
                                   defaultWorkingHoursColor));

  KPrefsItem::setCurrentGroup("Views");

  addPrefsItem(new KPrefsItemBool("Show Daily Recurrences",&mDailyRecur,true));
  addPrefsItem(new KPrefsItemBool("Show Weekly Recurrences",&mWeeklyRecur,
                                  true));
  addPrefsItem(new KPrefsItemBool("Enable ToolTips",&mEnableToolTips,false));
  addPrefsItem(new KPrefsItemBool("Enable MonthView ScrollBars",
                                  &mEnableMonthScroll,false));

  addPrefsItem(new KPrefsItemInt("Day Begins",&mDayBegins,7));
  addPrefsItem(new KPrefsItemInt("Working Hours Start",&mWorkingHoursStart,8));
  addPrefsItem(new KPrefsItemInt("Working Hours End",&mWorkingHoursEnd,17));
  addPrefsItem(new KPrefsItemBool("Exclude Holidays",&mExcludeHolidays,true));
  addPrefsItem(new KPrefsItemBool("Exclude Saturdays",&mExcludeSaturdays,true));

  addPrefsItem(new KPrefsItemBool("Full View Month",&mFullViewMonth,false));
  addPrefsItem(new KPrefsItemBool("Full View Todo",&mFullViewTodo,true));
}

KOPrefs::~KOPrefs()
{
  kdDebug() << "KOPrefs::~KOPrefs()" << endl;

  delete mInstance;
  mInstance = 0;
}

KOPrefs *KOPrefs::instance()
{
  if (!mInstance) {
    mInstance = new KOPrefs();
    mInstance->readConfig();
  }

  return mInstance;
}

void KOPrefs::usrSetDefaults()
{
  // Default should be set a bit smarter, respecting username and locale
  // settings for example.

  mAutoSave = false;
  mAutoSaveInterval = 10;
  mConfirm = true;

  KEMailSettings settings;
  mName = settings.getSetting(KEMailSettings::RealName);
  mEmail = settings.getSetting(KEMailSettings::RealName);
  if (mName.isEmpty()) mName = i18n("Anonoymous");
  if (mEmail.isEmpty()) mEmail = i18n("nobody@nowhere");
  mBcc = false;

  mAdditional = "";
  mHoliday = KGlobal::locale()->country();

  mTimeZone = "+0000";
  mStartTime = 10;
  mDefaultDuration = 2;
  mAlarmTime = 0;
  mDaylightSavings = 0;

//  mDayBegins = 8;
  mHourSize = 10;
//  mDailyRecur = true;
//  mWeeklyRecur = true;
//  mEnableToolTips = false;

  mTimeBarFont = mDefaultTimeBarFont;
  mMonthViewFont = mDefaultViewFont;
  mAgendaViewFont = mDefaultViewFont;

//  mHolidayColor = mDefaultHolidayColor;
//  mHighlightColor = mDefaultHighlightColor;
//  mEventColor = mDefaultCategoryColor;
//  mAgendaBgColor = mDefaultAgendaBgColor;

  mPrinter = "";
  mPaperSize = 0;
  mPaperOrientation = 0;
  mPrintPreview = "kghostview";

  setCategoryDefaults();
}

void KOPrefs::setCategoryDefaults()
{
  mCustomCategories.clear();

  mCustomCategories << i18n("Appointment") << i18n("Business")
      << i18n("Meeting") << i18n("Phone Call") << i18n("Education")
      << i18n("Holiday") << i18n("Vacation") << i18n("Special Occasion")
      << i18n("Personal") << i18n("Travel") << i18n("Miscellaneous")
      << i18n("Birthday");

  QStringList::Iterator it;
  for (it = mCustomCategories.begin();it != mCustomCategories.end();++it ) {
    setCategoryColor(*it,mDefaultCategoryColor);
  }
}

void KOPrefs::usrReadConfig()
{
  kdDebug() << "KOPrefs::usrReadConfig()" << endl;

  mConfig->setGroup("General");
  mAutoSave = mConfig->readBoolEntry("Auto Save",false);
  mAutoSaveInterval = mConfig->readNumEntry("Auto Save Interval",10);
  mConfirm = mConfig->readBoolEntry("Confirm Deletes",true);
  mCustomCategories = mConfig->readListEntry("Custom Categories");
  if (mCustomCategories.isEmpty()) setCategoryDefaults();

  mArchiveFile = mConfig->readEntry("Archive File");
  mHtmlExportFile = mConfig->readEntry("Html Export File",QDir::homeDirPath() +
                                       "/calendar.html");

  mConfig->setGroup("Personal Settings");
  mName = mConfig->readEntry("user_name","");
  mEmail = mConfig->readEntry("user_email","");
  mAdditional = mConfig->readEntry("Additional","");
  mBcc = mConfig->readBoolEntry("Bcc",false);

  mHoliday = mConfig->readEntry("Holidays", KGlobal::locale()->country());

  mConfig->setGroup("Time & Date");
  mTimeZone = mConfig->readEntry("Time Zone","+0000");
  mStartTime = mConfig->readNumEntry("Default Start Time",10);
  mDefaultDuration = mConfig->readNumEntry("Default Duration",2);
  mAlarmTime = mConfig->readNumEntry("Default Alarm Time",0);
  mDaylightSavings = mConfig->readNumEntry("Daylight Savings", 0);

  mConfig->setGroup("Views");
//  mDayBegins = mConfig->readNumEntry("Day Begins",8);
  mHourSize = mConfig->readNumEntry("Hour Size",10);
//  mDailyRecur = mConfig->readBoolEntry("Show Daily Recurrences",true);
//  mWeeklyRecur = mConfig->readBoolEntry("Show Weekly Recurrences",true);
//  mEnableToolTips = mConfig->readBoolEntry("Enable ToolTips",false);

  mConfig->setGroup("Fonts");
  mTimeBarFont = mConfig->readFontEntry("TimeBar Font",&mDefaultTimeBarFont);
  mMonthViewFont = mConfig->readFontEntry("MonthView Font",
                                          &mDefaultViewFont);
  mAgendaViewFont = mConfig->readFontEntry("AgendaView Font",
                                          &mDefaultViewFont);

  mConfig->setGroup("Colors");
//  mHolidayColor = mConfig->readColorEntry("Holiday Color",
//                                         &mDefaultHolidayColor);
//  mHighlightColor = mConfig->readColorEntry("Highlight Color",
//                                            &mDefaultHighlightColor);
//  mEventColor = mConfig->readColorEntry("Event Color",
//                                            &mDefaultCategoryColor);
//  mAgendaBgColor = mConfig->readColorEntry("Agenda Background Color",
//                                            &mDefaultAgendaBgColor);

  mConfig->setGroup("Category Colors");
  QStringList::Iterator it;
  for (it = mCustomCategories.begin();it != mCustomCategories.end();++it ) {
    setCategoryColor(*it,mConfig->readColorEntry(*it,&mDefaultCategoryColor));
  }

  mConfig->setGroup("Printer");
  mPrinter = mConfig->readEntry("Printer Name",0);
  mPaperSize = mConfig->readNumEntry("Paper Size",0);
  mPaperOrientation = mConfig->readNumEntry("Paper Orientation",0);
  mPrintPreview = mConfig->readEntry("Preview","kghostview");

  kdDebug() << "KOPrefs::usrReadConfig() done" << endl;
}

void KOPrefs::usrWriteConfig()
{
//  kdDebug() << "KOPrefs::writeConfig()" << endl;

  mConfig->setGroup("General");
  mConfig->writeEntry("Auto Save",mAutoSave);
  mConfig->writeEntry("Auto Save Interval",mAutoSaveInterval);
  mConfig->writeEntry("Confirm Deletes",mConfirm);
  mConfig->writeEntry("Custom Categories",mCustomCategories);

  mConfig->writeEntry("Archive File",mArchiveFile);
  mConfig->writeEntry("Html Export File",mHtmlExportFile);

  mConfig->setGroup("Personal Settings");
  mConfig->writeEntry("user_name",mName);
  mConfig->writeEntry("user_email",mEmail);
  mConfig->writeEntry("Additional",mAdditional);
  mConfig->writeEntry("Bcc",mBcc);
  mConfig->writeEntry("Holidays",mHoliday);

  mConfig->setGroup("Time & Date");
  mConfig->writeEntry("Time Zone",mTimeZone);
  mConfig->writeEntry("Default Start Time",mStartTime);
  mConfig->writeEntry("Default Duration",mDefaultDuration);
  mConfig->writeEntry("Default Alarm Time",mAlarmTime);
  mConfig->writeEntry("Daylight Savings",mDaylightSavings);

  mConfig->setGroup("Views");
//  mConfig->writeEntry("Day Begins",mDayBegins);
  mConfig->writeEntry("Hour Size",mHourSize);
//  mConfig->writeEntry("Show Daily Recurrences",mDailyRecur);
//  mConfig->writeEntry("Show Weekly Recurrences",mWeeklyRecur);
//  mConfig->writeEntry("Enable ToolTips",mEnableToolTips);

  mConfig->setGroup("Fonts");
  mConfig->writeEntry("TimeBar Font",mTimeBarFont);
  mConfig->writeEntry("MonthView Font",mMonthViewFont);
  mConfig->writeEntry("AgendaView Font",mAgendaViewFont);

  mConfig->setGroup("Colors");
//  mConfig->writeEntry("Holiday Color",mHolidayColor);
//  mConfig->writeEntry("Highlight Color",mHighlightColor);
//  mConfig->writeEntry("Event Color",mEventColor);
//  mConfig->writeEntry("Agenda Background Color",mAgendaBgColor);

  mConfig->setGroup("Category Colors");
  QDictIterator<QColor> it(mCategoryColors);
  while (it.current()) {
    mConfig->writeEntry(it.currentKey(),*(it.current()));
    ++it;
  }

  mConfig->setGroup("Printer");
  mConfig->writeEntry("Printer Name",mPrinter);
  mConfig->writeEntry("Paper Size",mPaperSize);
  mConfig->writeEntry("Paper Orientation",mPaperOrientation);
  mConfig->writeEntry("Preview",mPrintPreview);
}

void KOPrefs::setCategoryColor(QString cat,const QColor & color)
{
  mCategoryColors.replace(cat,new QColor(color));
}

QColor *KOPrefs::categoryColor(QString cat)
{
  QColor *color = 0;

  if (!cat.isEmpty()) color = mCategoryColors[cat];

  if (color) return color;
  else return &mDefaultCategoryColor;
}

void KOPrefs::setFullName(const QString &name)
{
  mName = name;
}

void KOPrefs::setEmail(const QString &email)
{
  mEmail = email;
}

QString KOPrefs::fullName()
{
  if (mEmailControlCenter) {
    KEMailSettings settings;
    return settings.getSetting(KEMailSettings::RealName);
  } else {
    return mName;
  }
}

QString KOPrefs::email()
{
  if (mEmailControlCenter) {
    KEMailSettings settings;
    return settings.getSetting(KEMailSettings::EmailAddress);
  } else {
    return mEmail;
  }
}
<commit_msg>Correcting typo.<commit_after>// $Id$

#include <qdir.h>

#include "koprefs.h"

#include <kconfig.h>
#include <ksimpleconfig.h>
#include <kstddirs.h>
#include <klocale.h>
#include <kdebug.h>
#include <kemailsettings.h>

KOPrefs *KOPrefs::mInstance = 0;

KOPrefs::KOPrefs() :
  KPrefs("korganizerrc")
{
  mCategoryColors.setAutoDelete(true);

  mDefaultCategoryColor           = QColor(196,196,196);
  QColor defaultHolidayColor      = QColor("red");
  QColor defaultHighlightColor    = QColor("blue");
  QColor defaultAgendaBgColor     = QColor(128,128,128);
  QColor defaultWorkingHoursColor = QColor(160,160,160);

  mDefaultTimeBarFont = QFont("helvetica",12,QFont::Bold);
  mDefaultViewFont = QFont("helvetica",12);

  KPrefsItem::setCurrentGroup("General");

  addPrefsItem(new KPrefsItemBool("Enable Group Scheduling",
                                  &mEnableGroupScheduling,false));
  addPrefsItem(new KPrefsItemBool("Enable Project View",
                                  &mEnableProjectView,false));

  KPrefsItem::setCurrentGroup("Personal Settings");

  addPrefsItem(new KPrefsItemInt("Mail Client",&mMailClient,
                                 MailClientKMail));
  addPrefsItem(new KPrefsItemBool("Use Control Center Email",
                                  &mEmailControlCenter,false));

  KPrefsItem::setCurrentGroup("AlarmDaemon");

  addPrefsItem(new KPrefsItemBool("Autostart",&mAlarmdAutostart,false));

  KPrefsItem::setCurrentGroup("Calendar");

  addPrefsItem(new KPrefsItemInt("Default Calendar Format",&mDefaultFormat,
                                 FormatICalendar));

  KPrefsItem::setCurrentGroup("Colors");

  addPrefsItem(new KPrefsItemColor("Holiday Color",&mHolidayColor,
                                   defaultHolidayColor));
  addPrefsItem(new KPrefsItemColor("Highlight Color",&mHighlightColor,
                                   defaultHighlightColor));
  addPrefsItem(new KPrefsItemColor("Event Color",&mEventColor,
                                   mDefaultCategoryColor));
  addPrefsItem(new KPrefsItemColor("Agenda Background Color",&mAgendaBgColor,
                                   defaultAgendaBgColor));
  addPrefsItem(new KPrefsItemColor("WorkingHours Color",&mWorkingHoursColor,
                                   defaultWorkingHoursColor));

  KPrefsItem::setCurrentGroup("Views");

  addPrefsItem(new KPrefsItemBool("Show Daily Recurrences",&mDailyRecur,true));
  addPrefsItem(new KPrefsItemBool("Show Weekly Recurrences",&mWeeklyRecur,
                                  true));
  addPrefsItem(new KPrefsItemBool("Enable ToolTips",&mEnableToolTips,false));
  addPrefsItem(new KPrefsItemBool("Enable MonthView ScrollBars",
                                  &mEnableMonthScroll,false));

  addPrefsItem(new KPrefsItemInt("Day Begins",&mDayBegins,7));
  addPrefsItem(new KPrefsItemInt("Working Hours Start",&mWorkingHoursStart,8));
  addPrefsItem(new KPrefsItemInt("Working Hours End",&mWorkingHoursEnd,17));
  addPrefsItem(new KPrefsItemBool("Exclude Holidays",&mExcludeHolidays,true));
  addPrefsItem(new KPrefsItemBool("Exclude Saturdays",&mExcludeSaturdays,true));

  addPrefsItem(new KPrefsItemBool("Full View Month",&mFullViewMonth,false));
  addPrefsItem(new KPrefsItemBool("Full View Todo",&mFullViewTodo,true));
}

KOPrefs::~KOPrefs()
{
  kdDebug() << "KOPrefs::~KOPrefs()" << endl;

  delete mInstance;
  mInstance = 0;
}

KOPrefs *KOPrefs::instance()
{
  if (!mInstance) {
    mInstance = new KOPrefs();
    mInstance->readConfig();
  }

  return mInstance;
}

void KOPrefs::usrSetDefaults()
{
  // Default should be set a bit smarter, respecting username and locale
  // settings for example.

  mAutoSave = false;
  mAutoSaveInterval = 10;
  mConfirm = true;

  KEMailSettings settings;
  mName = settings.getSetting(KEMailSettings::RealName);
  mEmail = settings.getSetting(KEMailSettings::RealName);
  if (mName.isEmpty()) mName = i18n("Anonymous");
  if (mEmail.isEmpty()) mEmail = i18n("nobody@nowhere");
  mBcc = false;

  mAdditional = "";
  mHoliday = KGlobal::locale()->country();

  mTimeZone = "+0000";
  mStartTime = 10;
  mDefaultDuration = 2;
  mAlarmTime = 0;
  mDaylightSavings = 0;

//  mDayBegins = 8;
  mHourSize = 10;
//  mDailyRecur = true;
//  mWeeklyRecur = true;
//  mEnableToolTips = false;

  mTimeBarFont = mDefaultTimeBarFont;
  mMonthViewFont = mDefaultViewFont;
  mAgendaViewFont = mDefaultViewFont;

//  mHolidayColor = mDefaultHolidayColor;
//  mHighlightColor = mDefaultHighlightColor;
//  mEventColor = mDefaultCategoryColor;
//  mAgendaBgColor = mDefaultAgendaBgColor;

  mPrinter = "";
  mPaperSize = 0;
  mPaperOrientation = 0;
  mPrintPreview = "kghostview";

  setCategoryDefaults();
}

void KOPrefs::setCategoryDefaults()
{
  mCustomCategories.clear();

  mCustomCategories << i18n("Appointment") << i18n("Business")
      << i18n("Meeting") << i18n("Phone Call") << i18n("Education")
      << i18n("Holiday") << i18n("Vacation") << i18n("Special Occasion")
      << i18n("Personal") << i18n("Travel") << i18n("Miscellaneous")
      << i18n("Birthday");

  QStringList::Iterator it;
  for (it = mCustomCategories.begin();it != mCustomCategories.end();++it ) {
    setCategoryColor(*it,mDefaultCategoryColor);
  }
}

void KOPrefs::usrReadConfig()
{
  kdDebug() << "KOPrefs::usrReadConfig()" << endl;

  mConfig->setGroup("General");
  mAutoSave = mConfig->readBoolEntry("Auto Save",false);
  mAutoSaveInterval = mConfig->readNumEntry("Auto Save Interval",10);
  mConfirm = mConfig->readBoolEntry("Confirm Deletes",true);
  mCustomCategories = mConfig->readListEntry("Custom Categories");
  if (mCustomCategories.isEmpty()) setCategoryDefaults();

  mArchiveFile = mConfig->readEntry("Archive File");
  mHtmlExportFile = mConfig->readEntry("Html Export File",QDir::homeDirPath() +
                                       "/calendar.html");

  mConfig->setGroup("Personal Settings");
  mName = mConfig->readEntry("user_name","");
  mEmail = mConfig->readEntry("user_email","");
  mAdditional = mConfig->readEntry("Additional","");
  mBcc = mConfig->readBoolEntry("Bcc",false);

  mHoliday = mConfig->readEntry("Holidays", KGlobal::locale()->country());

  mConfig->setGroup("Time & Date");
  mTimeZone = mConfig->readEntry("Time Zone","+0000");
  mStartTime = mConfig->readNumEntry("Default Start Time",10);
  mDefaultDuration = mConfig->readNumEntry("Default Duration",2);
  mAlarmTime = mConfig->readNumEntry("Default Alarm Time",0);
  mDaylightSavings = mConfig->readNumEntry("Daylight Savings", 0);

  mConfig->setGroup("Views");
//  mDayBegins = mConfig->readNumEntry("Day Begins",8);
  mHourSize = mConfig->readNumEntry("Hour Size",10);
//  mDailyRecur = mConfig->readBoolEntry("Show Daily Recurrences",true);
//  mWeeklyRecur = mConfig->readBoolEntry("Show Weekly Recurrences",true);
//  mEnableToolTips = mConfig->readBoolEntry("Enable ToolTips",false);

  mConfig->setGroup("Fonts");
  mTimeBarFont = mConfig->readFontEntry("TimeBar Font",&mDefaultTimeBarFont);
  mMonthViewFont = mConfig->readFontEntry("MonthView Font",
                                          &mDefaultViewFont);
  mAgendaViewFont = mConfig->readFontEntry("AgendaView Font",
                                          &mDefaultViewFont);

  mConfig->setGroup("Colors");
//  mHolidayColor = mConfig->readColorEntry("Holiday Color",
//                                         &mDefaultHolidayColor);
//  mHighlightColor = mConfig->readColorEntry("Highlight Color",
//                                            &mDefaultHighlightColor);
//  mEventColor = mConfig->readColorEntry("Event Color",
//                                            &mDefaultCategoryColor);
//  mAgendaBgColor = mConfig->readColorEntry("Agenda Background Color",
//                                            &mDefaultAgendaBgColor);

  mConfig->setGroup("Category Colors");
  QStringList::Iterator it;
  for (it = mCustomCategories.begin();it != mCustomCategories.end();++it ) {
    setCategoryColor(*it,mConfig->readColorEntry(*it,&mDefaultCategoryColor));
  }

  mConfig->setGroup("Printer");
  mPrinter = mConfig->readEntry("Printer Name",0);
  mPaperSize = mConfig->readNumEntry("Paper Size",0);
  mPaperOrientation = mConfig->readNumEntry("Paper Orientation",0);
  mPrintPreview = mConfig->readEntry("Preview","kghostview");

  kdDebug() << "KOPrefs::usrReadConfig() done" << endl;
}

void KOPrefs::usrWriteConfig()
{
//  kdDebug() << "KOPrefs::writeConfig()" << endl;

  mConfig->setGroup("General");
  mConfig->writeEntry("Auto Save",mAutoSave);
  mConfig->writeEntry("Auto Save Interval",mAutoSaveInterval);
  mConfig->writeEntry("Confirm Deletes",mConfirm);
  mConfig->writeEntry("Custom Categories",mCustomCategories);

  mConfig->writeEntry("Archive File",mArchiveFile);
  mConfig->writeEntry("Html Export File",mHtmlExportFile);

  mConfig->setGroup("Personal Settings");
  mConfig->writeEntry("user_name",mName);
  mConfig->writeEntry("user_email",mEmail);
  mConfig->writeEntry("Additional",mAdditional);
  mConfig->writeEntry("Bcc",mBcc);
  mConfig->writeEntry("Holidays",mHoliday);

  mConfig->setGroup("Time & Date");
  mConfig->writeEntry("Time Zone",mTimeZone);
  mConfig->writeEntry("Default Start Time",mStartTime);
  mConfig->writeEntry("Default Duration",mDefaultDuration);
  mConfig->writeEntry("Default Alarm Time",mAlarmTime);
  mConfig->writeEntry("Daylight Savings",mDaylightSavings);

  mConfig->setGroup("Views");
//  mConfig->writeEntry("Day Begins",mDayBegins);
  mConfig->writeEntry("Hour Size",mHourSize);
//  mConfig->writeEntry("Show Daily Recurrences",mDailyRecur);
//  mConfig->writeEntry("Show Weekly Recurrences",mWeeklyRecur);
//  mConfig->writeEntry("Enable ToolTips",mEnableToolTips);

  mConfig->setGroup("Fonts");
  mConfig->writeEntry("TimeBar Font",mTimeBarFont);
  mConfig->writeEntry("MonthView Font",mMonthViewFont);
  mConfig->writeEntry("AgendaView Font",mAgendaViewFont);

  mConfig->setGroup("Colors");
//  mConfig->writeEntry("Holiday Color",mHolidayColor);
//  mConfig->writeEntry("Highlight Color",mHighlightColor);
//  mConfig->writeEntry("Event Color",mEventColor);
//  mConfig->writeEntry("Agenda Background Color",mAgendaBgColor);

  mConfig->setGroup("Category Colors");
  QDictIterator<QColor> it(mCategoryColors);
  while (it.current()) {
    mConfig->writeEntry(it.currentKey(),*(it.current()));
    ++it;
  }

  mConfig->setGroup("Printer");
  mConfig->writeEntry("Printer Name",mPrinter);
  mConfig->writeEntry("Paper Size",mPaperSize);
  mConfig->writeEntry("Paper Orientation",mPaperOrientation);
  mConfig->writeEntry("Preview",mPrintPreview);
}

void KOPrefs::setCategoryColor(QString cat,const QColor & color)
{
  mCategoryColors.replace(cat,new QColor(color));
}

QColor *KOPrefs::categoryColor(QString cat)
{
  QColor *color = 0;

  if (!cat.isEmpty()) color = mCategoryColors[cat];

  if (color) return color;
  else return &mDefaultCategoryColor;
}

void KOPrefs::setFullName(const QString &name)
{
  mName = name;
}

void KOPrefs::setEmail(const QString &email)
{
  mEmail = email;
}

QString KOPrefs::fullName()
{
  if (mEmailControlCenter) {
    KEMailSettings settings;
    return settings.getSetting(KEMailSettings::RealName);
  } else {
    return mName;
  }
}

QString KOPrefs::email()
{
  if (mEmailControlCenter) {
    KEMailSettings settings;
    return settings.getSetting(KEMailSettings::EmailAddress);
  } else {
    return mEmail;
  }
}
<|endoftext|>


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

#ifndef _SCRIPT_FRAMEWORK_MISCUTILS_HXX_
#define _SCRIPT_FRAMEWORK_MISCUTILS_HXX_

#include <rtl/ustring>

#include <ucbhelper/content.hxx>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <com/sun/star/frame/XModel.hpp>
#include <com/sun/star/document/XDocumentInfoSupplier.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/container/XContentEnumerationAccess.hpp>
#include <com/sun/star/ucb/XCommandEnvironment.hpp>
#include <com/sun/star/ucb/XSimpleFileAccess.hpp>
#include <com/sun/star/ucb/XContentAccess.hpp>
#include <com/sun/star/sdbc/XResultSet.hpp>
#include <com/sun/star/sdbc/XRow.hpp>
#include <com/sun/star/lang/XMultiComponentFactory.hpp>

#include "util.hxx"

namespace sf_misc
{
// for simplification
#define css ::com::sun::star

class MiscUtils
{
public:
    static css::uno::Sequence< ::rtl::OUString > allOpenTDocUrls( const  css::uno::Reference< css::uno::XComponentContext >& xCtx)
{
    OSL_TRACE("MiscUtils::allOpenTDocUrls");
    css::uno::Sequence< ::rtl::OUString > result;
    try
    {
        if ( !xCtx.is() )
        {
            return result;
        }
        css::uno::Reference < css::lang::XMultiComponentFactory > xFac( xCtx->getServiceManager(), css::uno::UNO_QUERY );
        if ( xFac.is() )
        {
            css::uno::Reference < com::sun::star::ucb::XSimpleFileAccess > xSFA( xFac->createInstanceWithContext( OUSTR("com.sun.star.ucb.SimpleFileAccess"), xCtx ), css::uno::UNO_QUERY );
            if ( xSFA.is() )
            {
                OSL_TRACE("Getting folder contents of vnd.sun.star.tdoc:");
                result = xSFA->getFolderContents( OUSTR("vnd.sun.star.tdoc:/"), true );
                OSL_TRACE("Getting folder contents is %d", result.getLength());
            }
        }
    }
    catch ( css::uno::Exception& e )
    {
    }
    return result;
}
    static ::rtl::OUString xModelToDocTitle( const css::uno::Reference< css::frame::XModel >& xModel )
{
    OSL_TRACE("MiscUtils::xModelToDocTitle() ");
    // Set a default name, this should never be seen.
    ::rtl::OUString docNameOrURL =
        ::rtl::OUString::createFromAscii("Unknown");
    if ( xModel.is() )
    {
        ::rtl::OUString tempName;
        try
        {
            css::uno::Reference< css::beans::XPropertySet > propSet( xModel->getCurrentController()->getFrame(), css::uno::UNO_QUERY );
            if ( propSet.is() )
            {
                if ( sal_True == ( propSet->getPropertyValue(::rtl::OUString::createFromAscii( "Title" ) ) >>= tempName ) )
                {
                    docNameOrURL = tempName;
                    if ( xModel->getURL().getLength() == 0 )
                    {
                        // process "UntitledX - YYYYYYYY"
                        // to get UntitledX
                        sal_Int32 pos = 0;
                        docNameOrURL = tempName.getToken(0,' ',pos);
                        OSL_TRACE("MiscUtils::xModelToDocTitle() Title for document is %s.",
                            ::rtl::OUStringToOString( docNameOrURL,
                                            RTL_TEXTENCODING_ASCII_US ).pData->buffer );
                    }
                    else
                    {
                        css::uno::Reference< css::document::XDocumentInfoSupplier >  xDIS( xModel, css::uno::UNO_QUERY_THROW );
                        css::uno::Reference< css::beans::XPropertySet > xProp (xDIS->getDocumentInfo(),  css::uno::UNO_QUERY_THROW );
                        css::uno::Any aTitle = xProp->getPropertyValue(::rtl::OUString::createFromAscii( "Title" ) );

                        aTitle >>= docNameOrURL;
                        if ( docNameOrURL.getLength() == 0 )
                        {
                            docNameOrURL =  parseLocationName( xModel->getURL() );
                        }
                    }
                }
            }
        }
        catch ( css::uno::Exception& e )
        {
            OSL_TRACE("MiscUtils::xModelToDocTitle() exception thrown: !!! %s",
                ::rtl::OUStringToOString( e.Message,
                    RTL_TEXTENCODING_ASCII_US ).pData->buffer );
        }

    }
    else
    {
        OSL_TRACE("MiscUtils::xModelToDocTitle() doc model is null" );
    }
    return docNameOrURL;
}

    static ::rtl::OUString tDocUrlToTitle( const ::rtl::OUString& url )
{
    ::rtl::OUString title;
    ::ucb::Content root( url, NULL );
    ::rtl::OUString propName =  OUSTR("Title");
    getUCBProperty( root, propName ) >>= title;
    return title;
}
    static ::rtl::OUString xModelToTdocUrl( const css::uno::Reference< css::frame::XModel >& xModel )
{
    OSL_TRACE("MiscUtils::xModelToDocTitle() ");
    css::uno::Reference < com::sun::star::ucb::XCommandEnvironment > dummy;
    ::rtl::OUString sDocRoot = OUSTR( "vnd.sun.star.tdoc:/" );
    ::ucb::Content root( sDocRoot, dummy );

    OSL_TRACE( "get root content" );

    css::uno::Sequence < ::rtl::OUString > aPropertyNames( 0 );
    ::rtl::OUString propName = OUSTR( "DocumentModel" );

    css::uno::Reference < com::sun::star::sdbc::XResultSet > xResultSet =
        root.createCursor( aPropertyNames );

    OSL_TRACE( "get list of documents" );

    css::uno::Reference< com::sun::star::ucb::XContentAccess > xContentAccess(
        xResultSet, css::uno::UNO_QUERY );
    OSL_TRACE( "got contentaccess" );
    ::rtl::OUString docUrl;
    if ( xResultSet.is() && xContentAccess.is() )
    {
        css::uno::Reference< css::sdbc::XRow > values( xResultSet, css::uno::UNO_QUERY );
        if ( values.is() )
        {
            while ( xResultSet->next() )
            {
                ::rtl::OUString url = xContentAccess->queryContentIdentifierString();
                css::uno::Reference < css::frame::XModel > xMod( tDocUrlToModel( url ), css::uno::UNO_QUERY );

                OSL_TRACE( "xModelToTdocUrl: url is %s",
                    ::rtl::OUStringToOString( url,
                            RTL_TEXTENCODING_ASCII_US ).pData->buffer );
                if ( xMod.is() && xMod == xModel )
                {
                    docUrl = url;
                    OSL_TRACE( "xModelToTdocUrl: match for model url is %s",
                        ::rtl::OUStringToOString( url,
                            RTL_TEXTENCODING_ASCII_US ).pData->buffer );
                    break;
                }
            }
        }
    }
    return docUrl;
}
    static css::uno::Reference< css::frame::XModel > tDocUrlToModel( const ::rtl::OUString& url )
{
    css::uno::Any result;
    ::ucb::Content root( url, NULL );
    ::rtl::OUString propName =  OUSTR("DocumentModel");
    result = getUCBProperty( root, propName );

    css::uno::Reference< css::frame::XModel > xModel( result, css::uno::UNO_QUERY );
    return xModel;
}

    static css::uno::Any getUCBProperty( ::ucb::Content& content, ::rtl::OUString& prop )
{
    css::uno::Sequence < ::rtl::OUString > aPropertyNames( 1 );
    ::rtl::OUString* pNames = aPropertyNames.getArray();
    pNames[ 0 ] = prop;
    css::uno::Any result;
    try
    {
        css::uno::Sequence< css::uno::Any > props = content.getPropertyValues( aPropertyNames );
        if ( props.getLength() )
        {
            result = props[ 0 ];
        }
    }
/*    catch ( ucb::CommandAbortedException& e )
    {
    }*/
    catch ( css::uno::Exception& e )
    {
    }
    return result;
}

private:
static ::rtl::OUString parseLocationName( const ::rtl::OUString& location )
{
    // strip out the last leaf of location name
    // e.g. file://dir1/dir2/Blah.sxw - > Blah.sxw
    ::rtl::OUString temp = location;
    sal_Int32 lastSlashIndex = temp.lastIndexOf( ::rtl::OUString::createFromAscii( "/" ) );

    if ( ( lastSlashIndex + 1 ) <  temp.getLength()  )
    {
        temp = temp.copy( lastSlashIndex + 1 );
    }
    // maybe we should throw here!!!
    else
    {
        OSL_TRACE("Something wrong with name, perhaps we should throw an exception");
    }
    return temp;
}

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

#ifndef _SCRIPT_FRAMEWORK_MISCUTILS_HXX_
#define _SCRIPT_FRAMEWORK_MISCUTILS_HXX_

#include <rtl/ustring>

#include <ucbhelper/content.hxx>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <com/sun/star/frame/XModel.hpp>
#include <com/sun/star/document/XDocumentInfoSupplier.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/container/XContentEnumerationAccess.hpp>
#include <com/sun/star/ucb/XCommandEnvironment.hpp>
#include <com/sun/star/ucb/XSimpleFileAccess.hpp>
#include <com/sun/star/ucb/XContentAccess.hpp>
#include <com/sun/star/sdbc/XResultSet.hpp>
#include <com/sun/star/sdbc/XRow.hpp>
#include <com/sun/star/lang/XMultiComponentFactory.hpp>

#include "util.hxx"

namespace sf_misc
{
// for simplification
#define css ::com::sun::star

class MiscUtils
{
public:
    static css::uno::Sequence< ::rtl::OUString > allOpenTDocUrls( const  css::uno::Reference< css::uno::XComponentContext >& xCtx)
{
    css::uno::Sequence< ::rtl::OUString > result;
    try
    {
        if ( !xCtx.is() )
        {
            return result;
        }
        css::uno::Reference < css::lang::XMultiComponentFactory > xFac( xCtx->getServiceManager(), css::uno::UNO_QUERY );
        if ( xFac.is() )
        {
            css::uno::Reference < com::sun::star::ucb::XSimpleFileAccess > xSFA( xFac->createInstanceWithContext( OUSTR("com.sun.star.ucb.SimpleFileAccess"), xCtx ), css::uno::UNO_QUERY );
            if ( xSFA.is() )
            {
                result = xSFA->getFolderContents( OUSTR("vnd.sun.star.tdoc:/"), true );
            }
        }
    }
    catch ( css::uno::Exception& e )
    {
    }
    return result;
}
    static ::rtl::OUString xModelToDocTitle( const css::uno::Reference< css::frame::XModel >& xModel )
{
    // Set a default name, this should never be seen.
    ::rtl::OUString docNameOrURL =
        ::rtl::OUString::createFromAscii("Unknown");
    if ( xModel.is() )
    {
        ::rtl::OUString tempName;
        try
        {
            css::uno::Reference< css::beans::XPropertySet > propSet( xModel->getCurrentController()->getFrame(), css::uno::UNO_QUERY );
            if ( propSet.is() )
            {
                if ( sal_True == ( propSet->getPropertyValue(::rtl::OUString::createFromAscii( "Title" ) ) >>= tempName ) )
                {
                    docNameOrURL = tempName;
                    if ( xModel->getURL().getLength() == 0 )
                    {
                        // process "UntitledX - YYYYYYYY"
                        // to get UntitledX
                        sal_Int32 pos = 0;
                        docNameOrURL = tempName.getToken(0,' ',pos);
                    }
                    else
                    {
                        css::uno::Reference< css::document::XDocumentInfoSupplier >  xDIS( xModel, css::uno::UNO_QUERY_THROW );
                        css::uno::Reference< css::beans::XPropertySet > xProp (xDIS->getDocumentInfo(),  css::uno::UNO_QUERY_THROW );
                        css::uno::Any aTitle = xProp->getPropertyValue(::rtl::OUString::createFromAscii( "Title" ) );

                        aTitle >>= docNameOrURL;
                        if ( docNameOrURL.getLength() == 0 )
                        {
                            docNameOrURL =  parseLocationName( xModel->getURL() );
                        }
                    }
                }
            }
        }
        catch ( css::uno::Exception& e )
        {
            OSL_TRACE("MiscUtils::xModelToDocTitle() exception thrown: !!! %s",
                ::rtl::OUStringToOString( e.Message,
                    RTL_TEXTENCODING_ASCII_US ).pData->buffer );
        }
    }
    return docNameOrURL;
}

    static ::rtl::OUString tDocUrlToTitle( const ::rtl::OUString& url )
{
    ::rtl::OUString title;

    try
    {
        ::ucb::Content root( url, NULL );
        ::rtl::OUString propName =  OUSTR("Title");
        getUCBProperty( root, propName ) >>= title;
    }
    catch ( css::ucb::ContentCreationException& cce )
    {
        // carry on, empty value will be returned
    }
    catch ( css::uno::RuntimeException& re )
    {
        // carry on, empty value will be returned
    }

    return title;
}
    static ::rtl::OUString xModelToTdocUrl( const css::uno::Reference< css::frame::XModel >& xModel )
{
    css::uno::Reference < com::sun::star::ucb::XCommandEnvironment > dummy;
    ::rtl::OUString sDocRoot = OUSTR( "vnd.sun.star.tdoc:/" );
    ::ucb::Content root( sDocRoot, dummy );

    css::uno::Sequence < ::rtl::OUString > aPropertyNames( 0 );
    ::rtl::OUString propName = OUSTR( "DocumentModel" );

    css::uno::Reference < com::sun::star::sdbc::XResultSet > xResultSet =
        root.createCursor( aPropertyNames );

    css::uno::Reference< com::sun::star::ucb::XContentAccess > xContentAccess(
        xResultSet, css::uno::UNO_QUERY );
    ::rtl::OUString docUrl;
    if ( xResultSet.is() && xContentAccess.is() )
    {
        css::uno::Reference< css::sdbc::XRow > values( xResultSet, css::uno::UNO_QUERY );
        if ( values.is() )
        {
            while ( xResultSet->next() )
            {
                ::rtl::OUString url = xContentAccess->queryContentIdentifierString();
                css::uno::Reference < css::frame::XModel > xMod( tDocUrlToModel( url ), css::uno::UNO_QUERY );

                if ( xMod.is() && xMod == xModel )
                {
                    docUrl = url;
                    break;
                }
            }
        }
    }
    return docUrl;
}
    static css::uno::Reference< css::frame::XModel > tDocUrlToModel( const ::rtl::OUString& url )
{
    css::uno::Any result;

    try
    {
        ::ucb::Content root( url, NULL );
        ::rtl::OUString propName =  OUSTR("DocumentModel");
        result = getUCBProperty( root, propName );
    }
    catch ( css::ucb::ContentCreationException& cce )
    {
        // carry on, empty value will be returned
    }
    catch ( css::uno::RuntimeException& re )
    {
        // carry on, empty value will be returned
    }

    css::uno::Reference< css::frame::XModel > xModel(
        result, css::uno::UNO_QUERY );

    return xModel;
}

    static css::uno::Any getUCBProperty( ::ucb::Content& content, ::rtl::OUString& prop )
{
    css::uno::Sequence < ::rtl::OUString > aPropertyNames( 1 );
    ::rtl::OUString* pNames = aPropertyNames.getArray();
    pNames[ 0 ] = prop;
    css::uno::Any result;
    try
    {
        css::uno::Sequence< css::uno::Any > props = content.getPropertyValues( aPropertyNames );
        if ( props.getLength() )
        {
            result = props[ 0 ];
        }
    }
/*    catch ( ucb::CommandAbortedException& e )
    {
    }*/
    catch ( css::uno::Exception& e )
    {
    }
    return result;
}

private:
static ::rtl::OUString parseLocationName( const ::rtl::OUString& location )
{
    // strip out the last leaf of location name
    // e.g. file://dir1/dir2/Blah.sxw - > Blah.sxw
    ::rtl::OUString temp = location;
    sal_Int32 lastSlashIndex = temp.lastIndexOf( ::rtl::OUString::createFromAscii( "/" ) );

    if ( ( lastSlashIndex + 1 ) <  temp.getLength()  )
    {
        temp = temp.copy( lastSlashIndex + 1 );
    }
    return temp;
}

};
} // namespace sf_misc
#endif //
<|endoftext|>