<commit_before>// Filename: find_root_dir.cxx
// Created by:  drose (29Jun09)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) Carnegie Mellon University.  All rights reserved.
//
// All use of this software is subject to the terms of the revised BSD
// license.  You should have received a copy of this license along
// with this source code in a file named "LICENSE."
//
////////////////////////////////////////////////////////////////////

#include "find_root_dir.h"
#include "mkdir_complete.h"
#include "get_tinyxml.h"

#ifdef _WIN32
#include <windows.h>
#include <shlobj.h>
#else
#include <unistd.h>
#include <stdlib.h>
#include <pwd.h>
#include <errno.h>
#include <sys/stat.h>
#endif

#ifdef _WIN32
// From KnownFolders.h (part of Vista SDK):
#define DEFINE_KNOWN_FOLDER(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \
   const GUID name = { l, w1, w2, { b1, b2,  b3,  b4,  b5,  b6,  b7,  b8 } }
DEFINE_KNOWN_FOLDER(FOLDERID_LocalAppData, 0xF1B32785, 0x6FBA, 0x4FCF, 0x9D, 0x55, 0x7B, 0x8E, 0x7F, 0x15, 0x70, 0x91);
DEFINE_KNOWN_FOLDER(FOLDERID_LocalAppDataLow, 0xA520A1A4, 0x1780, 0x4FF6, 0xBD, 0x18, 0x16, 0x73, 0x43, 0xC5, 0xAF, 0x16);
DEFINE_KNOWN_FOLDER(FOLDERID_InternetCache, 0x352481E8, 0x33BE, 0x4251, 0xBA, 0x85, 0x60, 0x07, 0xCA, 0xED, 0xCF, 0x9D);
#endif  // _WIN32

#ifdef _WIN32
////////////////////////////////////////////////////////////////////
//     Function: get_csidl_dir
//  Description: A wrapper around SHGetSpecialFolderPath(), to return
//               the Panda3D directory under the indicated CSIDL
//               folder.
////////////////////////////////////////////////////////////////////
static string
get_csidl_dir(int csidl) {
  static const int buffer_size = MAX_PATH;
  char buffer[buffer_size];
  if (SHGetSpecialFolderPath(NULL, buffer, csidl, true)) {
    string root = buffer;
    root += string("/Panda3D");

    if (mkdir_complete(root, cerr)) {
      return root;
    }
  }

  // Something went wrong.
  return string();
}
#endif  // _WIN32

#ifdef _WIN32
////////////////////////////////////////////////////////////////////
//     Function: wstr_to_string
//  Description: Converts Windows' LPWSTR to a std::string.
////////////////////////////////////////////////////////////////////
static bool
wstr_to_string(string &result, const LPWSTR wstr) {
  bool success = false;
  int size = WideCharToMultiByte(CP_UTF8, 0, wstr, -1,
                                 NULL, 0, NULL, NULL);
  if (size > 0) {
    char *buffer = new char[size];
    int rc = WideCharToMultiByte(CP_UTF8, 0, wstr, -1,
                                 buffer, size, NULL, NULL);
    if (rc != 0) {
      buffer[size - 1] = 0;
      result = buffer;
      success = true;
    }
    delete[] buffer;
  }

  return success;
}
#endif  // _WIN32

////////////////////////////////////////////////////////////////////
//     Function: find_root_dir_default
//  Description: Returns the path to the system-default for the root
//               directory.  This is where we look first.
////////////////////////////////////////////////////////////////////
static string
find_root_dir_default() {
#ifdef _WIN32
  // First, use IEIsProtectedModeProcess() to determine if we are
  // running in IE's "protected mode" under Vista.

  string root;
  bool is_protected = false;
  HMODULE ieframe = LoadLibrary("ieframe.dll");
  if (ieframe != NULL) {
    typedef HRESULT STDAPICALLTYPE IEIsProtectedModeProcess(BOOL *pbResult);
    IEIsProtectedModeProcess *func = (IEIsProtectedModeProcess *)GetProcAddress(ieframe, "IEIsProtectedModeProcess");
    if (func != NULL) {
      BOOL result = false;
      HRESULT hr = (*func)(&result);
      if (hr == S_OK) {
        is_protected = (result != 0);
      }
      // Any other return value means some error, especially
      // E_NOTIMPL, which means we're not running under Vista.  In
      // this case we can assume we're not running in protected mode.
    }

    if (is_protected) {
      // If we *are* running in protected mode, we need to use
      // FOLDERID_LocalAppDataLow.

      // We should be able to use IEGetWriteableFolderPath() to query
      // this folder, but for some reason, that function returns
      // E_ACCESSDENIED on FOLDERID_LocalAppDataLow, even though this is
      // certainly a folder we have write access to.

      // Well, SHGetKnownFolderPath() does work.  This function only
      // exists on Vista and above, though, so we still have to pull it
      // out of the DLL instead of hard-linking it.

      HMODULE shell32 = LoadLibrary("shell32.dll");
      if (shell32 != NULL) {
        typedef HRESULT STDAPICALLTYPE SHGetKnownFolderPath(REFGUID rfid, DWORD dwFlags, HANDLE hToken, PWSTR *ppszPath);
        SHGetKnownFolderPath *func = (SHGetKnownFolderPath *)GetProcAddress(shell32, "SHGetKnownFolderPath");
        if (func != NULL) {
          LPWSTR cache_path = NULL;
          HRESULT hr = (*func)(FOLDERID_LocalAppDataLow, 0, NULL, &cache_path);

          if (SUCCEEDED(hr)) {
            if (!wstr_to_string(root, cache_path)) {
              // Couldn't decode the LPWSTR.
              CoTaskMemFree(cache_path);
            } else {
              CoTaskMemFree(cache_path);

              root += string("/Panda3D");
              if (mkdir_complete(root, cerr)) {
                FreeLibrary(shell32);
                FreeLibrary(ieframe);
                return root;
              }
            }
          }
        }
        FreeLibrary(shell32);
      }

      // Couldn't get FOLDERID_LocalAppDataLow for some reason.  We're
      // in fallback mode now.  Use IEGetWriteableFolderPath to get
      // the standard cache folder.
      typedef HRESULT STDAPICALLTYPE IEGetWriteableFolderPath(REFGUID clsidFolderID, LPWSTR* lppwstrPath);
      IEGetWriteableFolderPath *func = (IEGetWriteableFolderPath *)GetProcAddress(ieframe, "IEGetWriteableFolderPath");
      if (func != NULL) {
        LPWSTR cache_path = NULL;

        // Since we're here, we'll start by asking for
        // LocalAppDataLow, even though I know it doesn't work.
        HRESULT hr = (*func)(FOLDERID_LocalAppDataLow, &cache_path);
        if (FAILED(hr)) {
          // This one should work.
          hr = (*func)(FOLDERID_InternetCache, &cache_path);
        }

        if (SUCCEEDED(hr)) {
          if (!wstr_to_string(root, cache_path)) {
            // Couldn't decode the LPWSTR.
            CoTaskMemFree(cache_path);
          } else {
            CoTaskMemFree(cache_path);
            root += string("/Panda3D");
            if (mkdir_complete(root, cerr)) {
              FreeLibrary(ieframe);
              return root;
            }
          }
        }
      }
    }

    FreeLibrary(ieframe);
  }

  // All right, here we are in the normal, unprotected mode.  This is
  // also the normal XP codepath.

  // e.g., c:/Documents and Settings/<username>/Local Settings/Application Data/Panda3D
  root = get_csidl_dir(CSIDL_LOCAL_APPDATA);
  if (!root.empty()) {
    return root;
  }

  // For some crazy reason, we can't get CSIDL_LOCAL_APPDATA.  Fall
  // back to the cache folder.

  // e.g. c:/Documents and Settings/<username>/Local Settings/Temporary Internet Files/Panda3D
  root = get_csidl_dir(CSIDL_INTERNET_CACHE);
  if (!root.empty()) {
    return root;
  }

  // If we couldn't get any of those folders, huh.  Punt and try for
  // the old standby GetTempPath, for lack of anything better.
  static const int buffer_size = MAX_PATH;
  char buffer[buffer_size];
  if (GetTempPath(buffer_size, buffer) != 0) {
    root = buffer;
    root += string("Panda3D");
    if (mkdir_complete(root, cerr)) {
      return root;
    }
  }

#elif defined(__APPLE__)
  // e.g., /Users/<username>/Library/Caches/Panda3D
  string root = find_osx_root_dir();
  if (!root.empty()) {
    return root;
  }

#else  // The Linux case
  // e.g., /home/<username>/.panda3d

  string root;
  const char *uname = getlogin();
  if (uname == NULL) uname = getenv("USER");

  const passwd *pwdata = getpwnam(uname);
  if (pwdata == NULL) {
    root = getenv("HOME");
  } else {
    root = pwdata->pw_dir;
  }

  root += "/.panda3d";
  if (mkdir(root.c_str(), 0700) == 0 || errno == EEXIST) {
    return root;
  }

#endif

  // Couldn't find a directory.  Punt.
  return ".";
}

////////////////////////////////////////////////////////////////////
//     Function: find_root_dir
//  Description: Returns the path to the installable Panda3D directory
//               on the user's machine.
////////////////////////////////////////////////////////////////////
string
find_root_dir() {
  string root = find_root_dir_default();

  // Now look for a config.xml file in that directory, which might
  // redirect us elsewhere.
  string config_filename = root + "/config.xml";
  TiXmlDocument doc(config_filename);
  if (!doc.LoadFile()) {
    // No config.xml found, or not valid xml.
    return root;
  }

  TiXmlElement *xconfig = doc.FirstChildElement("config");
  if (xconfig == NULL) {
    // No <config> element within config.xml.
    return root;
  }

  const char *new_root = xconfig->Attribute("root_dir");
  if (new_root == NULL || *new_root == '\0') {
    // No root_dir specified.
    return root;
  }

  if (!mkdir_complete(new_root, cerr)) {
    // The specified root_dir wasn't valid.
    return root;
  }

  // We've been redirected to another location.  Respect that.
  return new_root;
}
<commit_msg>Fix segmentation fault that only seems to happen in the buildbot's master shell environment.  But I suppose the crash could manifest in other environments where getlogin() fails<commit_after>// Filename: find_root_dir.cxx
// Created by:  drose (29Jun09)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) Carnegie Mellon University.  All rights reserved.
//
// All use of this software is subject to the terms of the revised BSD
// license.  You should have received a copy of this license along
// with this source code in a file named "LICENSE."
//
////////////////////////////////////////////////////////////////////

#include "find_root_dir.h"
#include "mkdir_complete.h"
#include "get_tinyxml.h"

#ifdef _WIN32
#include <windows.h>
#include <shlobj.h>
#else
#include <unistd.h>
#include <stdlib.h>
#include <pwd.h>
#include <errno.h>
#include <sys/stat.h>
#endif

#ifdef _WIN32
// From KnownFolders.h (part of Vista SDK):
#define DEFINE_KNOWN_FOLDER(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \
   const GUID name = { l, w1, w2, { b1, b2,  b3,  b4,  b5,  b6,  b7,  b8 } }
DEFINE_KNOWN_FOLDER(FOLDERID_LocalAppData, 0xF1B32785, 0x6FBA, 0x4FCF, 0x9D, 0x55, 0x7B, 0x8E, 0x7F, 0x15, 0x70, 0x91);
DEFINE_KNOWN_FOLDER(FOLDERID_LocalAppDataLow, 0xA520A1A4, 0x1780, 0x4FF6, 0xBD, 0x18, 0x16, 0x73, 0x43, 0xC5, 0xAF, 0x16);
DEFINE_KNOWN_FOLDER(FOLDERID_InternetCache, 0x352481E8, 0x33BE, 0x4251, 0xBA, 0x85, 0x60, 0x07, 0xCA, 0xED, 0xCF, 0x9D);
#endif  // _WIN32

#ifdef _WIN32
////////////////////////////////////////////////////////////////////
//     Function: get_csidl_dir
//  Description: A wrapper around SHGetSpecialFolderPath(), to return
//               the Panda3D directory under the indicated CSIDL
//               folder.
////////////////////////////////////////////////////////////////////
static string
get_csidl_dir(int csidl) {
  static const int buffer_size = MAX_PATH;
  char buffer[buffer_size];
  if (SHGetSpecialFolderPath(NULL, buffer, csidl, true)) {
    string root = buffer;
    root += string("/Panda3D");

    if (mkdir_complete(root, cerr)) {
      return root;
    }
  }

  // Something went wrong.
  return string();
}
#endif  // _WIN32

#ifdef _WIN32
////////////////////////////////////////////////////////////////////
//     Function: wstr_to_string
//  Description: Converts Windows' LPWSTR to a std::string.
////////////////////////////////////////////////////////////////////
static bool
wstr_to_string(string &result, const LPWSTR wstr) {
  bool success = false;
  int size = WideCharToMultiByte(CP_UTF8, 0, wstr, -1,
                                 NULL, 0, NULL, NULL);
  if (size > 0) {
    char *buffer = new char[size];
    int rc = WideCharToMultiByte(CP_UTF8, 0, wstr, -1,
                                 buffer, size, NULL, NULL);
    if (rc != 0) {
      buffer[size - 1] = 0;
      result = buffer;
      success = true;
    }
    delete[] buffer;
  }

  return success;
}
#endif  // _WIN32

////////////////////////////////////////////////////////////////////
//     Function: find_root_dir_default
//  Description: Returns the path to the system-default for the root
//               directory.  This is where we look first.
////////////////////////////////////////////////////////////////////
static string
find_root_dir_default() {
#ifdef _WIN32
  // First, use IEIsProtectedModeProcess() to determine if we are
  // running in IE's "protected mode" under Vista.

  string root;
  bool is_protected = false;
  HMODULE ieframe = LoadLibrary("ieframe.dll");
  if (ieframe != NULL) {
    typedef HRESULT STDAPICALLTYPE IEIsProtectedModeProcess(BOOL *pbResult);
    IEIsProtectedModeProcess *func = (IEIsProtectedModeProcess *)GetProcAddress(ieframe, "IEIsProtectedModeProcess");
    if (func != NULL) {
      BOOL result = false;
      HRESULT hr = (*func)(&result);
      if (hr == S_OK) {
        is_protected = (result != 0);
      }
      // Any other return value means some error, especially
      // E_NOTIMPL, which means we're not running under Vista.  In
      // this case we can assume we're not running in protected mode.
    }

    if (is_protected) {
      // If we *are* running in protected mode, we need to use
      // FOLDERID_LocalAppDataLow.

      // We should be able to use IEGetWriteableFolderPath() to query
      // this folder, but for some reason, that function returns
      // E_ACCESSDENIED on FOLDERID_LocalAppDataLow, even though this is
      // certainly a folder we have write access to.

      // Well, SHGetKnownFolderPath() does work.  This function only
      // exists on Vista and above, though, so we still have to pull it
      // out of the DLL instead of hard-linking it.

      HMODULE shell32 = LoadLibrary("shell32.dll");
      if (shell32 != NULL) {
        typedef HRESULT STDAPICALLTYPE SHGetKnownFolderPath(REFGUID rfid, DWORD dwFlags, HANDLE hToken, PWSTR *ppszPath);
        SHGetKnownFolderPath *func = (SHGetKnownFolderPath *)GetProcAddress(shell32, "SHGetKnownFolderPath");
        if (func != NULL) {
          LPWSTR cache_path = NULL;
          HRESULT hr = (*func)(FOLDERID_LocalAppDataLow, 0, NULL, &cache_path);

          if (SUCCEEDED(hr)) {
            if (!wstr_to_string(root, cache_path)) {
              // Couldn't decode the LPWSTR.
              CoTaskMemFree(cache_path);
            } else {
              CoTaskMemFree(cache_path);

              root += string("/Panda3D");
              if (mkdir_complete(root, cerr)) {
                FreeLibrary(shell32);
                FreeLibrary(ieframe);
                return root;
              }
            }
          }
        }
        FreeLibrary(shell32);
      }

      // Couldn't get FOLDERID_LocalAppDataLow for some reason.  We're
      // in fallback mode now.  Use IEGetWriteableFolderPath to get
      // the standard cache folder.
      typedef HRESULT STDAPICALLTYPE IEGetWriteableFolderPath(REFGUID clsidFolderID, LPWSTR* lppwstrPath);
      IEGetWriteableFolderPath *func = (IEGetWriteableFolderPath *)GetProcAddress(ieframe, "IEGetWriteableFolderPath");
      if (func != NULL) {
        LPWSTR cache_path = NULL;

        // Since we're here, we'll start by asking for
        // LocalAppDataLow, even though I know it doesn't work.
        HRESULT hr = (*func)(FOLDERID_LocalAppDataLow, &cache_path);
        if (FAILED(hr)) {
          // This one should work.
          hr = (*func)(FOLDERID_InternetCache, &cache_path);
        }

        if (SUCCEEDED(hr)) {
          if (!wstr_to_string(root, cache_path)) {
            // Couldn't decode the LPWSTR.
            CoTaskMemFree(cache_path);
          } else {
            CoTaskMemFree(cache_path);
            root += string("/Panda3D");
            if (mkdir_complete(root, cerr)) {
              FreeLibrary(ieframe);
              return root;
            }
          }
        }
      }
    }

    FreeLibrary(ieframe);
  }

  // All right, here we are in the normal, unprotected mode.  This is
  // also the normal XP codepath.

  // e.g., c:/Documents and Settings/<username>/Local Settings/Application Data/Panda3D
  root = get_csidl_dir(CSIDL_LOCAL_APPDATA);
  if (!root.empty()) {
    return root;
  }

  // For some crazy reason, we can't get CSIDL_LOCAL_APPDATA.  Fall
  // back to the cache folder.

  // e.g. c:/Documents and Settings/<username>/Local Settings/Temporary Internet Files/Panda3D
  root = get_csidl_dir(CSIDL_INTERNET_CACHE);
  if (!root.empty()) {
    return root;
  }

  // If we couldn't get any of those folders, huh.  Punt and try for
  // the old standby GetTempPath, for lack of anything better.
  static const int buffer_size = MAX_PATH;
  char buffer[buffer_size];
  if (GetTempPath(buffer_size, buffer) != 0) {
    root = buffer;
    root += string("Panda3D");
    if (mkdir_complete(root, cerr)) {
      return root;
    }
  }

#elif defined(__APPLE__)
  // e.g., /Users/<username>/Library/Caches/Panda3D
  string root = find_osx_root_dir();
  if (!root.empty()) {
    return root;
  }

#else  // The Linux/*BSD case
  // e.g., /home/<username>/.panda3d

  string root;
  const passwd *pwdata = getpwuid(getuid());
  if (pwdata == NULL) {
    char *home = getenv("HOME");
    if (home == NULL) {
      // Beh.  Let's hope it never gets to this point.
      return ".";
    } else {
      root = home;
    }
  } else {
    root = pwdata->pw_dir;
  }

  root += "/.panda3d";
  if (mkdir(root.c_str(), 0700) == 0 || errno == EEXIST) {
    return root;
  }

#endif

  // Couldn't find a directory.  Punt.
  return ".";
}

////////////////////////////////////////////////////////////////////
//     Function: find_root_dir
//  Description: Returns the path to the installable Panda3D directory
//               on the user's machine.
////////////////////////////////////////////////////////////////////
string
find_root_dir() {
  string root = find_root_dir_default();

  // Now look for a config.xml file in that directory, which might
  // redirect us elsewhere.
  string config_filename = root + "/config.xml";
  TiXmlDocument doc(config_filename);
  if (!doc.LoadFile()) {
    // No config.xml found, or not valid xml.
    return root;
  }

  TiXmlElement *xconfig = doc.FirstChildElement("config");
  if (xconfig == NULL) {
    // No <config> element within config.xml.
    return root;
  }

  const char *new_root = xconfig->Attribute("root_dir");
  if (new_root == NULL || *new_root == '\0') {
    // No root_dir specified.
    return root;
  }

  if (!mkdir_complete(new_root, cerr)) {
    // The specified root_dir wasn't valid.
    return root;
  }

  // We've been redirected to another location.  Respect that.
  return new_root;
}
<|endoftext|>


<commit_before>// Copyright (C) 2020 Jérôme Leclercq
// This file is part of the "Nazara Engine - Vulkan Renderer"
// For conditions of distribution and use, see copyright notice in Config.hpp

#include <Nazara/VulkanRenderer/Wrapper/DeviceObject.hpp>
#include <Nazara/Core/Error.hpp>
#include <Nazara/VulkanRenderer/Utils.hpp>
#include <Nazara/VulkanRenderer/Debug.hpp>

namespace Nz
{
	namespace Vk
	{
		template<typename C, typename VkType, typename CreateInfo, VkObjectType ObjectType>
		DeviceObject<C, VkType, CreateInfo, ObjectType>::DeviceObject() :
		m_handle(VK_NULL_HANDLE)
		{
		}

		template<typename C, typename VkType, typename CreateInfo, VkObjectType ObjectType>
		DeviceObject<C, VkType, CreateInfo, ObjectType>::DeviceObject(DeviceObject&& object) noexcept :
		m_device(std::move(object.m_device)),
		m_allocator(object.m_allocator),
		m_handle(object.m_handle),
		m_lastErrorCode(object.m_lastErrorCode)
		{
			object.m_handle = VK_NULL_HANDLE;
		}

		template<typename C, typename VkType, typename CreateInfo, VkObjectType ObjectType>
		DeviceObject<C, VkType, CreateInfo, ObjectType>::~DeviceObject()
		{
			Destroy();
		}

		template<typename C, typename VkType, typename CreateInfo, VkObjectType ObjectType>
		bool DeviceObject<C, VkType, CreateInfo, ObjectType>::Create(Device& device, const CreateInfo& createInfo, const VkAllocationCallbacks* allocator)
		{
			m_device = &device;
			m_lastErrorCode = C::CreateHelper(*m_device, &createInfo, allocator, &m_handle);
			if (m_lastErrorCode != VkResult::VK_SUCCESS)
			{
				NazaraError("Failed to create Vulkan object: " + TranslateVulkanError(m_lastErrorCode));
				return false;
			}

			// Store the allocator to access them when needed
			if (allocator)
				m_allocator = *allocator;
			else
				m_allocator.pfnAllocation = nullptr;

			return true;
		}

		template<typename C, typename VkType, typename CreateInfo, VkObjectType ObjectType>
		void DeviceObject<C, VkType, CreateInfo, ObjectType>::Destroy()
		{
			if (IsValid())
			{
				C::DestroyHelper(*m_device, m_handle, (m_allocator.pfnAllocation) ? &m_allocator : nullptr);
				m_handle = VK_NULL_HANDLE;
			}
		}

		template<typename C, typename VkType, typename CreateInfo, VkObjectType ObjectType>
		bool DeviceObject<C, VkType, CreateInfo, ObjectType>::IsValid() const
		{
			return m_handle != VK_NULL_HANDLE;
		}

		template<typename C, typename VkType, typename CreateInfo, VkObjectType ObjectType>
		Device* DeviceObject<C, VkType, CreateInfo, ObjectType>::GetDevice() const
		{
			return m_device;
		}

		template<typename C, typename VkType, typename CreateInfo, VkObjectType ObjectType>
		VkResult DeviceObject<C, VkType, CreateInfo, ObjectType>::GetLastErrorCode() const
		{
			return m_lastErrorCode;
		}

		template<typename C, typename VkType, typename CreateInfo, VkObjectType ObjectType>
		void DeviceObject<C, VkType, CreateInfo, ObjectType>::SetDebugName(const char* name)
		{
			if (m_device->vkSetDebugUtilsObjectNameEXT)
			{
				VkDebugUtilsObjectNameInfoEXT debugName = { VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT };
				debugName.objectType = ObjectType;
				debugName.objectHandle = static_cast<UInt64>(reinterpret_cast<std::uintptr_t>(m_handle));
				debugName.pObjectName = name;

				m_device->vkSetDebugUtilsObjectNameEXT(*m_device, &debugName);
			}
		}

		template<typename C, typename VkType, typename CreateInfo, VkObjectType ObjectType>
		void DeviceObject<C, VkType, CreateInfo, ObjectType>::SetDebugName(const std::string& name)
		{
			return SetDebugName(name.data());
		}

		template<typename C, typename VkType, typename CreateInfo, VkObjectType ObjectType>
		auto DeviceObject<C, VkType, CreateInfo, ObjectType>::operator=(DeviceObject&& object) noexcept -> DeviceObject&
		{
			std::swap(m_allocator, object.m_allocator);
			std::swap(m_device, object.m_device);
			std::swap(m_handle, object.m_handle);
			std::swap(m_lastErrorCode, object.m_lastErrorCode);

			return *this;
		}

		template<typename C, typename VkType, typename CreateInfo, VkObjectType ObjectType>
		DeviceObject<C, VkType, CreateInfo, ObjectType>::operator VkType() const
		{
			return m_handle;
		}
	}
}

#include <Nazara/VulkanRenderer/DebugOff.hpp>
<commit_msg>Vulkan: Fix DeviceObject not destroying previous object<commit_after>// Copyright (C) 2020 Jérôme Leclercq
// This file is part of the "Nazara Engine - Vulkan Renderer"
// For conditions of distribution and use, see copyright notice in Config.hpp

#include <Nazara/VulkanRenderer/Wrapper/DeviceObject.hpp>
#include <Nazara/Core/Error.hpp>
#include <Nazara/VulkanRenderer/Utils.hpp>
#include <Nazara/VulkanRenderer/Debug.hpp>

namespace Nz
{
	namespace Vk
	{
		template<typename C, typename VkType, typename CreateInfo, VkObjectType ObjectType>
		DeviceObject<C, VkType, CreateInfo, ObjectType>::DeviceObject() :
		m_handle(VK_NULL_HANDLE)
		{
		}

		template<typename C, typename VkType, typename CreateInfo, VkObjectType ObjectType>
		DeviceObject<C, VkType, CreateInfo, ObjectType>::DeviceObject(DeviceObject&& object) noexcept :
		m_device(std::move(object.m_device)),
		m_allocator(object.m_allocator),
		m_handle(object.m_handle),
		m_lastErrorCode(object.m_lastErrorCode)
		{
			object.m_handle = VK_NULL_HANDLE;
		}

		template<typename C, typename VkType, typename CreateInfo, VkObjectType ObjectType>
		DeviceObject<C, VkType, CreateInfo, ObjectType>::~DeviceObject()
		{
			Destroy();
		}

		template<typename C, typename VkType, typename CreateInfo, VkObjectType ObjectType>
		bool DeviceObject<C, VkType, CreateInfo, ObjectType>::Create(Device& device, const CreateInfo& createInfo, const VkAllocationCallbacks* allocator)
		{
			Destroy();

			m_device = &device;
			m_lastErrorCode = C::CreateHelper(*m_device, &createInfo, allocator, &m_handle);
			if (m_lastErrorCode != VkResult::VK_SUCCESS)
			{
				NazaraError("Failed to create Vulkan object: " + TranslateVulkanError(m_lastErrorCode));
				return false;
			}

			// Store the allocator to access them when needed
			if (allocator)
				m_allocator = *allocator;
			else
				m_allocator.pfnAllocation = nullptr;

			return true;
		}

		template<typename C, typename VkType, typename CreateInfo, VkObjectType ObjectType>
		void DeviceObject<C, VkType, CreateInfo, ObjectType>::Destroy()
		{
			if (IsValid())
			{
				C::DestroyHelper(*m_device, m_handle, (m_allocator.pfnAllocation) ? &m_allocator : nullptr);
				m_handle = VK_NULL_HANDLE;
			}
		}

		template<typename C, typename VkType, typename CreateInfo, VkObjectType ObjectType>
		bool DeviceObject<C, VkType, CreateInfo, ObjectType>::IsValid() const
		{
			return m_handle != VK_NULL_HANDLE;
		}

		template<typename C, typename VkType, typename CreateInfo, VkObjectType ObjectType>
		Device* DeviceObject<C, VkType, CreateInfo, ObjectType>::GetDevice() const
		{
			return m_device;
		}

		template<typename C, typename VkType, typename CreateInfo, VkObjectType ObjectType>
		VkResult DeviceObject<C, VkType, CreateInfo, ObjectType>::GetLastErrorCode() const
		{
			return m_lastErrorCode;
		}

		template<typename C, typename VkType, typename CreateInfo, VkObjectType ObjectType>
		void DeviceObject<C, VkType, CreateInfo, ObjectType>::SetDebugName(const char* name)
		{
			if (m_device->vkSetDebugUtilsObjectNameEXT)
			{
				VkDebugUtilsObjectNameInfoEXT debugName = { VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT };
				debugName.objectType = ObjectType;
				debugName.objectHandle = static_cast<UInt64>(reinterpret_cast<std::uintptr_t>(m_handle));
				debugName.pObjectName = name;

				m_device->vkSetDebugUtilsObjectNameEXT(*m_device, &debugName);
			}
		}

		template<typename C, typename VkType, typename CreateInfo, VkObjectType ObjectType>
		void DeviceObject<C, VkType, CreateInfo, ObjectType>::SetDebugName(const std::string& name)
		{
			return SetDebugName(name.data());
		}

		template<typename C, typename VkType, typename CreateInfo, VkObjectType ObjectType>
		auto DeviceObject<C, VkType, CreateInfo, ObjectType>::operator=(DeviceObject&& object) noexcept -> DeviceObject&
		{
			std::swap(m_allocator, object.m_allocator);
			std::swap(m_device, object.m_device);
			std::swap(m_handle, object.m_handle);
			std::swap(m_lastErrorCode, object.m_lastErrorCode);

			return *this;
		}

		template<typename C, typename VkType, typename CreateInfo, VkObjectType ObjectType>
		DeviceObject<C, VkType, CreateInfo, ObjectType>::operator VkType() const
		{
			return m_handle;
		}
	}
}

#include <Nazara/VulkanRenderer/DebugOff.hpp>
<|endoftext|>


<commit_before>/**
 * \file
 * \brief MessageQueueBase class header
 *
 * \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * \date 2015-01-14
 */

#ifndef INCLUDE_DISTORTOS_SYNCHRONIZATION_MESSAGEQUEUEBASE_HPP_
#define INCLUDE_DISTORTOS_SYNCHRONIZATION_MESSAGEQUEUEBASE_HPP_

#include "distortos/Semaphore.hpp"

#include "distortos/allocators/FeedablePool.hpp"

#include "distortos/estd/TypeErasedFunctor.hpp"

#include <forward_list>

namespace distortos
{

namespace synchronization
{

/// MessageQueueBase class implements basic functionality of MessageQueue template class
class MessageQueueBase
{
public:

	/// entry in the MessageQueueBase
	struct Entry
	{
		/**
		 * \brief Entry's constructor
		 *
		 * \param [in] priorityy is the priority of the entry
		 * \param [in] storagee is the storage for the entry
		 */

		constexpr Entry(const uint8_t priorityy, void* const storagee) :
				priority{priorityy},
				storage{storagee}
		{

		}

		/// default copy constructor
		constexpr Entry(const Entry&) = default;

		/// priority of the entry
		uint8_t priority;

		/// storage for the entry
		void* storage;
	};

	/**
	 * \brief Functor is a type-erased interface for functors which execute some action on queue's storage (like
	 * copy-constructing, swapping, destroying, emplacing, ...).
	 *
	 * The functor will be called by MessageQueueBase internals with one argument - \a storage - which is a pointer to
	 * storage with/for element.
	 */

	using Functor = estd::TypeErasedFunctor<void(void*)>;

	/// link and Entry
	using LinkAndEntry = std::pair<void*, Entry>;

	/**
	 * type of uninitialized storage for data
	 *
	 * \param T is the type of data in queue
	 */

	template<typename T>
	struct Storage
	{
		/// storage for Entry
		typename std::aligned_storage<sizeof(LinkAndEntry), alignof(LinkAndEntry)>::type entryStorage;

		/// storage for value
		typename std::aligned_storage<sizeof(T), alignof(T)>::type valueStorage;
	};

	/// functor which gives descending priority order of elements on the list
	struct DescendingPriority
	{
		/**
		 * \brief operator()
		 *
		 * \param [in] left is the object on the left side of comparison
		 * \param [in] right is the object on the right side of comparison
		 *
		 * \return true if left's priority is less than right's priority
		 */

		bool operator()(const Entry& left, const Entry& right)
		{
			return left.priority < right.priority;
		}
	};

	/// type of pool
	using Pool = allocators::FeedablePool;

	/// type of pool allocator
	using PoolAllocator = allocators::PoolAllocator<Entry, Pool>;

	/// type of entry list
	using EntryList = containers::SortedContainer<std::forward_list<Entry, PoolAllocator>, DescendingPriority>;

	/// type of free entry list
	using FreeEntryList = std::forward_list<Entry, PoolAllocator>;

	/**
	 * \brief MessageQueueBase's constructor
	 *
	 * \param T is the type of data in queue
	 *
	 * \param [in] storage is an array of Storage elements
	 * \param [in] maxElements is the number of elements in \a storage array
	 */

	template<typename T>
	MessageQueueBase(Storage<T>* const storage, const size_t maxElements) :
			MessageQueueBase{maxElements}
	{
		for (size_t i = 0; i < maxElements; ++i)
		{
			pool_.feed(storage[i].entryStorage);
			freeEntryList_.emplace_front(uint8_t{}, &storage[i].valueStorage);
		}
	}

private:

	/**
	 * \brief MessageQueueBase's constructor - internal version
	 *
	 * \param [in] maxElements is the maximum number of elements the queue can hold
	 */

	explicit MessageQueueBase(size_t maxElements);

	/// semaphore guarding access to "pop" functions - its value is equal to the number of available elements
	Semaphore popSemaphore_;

	/// semaphore guarding access to "push" functions - its value is equal to the number of free slots
	Semaphore pushSemaphore_;

	/// FeedablePool used by \a poolAllocator_
	Pool pool_;

	/// PoolAllocator used by \a entryList_ and \a freeList_
	PoolAllocator poolAllocator_;

	/// list of available entries, sorted in descending order of priority
	EntryList entryList_;

	/// list of "free" entries
	FreeEntryList freeEntryList_;
};

}	// namespace synchronization

}	// namespace distortos

#endif	// INCLUDE_DISTORTOS_SYNCHRONIZATION_MESSAGEQUEUEBASE_HPP_
<commit_msg>MessageQueueBase: add MessageQueueBase::InternalFunctor type alias<commit_after>/**
 * \file
 * \brief MessageQueueBase class header
 *
 * \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * \date 2015-01-14
 */

#ifndef INCLUDE_DISTORTOS_SYNCHRONIZATION_MESSAGEQUEUEBASE_HPP_
#define INCLUDE_DISTORTOS_SYNCHRONIZATION_MESSAGEQUEUEBASE_HPP_

#include "distortos/Semaphore.hpp"

#include "distortos/allocators/FeedablePool.hpp"

#include "distortos/estd/TypeErasedFunctor.hpp"

#include <forward_list>

namespace distortos
{

namespace synchronization
{

/// MessageQueueBase class implements basic functionality of MessageQueue template class
class MessageQueueBase
{
public:

	/// entry in the MessageQueueBase
	struct Entry
	{
		/**
		 * \brief Entry's constructor
		 *
		 * \param [in] priorityy is the priority of the entry
		 * \param [in] storagee is the storage for the entry
		 */

		constexpr Entry(const uint8_t priorityy, void* const storagee) :
				priority{priorityy},
				storage{storagee}
		{

		}

		/// default copy constructor
		constexpr Entry(const Entry&) = default;

		/// priority of the entry
		uint8_t priority;

		/// storage for the entry
		void* storage;
	};

	/**
	 * \brief Functor is a type-erased interface for functors which execute some action on queue's storage (like
	 * copy-constructing, swapping, destroying, emplacing, ...).
	 *
	 * The functor will be called by MessageQueueBase internals with one argument - \a storage - which is a pointer to
	 * storage with/for element.
	 */

	using Functor = estd::TypeErasedFunctor<void(void*)>;

	/// link and Entry
	using LinkAndEntry = std::pair<void*, Entry>;

	/**
	 * type of uninitialized storage for data
	 *
	 * \param T is the type of data in queue
	 */

	template<typename T>
	struct Storage
	{
		/// storage for Entry
		typename std::aligned_storage<sizeof(LinkAndEntry), alignof(LinkAndEntry)>::type entryStorage;

		/// storage for value
		typename std::aligned_storage<sizeof(T), alignof(T)>::type valueStorage;
	};

	/// functor which gives descending priority order of elements on the list
	struct DescendingPriority
	{
		/**
		 * \brief operator()
		 *
		 * \param [in] left is the object on the left side of comparison
		 * \param [in] right is the object on the right side of comparison
		 *
		 * \return true if left's priority is less than right's priority
		 */

		bool operator()(const Entry& left, const Entry& right)
		{
			return left.priority < right.priority;
		}
	};

	/// type of pool
	using Pool = allocators::FeedablePool;

	/// type of pool allocator
	using PoolAllocator = allocators::PoolAllocator<Entry, Pool>;

	/// type of entry list
	using EntryList = containers::SortedContainer<std::forward_list<Entry, PoolAllocator>, DescendingPriority>;

	/// type of free entry list
	using FreeEntryList = std::forward_list<Entry, PoolAllocator>;

	/**
	 * \brief InternalFunctor is a type-erased interface for functors which execute common code of pop() and push()
	 * operations.
	 *
	 * The functor will be called by MessageQueueBase internals with references to \a entryList_ and \a freeEntryList_.
	 * It should perform common actions and execute the Functor passed from callers.
	 */

	using InternalFunctor = estd::TypeErasedFunctor<void(EntryList&, FreeEntryList&)>;

	/**
	 * \brief MessageQueueBase's constructor
	 *
	 * \param T is the type of data in queue
	 *
	 * \param [in] storage is an array of Storage elements
	 * \param [in] maxElements is the number of elements in \a storage array
	 */

	template<typename T>
	MessageQueueBase(Storage<T>* const storage, const size_t maxElements) :
			MessageQueueBase{maxElements}
	{
		for (size_t i = 0; i < maxElements; ++i)
		{
			pool_.feed(storage[i].entryStorage);
			freeEntryList_.emplace_front(uint8_t{}, &storage[i].valueStorage);
		}
	}

private:

	/**
	 * \brief MessageQueueBase's constructor - internal version
	 *
	 * \param [in] maxElements is the maximum number of elements the queue can hold
	 */

	explicit MessageQueueBase(size_t maxElements);

	/// semaphore guarding access to "pop" functions - its value is equal to the number of available elements
	Semaphore popSemaphore_;

	/// semaphore guarding access to "push" functions - its value is equal to the number of free slots
	Semaphore pushSemaphore_;

	/// FeedablePool used by \a poolAllocator_
	Pool pool_;

	/// PoolAllocator used by \a entryList_ and \a freeList_
	PoolAllocator poolAllocator_;

	/// list of available entries, sorted in descending order of priority
	EntryList entryList_;

	/// list of "free" entries
	FreeEntryList freeEntryList_;
};

}	// namespace synchronization

}	// namespace distortos

#endif	// INCLUDE_DISTORTOS_SYNCHRONIZATION_MESSAGEQUEUEBASE_HPP_
<|endoftext|>


<commit_before>#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>

#include <iostream>
#include <string>
#include <cstring>
#include <vector>
#include <fstream>
#include <sstream>
#include <stdlib.h>

using namespace std;

const int MAX_PACKET_SIZE = 1000;

struct message {
	bool type;
	int seq_num;
	int packet_num;
	bool last_packet;
	char body[1000];
};

int main(int argc, char** argv) {
	int sockfd, portno, n, seq_num = 0, counter = 0, packet_num = 0;
	struct sockaddr_in serv_addr, client_addr;
	socklen_t len = sizeof(struct sockaddr_in);
	string filename, line, buffer;
	char temp[100];
	message initial, current;
	vector<message> packets;

	if (argc < 2) {
		cerr << "ERROR: Incorrect number of arguments" << endl;
		cerr << "sender <portnumber>" << endl;
		return -1;
	}

	portno = atoi(argv[1]);

	// Set socket and populate server address
	sockfd = socket(AF_INET, SOCK_DGRAM, 0);
	bzero((char*) &serv_addr, sizeof(serv_addr));
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_port = htons(portno);
	serv_addr.sin_addr.s_addr = INADDR_ANY;			// Server binds to any/all interfaces

	// Bind server to socket
	if (bind(sockfd, (struct sockaddr*) &serv_addr, len) == -1) {
		cerr << "ERROR: Failed to bind socket" << endl;
		return -1;
	}

	// Get file request
	do {
		n = recvfrom(sockfd, temp, 100, 0,
			(struct sockaddr*) &client_addr, &len);
	} while (n == -1);

	for (int i = 0; i < strlen(temp); i++) {
		filename += temp[i];
	}

	cout << "Filename: " << filename << endl;

	// Create initial ACK for file request
	initial.type = false;
	initial.seq_num = seq_num;
	initial.packet_num = packet_num;
	initial.last_packet = true;
	seq_num++;				//should we increment?
	packet_num++; 			//should we increment?

	// Send ACK with initial seq number 0
	sendto(sockfd, &initial, sizeof(initial), 0,
		(struct sockaddr*) &client_addr, len);

	ostringstream response;
	ifstream request(filename.c_str(), ios::in|ios::binary);

	if (request) {
	  response << request.rdbuf();
	  request.close();
	  buffer = response.str();
	} else {
		cerr << "ERROR: File not found" << endl;
		return -1;
	}

	// Split data into packets
	current.last_packet = false;
	current.type = true;
	for (int i = 0; i < buffer.size(); i++) {
		current.body[counter] = buffer[i];
		if (counter == MAX_PACKET_SIZE - 2) {
			cout << "Packet has 999 bytes" << endl;
			current.body[MAX_PACKET_SIZE - 1] = '\0';
			current.seq_num = seq_num;
			current.packet_num = packet_num;
			packets.push_back(current);

			counter = -1;
			seq_num += MAX_PACKET_SIZE;
			packet_num++;
		}
		counter++;
	}

	if (counter != 0) {
		cout << "Last packet is smaller than max packet size" << endl;
		current.body[counter] = '\0';
		// cout << "Last packet data: " << current.body << endl;
		current.seq_num = seq_num;
		current.packet_num = packet_num;
		cout << "Last Packet seq_num: " << current.seq_num << endl;
		cout << "Last Packet packet_num: " << current.packet_num << endl;
		current.last_packet = true;
		packets.push_back(current);
		//seq_num++; why is this even here o.O
		packet_num++;
	} else {
		packets[packets.size() - 1].last_packet = true;
	}

	int cwnd = 5;
	int base = 0;
	int next_seq_num = base + cwnd;

	cout << "Number of packets: " << packets.size() << endl;
	// Send initial packets
	for (int i = 0; i < cwnd; i++) {
		cout << "Data: " << packets[i].body << endl;
		sendto(sockfd, &packets[i], sizeof(packets[i]), 0,
			(struct sockaddr*) &client_addr, len);
	}

	while (true) {
		// Get a packet
		message received;
		n = recvfrom(sockfd, &received, sizeof(received), 0,
			(struct sockaddr*) &client_addr, &len);
		if (n == 0)
			continue;	// No more messages
		else if (n < 0)
			break;	// Error

		// TODO: Check corruption and randomly drop packets

		cout << "Received ACK " << received.seq_num << endl;

		if (received.seq_num >= base) {
			// Send up to window size
			base = received.seq_num + 1;
			for (int i = next_seq_num; i < base + cwnd; i++) {
				sendto(sockfd, &packets[i], sizeof(packets[i]), 0,
					(struct sockaddr*) &client_addr, len);
			}
			next_seq_num = base + cwnd;
		}
	}

}<commit_msg>Finished GBN for sender<commit_after>#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>

#include <iostream>
#include <string>
#include <cstring>
#include <vector>
#include <fstream>
#include <sstream>
#include <stdlib.h>

using namespace std;

const int MAX_PACKET_SIZE = 1000;
const int WINDOW_SIZE = 5;

struct message {
	bool type;
	int seq_num;
	int packet_num;
	bool last_packet;
	char body[1000];
};

int main(int argc, char** argv) {
	int sockfd, portno, n, seq_num = 0, counter = 0, packet_num = 0;
	struct sockaddr_in serv_addr, client_addr;
	socklen_t len = sizeof(struct sockaddr_in);
	string filename, line, buffer;
	char temp[100];
	message initial, current;
	vector<message> packets;

	if (argc < 2) {
		cerr << "ERROR: Incorrect number of arguments" << endl;
		cerr << "sender <portnumber>" << endl;
		return -1;
	}

	portno = atoi(argv[1]);

	// Set socket and populate server address
	sockfd = socket(AF_INET, SOCK_DGRAM, 0);
	bzero((char*) &serv_addr, sizeof(serv_addr));
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_port = htons(portno);
	serv_addr.sin_addr.s_addr = INADDR_ANY;			// Server binds to any/all interfaces

	// Bind server to socket
	if (bind(sockfd, (struct sockaddr*) &serv_addr, len) == -1) {
		cerr << "ERROR: Failed to bind socket" << endl;
		return -1;
	}

	// Get file request
	do {
		n = recvfrom(sockfd, temp, 100, 0,
			(struct sockaddr*) &client_addr, &len);
	} while (n == -1);

	for (int i = 0; i < strlen(temp); i++) {
		filename += temp[i];
	}

	cout << "Filename: " << filename << endl;

	// Create initial ACK for file request
	initial.type = false;
	initial.seq_num = seq_num;
	initial.packet_num = packet_num;
	initial.last_packet = true;
	seq_num++;				//should we increment?
	packet_num++; 			//should we increment?

	// Send ACK with initial seq number 0
	sendto(sockfd, &initial, sizeof(initial), 0,
		(struct sockaddr*) &client_addr, len);

	ostringstream response;
	ifstream request(filename.c_str(), ios::in|ios::binary);

	if (request) {
	  response << request.rdbuf();
	  request.close();
	  buffer = response.str();
	} else {
		cerr << "ERROR: File not found" << endl;
		return -1;
	}

	// Split data into packets
	current.last_packet = false;
	current.type = true;
	for (int i = 0; i < buffer.size(); i++) {
		current.body[counter] = buffer[i];
		if (counter == MAX_PACKET_SIZE - 2) {
			cout << "Packet has 999 bytes" << endl;
			current.body[MAX_PACKET_SIZE - 1] = '\0';
			current.seq_num = seq_num;
			current.packet_num = packet_num;
			packets.push_back(current);

			counter = -1;
			seq_num += MAX_PACKET_SIZE;
			packet_num++;
		}
		counter++;
	}

	if (counter != 0) {
		cout << "Last packet is smaller than max packet size" << endl;
		current.body[counter] = '\0';
		// cout << "Last packet data: " << current.body << endl;
		current.seq_num = seq_num;
		current.packet_num = packet_num;
		cout << "Last Packet seq_num: " << current.seq_num << endl;
		cout << "Last Packet packet_num: " << current.packet_num << endl;
		current.last_packet = true;
		packets.push_back(current);
		//seq_num++; why is this even here o.O
		packet_num++;
	} else {
		packets[packets.size() - 1].last_packet = true;
	}

	int base = 0;
	int next_packet_num = base + WINDOW_SIZE;

	cout << "Number of packets: " << packets.size() << endl;
	// Send initial packets
	for (int i = 0; i < WINDOW_SIZE; i++) {
		cout << "Data: " << packets[i].body << endl;
		sendto(sockfd, &packets[i], sizeof(packets[i]), 0,
			(struct sockaddr*) &client_addr, len);
	}

	while (true) {
		// Get a packet
		message received;
		n = recvfrom(sockfd, &received, sizeof(received), 0,
			(struct sockaddr*) &client_addr, &len);
		if (n == 0)
			continue;	// No more messages
		else if (n < 0)
			break;	// Error

		// TODO: Check corruption and randomly drop packets

		cout << "Received ACK " << received.seq_num << endl;

		if (received.packet_num >= base) {
			// Send up to window size
			base = received.packet_num + 1;
			for (int i = next_packet_num; i < base + WINDOW_SIZE && packets.size(); i++) {
				sendto(sockfd, &packets[i], sizeof(packets[i]), 0,
					(struct sockaddr*) &client_addr, len);
			}
			next_packet_num = base + WINDOW_SIZE;
		}
	}

}<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */
#ifndef INCLUDED_REPORTDESIGN_SOURCE_UI_INC_DATETIME_HXX
#define INCLUDED_REPORTDESIGN_SOURCE_UI_INC_DATETIME_HXX

#include <vcl/dialog.hxx>
#include <vcl/fixed.hxx>
#include <vcl/lstbox.hxx>
#include <vcl/field.hxx>
#include <vcl/button.hxx>
#include <com/sun/star/report/XReportDefinition.hpp>
#include <com/sun/star/util/XNumberFormats.hpp>
#include <com/sun/star/lang/Locale.hpp>

#include <svtools/dialogcontrolling.hxx>

namespace rptui
{
class OReportController;
/*************************************************************************
|*
|* Groups and Sorting dialog
|*
\************************************************************************/
class ODateTimeDialog : public ModalDialog
{
    CheckBox*                                m_pDate;
    FixedText*                               m_pFTDateFormat;
    ListBox*                                 m_pDateListBox;
    CheckBox*                                m_pTime;
    FixedText*                               m_pFTTimeFormat;
    ListBox*                                 m_pTimeListBox;
    OKButton*                                m_pPB_OK;
    CancelButton*                            m_pPB_CANCEL;
    HelpButton*                              m_pPB_Help;

    svt::ControlDependencyManager           m_aDateControlling;
    svt::ControlDependencyManager           m_aTimeControlling;

    ::rptui::OReportController*             m_pController;
    ::com::sun::star::uno::Reference< ::com::sun::star::report::XSection>
                                            m_xHoldAlive;
    ::com::sun::star::lang::Locale          m_nLocale;

    /** returns the frmat string
    *
    * \param _nNumberFormatKey the number format key
    * \param _xFormats
    * \param _bTime
    * \return
    */
    OUString getFormatStringByKey(::sal_Int32 _nNumberFormatKey,const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormats>& _xFormats,bool _bTime);

    /** returns the number format key
        @param  _nNumberFormatIndex the number format index @see com::sun::star::i18n::NumberFormatIndex
    */
    sal_Int32 getFormatKey(sal_Bool _bDate) const;

    DECL_LINK( CBClickHdl, CheckBox* );
    ODateTimeDialog(const ODateTimeDialog&);
    void operator =(const ODateTimeDialog&);

    // fill methods
    void InsertEntry(sal_Int16 _nNumberFormatId);
public:
    ODateTimeDialog( Window* pParent
                        ,const ::com::sun::star::uno::Reference< ::com::sun::star::report::XSection>& _xHoldAlive
                        ,::rptui::OReportController* _pController);
    virtual ~ODateTimeDialog();
    virtual short   Execute() SAL_OVERRIDE;
};

} // namespace rptui

#endif // INCLUDED_REPORTDESIGN_SOURCE_UI_INC_DATETIME_HXX

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>coverity#1210196 Uninitialized pointer field<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */
#ifndef INCLUDED_REPORTDESIGN_SOURCE_UI_INC_DATETIME_HXX
#define INCLUDED_REPORTDESIGN_SOURCE_UI_INC_DATETIME_HXX

#include <vcl/dialog.hxx>
#include <vcl/fixed.hxx>
#include <vcl/lstbox.hxx>
#include <vcl/field.hxx>
#include <vcl/button.hxx>
#include <com/sun/star/report/XReportDefinition.hpp>
#include <com/sun/star/util/XNumberFormats.hpp>
#include <com/sun/star/lang/Locale.hpp>

#include <svtools/dialogcontrolling.hxx>

namespace rptui
{
class OReportController;
/*************************************************************************
|*
|* Groups and Sorting dialog
|*
\************************************************************************/
class ODateTimeDialog : public ModalDialog
{
    CheckBox*                                m_pDate;
    FixedText*                               m_pFTDateFormat;
    ListBox*                                 m_pDateListBox;
    CheckBox*                                m_pTime;
    FixedText*                               m_pFTTimeFormat;
    ListBox*                                 m_pTimeListBox;
    OKButton*                                m_pPB_OK;

    svt::ControlDependencyManager           m_aDateControlling;
    svt::ControlDependencyManager           m_aTimeControlling;

    ::rptui::OReportController*             m_pController;
    ::com::sun::star::uno::Reference< ::com::sun::star::report::XSection>
                                            m_xHoldAlive;
    ::com::sun::star::lang::Locale          m_nLocale;

    /** returns the frmat string
    *
    * \param _nNumberFormatKey the number format key
    * \param _xFormats
    * \param _bTime
    * \return
    */
    OUString getFormatStringByKey(::sal_Int32 _nNumberFormatKey,const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormats>& _xFormats,bool _bTime);

    /** returns the number format key
        @param  _nNumberFormatIndex the number format index @see com::sun::star::i18n::NumberFormatIndex
    */
    sal_Int32 getFormatKey(sal_Bool _bDate) const;

    DECL_LINK( CBClickHdl, CheckBox* );
    ODateTimeDialog(const ODateTimeDialog&);
    void operator =(const ODateTimeDialog&);

    // fill methods
    void InsertEntry(sal_Int16 _nNumberFormatId);
public:
    ODateTimeDialog( Window* pParent
                        ,const ::com::sun::star::uno::Reference< ::com::sun::star::report::XSection>& _xHoldAlive
                        ,::rptui::OReportController* _pController);
    virtual ~ODateTimeDialog();
    virtual short   Execute() SAL_OVERRIDE;
};

} // namespace rptui

#endif // INCLUDED_REPORTDESIGN_SOURCE_UI_INC_DATETIME_HXX

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>//
// AUTOGENERATED, DO NOT EDIT
//
#ifndef __OPENCV_OCL_CL_RUNTIME_HPP__
#define __OPENCV_OCL_CL_RUNTIME_HPP__

#ifdef HAVE_OPENCL

#if defined(HAVE_OPENCL12)
#include "cl_runtime_opencl12.hpp"
#elif defined(HAVE_OPENCL11)
#include "cl_runtime_opencl11.hpp"
#else
#error Invalid OpenCL configuration
#endif

#endif

#endif // __OPENCV_OCL_CL_RUNTIME_HPP__
<commit_msg>removed invalid comment<commit_after>#ifndef __OPENCV_OCL_CL_RUNTIME_HPP__
#define __OPENCV_OCL_CL_RUNTIME_HPP__

#ifdef HAVE_OPENCL

#if defined(HAVE_OPENCL12)
#include "cl_runtime_opencl12.hpp"
#elif defined(HAVE_OPENCL11)
#include "cl_runtime_opencl11.hpp"
#else
#error Invalid OpenCL configuration
#endif

#endif

#endif // __OPENCV_OCL_CL_RUNTIME_HPP__
<|endoftext|>


<commit_before>#include "Stdafx.h"
#include "BlurMeasure.h"

using namespace std;
using namespace cv;

namespace ImageQuality
{
	double BlurMeasure::BlurTest(array<byte>^ buffer)
	{
		Mat image = ReadImage(buffer);
		resize(image, image, Size(512, 512));

		Mat gray;
		cvtColor(image, gray, CV_BGR2GRAY);

		Mat detected_edges;
		Canny(gray, detected_edges, 0.4, 0.4 * 3, 3);

		double maxval;
		double average = mean(detected_edges)[0];
		int* const maxIdx = (int*)malloc(sizeof(detected_edges));

		minMaxIdx(detected_edges, 0, &maxval, 0, maxIdx);

		double blurresult = average / maxval;
		return blurresult;
	}

	Mat BlurMeasure::ReadImage(array<byte>^ buffer)
	{
		pin_ptr<byte> px = &buffer[0];
		Mat datax(1, buffer->Length, CV_8U, (void*)px, CV_AUTO_STEP);
		return imdecode(datax, CV_LOAD_IMAGE_COLOR);
	}
}<commit_msg>Blur measure algorithm<commit_after>#include "Stdafx.h"
#include "BlurMeasure.h"

using namespace std;
using namespace cv;

namespace ImageQuality
{
	double BlurMeasure::BlurTest(array<byte>^ buffer)
	{
		Mat image = ReadImage(buffer);
		resize(image, image, Size(512, 512));

		Mat gray;
		cvtColor(image, gray, CV_BGR2GRAY);

		Mat laplacian;
		Laplacian(gray, laplacian, CV_64F);

		Mat mean, stddev;
		meanStdDev(laplacian, mean, stddev);
		double val = stddev.at<double>(0, 0);
		return val * val;
	}

	Mat BlurMeasure::ReadImage(array<byte>^ buffer)
	{
		pin_ptr<byte> px = &buffer[0];
		Mat datax(1, buffer->Length, CV_8U, (void*)px, CV_AUTO_STEP);
		return imdecode(datax, CV_LOAD_IMAGE_COLOR);
	}
}<|endoftext|>


<commit_before>// This code is based on Sabberstone project.
// Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva
// Hearthstone++ is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

#ifndef ROSETTASTONE_TARGETING_HPP
#define ROSETTASTONE_TARGETING_HPP

#include <Rosetta/Models/Minion.hpp>

namespace RosettaStone::Generic
{
//! Summons an minion on battlefield.
//! \param player The player to summon an minion on battlefield.
//! \param minion An minion to summon.
//! \param fieldPos The position of minion to summon.
void Summon(Player& player, Minion* minion, int fieldPos);
}  // namespace RosettaStone::Generic

#endif  // ROSETTASTONE_TARGETING_HPP
<commit_msg>fix: Correct LGTM issues<commit_after>// This code is based on Sabberstone project.
// Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva
// Hearthstone++ is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

#ifndef ROSETTASTONE_SUMMON_HPP
#define ROSETTASTONE_SUMMON_HPP

#include <Rosetta/Models/Minion.hpp>

namespace RosettaStone::Generic
{
//! Summons an minion on battlefield.
//! \param player The player to summon an minion on battlefield.
//! \param minion An minion to summon.
//! \param fieldPos The position of minion to summon.
void Summon(Player& player, Minion* minion, int fieldPos);
}  // namespace RosettaStone::Generic

#endif  // ROSETTASTONE_SUMMON_HPP
<|endoftext|>


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

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

//#define TF_NEWDESKTOP

#define _SDINTERN_HXX

#ifndef GCC
#endif
#include <stdio.h>

#ifndef _URLOBJ_HXX //autogen
#include <tools/urlobj.hxx>
#endif
#ifndef _CSTITEM_HXX //autogen
#include <svtools/cstitem.hxx>
#endif
#ifndef _CONFIG_HXX
#include <tools/config.hxx>
#endif
#ifndef _EHDL_HXX
#include <svtools/ehdl.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_STARTOPTIONS_HXX
#include <svtools/startoptions.hxx>
#endif
#include <svtools/itempool.hxx>
#include <svtools/urihelper.hxx>
#include <svtools/helpopt.hxx>
#include <vos/process.hxx>
#include <framework/sfxhelperfunctions.hxx>
#include <rtl/ustring.hxx>
#include <com/sun/star/uno/Exception.hpp>
#include <com/sun/star/uno/RuntimeException.hpp>
#include <com/sun/star/uno/Reference.hxx>

#include "sfxtypes.hxx"
#include "appdata.hxx"
#include <sfx2/docfac.hxx>
#include <sfx2/app.hxx>
#include "arrdecl.hxx"
#include <sfx2/dispatch.hxx>
#include "sfxresid.hxx"
#include <sfx2/fcontnr.hxx>
#include <sfx2/viewsh.hxx>
#include "intro.hxx"
#include <sfx2/msgpool.hxx>
#include <sfx2/mnumgr.hxx>
#include <sfx2/appuno.hxx>
#include <sfx2/objuno.hxx>
#include "app.hrc"
#include <sfx2/docfile.hxx>
#include "workwin.hxx"

#ifdef UNX
#define stricmp(a,b) strcmp(a,b)
#endif

//===================================================================

DBG_NAME(SfxAppMainNewMenu)
DBG_NAME(SfxAppMainBmkMenu)
DBG_NAME(SfxAppMainWizMenu)
DBG_NAME(SfxAppMainOLEReg)
DBG_NAME(SfxAppMainCHAOSReg)

//===================================================================

#define SFX_TEMPNAMEBASE_DIR    "soffice.tmp"
#define SFX_KEY_TEMPNAMEBASE    "Temp-Dir"

//===================================================================

#ifdef TF_POOLABLE
static SfxItemInfo __READONLY_DATA aItemInfos[] =
{
    { 0, 0 }
};
#endif

//===================================================================

typedef Link* LinkPtr;
SV_DECL_PTRARR(SfxInitLinkList, LinkPtr, 4, 4)

TYPEINIT2(SfxApplication,SfxShell,SfxBroadcaster);

//--------------------------------------------------------------------
void SfxApplication::Init
(
)

/*  [Beschreibung]

    Diese virtuelle Methode wird vom SFx aus Application:a:Main() gerufen,
    bevor Execute() ausgef"uhrt wird und
    - das Intro bereits angezeigt ist,
    - das Applikationsfenster exisitiert, aber noch hidden ist,
    - die Bindings bereits existieren (Controller sind anmeldbar),
    - der Ini- und Config-Manager bereits existiert,
    - die Standard-Controller bereits exisitieren,
    - die SFx-Shells ihre Interfaces bereits registriert haben.

    [Querverweise]
    <SfxApplication::Exit()>
    <SfxApplication::OpenClients()>
*/
{
#ifdef DDE_AVAILABLE
#ifdef PRODUCT
    InitializeDde();
#else
    if( !InitializeDde() )
    {
        ByteString aStr( "Kein DDE-Service moeglich. Fehler: " );
        if( GetDdeService() )
            aStr += GetDdeService()->GetError();
        else
            aStr += '?';
        DBG_ASSERT( sal_False, aStr.GetBuffer() )
    }
#endif
#endif
}

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

void SfxApplication::Exit()

/*  [Beschreibung]

    Diese virtuelle Methode wird vom SFx aus Application::Main() gerufen,
    nachdem Execute() beendet ist und
    - die Konfiguration (SfxConfigManager) bereits gespeichert wurde,
    - die Fensterpostionen etc. in den SfxIniManager geschrieben wurden,
    - das Applikationsfenster noch existiert, aber hidden ist
    - s"amtliche Dokumente und deren Views bereits geschlossen sind.
    - Dispatcher, Bindings etc. bereits zerst"ort sind

    [Querverweise]
    <SfxApplication::Init(int,char*[])>
*/

{
}

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

void SfxApplication::PreInit( )
{
}

//---------------------------------------------------------------------------
bool SfxApplication::InitLabelResMgr( const char* _pLabelPrefix, bool _bException )
{
    bool bRet = false;
    // Label-DLL mit diversen Resourcen fuer OEM-Ver. etc. (Intro, Titel, About)
    DBG_ASSERT( _pLabelPrefix, "Wrong initialisation!" );
    if ( _pLabelPrefix )
    {
        // versuchen, die Label-DLL zu erzeugen
        pAppData_Impl->pLabelResMgr = CreateResManager( _pLabelPrefix );

        // keine separate Label-DLL vorhanden?
        if ( !pAppData_Impl->pLabelResMgr )
        {
            if ( _bException )
            {
                // maybe corrupted installation
                throw (::com::sun::star::uno::RuntimeException(
                    ::rtl::OUString::createFromAscii("iso resource could not be loaded by SfxApplication"),
                    ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >()));
            }
        }
        else
            bRet = true;
    }

    return bRet;
}

void SfxApplication::Main( )
{
}

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

SfxFilterMatcher& SfxApplication::GetFilterMatcher()
{
    if( !pAppData_Impl->pMatcher )
    {
        pAppData_Impl->pMatcher = new SfxFilterMatcher();
        URIHelper::SetMaybeFileHdl( STATIC_LINK(
            pAppData_Impl->pMatcher, SfxFilterMatcher, MaybeFileHdl_Impl ) );
    }
    return *pAppData_Impl->pMatcher;
}
<commit_msg>INTEGRATION: CWS custommeta (1.33.70); FILE MERGED 2008/02/01 10:38:49 mst 1.33.70.2: RESYNC: (1.33-1.34); FILE MERGED 2008/01/25 14:19:26 mst 1.33.70.1: - sfx2/inc/sfx2/{frmhtmlw.hxx,sfxhtml.hxx},   sfx2/source/appl/{appbas.cxx,appcfg.cxx,appmain.cxx,appserv.cxx},   sfx2/source/bastyp/{fltfnc.cxx,frmhtml.cxx}, sfx2/source/config/evntconf.cxx,   sfx2/source/doc/new.cxx, sfx2/source/doc/oleprops.cxx:   + remove unneeded includes and assorted detritus<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: appmain.cxx,v $
 *
 *  $Revision: 1.35 $
 *
 *  last change: $Author: obo $ $Date: 2008-02-26 15:01:27 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

//#define TF_NEWDESKTOP

#define _SDINTERN_HXX

#include <stdio.h>

#ifndef _URLOBJ_HXX //autogen
#include <tools/urlobj.hxx>
#endif
#ifndef _CSTITEM_HXX //autogen
#include <svtools/cstitem.hxx>
#endif
#ifndef _CONFIG_HXX
#include <tools/config.hxx>
#endif
#ifndef _EHDL_HXX
#include <svtools/ehdl.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_STARTOPTIONS_HXX
#include <svtools/startoptions.hxx>
#endif
#include <svtools/itempool.hxx>
#include <svtools/urihelper.hxx>
#include <svtools/helpopt.hxx>
#include <vos/process.hxx>
#include <framework/sfxhelperfunctions.hxx>
#include <rtl/ustring.hxx>
#include <com/sun/star/uno/Exception.hpp>
#include <com/sun/star/uno/RuntimeException.hpp>
#include <com/sun/star/uno/Reference.hxx>

#include "sfxtypes.hxx"
#include "appdata.hxx"
#include <sfx2/docfac.hxx>
#include <sfx2/app.hxx>
#include "arrdecl.hxx"
#include <sfx2/dispatch.hxx>
#include "sfxresid.hxx"
#include <sfx2/fcontnr.hxx>
#include <sfx2/viewsh.hxx>
#include "intro.hxx"
#include <sfx2/msgpool.hxx>
#include <sfx2/mnumgr.hxx>
#include <sfx2/appuno.hxx>
#include "app.hrc"
#include <sfx2/docfile.hxx>
#include "workwin.hxx"

#ifdef UNX
#define stricmp(a,b) strcmp(a,b)
#endif

//===================================================================

DBG_NAME(SfxAppMainNewMenu)
DBG_NAME(SfxAppMainBmkMenu)
DBG_NAME(SfxAppMainWizMenu)
DBG_NAME(SfxAppMainOLEReg)
DBG_NAME(SfxAppMainCHAOSReg)

//===================================================================

#define SFX_TEMPNAMEBASE_DIR    "soffice.tmp"
#define SFX_KEY_TEMPNAMEBASE    "Temp-Dir"

//===================================================================

#ifdef TF_POOLABLE
static SfxItemInfo __READONLY_DATA aItemInfos[] =
{
    { 0, 0 }
};
#endif

//===================================================================

typedef Link* LinkPtr;
SV_DECL_PTRARR(SfxInitLinkList, LinkPtr, 4, 4)

TYPEINIT2(SfxApplication,SfxShell,SfxBroadcaster);

//--------------------------------------------------------------------
void SfxApplication::Init
(
)

/*  [Beschreibung]

    Diese virtuelle Methode wird vom SFx aus Application:a:Main() gerufen,
    bevor Execute() ausgef"uhrt wird und
    - das Intro bereits angezeigt ist,
    - das Applikationsfenster exisitiert, aber noch hidden ist,
    - die Bindings bereits existieren (Controller sind anmeldbar),
    - der Ini- und Config-Manager bereits existiert,
    - die Standard-Controller bereits exisitieren,
    - die SFx-Shells ihre Interfaces bereits registriert haben.

    [Querverweise]
    <SfxApplication::Exit()>
    <SfxApplication::OpenClients()>
*/
{
#ifdef DDE_AVAILABLE
#ifdef PRODUCT
    InitializeDde();
#else
    if( !InitializeDde() )
    {
        ByteString aStr( "Kein DDE-Service moeglich. Fehler: " );
        if( GetDdeService() )
            aStr += GetDdeService()->GetError();
        else
            aStr += '?';
        DBG_ASSERT( sal_False, aStr.GetBuffer() )
    }
#endif
#endif
}

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

void SfxApplication::Exit()

/*  [Beschreibung]

    Diese virtuelle Methode wird vom SFx aus Application::Main() gerufen,
    nachdem Execute() beendet ist und
    - die Konfiguration (SfxConfigManager) bereits gespeichert wurde,
    - die Fensterpostionen etc. in den SfxIniManager geschrieben wurden,
    - das Applikationsfenster noch existiert, aber hidden ist
    - s"amtliche Dokumente und deren Views bereits geschlossen sind.
    - Dispatcher, Bindings etc. bereits zerst"ort sind

    [Querverweise]
    <SfxApplication::Init(int,char*[])>
*/

{
}

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

void SfxApplication::PreInit( )
{
}

//---------------------------------------------------------------------------
bool SfxApplication::InitLabelResMgr( const char* _pLabelPrefix, bool _bException )
{
    bool bRet = false;
    // Label-DLL mit diversen Resourcen fuer OEM-Ver. etc. (Intro, Titel, About)
    DBG_ASSERT( _pLabelPrefix, "Wrong initialisation!" );
    if ( _pLabelPrefix )
    {
        // versuchen, die Label-DLL zu erzeugen
        pAppData_Impl->pLabelResMgr = CreateResManager( _pLabelPrefix );

        // keine separate Label-DLL vorhanden?
        if ( !pAppData_Impl->pLabelResMgr )
        {
            if ( _bException )
            {
                // maybe corrupted installation
                throw (::com::sun::star::uno::RuntimeException(
                    ::rtl::OUString::createFromAscii("iso resource could not be loaded by SfxApplication"),
                    ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >()));
            }
        }
        else
            bRet = true;
    }

    return bRet;
}

void SfxApplication::Main( )
{
}

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

SfxFilterMatcher& SfxApplication::GetFilterMatcher()
{
    if( !pAppData_Impl->pMatcher )
    {
        pAppData_Impl->pMatcher = new SfxFilterMatcher();
        URIHelper::SetMaybeFileHdl( STATIC_LINK(
            pAppData_Impl->pMatcher, SfxFilterMatcher, MaybeFileHdl_Impl ) );
    }
    return *pAppData_Impl->pMatcher;
}
<|endoftext|>


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

#include "inettbc.hxx"

#ifndef GCC
#pragma hdrstop
#endif

#ifndef _COM_SUN_STAR_UNO_ANY_H_
#include <com/sun/star/uno/Any.h>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAMESSUPLLIER_HPP_
#include <com/sun/star/frame/XFramesSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_TASK_XINTERACTIONHANDLER_HPP_
#include <com/sun/star/task/XInteractionHandler.hpp>
#endif

#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXCANCEL_HXX //autogen
#include <svtools/cancel.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_HISTORYOPTIONS_HXX
#include <svtools/historyoptions.hxx>
#endif
#ifndef SVTOOLS_FOLDER_RESTRICTION_HXX
#include <svtools/folderrestriction.hxx>
#endif
#include <vcl/toolbox.hxx>
#ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_
#include <toolkit/unohlp.hxx>
#endif
#ifndef _VOS_THREAD_HXX //autogen
#include <vos/thread.hxx>
#endif
#ifndef _VOS_MUTEX_HXX //autogen
#include <vos/mutex.hxx>
#endif
#include <rtl/ustring.hxx>

#include <svtools/itemset.hxx>
#include <svtools/urihelper.hxx>
#include <svtools/pathoptions.hxx>
#include <svtools/asynclink.hxx>
#include <svtools/inettbc.hxx>

#include <unotools/localfilehelper.hxx>
#include <comphelper/processfactory.hxx>

#include "sfx.hrc"
#include "dispatch.hxx"
#include "viewfrm.hxx"
#include "objsh.hxx"
#include "referers.hxx"
#include "sfxtypes.hxx"
#include "helper.hxx"

using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::task;

//***************************************************************************
// SfxURLToolBoxControl_Impl
//***************************************************************************

SFX_IMPL_TOOLBOX_CONTROL(SfxURLToolBoxControl_Impl,SfxStringItem)

SfxURLToolBoxControl_Impl::SfxURLToolBoxControl_Impl( USHORT nSlotId, USHORT nId, ToolBox& rBox )
    : SfxToolBoxControl( nSlotId, nId, rBox ),
    pAccExec( 0 )
{
    addStatusListener( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ".uno:CurrentURL" )));
}

SfxURLToolBoxControl_Impl::~SfxURLToolBoxControl_Impl()
{
    delete pAccExec;
}

SvtURLBox* SfxURLToolBoxControl_Impl::GetURLBox() const
{
    return (SvtURLBox*)GetToolBox().GetItemWindow( GetId() );
}

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

void SfxURLToolBoxControl_Impl::OpenURL( const String& rName, BOOL bNew ) const
{
    String aName;
    String aFilter;
    String aOptions;

    INetURLObject aObj( rName );
    if ( aObj.GetProtocol() == INET_PROT_NOT_VALID )
    {
        String aBaseURL = GetURLBox()->GetBaseURL();
        aName = SvtURLBox::ParseSmart( rName, aBaseURL, SvtPathOptions().GetWorkPath() );
    }
    else
        aName = rName;

    if ( !aName.Len() )
        return;

    Reference< XDispatchProvider > xDispatchProvider( getFrameInterface(), UNO_QUERY );
    if ( xDispatchProvider.is() && m_xServiceManager.is() )
    {
        URL             aTargetURL;
        ::rtl::OUString aTarget( ::rtl::OUString::createFromAscii( "_default" ));

        aTargetURL.Complete = aName;

        getURLTransformer()->parseStrict( aTargetURL );
        Reference< XDispatch > xDispatch = xDispatchProvider->queryDispatch( aTargetURL, aTarget, 0 );
        if ( xDispatch.is() )
        {
            Sequence< PropertyValue > aArgs( 2 );
            aArgs[0].Name = OUString::createFromAscii( "Referer" );
            aArgs[0].Value = makeAny( ::rtl::OUString::createFromAscii( SFX_REFERER_USER ));
            aArgs[1].Name = OUString( RTL_CONSTASCII_USTRINGPARAM( "FileName" ));
            aArgs[1].Value = makeAny( OUString( aName ));

            if ( aFilter.Len() )
            {
                aArgs.realloc( 4 );
                aArgs[2].Name = OUString::createFromAscii( "FilterOptions" );
                aArgs[2].Value = makeAny( OUString( aOptions ));
                aArgs[3].Name = OUString::createFromAscii( "FilterName" );
                aArgs[3].Value = makeAny( OUString( aFilter ));
            }

            SfxURLToolBoxControl_Impl::ExecuteInfo* pExecuteInfo = new SfxURLToolBoxControl_Impl::ExecuteInfo;
            pExecuteInfo->xDispatch     = xDispatch;
            pExecuteInfo->aTargetURL    = aTargetURL;
            pExecuteInfo->aArgs         = aArgs;
            Application::PostUserEvent( STATIC_LINK( 0, SfxURLToolBoxControl_Impl, ExecuteHdl_Impl), pExecuteInfo );
        }
    }
}

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

IMPL_STATIC_LINK( SfxURLToolBoxControl_Impl, ExecuteHdl_Impl, ExecuteInfo*, pExecuteInfo )
{
    try
    {
        // Asynchronous execution as this can lead to our own destruction!
        // Framework can recycle our current frame and the layout manager disposes all user interface
        // elements if a component gets detached from its frame!
        pExecuteInfo->xDispatch->dispatch( pExecuteInfo->aTargetURL, pExecuteInfo->aArgs );
    }
    catch ( Exception& )
    {
    }

    delete pExecuteInfo;
    return 0;
}

Window* SfxURLToolBoxControl_Impl::CreateItemWindow( Window* pParent )
{
    SvtURLBox* pURLBox = new SvtURLBox( pParent );
    pURLBox->SetOpenHdl( LINK( this, SfxURLToolBoxControl_Impl, OpenHdl ) );
    pURLBox->SetSelectHdl( LINK( this, SfxURLToolBoxControl_Impl, SelectHdl ) );

    return pURLBox;
}

IMPL_LINK( SfxURLToolBoxControl_Impl, SelectHdl, void*, pVoid )
{
    SvtURLBox* pURLBox = GetURLBox();
    String aName( pURLBox->GetURL() );

    if ( !pURLBox->IsTravelSelect() && aName.Len() )
        OpenURL( aName, FALSE );

    return 1L;
}

IMPL_LINK( SfxURLToolBoxControl_Impl, OpenHdl, void*, pVoid )
{
    SvtURLBox* pURLBox = GetURLBox();
    OpenURL( pURLBox->GetURL(), pURLBox->IsCtrlOpen() );

    if ( m_xServiceManager.is() )
    {
        Reference< XFramesSupplier > xDesktop( m_xServiceManager->createInstance(
                                                OUString::createFromAscii( "com.sun.star.frame.Desktop" )),
                                             UNO_QUERY );
        Reference< XFrame > xFrame( xDesktop->getActiveFrame(), UNO_QUERY );
        if ( xFrame.is() )
        {
            Window* pWin = VCLUnoHelper::GetWindow( xFrame->getContainerWindow() );
            if ( pWin )
            {
                pWin->GrabFocus();
                pWin->ToTop( TOTOP_RESTOREWHENMIN );
            }
        }
    }

    return 1L;
}

IMPL_LINK( SfxURLToolBoxControl_Impl, WindowEventListener, VclSimpleEvent*, pEvent )
{
    if ( pAccExec &&
         pEvent &&
         pEvent->ISA( VclWindowEvent ) &&
         ( pEvent->GetId() == VCLEVENT_WINDOW_KEYINPUT ))
    {
        VclWindowEvent* pWinEvent = static_cast< VclWindowEvent* >( pEvent );
        KeyEvent* pKeyEvent = static_cast< KeyEvent* >( pWinEvent->GetData() );

        pAccExec->execute( pKeyEvent->GetKeyCode() );
    }

    return 1;
}

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

void SfxURLToolBoxControl_Impl::StateChanged
(
    USHORT              nSID,
    SfxItemState        eState,
    const SfxPoolItem*  pState
)
{
    if ( nSID == SID_OPENURL )
    {
        // Disable URL box if command is disabled #111014#
        GetURLBox()->Enable( SFX_ITEM_DISABLED != eState );
    }

    if ( GetURLBox()->IsEnabled() )
    {
        if( nSID == SID_FOCUSURLBOX )
        {
            if ( GetURLBox()->IsVisible() )
                GetURLBox()->GrabFocus();
        }
        else if ( !GetURLBox()->IsModified() && SFX_ITEM_AVAILABLE == eState )
        {
            SvtURLBox* pURLBox = GetURLBox();
            pURLBox->Clear();

            ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > > lList = SvtHistoryOptions().GetList(eHISTORY);
            for (sal_Int32 i=0; i<lList.getLength(); ++i)
            {
                ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > lProps = lList[i];
                for (sal_Int32 p=0; p<lProps.getLength(); ++p)
                {
                    if (lProps[p].Name != HISTORY_PROPERTYNAME_URL)
                        continue;

                    ::rtl::OUString sURL;
                    if (!(lProps[p].Value>>=sURL) || !sURL.getLength())
                        continue;

                    INetURLObject aURL    ( sURL );
                    String        sMainURL( aURL.GetMainURL( INetURLObject::DECODE_WITH_CHARSET ) );
                    String        sFile;

                    if (::utl::LocalFileHelper::ConvertURLToSystemPath(sMainURL,sFile))
                        pURLBox->InsertEntry(sFile);
                    else
                        pURLBox->InsertEntry(sMainURL);
                }
            }

            const SfxStringItem *pURL = PTR_CAST(SfxStringItem,pState);
            String aRep( pURL->GetValue() );
            INetURLObject aURL( aRep );
            INetProtocol eProt = aURL.GetProtocol();
            if ( eProt == INET_PROT_FILE )
            {
                pURLBox->SetText( aURL.PathToFileName() );
            }
            else
                pURLBox->SetText( aURL.GetURLNoPass() );
        }
    }
}

//***************************************************************************
// SfxCancelToolBoxControl_Impl
//***************************************************************************

SFX_IMPL_TOOLBOX_CONTROL(SfxCancelToolBoxControl_Impl,SfxBoolItem)

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

SfxCancelToolBoxControl_Impl::SfxCancelToolBoxControl_Impl( USHORT nSlotId, USHORT nId, ToolBox& rBox ) :
    SfxToolBoxControl( nSlotId, nId, rBox )
{
}

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

SfxPopupWindowType SfxCancelToolBoxControl_Impl::GetPopupWindowType() const
{
    return SFX_POPUPWINDOW_ONTIMEOUT;
}

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

SfxPopupWindow* SfxCancelToolBoxControl_Impl::CreatePopupWindow()
{
    PopupMenu aMenu;
    BOOL bExecute = FALSE, bSeparator = FALSE;
    USHORT nIndex = 1;
    for ( SfxCancelManager *pCancelMgr = SfxViewFrame::Current()->GetTopViewFrame()->GetCancelManager();
          pCancelMgr;
          pCancelMgr = pCancelMgr->GetParent() )
    {
        for ( USHORT n=0; n<pCancelMgr->GetCancellableCount(); ++n )
        {
            if ( !n && bSeparator )
            {
                aMenu.InsertSeparator();
                bSeparator = FALSE;
            }
            String aItemText = pCancelMgr->GetCancellable(n)->GetTitle();
            if ( aItemText.Len() > 50 )
            {
                aItemText.Erase( 48 );
                aItemText += DEFINE_CONST_UNICODE("...");
            }
            aMenu.InsertItem( nIndex++, aItemText );
            bExecute = TRUE;
            bSeparator = TRUE;
        }
    }

    ToolBox& rToolBox = GetToolBox();
    USHORT nId = bExecute ? nId = aMenu.Execute( &rToolBox, rToolBox.GetPointerPosPixel() ) : 0;
    GetToolBox().EndSelection();
//  ClearCache();
//  UpdateSlot();
    if ( nId )
    {
        String aSearchText = aMenu.GetItemText(nId);
        for ( SfxCancelManager *pCancelMgr = SfxViewFrame::Current()->GetTopViewFrame()->GetCancelManager();
              pCancelMgr;
              pCancelMgr = pCancelMgr->GetParent() )
        {
            for ( USHORT n = 0; n < pCancelMgr->GetCancellableCount(); ++n )
            {
                SfxCancellable *pCancel = pCancelMgr->GetCancellable(n);
                String aItemText = pCancel->GetTitle();
                if ( aItemText.Len() > 50 )
                {
                    aItemText.Erase( 48 );
                    aItemText += DEFINE_CONST_UNICODE("...");
                }

                if ( aItemText == aSearchText )
                {
                    pCancel->Cancel();
                    return 0;
                }
            }
        }

    }

    return 0;
}

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

void SfxCancelToolBoxControl_Impl::StateChanged
(
    USHORT              nSID,
    SfxItemState        eState,
    const SfxPoolItem*  pState
)
{
    SfxVoidItem aVoidItem( nSID );
    //SfxToolBoxControl::StateChanged( nSID, eState, pState ? &aVoidItem : 0 );
    SfxToolBoxControl::StateChanged( nSID, eState, pState );
}
<commit_msg>INTEGRATION: CWS warnings01 (1.31.64); FILE MERGED 2005/11/28 16:16:37 cd 1.31.64.1: #i55991# Remove warnings<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: inettbc.cxx,v $
 *
 *  $Revision: 1.32 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 22:35:18 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include "inettbc.hxx"

#ifndef GCC
#pragma hdrstop
#endif

#ifndef _COM_SUN_STAR_UNO_ANY_H_
#include <com/sun/star/uno/Any.h>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAMESSUPLLIER_HPP_
#include <com/sun/star/frame/XFramesSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_TASK_XINTERACTIONHANDLER_HPP_
#include <com/sun/star/task/XInteractionHandler.hpp>
#endif

#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXCANCEL_HXX //autogen
#include <svtools/cancel.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_HISTORYOPTIONS_HXX
#include <svtools/historyoptions.hxx>
#endif
#ifndef SVTOOLS_FOLDER_RESTRICTION_HXX
#include <svtools/folderrestriction.hxx>
#endif
#include <vcl/toolbox.hxx>
#ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_
#include <toolkit/unohlp.hxx>
#endif
#ifndef _VOS_THREAD_HXX //autogen
#include <vos/thread.hxx>
#endif
#ifndef _VOS_MUTEX_HXX //autogen
#include <vos/mutex.hxx>
#endif
#include <rtl/ustring.hxx>

#include <svtools/itemset.hxx>
#include <svtools/urihelper.hxx>
#include <svtools/pathoptions.hxx>
#include <svtools/asynclink.hxx>
#include <svtools/inettbc.hxx>

#include <unotools/localfilehelper.hxx>
#include <comphelper/processfactory.hxx>

#include "sfx.hrc"
#include "dispatch.hxx"
#include "viewfrm.hxx"
#include "objsh.hxx"
#include "referers.hxx"
#include "sfxtypes.hxx"
#include "helper.hxx"

using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::task;

//***************************************************************************
// SfxURLToolBoxControl_Impl
//***************************************************************************

SFX_IMPL_TOOLBOX_CONTROL(SfxURLToolBoxControl_Impl,SfxStringItem)

SfxURLToolBoxControl_Impl::SfxURLToolBoxControl_Impl( USHORT nSlotId, USHORT nId, ToolBox& rBox )
    : SfxToolBoxControl( nSlotId, nId, rBox ),
    pAccExec( 0 )
{
    addStatusListener( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ".uno:CurrentURL" )));
}

SfxURLToolBoxControl_Impl::~SfxURLToolBoxControl_Impl()
{
    delete pAccExec;
}

SvtURLBox* SfxURLToolBoxControl_Impl::GetURLBox() const
{
    return (SvtURLBox*)GetToolBox().GetItemWindow( GetId() );
}

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

void SfxURLToolBoxControl_Impl::OpenURL( const String& rName, BOOL /*bNew*/ ) const
{
    String aName;
    String aFilter;
    String aOptions;

    INetURLObject aObj( rName );
    if ( aObj.GetProtocol() == INET_PROT_NOT_VALID )
    {
        String aBaseURL = GetURLBox()->GetBaseURL();
        aName = SvtURLBox::ParseSmart( rName, aBaseURL, SvtPathOptions().GetWorkPath() );
    }
    else
        aName = rName;

    if ( !aName.Len() )
        return;

    Reference< XDispatchProvider > xDispatchProvider( getFrameInterface(), UNO_QUERY );
    if ( xDispatchProvider.is() && m_xServiceManager.is() )
    {
        URL             aTargetURL;
        ::rtl::OUString aTarget( ::rtl::OUString::createFromAscii( "_default" ));

        aTargetURL.Complete = aName;

        getURLTransformer()->parseStrict( aTargetURL );
        Reference< XDispatch > xDispatch = xDispatchProvider->queryDispatch( aTargetURL, aTarget, 0 );
        if ( xDispatch.is() )
        {
            Sequence< PropertyValue > aArgs( 2 );
            aArgs[0].Name = OUString::createFromAscii( "Referer" );
            aArgs[0].Value = makeAny( ::rtl::OUString::createFromAscii( SFX_REFERER_USER ));
            aArgs[1].Name = OUString( RTL_CONSTASCII_USTRINGPARAM( "FileName" ));
            aArgs[1].Value = makeAny( OUString( aName ));

            if ( aFilter.Len() )
            {
                aArgs.realloc( 4 );
                aArgs[2].Name = OUString::createFromAscii( "FilterOptions" );
                aArgs[2].Value = makeAny( OUString( aOptions ));
                aArgs[3].Name = OUString::createFromAscii( "FilterName" );
                aArgs[3].Value = makeAny( OUString( aFilter ));
            }

            SfxURLToolBoxControl_Impl::ExecuteInfo* pExecuteInfo = new SfxURLToolBoxControl_Impl::ExecuteInfo;
            pExecuteInfo->xDispatch     = xDispatch;
            pExecuteInfo->aTargetURL    = aTargetURL;
            pExecuteInfo->aArgs         = aArgs;
            Application::PostUserEvent( STATIC_LINK( 0, SfxURLToolBoxControl_Impl, ExecuteHdl_Impl), pExecuteInfo );
        }
    }
}

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

IMPL_STATIC_LINK_NOINSTANCE( SfxURLToolBoxControl_Impl, ExecuteHdl_Impl, ExecuteInfo*, pExecuteInfo )
{
    try
    {
        // Asynchronous execution as this can lead to our own destruction!
        // Framework can recycle our current frame and the layout manager disposes all user interface
        // elements if a component gets detached from its frame!
        pExecuteInfo->xDispatch->dispatch( pExecuteInfo->aTargetURL, pExecuteInfo->aArgs );
    }
    catch ( Exception& )
    {
    }

    delete pExecuteInfo;
    return 0;
}

Window* SfxURLToolBoxControl_Impl::CreateItemWindow( Window* pParent )
{
    SvtURLBox* pURLBox = new SvtURLBox( pParent );
    pURLBox->SetOpenHdl( LINK( this, SfxURLToolBoxControl_Impl, OpenHdl ) );
    pURLBox->SetSelectHdl( LINK( this, SfxURLToolBoxControl_Impl, SelectHdl ) );

    return pURLBox;
}

IMPL_LINK( SfxURLToolBoxControl_Impl, SelectHdl, void*, EMPTYARG )
{
    SvtURLBox* pURLBox = GetURLBox();
    String aName( pURLBox->GetURL() );

    if ( !pURLBox->IsTravelSelect() && aName.Len() )
        OpenURL( aName, FALSE );

    return 1L;
}

IMPL_LINK( SfxURLToolBoxControl_Impl, OpenHdl, void*, EMPTYARG )
{
    SvtURLBox* pURLBox = GetURLBox();
    OpenURL( pURLBox->GetURL(), pURLBox->IsCtrlOpen() );

    if ( m_xServiceManager.is() )
    {
        Reference< XFramesSupplier > xDesktop( m_xServiceManager->createInstance(
                                                OUString::createFromAscii( "com.sun.star.frame.Desktop" )),
                                             UNO_QUERY );
        Reference< XFrame > xFrame( xDesktop->getActiveFrame(), UNO_QUERY );
        if ( xFrame.is() )
        {
            Window* pWin = VCLUnoHelper::GetWindow( xFrame->getContainerWindow() );
            if ( pWin )
            {
                pWin->GrabFocus();
                pWin->ToTop( TOTOP_RESTOREWHENMIN );
            }
        }
    }

    return 1L;
}

IMPL_LINK( SfxURLToolBoxControl_Impl, WindowEventListener, VclSimpleEvent*, pEvent )
{
    if ( pAccExec &&
         pEvent &&
         pEvent->ISA( VclWindowEvent ) &&
         ( pEvent->GetId() == VCLEVENT_WINDOW_KEYINPUT ))
    {
        VclWindowEvent* pWinEvent = static_cast< VclWindowEvent* >( pEvent );
        KeyEvent* pKeyEvent = static_cast< KeyEvent* >( pWinEvent->GetData() );

        pAccExec->execute( pKeyEvent->GetKeyCode() );
    }

    return 1;
}

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

void SfxURLToolBoxControl_Impl::StateChanged
(
    USHORT              nSID,
    SfxItemState        eState,
    const SfxPoolItem*  pState
)
{
    if ( nSID == SID_OPENURL )
    {
        // Disable URL box if command is disabled #111014#
        GetURLBox()->Enable( SFX_ITEM_DISABLED != eState );
    }

    if ( GetURLBox()->IsEnabled() )
    {
        if( nSID == SID_FOCUSURLBOX )
        {
            if ( GetURLBox()->IsVisible() )
                GetURLBox()->GrabFocus();
        }
        else if ( !GetURLBox()->IsModified() && SFX_ITEM_AVAILABLE == eState )
        {
            SvtURLBox* pURLBox = GetURLBox();
            pURLBox->Clear();

            ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > > lList = SvtHistoryOptions().GetList(eHISTORY);
            for (sal_Int32 i=0; i<lList.getLength(); ++i)
            {
                ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > lProps = lList[i];
                for (sal_Int32 p=0; p<lProps.getLength(); ++p)
                {
                    if (lProps[p].Name != HISTORY_PROPERTYNAME_URL)
                        continue;

                    ::rtl::OUString sURL;
                    if (!(lProps[p].Value>>=sURL) || !sURL.getLength())
                        continue;

                    INetURLObject aURL    ( sURL );
                    String        sMainURL( aURL.GetMainURL( INetURLObject::DECODE_WITH_CHARSET ) );
                    String        sFile;

                    if (::utl::LocalFileHelper::ConvertURLToSystemPath(sMainURL,sFile))
                        pURLBox->InsertEntry(sFile);
                    else
                        pURLBox->InsertEntry(sMainURL);
                }
            }

            const SfxStringItem *pURL = PTR_CAST(SfxStringItem,pState);
            String aRep( pURL->GetValue() );
            INetURLObject aURL( aRep );
            INetProtocol eProt = aURL.GetProtocol();
            if ( eProt == INET_PROT_FILE )
            {
                pURLBox->SetText( aURL.PathToFileName() );
            }
            else
                pURLBox->SetText( aURL.GetURLNoPass() );
        }
    }
}

//***************************************************************************
// SfxCancelToolBoxControl_Impl
//***************************************************************************

SFX_IMPL_TOOLBOX_CONTROL(SfxCancelToolBoxControl_Impl,SfxBoolItem)

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

SfxCancelToolBoxControl_Impl::SfxCancelToolBoxControl_Impl( USHORT nSlotId, USHORT nId, ToolBox& rBox ) :
    SfxToolBoxControl( nSlotId, nId, rBox )
{
}

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

SfxPopupWindowType SfxCancelToolBoxControl_Impl::GetPopupWindowType() const
{
    return SFX_POPUPWINDOW_ONTIMEOUT;
}

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

SfxPopupWindow* SfxCancelToolBoxControl_Impl::CreatePopupWindow()
{
    PopupMenu aMenu;
    BOOL bExecute = FALSE, bSeparator = FALSE;
    USHORT nIndex = 1;
    for ( SfxCancelManager *pCancelMgr = SfxViewFrame::Current()->GetTopViewFrame()->GetCancelManager();
          pCancelMgr;
          pCancelMgr = pCancelMgr->GetParent() )
    {
        for ( USHORT n=0; n<pCancelMgr->GetCancellableCount(); ++n )
        {
            if ( !n && bSeparator )
            {
                aMenu.InsertSeparator();
                bSeparator = FALSE;
            }
            String aItemText = pCancelMgr->GetCancellable(n)->GetTitle();
            if ( aItemText.Len() > 50 )
            {
                aItemText.Erase( 48 );
                aItemText += DEFINE_CONST_UNICODE("...");
            }
            aMenu.InsertItem( nIndex++, aItemText );
            bExecute = TRUE;
            bSeparator = TRUE;
        }
    }

    ToolBox& rToolBox = GetToolBox();
    USHORT nId = bExecute ? nId = aMenu.Execute( &rToolBox, rToolBox.GetPointerPosPixel() ) : 0;
    GetToolBox().EndSelection();
//  ClearCache();
//  UpdateSlot();
    if ( nId )
    {
        String aSearchText = aMenu.GetItemText(nId);
        for ( SfxCancelManager *pCancelMgr = SfxViewFrame::Current()->GetTopViewFrame()->GetCancelManager();
              pCancelMgr;
              pCancelMgr = pCancelMgr->GetParent() )
        {
            for ( USHORT n = 0; n < pCancelMgr->GetCancellableCount(); ++n )
            {
                SfxCancellable *pCancel = pCancelMgr->GetCancellable(n);
                String aItemText = pCancel->GetTitle();
                if ( aItemText.Len() > 50 )
                {
                    aItemText.Erase( 48 );
                    aItemText += DEFINE_CONST_UNICODE("...");
                }

                if ( aItemText == aSearchText )
                {
                    pCancel->Cancel();
                    return 0;
                }
            }
        }

    }

    return 0;
}

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

void SfxCancelToolBoxControl_Impl::StateChanged
(
    USHORT              nSID,
    SfxItemState        eState,
    const SfxPoolItem*  pState
)
{
    SfxVoidItem aVoidItem( nSID );
    //SfxToolBoxControl::StateChanged( nSID, eState, pState ? &aVoidItem : 0 );
    SfxToolBoxControl::StateChanged( nSID, eState, pState );
}
<|endoftext|>