<commit_before>#include "stdafx.h"
#include "sysinv.h"

PNODE GetDiskNode(__in PNODE parent, HDEVINFO hDevInfo, DWORD index);

PNODE GetDisksNode()
{
	HDEVINFO hDevInfo;
	SP_DEVINFO_DATA *deviceInfoData = NULL;
	SP_DEVICE_INTERFACE_DATA *interfaceData = NULL;
	SP_INTERFACE_DEVICE_DETAIL_DATA *detailData = NULL;
	DWORD index = 0;

	// Get device info handle
	hDevInfo = SetupDiGetClassDevs(&GUID_DEVINTERFACE_DISK, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
	if(INVALID_HANDLE_VALUE == hDevInfo)
		return NULL;

	PNODE node = node_alloc(L"Disks", NODE_FLAG_TABLE);
	while(NULL != GetDiskNode(node, hDevInfo, index++))
	{}

	return node;
}

PNODE GetDiskNode(__in PNODE parent, HDEVINFO hDevInfo, DWORD index)
{
	PNODE node = NULL, geoNode = NULL, partsNode = NULL, partNode = NULL;
	TCHAR strBuffer[MAX_PATH + 1];
	LPOLESTR oleBuffer;
	DWORD bufferSize = 0, i = 0, dataType = 0, partCount = 0;
	FLOAT f;
	LONGLONG q;

	SP_DEVINFO_DATA *deviceInfoData = NULL;
	SP_DEVICE_INTERFACE_DATA *interfaceData = NULL;
	SP_INTERFACE_DEVICE_DETAIL_DATA *detailData = NULL;
	HANDLE hDiskDrive = INVALID_HANDLE_VALUE;
	STORAGE_DEVICE_NUMBER *deviceNumber = NULL;
	DRIVE_LAYOUT_INFORMATION_EX *diskLayout = NULL;
	DISK_GEOMETRY_EX *diskGeometry = NULL;

	// Create return node
	node = node_alloc(L"Disk", NODE_FLAG_TABLE_ENTRY);

	// SP_DEVINFO_DATA *deviceInfoData
	// Get device info (used for getting device properties from the registry)
	deviceInfoData = (SP_DEVINFO_DATA *) LocalAlloc(LPTR, sizeof(SP_DEVINFO_DATA));
	deviceInfoData->cbSize = sizeof(SP_DEVINFO_DATA);
	if(!SetupDiEnumDeviceInfo(hDevInfo, index, deviceInfoData))
		goto error;

	// SP_DEVICE_INTERFACE_DATA *interfaceData
	// Get device interface data (used to get interface details)
	interfaceData = (SP_DEVICE_INTERFACE_DATA *) LocalAlloc(LPTR, sizeof(SP_DEVICE_INTERFACE_DATA));
	interfaceData->cbSize = sizeof(SP_INTERFACE_DEVICE_DATA);
	if(!SetupDiEnumInterfaceDevice(hDevInfo, NULL, &GUID_DEVINTERFACE_DISK, index, interfaceData))
		goto error;

	// SP_INTERFACE_DEVICE_DETAIL_DATA* detailData;
	// Get device interface details (used to get device path and subsequently, file handle)
	SetupDiGetDeviceInterfaceDetail(hDevInfo, interfaceData, NULL, NULL, &bufferSize, NULL);
	detailData = (SP_INTERFACE_DEVICE_DETAIL_DATA*) malloc(bufferSize);
	detailData->cbSize = sizeof(SP_INTERFACE_DEVICE_DETAIL_DATA);
	if (!SetupDiGetDeviceInterfaceDetail(hDevInfo, interfaceData, detailData, bufferSize, NULL, NULL))
		goto error;

	// HANDLE hDiskDrive
	// Get a file handle to the disk
	hDiskDrive = CreateFile(detailData->DevicePath, 0, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
	if(INVALID_HANDLE_VALUE == hDiskDrive)
		goto error;

	// STORAGE_DEVICE_NUMBER deviceNumber;
	// Get disk index number
	bufferSize = sizeof(STORAGE_DEVICE_NUMBER);
	deviceNumber = (STORAGE_DEVICE_NUMBER *) LocalAlloc(LPTR, bufferSize);
	if(!DeviceIoControl(hDiskDrive, IOCTL_STORAGE_GET_DEVICE_NUMBER, NULL, 0, deviceNumber, bufferSize, &bufferSize, NULL))
		goto error;

	// DISK_GEOMETRY_EX diskGeometry
	// Get disk geometry
	bufferSize = sizeof(DISK_GEOMETRY_EX);
	diskGeometry = (DISK_GEOMETRY_EX *) LocalAlloc(LPTR, bufferSize);
	while(!DeviceIoControl(hDiskDrive, IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, NULL, 0, diskGeometry, bufferSize, &bufferSize, NULL)) {
		if(ERROR_INSUFFICIENT_BUFFER == GetLastError()) {
			LocalFree(diskGeometry);
			bufferSize *= 2;
			diskGeometry = (DISK_GEOMETRY_EX *) LocalAlloc(LPTR, bufferSize);
		}

		else {
			goto error;
		}
	}

	// DRIVE_LAYOUT_INFORMATION_EX *diskLayout
	// Get disk layout (partitions)
	bufferSize = sizeof(DRIVE_LAYOUT_INFORMATION_EX);
	diskLayout = (DRIVE_LAYOUT_INFORMATION_EX *) LocalAlloc(LPTR,bufferSize);
	while(!DeviceIoControl(hDiskDrive, IOCTL_DISK_GET_DRIVE_LAYOUT_EX, NULL, 0, diskLayout, bufferSize, &bufferSize, NULL)) {
		if(ERROR_INSUFFICIENT_BUFFER == GetLastError()) {
			if(diskLayout)
				LocalFree(diskLayout);

			bufferSize *= 2;
			diskLayout = (DRIVE_LAYOUT_INFORMATION_EX *) LocalAlloc(LPTR, bufferSize);
		} else {
			goto error;
		}
	}
		swprintf(strBuffer, L"%d", deviceNumber->DeviceNumber);
	node_att_set(node, L"Index", strBuffer, NODE_ATT_FLAG_KEY);

	swprintf(strBuffer, L"\\\\.\\PHYSICALDRIVE%u", deviceNumber->DeviceNumber);
	node_att_set(node, L"DeviceId", strBuffer, 0);

	swprintf(strBuffer, L"%llu", diskGeometry->DiskSize.QuadPart);
	node_att_set(node, L"Size", strBuffer, 0);

	f = (diskGeometry->DiskSize.QuadPart / 1073741824);
	swprintf(strBuffer, L"%.0fGB", f);
	node_att_set(node, L"SizeGb", strBuffer, 0);

	geoNode = node_append_new(node, L"Geometry", 0);

	swprintf(strBuffer, L"%llu", diskGeometry->Geometry.Cylinders);
	node_att_set(geoNode, L"TotalCylinders", strBuffer, 0);

	q = diskGeometry->Geometry.Cylinders.QuadPart * diskGeometry->Geometry.TracksPerCylinder;
	swprintf(strBuffer, L"%llu", q);
	node_att_set(geoNode, L"TotalTracks", strBuffer, 0);

	q *= diskGeometry->Geometry.SectorsPerTrack;
	swprintf(strBuffer, L"%llu", q);
	node_att_set(geoNode, L"TotalSectors", strBuffer, 0);

	swprintf(strBuffer, L"%u", diskGeometry->Geometry.TracksPerCylinder);
	node_att_set(geoNode, L"TracksPerCylinder", strBuffer, 0);

	swprintf(strBuffer, L"%u", diskGeometry->Geometry.SectorsPerTrack);
	node_att_set(geoNode, L"SectorsPerTrack", strBuffer, 0);

	swprintf(strBuffer, L"%u", diskGeometry->Geometry.BytesPerSector);
	node_att_set(geoNode, L"BytesPerSector", strBuffer, 0);

	// Friendly name
	bufferSize = MAX_PATH + 1;
	if(SetupDiGetDeviceRegistryProperty(hDevInfo, deviceInfoData, SPDRP_FRIENDLYNAME, &dataType, (PBYTE) &strBuffer, bufferSize, &bufferSize)) {
		node_att_set(node, L"Name", strBuffer, 0);
	}

	// Device name
	bufferSize = MAX_PATH + 1;
	if(SetupDiGetDeviceRegistryProperty(hDevInfo, deviceInfoData, SPDRP_PHYSICAL_DEVICE_OBJECT_NAME, &dataType, (PBYTE) &strBuffer, bufferSize, &bufferSize)) {
		node_att_set(node, L"DosPath", strBuffer, 0);
	}

	swprintf(strBuffer, L"Win32_DiskDrive.DeviceID=\"\\\\.\\PHYSICALDRIVE%u\"", deviceNumber->DeviceNumber);
	node_att_set(node, L"WmiPath", strBuffer, 0);

	// TODO: Add first drive letter to the perf counter path
	swprintf(strBuffer, L"\\PhysicalDisk(%u)", deviceNumber->DeviceNumber);
	node_att_set(node, L"PerfCounterPath", strBuffer, 0);

	node_att_set(node, L"PnpPath", detailData->DevicePath, 0);

	// Description
	bufferSize = MAX_PATH + 1;
	if(SetupDiGetDeviceRegistryProperty(hDevInfo, deviceInfoData, SPDRP_DEVICEDESC, &dataType, (PBYTE) &strBuffer, bufferSize, &bufferSize)) {
		node_att_set(node, L"Description", strBuffer, 0);
	}

	// Get manufacturer
	bufferSize = MAX_PATH + 1;
	if(SetupDiGetDeviceRegistryProperty(hDevInfo, deviceInfoData, SPDRP_MFG, &dataType, (PBYTE) &strBuffer, bufferSize, &bufferSize)) {
		node_att_set(node, L"Manufacturer", strBuffer, 0);
	}

	if(NULL != diskLayout) {
		// Get partition style
		switch(diskLayout->PartitionStyle) {
		case PARTITION_STYLE_MBR:
			node_att_set(node, L"PartitionStyle", L"MBR", 0);
			swprintf(strBuffer, L"%u", diskLayout->Mbr.Signature);
			node_att_set(node, L"Signature", strBuffer, 0);
			swprintf(strBuffer, L"%08X", diskLayout->Mbr.Signature);
			node_att_set(node, L"SignatureHex", strBuffer, NODE_ATT_FLAG_KEY);
			break;

		case PARTITION_STYLE_GPT:
			node_att_set(node, L"PartitionStyle", L"GPT", 0);
			StringFromCLSID(diskLayout->Gpt.DiskId, &oleBuffer);
			node_att_set(node, L"Guid", oleBuffer, NODE_ATT_FLAG_KEY);
			CoTaskMemFree(oleBuffer);
			break;

		case PARTITION_STYLE_RAW:
			node_att_set(node, L"PartitionStyle", L"RAW", 0);
			break;
		}

		// Get partition info
		partsNode = node_append_new(node, L"Partitions", NODE_FLAG_TABLE);
		for(i = 0; i < diskLayout->PartitionCount; i++) {
			// Ignore '0' partition placeholders
			if(diskLayout->PartitionEntry[i].PartitionNumber > 0) {
				partCount++;
				partNode = node_append_new(partsNode, L"Partition", NODE_FLAG_TABLE_ENTRY);
				swprintf(strBuffer, L"%d", diskLayout->PartitionEntry[i].PartitionNumber);
				node_att_set(partNode, L"Number", strBuffer, NODE_ATT_FLAG_KEY);
				swprintf(strBuffer, L"%llu", diskLayout->PartitionEntry[i].StartingOffset.QuadPart);
				node_att_set(partNode, L"StartOffset", strBuffer, 0);
				swprintf(strBuffer, L"0x%llX", diskLayout->PartitionEntry[i].StartingOffset.QuadPart);
				node_att_set(partNode, L"StartOffsetHex", strBuffer, 0);
				swprintf(strBuffer, L"%llu", diskLayout->PartitionEntry[i].PartitionLength.QuadPart);
				node_att_set(partNode, L"Length", strBuffer, 0);
				f = (diskLayout->PartitionEntry[i].PartitionLength.QuadPart / 1073741824);
				swprintf(strBuffer, L"%.0fGB", f);
				node_att_set(partNode, L"LengthGb", strBuffer, 0);
			}
		}

		// Get partition count
		swprintf(strBuffer, L"%d", partCount);
		node_att_set(node, L"PartitionCount", strBuffer, 0);
	}

	// Finalise node result
	node_append_child(parent, node);
	goto cleanup;

error:
	free(node);
	node = NULL;

cleanup:
	if(INVALID_HANDLE_VALUE != hDiskDrive)
		CloseHandle(hDiskDrive);

	if(NULL != deviceInfoData)
		LocalFree(deviceInfoData);

	if(NULL != interfaceData)
		LocalFree(interfaceData);

	if(NULL != detailData)
		LocalFree(detailData);

	if(NULL != diskGeometry)
		LocalFree(diskGeometry);

	if(NULL != diskLayout)
		LocalFree(diskLayout);

	return node;
}<commit_msg>Extended WMI path of disks<commit_after>#include "stdafx.h"
#include "sysinv.h"

PNODE GetDiskNode(__in PNODE parent, HDEVINFO hDevInfo, DWORD index);

PNODE GetDisksNode()
{
	HDEVINFO hDevInfo;
	SP_DEVINFO_DATA *deviceInfoData = NULL;
	SP_DEVICE_INTERFACE_DATA *interfaceData = NULL;
	SP_INTERFACE_DEVICE_DETAIL_DATA *detailData = NULL;
	DWORD index = 0;

	// Get device info handle
	hDevInfo = SetupDiGetClassDevs(&GUID_DEVINTERFACE_DISK, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
	if(INVALID_HANDLE_VALUE == hDevInfo)
		return NULL;

	PNODE node = node_alloc(L"Disks", NODE_FLAG_TABLE);
	while(NULL != GetDiskNode(node, hDevInfo, index++))
	{}

	return node;
}

PNODE GetDiskNode(__in PNODE parent, HDEVINFO hDevInfo, DWORD index)
{
	PNODE node = NULL, geoNode = NULL, partsNode = NULL, partNode = NULL;
	TCHAR strBuffer[MAX_PATH + 1];
	LPOLESTR oleBuffer;
	DWORD bufferSize = 0, i = 0, dataType = 0, partCount = 0;
	FLOAT f;
	LONGLONG q;

	SP_DEVINFO_DATA *deviceInfoData = NULL;
	SP_DEVICE_INTERFACE_DATA *interfaceData = NULL;
	SP_INTERFACE_DEVICE_DETAIL_DATA *detailData = NULL;
	HANDLE hDiskDrive = INVALID_HANDLE_VALUE;
	STORAGE_DEVICE_NUMBER *deviceNumber = NULL;
	DRIVE_LAYOUT_INFORMATION_EX *diskLayout = NULL;
	DISK_GEOMETRY_EX *diskGeometry = NULL;

	// Create return node
	node = node_alloc(L"Disk", NODE_FLAG_TABLE_ENTRY);

	// SP_DEVINFO_DATA *deviceInfoData
	// Get device info (used for getting device properties from the registry)
	deviceInfoData = (SP_DEVINFO_DATA *) LocalAlloc(LPTR, sizeof(SP_DEVINFO_DATA));
	deviceInfoData->cbSize = sizeof(SP_DEVINFO_DATA);
	if(!SetupDiEnumDeviceInfo(hDevInfo, index, deviceInfoData))
		goto error;

	// SP_DEVICE_INTERFACE_DATA *interfaceData
	// Get device interface data (used to get interface details)
	interfaceData = (SP_DEVICE_INTERFACE_DATA *) LocalAlloc(LPTR, sizeof(SP_DEVICE_INTERFACE_DATA));
	interfaceData->cbSize = sizeof(SP_INTERFACE_DEVICE_DATA);
	if(!SetupDiEnumInterfaceDevice(hDevInfo, NULL, &GUID_DEVINTERFACE_DISK, index, interfaceData))
		goto error;

	// SP_INTERFACE_DEVICE_DETAIL_DATA* detailData;
	// Get device interface details (used to get device path and subsequently, file handle)
	SetupDiGetDeviceInterfaceDetail(hDevInfo, interfaceData, NULL, NULL, &bufferSize, NULL);
	detailData = (SP_INTERFACE_DEVICE_DETAIL_DATA*) malloc(bufferSize);
	detailData->cbSize = sizeof(SP_INTERFACE_DEVICE_DETAIL_DATA);
	if (!SetupDiGetDeviceInterfaceDetail(hDevInfo, interfaceData, detailData, bufferSize, NULL, NULL))
		goto error;

	// HANDLE hDiskDrive
	// Get a file handle to the disk
	hDiskDrive = CreateFile(detailData->DevicePath, 0, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
	if(INVALID_HANDLE_VALUE == hDiskDrive)
		goto error;

	// STORAGE_DEVICE_NUMBER deviceNumber;
	// Get disk index number
	bufferSize = sizeof(STORAGE_DEVICE_NUMBER);
	deviceNumber = (STORAGE_DEVICE_NUMBER *) LocalAlloc(LPTR, bufferSize);
	if(!DeviceIoControl(hDiskDrive, IOCTL_STORAGE_GET_DEVICE_NUMBER, NULL, 0, deviceNumber, bufferSize, &bufferSize, NULL))
		goto error;

	// DISK_GEOMETRY_EX diskGeometry
	// Get disk geometry
	bufferSize = sizeof(DISK_GEOMETRY_EX);
	diskGeometry = (DISK_GEOMETRY_EX *) LocalAlloc(LPTR, bufferSize);
	while(!DeviceIoControl(hDiskDrive, IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, NULL, 0, diskGeometry, bufferSize, &bufferSize, NULL)) {
		if(ERROR_INSUFFICIENT_BUFFER == GetLastError()) {
			LocalFree(diskGeometry);
			bufferSize *= 2;
			diskGeometry = (DISK_GEOMETRY_EX *) LocalAlloc(LPTR, bufferSize);
		}

		else {
			goto error;
		}
	}

	// DRIVE_LAYOUT_INFORMATION_EX *diskLayout
	// Get disk layout (partitions)
	bufferSize = sizeof(DRIVE_LAYOUT_INFORMATION_EX);
	diskLayout = (DRIVE_LAYOUT_INFORMATION_EX *) LocalAlloc(LPTR,bufferSize);
	while(!DeviceIoControl(hDiskDrive, IOCTL_DISK_GET_DRIVE_LAYOUT_EX, NULL, 0, diskLayout, bufferSize, &bufferSize, NULL)) {
		if(ERROR_INSUFFICIENT_BUFFER == GetLastError()) {
			if(diskLayout)
				LocalFree(diskLayout);

			bufferSize *= 2;
			diskLayout = (DRIVE_LAYOUT_INFORMATION_EX *) LocalAlloc(LPTR, bufferSize);
		} else {
			goto error;
		}
	}
		swprintf(strBuffer, L"%d", deviceNumber->DeviceNumber);
	node_att_set(node, L"Index", strBuffer, NODE_ATT_FLAG_KEY);

	swprintf(strBuffer, L"\\\\.\\PHYSICALDRIVE%u", deviceNumber->DeviceNumber);
	node_att_set(node, L"DeviceId", strBuffer, 0);

	swprintf(strBuffer, L"%llu", diskGeometry->DiskSize.QuadPart);
	node_att_set(node, L"Size", strBuffer, 0);

	f = (diskGeometry->DiskSize.QuadPart / 1073741824);
	swprintf(strBuffer, L"%.0fGB", f);
	node_att_set(node, L"SizeGb", strBuffer, 0);

	geoNode = node_append_new(node, L"Geometry", 0);

	swprintf(strBuffer, L"%llu", diskGeometry->Geometry.Cylinders);
	node_att_set(geoNode, L"TotalCylinders", strBuffer, 0);

	q = diskGeometry->Geometry.Cylinders.QuadPart * diskGeometry->Geometry.TracksPerCylinder;
	swprintf(strBuffer, L"%llu", q);
	node_att_set(geoNode, L"TotalTracks", strBuffer, 0);

	q *= diskGeometry->Geometry.SectorsPerTrack;
	swprintf(strBuffer, L"%llu", q);
	node_att_set(geoNode, L"TotalSectors", strBuffer, 0);

	swprintf(strBuffer, L"%u", diskGeometry->Geometry.TracksPerCylinder);
	node_att_set(geoNode, L"TracksPerCylinder", strBuffer, 0);

	swprintf(strBuffer, L"%u", diskGeometry->Geometry.SectorsPerTrack);
	node_att_set(geoNode, L"SectorsPerTrack", strBuffer, 0);

	swprintf(strBuffer, L"%u", diskGeometry->Geometry.BytesPerSector);
	node_att_set(geoNode, L"BytesPerSector", strBuffer, 0);

	// Friendly name
	bufferSize = MAX_PATH + 1;
	if(SetupDiGetDeviceRegistryProperty(hDevInfo, deviceInfoData, SPDRP_FRIENDLYNAME, &dataType, (PBYTE) &strBuffer, bufferSize, &bufferSize)) {
		node_att_set(node, L"Name", strBuffer, 0);
	}

	// Device name
	bufferSize = MAX_PATH + 1;
	if(SetupDiGetDeviceRegistryProperty(hDevInfo, deviceInfoData, SPDRP_PHYSICAL_DEVICE_OBJECT_NAME, &dataType, (PBYTE) &strBuffer, bufferSize, &bufferSize)) {
		node_att_set(node, L"DosPath", strBuffer, 0);
	}

	swprintf(strBuffer, L"\\\\.\\ROOT\\CIMV2:Win32_DiskDrive.DeviceID=\"\\\\\\\\.\\\\PHYSICALDRIVE%u\"", deviceNumber->DeviceNumber);
	node_att_set(node, L"WmiPath", strBuffer, 0);

	// TODO: Add first drive letter to the perf counter path
	swprintf(strBuffer, L"\\PhysicalDisk(%u)", deviceNumber->DeviceNumber);
	node_att_set(node, L"PerfCounterPath", strBuffer, 0);

	node_att_set(node, L"PnpPath", detailData->DevicePath, 0);

	// Description
	bufferSize = MAX_PATH + 1;
	if(SetupDiGetDeviceRegistryProperty(hDevInfo, deviceInfoData, SPDRP_DEVICEDESC, &dataType, (PBYTE) &strBuffer, bufferSize, &bufferSize)) {
		node_att_set(node, L"Description", strBuffer, 0);
	}

	// Get manufacturer
	bufferSize = MAX_PATH + 1;
	if(SetupDiGetDeviceRegistryProperty(hDevInfo, deviceInfoData, SPDRP_MFG, &dataType, (PBYTE) &strBuffer, bufferSize, &bufferSize)) {
		node_att_set(node, L"Manufacturer", strBuffer, 0);
	}

	if(NULL != diskLayout) {
		// Get partition style
		switch(diskLayout->PartitionStyle) {
		case PARTITION_STYLE_MBR:
			node_att_set(node, L"PartitionStyle", L"MBR", 0);
			swprintf(strBuffer, L"%u", diskLayout->Mbr.Signature);
			node_att_set(node, L"Signature", strBuffer, 0);
			swprintf(strBuffer, L"%08X", diskLayout->Mbr.Signature);
			node_att_set(node, L"SignatureHex", strBuffer, NODE_ATT_FLAG_KEY);
			break;

		case PARTITION_STYLE_GPT:
			node_att_set(node, L"PartitionStyle", L"GPT", 0);
			StringFromCLSID(diskLayout->Gpt.DiskId, &oleBuffer);
			node_att_set(node, L"Guid", oleBuffer, NODE_ATT_FLAG_KEY);
			CoTaskMemFree(oleBuffer);
			break;

		case PARTITION_STYLE_RAW:
			node_att_set(node, L"PartitionStyle", L"RAW", 0);
			break;
		}

		// Get partition info
		partsNode = node_append_new(node, L"Partitions", NODE_FLAG_TABLE);
		for(i = 0; i < diskLayout->PartitionCount; i++) {
			// Ignore '0' partition placeholders
			if(diskLayout->PartitionEntry[i].PartitionNumber > 0) {
				partCount++;
				partNode = node_append_new(partsNode, L"Partition", NODE_FLAG_TABLE_ENTRY);
				swprintf(strBuffer, L"%d", diskLayout->PartitionEntry[i].PartitionNumber);
				node_att_set(partNode, L"Number", strBuffer, NODE_ATT_FLAG_KEY);
				swprintf(strBuffer, L"%llu", diskLayout->PartitionEntry[i].StartingOffset.QuadPart);
				node_att_set(partNode, L"StartOffset", strBuffer, 0);
				swprintf(strBuffer, L"0x%llX", diskLayout->PartitionEntry[i].StartingOffset.QuadPart);
				node_att_set(partNode, L"StartOffsetHex", strBuffer, 0);
				swprintf(strBuffer, L"%llu", diskLayout->PartitionEntry[i].PartitionLength.QuadPart);
				node_att_set(partNode, L"Length", strBuffer, 0);
				f = (diskLayout->PartitionEntry[i].PartitionLength.QuadPart / 1073741824);
				swprintf(strBuffer, L"%.0fGB", f);
				node_att_set(partNode, L"LengthGb", strBuffer, 0);
			}
		}

		// Get partition count
		swprintf(strBuffer, L"%d", partCount);
		node_att_set(node, L"PartitionCount", strBuffer, 0);
	}

	// Finalise node result
	node_append_child(parent, node);
	goto cleanup;

error:
	free(node);
	node = NULL;

cleanup:
	if(INVALID_HANDLE_VALUE != hDiskDrive)
		CloseHandle(hDiskDrive);

	if(NULL != deviceInfoData)
		LocalFree(deviceInfoData);

	if(NULL != interfaceData)
		LocalFree(interfaceData);

	if(NULL != detailData)
		LocalFree(detailData);

	if(NULL != diskGeometry)
		LocalFree(diskGeometry);

	if(NULL != diskLayout)
		LocalFree(diskLayout);

	return node;
}<|endoftext|>


<commit_before>//
// Aspia Project
// Copyright (C) 2019 Dmitry Chapyshev <dmitry@aspia.ru>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//

#include "base/win/scoped_impersonator.h"

#include "base/logging.h"

namespace base::win {

ScopedImpersonator::ScopedImpersonator()
{
    DETACH_FROM_THREAD(thread_checker_);
}

ScopedImpersonator::~ScopedImpersonator()
{
    revertToSelf();
}

bool ScopedImpersonator::loggedOnUser(HANDLE user_token)
{
    DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);

    if (!ImpersonateLoggedOnUser(user_token))
    {
        PLOG(LS_ERROR) << "ImpersonateLoggedOnUser failed";
        return false;
    }

    impersonated_ = true;
    return true;
}

bool ScopedImpersonator::anonymous()
{
    DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);

    if (!ImpersonateAnonymousToken(GetCurrentThread()))
    {
        PLOG(LS_ERROR) << "ImpersonateAnonymousToken failed";
        return false;
    }

    impersonated_ = true;
    return true;
}

bool ScopedImpersonator::namedPipeClient(HANDLE named_pipe)
{
    DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);

    if (!ImpersonateNamedPipeClient(named_pipe))
    {
        PLOG(LS_ERROR) << "ImpersonateNamedPipeClient failed";
        return false;
    }

    impersonated_ = true;
    return true;
}

void ScopedImpersonator::revertToSelf()
{
    DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);

    if (!impersonated_)
        return;

    BOOL ret = RevertToSelf();
    CHECK(ret);

    impersonated_ = false;
}

} // namespace base::win
<commit_msg>- Remove unneeded DETACH_FROM_THREAD.<commit_after>//
// Aspia Project
// Copyright (C) 2019 Dmitry Chapyshev <dmitry@aspia.ru>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//

#include "base/win/scoped_impersonator.h"

#include "base/logging.h"

namespace base::win {

ScopedImpersonator::ScopedImpersonator()
{
    // Nothing
}

ScopedImpersonator::~ScopedImpersonator()
{
    revertToSelf();
}

bool ScopedImpersonator::loggedOnUser(HANDLE user_token)
{
    DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);

    if (!ImpersonateLoggedOnUser(user_token))
    {
        PLOG(LS_ERROR) << "ImpersonateLoggedOnUser failed";
        return false;
    }

    impersonated_ = true;
    return true;
}

bool ScopedImpersonator::anonymous()
{
    DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);

    if (!ImpersonateAnonymousToken(GetCurrentThread()))
    {
        PLOG(LS_ERROR) << "ImpersonateAnonymousToken failed";
        return false;
    }

    impersonated_ = true;
    return true;
}

bool ScopedImpersonator::namedPipeClient(HANDLE named_pipe)
{
    DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);

    if (!ImpersonateNamedPipeClient(named_pipe))
    {
        PLOG(LS_ERROR) << "ImpersonateNamedPipeClient failed";
        return false;
    }

    impersonated_ = true;
    return true;
}

void ScopedImpersonator::revertToSelf()
{
    DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);

    if (!impersonated_)
        return;

    BOOL ret = RevertToSelf();
    CHECK(ret);

    impersonated_ = false;
}

} // namespace base::win
<|endoftext|>


<commit_before>#include <set>
#include <cstdlib>

#include <unsupported/Eigen/SparseExtra>

#include "utils.h"
#include "matrix_io.h"

const static Eigen::IOFormat csvFormat(6, Eigen::DontAlignCols, ",", "\n");

void writeToCSVfile(std::string filename, Eigen::MatrixXd matrix) {
  std::ofstream file(filename.c_str());
  file << matrix.rows() << std::endl;
  file << matrix.cols() << std::endl;
  file << matrix.format(csvFormat);
}

void readFromCSVfile(std::string filename, Eigen::MatrixXd &matrix) {
    std::ifstream file(filename.c_str());
    std::string line;

    // rows and cols
    getline(file, line);
    int nrow = atol(line.c_str());
    getline(file, line);
    int ncol = atol(line.c_str());
    matrix.resize(nrow, ncol);

    while (getline(file, line)) {
        std::stringstream lineStream(line);
        std::string cell;
        while (std::getline(lineStream, cell, ',')) matrix << strtod(cell.c_str(), NULL);
    }
}

std::unique_ptr<SparseFeat> load_bcsr(const char* filename) {
   SparseBinaryMatrix* A = read_sbm(filename);
   SparseFeat* sf = new SparseFeat(A->nrow, A->ncol, A->nnz, A->rows, A->cols);
   free_sbm(A);
   std::unique_ptr<SparseFeat> sf_ptr(sf);
   return sf_ptr;
}

std::unique_ptr<SparseDoubleFeat> load_csr(const char* filename) {

    struct SparseDoubleMatrix* A = read_sdm(filename);
    SparseDoubleFeat* sf = new SparseDoubleFeat(A->nrow, A->ncol, A->nnz, A->rows, A->cols, A->vals);
    delete A;
    std::unique_ptr<SparseDoubleFeat> sf_ptr(sf);
    return sf_ptr;
}

Eigen::MatrixXd sparse_to_dense(SparseBinaryMatrix &in)
{
    Eigen::MatrixXd out = Eigen::MatrixXd::Zero(in.nrow, in.ncol);
    for(int i=0; i<in.nnz; ++i) out(in.rows[i], in.cols[i]) = 1.;
    return out;
}

Eigen::MatrixXd sparse_to_dense(SparseDoubleMatrix &in)
{
    Eigen::MatrixXd out = Eigen::MatrixXd::Zero(in.nrow, in.ncol);
    for(int i=0; i<in.nnz; ++i) out(in.rows[i], in.cols[i]) = in.vals[i];
    return out;
}

static std::set<std::string> compact_matrix_fname_extensions = { ".sbm", ".sdm", ".ddm" };
static std::set<std::string> txt_matrix_fname_extensions = { ".mtx", ".mm", ".csv" };
static std::set<std::string> matrix_fname_extensions = { ".sbm", ".sdm", ".ddm", ".mtx", ".mm", ".csv" };
static std::set<std::string> sparse_fname_extensions = { ".sbm", ".sdm", ".mtx", ".mm" };

bool extension_in(std::string fname, const std::set<std::string> &extensions, bool = false);

bool is_matrix_fname(std::string fname) {
    return extension_in(fname, matrix_fname_extensions);
}

bool extension_in(std::string fname, const std::set<std::string> &extensions, bool die_if_not_found)
{
    std::string extension = fname.substr(fname.find_last_of("."));
    if (extensions.find(extension) != extensions.end()) return true;
    if (die_if_not_found) {
          die("Unknown extension: " + extension + " of filename: " + fname);
    }
    return false;
}

bool is_sparse_fname(std::string fname) {
    return extension_in(fname, sparse_fname_extensions);
}

bool is_sparse_binary_fname(std::string fname) {
    return extension_in(fname, { ".sbm" });
}

bool is_dense_fname(std::string fname) {
    return !is_sparse_fname(fname);
}

bool is_compact_fname(std::string fname) {
    return file_exists(fname) && extension_in(fname, compact_matrix_fname_extensions);
}

void read_dense(std::string fname, Eigen::VectorXd &V) {
   Eigen::MatrixXd X;
   read_dense(fname, X);
   V = X; // this will fail if X has more than one column
}

void read_dense(std::string fname, Eigen::MatrixXd &X) {
    die_unless_file_exists(fname);
    std::string extension = fname.substr(fname.size() - 4);
    if (extension == ".ddm") {
        read_ddm(fname.c_str(), X);
    } else if (extension == ".csv") {
        readFromCSVfile(fname, X);
    } else {
        die("Unknown filename in read_dense: " + fname);
    }
}

void write_dense(std::string fname, const Eigen::MatrixXd &X) {
    assert(is_dense_fname(fname));
    std::string extension = fname.substr(fname.size() - 4);
    if (extension == ".ddm") {
        write_ddm(fname.c_str(), X);
    } else if (extension == ".csv") {
        writeToCSVfile(fname, X);
    } else {
        die("Unknown filename in write_dense: " + fname);
    }
}

void write_ddm(std::string filename, const Eigen::MatrixXd& matrix) {
    std::ofstream out(filename,std::ios::out | std::ios::binary | std::ios::trunc);
    long rows = matrix.rows();
    long cols = matrix.cols();
    out.write((char*) (&rows), sizeof(long));
    out.write((char*) (&cols), sizeof(long));
    out.write((char*) matrix.data(), rows*cols*sizeof(typename Eigen::MatrixXd::Scalar) );
    out.close();
}

void read_ddm(std::string filename, Eigen::MatrixXd &matrix) {
    std::ifstream in(filename,std::ios::in | std::ios::binary);
    long rows=0, cols=0;
    in.read((char*) (&rows),sizeof(long));
    in.read((char*) (&cols),sizeof(long));
    matrix.resize(rows, cols);
    in.read( (char *) matrix.data() , rows*cols*sizeof(long) );
    in.close();
}

void read_sparse(std::string fname, Eigen::SparseMatrix<double> &M) {
    assert(is_sparse_fname(fname));
    std::string extension = fname.substr(fname.find_last_of("."));
    if (extension == ".sdm") {
        auto sdm_ptr = read_sdm(fname.c_str());
        M = to_eigen(*sdm_ptr);
        delete sdm_ptr;
    } else if (extension == ".sbm") {
        auto sbm_ptr = read_sbm(fname.c_str());
        M = to_eigen(*sbm_ptr);
        delete sbm_ptr;
    } else if (extension == ".mtx" || extension == ".mm") {
        loadMarket(M, fname.c_str());
    } else  {
        die("Unknown filename in read_sparse: " + fname);
    }
}
<commit_msg>Finished adding ::restore functionality<commit_after>#include <set>
#include <cstdlib>

#include <unsupported/Eigen/SparseExtra>

#include "utils.h"
#include "matrix_io.h"

const static Eigen::IOFormat csvFormat(6, Eigen::DontAlignCols, ",", "\n");

void writeToCSVfile(std::string filename, Eigen::MatrixXd matrix) {
  std::ofstream file(filename.c_str());
  file << matrix.rows() << std::endl;
  file << matrix.cols() << std::endl;
  file << matrix.format(csvFormat);
}

void readFromCSVfile(std::string filename, Eigen::MatrixXd &matrix) {
    std::ifstream file(filename.c_str());
    std::string line;

    // rows and cols
    getline(file, line);
    int nrow = atol(line.c_str());
    getline(file, line);
    int ncol = atol(line.c_str());
    matrix.resize(nrow, ncol);
    int pos = 0;

    while (getline(file, line)) {
        std::stringstream lineStream(line);
        std::string cell;
        while (std::getline(lineStream, cell, ',')) {
            matrix.data()[pos++] = strtod(cell.c_str(), NULL);
        }
    }
    assert(pos == nrow*ncol);
}

std::unique_ptr<SparseFeat> load_bcsr(const char* filename) {
   SparseBinaryMatrix* A = read_sbm(filename);
   SparseFeat* sf = new SparseFeat(A->nrow, A->ncol, A->nnz, A->rows, A->cols);
   free_sbm(A);
   std::unique_ptr<SparseFeat> sf_ptr(sf);
   return sf_ptr;
}

std::unique_ptr<SparseDoubleFeat> load_csr(const char* filename) {

    struct SparseDoubleMatrix* A = read_sdm(filename);
    SparseDoubleFeat* sf = new SparseDoubleFeat(A->nrow, A->ncol, A->nnz, A->rows, A->cols, A->vals);
    delete A;
    std::unique_ptr<SparseDoubleFeat> sf_ptr(sf);
    return sf_ptr;
}

Eigen::MatrixXd sparse_to_dense(SparseBinaryMatrix &in)
{
    Eigen::MatrixXd out = Eigen::MatrixXd::Zero(in.nrow, in.ncol);
    for(int i=0; i<in.nnz; ++i) out(in.rows[i], in.cols[i]) = 1.;
    return out;
}

Eigen::MatrixXd sparse_to_dense(SparseDoubleMatrix &in)
{
    Eigen::MatrixXd out = Eigen::MatrixXd::Zero(in.nrow, in.ncol);
    for(int i=0; i<in.nnz; ++i) out(in.rows[i], in.cols[i]) = in.vals[i];
    return out;
}

static std::set<std::string> compact_matrix_fname_extensions = { ".sbm", ".sdm", ".ddm" };
static std::set<std::string> txt_matrix_fname_extensions = { ".mtx", ".mm", ".csv" };
static std::set<std::string> matrix_fname_extensions = { ".sbm", ".sdm", ".ddm", ".mtx", ".mm", ".csv" };
static std::set<std::string> sparse_fname_extensions = { ".sbm", ".sdm", ".mtx", ".mm" };

bool extension_in(std::string fname, const std::set<std::string> &extensions, bool = false);

bool is_matrix_fname(std::string fname) {
    return extension_in(fname, matrix_fname_extensions);
}

bool extension_in(std::string fname, const std::set<std::string> &extensions, bool die_if_not_found)
{
    std::string extension = fname.substr(fname.find_last_of("."));
    if (extensions.find(extension) != extensions.end()) return true;
    if (die_if_not_found) {
          die("Unknown extension: " + extension + " of filename: " + fname);
    }
    return false;
}

bool is_sparse_fname(std::string fname) {
    return extension_in(fname, sparse_fname_extensions);
}

bool is_sparse_binary_fname(std::string fname) {
    return extension_in(fname, { ".sbm" });
}

bool is_dense_fname(std::string fname) {
    return !is_sparse_fname(fname);
}

bool is_compact_fname(std::string fname) {
    return file_exists(fname) && extension_in(fname, compact_matrix_fname_extensions);
}

void read_dense(std::string fname, Eigen::VectorXd &V) {
   Eigen::MatrixXd X;
   read_dense(fname, X);
   V = X; // this will fail if X has more than one column
}

void read_dense(std::string fname, Eigen::MatrixXd &X) {
    die_unless_file_exists(fname);
    std::string extension = fname.substr(fname.size() - 4);
    if (extension == ".ddm") {
        read_ddm(fname.c_str(), X);
    } else if (extension == ".csv") {
        readFromCSVfile(fname, X);
    } else {
        die("Unknown filename in read_dense: " + fname);
    }
}

void write_dense(std::string fname, const Eigen::MatrixXd &X) {
    assert(is_dense_fname(fname));
    std::string extension = fname.substr(fname.size() - 4);
    if (extension == ".ddm") {
        write_ddm(fname.c_str(), X);
    } else if (extension == ".csv") {
        writeToCSVfile(fname, X);
    } else {
        die("Unknown filename in write_dense: " + fname);
    }
}

void write_ddm(std::string filename, const Eigen::MatrixXd& matrix) {
    std::ofstream out(filename,std::ios::out | std::ios::binary | std::ios::trunc);
    long rows = matrix.rows();
    long cols = matrix.cols();
    out.write((char*) (&rows), sizeof(long));
    out.write((char*) (&cols), sizeof(long));
    out.write((char*) matrix.data(), rows*cols*sizeof(typename Eigen::MatrixXd::Scalar) );
    out.close();
}

void read_ddm(std::string filename, Eigen::MatrixXd &matrix) {
    std::ifstream in(filename,std::ios::in | std::ios::binary);
    long rows=0, cols=0;
    in.read((char*) (&rows),sizeof(long));
    in.read((char*) (&cols),sizeof(long));
    matrix.resize(rows, cols);
    in.read( (char *) matrix.data() , rows*cols*sizeof(long) );
    in.close();
}

void read_sparse(std::string fname, Eigen::SparseMatrix<double> &M) {
    assert(is_sparse_fname(fname));
    std::string extension = fname.substr(fname.find_last_of("."));
    if (extension == ".sdm") {
        auto sdm_ptr = read_sdm(fname.c_str());
        M = to_eigen(*sdm_ptr);
        delete sdm_ptr;
    } else if (extension == ".sbm") {
        auto sbm_ptr = read_sbm(fname.c_str());
        M = to_eigen(*sbm_ptr);
        delete sbm_ptr;
    } else if (extension == ".mtx" || extension == ".mm") {
        loadMarket(M, fname.c_str());
    } else  {
        die("Unknown filename in read_sparse: " + fname);
    }
}
<|endoftext|>


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

#ifndef SC_SPELLENG_HXX
#define SC_SPELLENG_HXX

#include "editutil.hxx"

class ScViewData;
class ScDocShell;
class ScDocument;
class SfxItemPool;

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

/** Base class for special type of edit engines, i.e. for spell checker and text conversion. */
class ScConversionEngineBase : public ScEditEngineDefaulter
{
public:
    explicit                ScConversionEngineBase(
                                SfxItemPool* pEnginePool,
                                ScViewData& rViewData,
                                ScDocument* pUndoDoc,
                                ScDocument* pRedoDoc,
                                ESelection* pEdSelection,
                                SCCOL nCol, SCROW nRow, SCTAB nTab,
                                bool bCellSelection );

    virtual                 ~ScConversionEngineBase();

    /** Derived classes implement to convert all cells in the selection or sheet. */
    virtual void            ConvertAll( EditView& rEditView ) = 0;

    /** Returns true, if at least one cell has been modified. */
    inline bool             IsAnyModified() const { return mbIsAnyModified; }

protected:
    /** Implementation of cell iteration. Finds a cell that needs conversion.
        @return  true = Current cell needs conversion (i.e. spelling error found). */
    bool                    FindNextConversionCell();

    /** Derived classes return, if the current text needs conversion (i.e. spelling error found).
        @return  true = Current edit text needs conversion. */
    virtual bool            NeedsConversion() = 0;

    /** Derived classes may show a query box that asks whether to restart at top of the sheet.
        @descr  Default here is no dialog and restart always.
        @return  true = Restart at top, false = Stop the conversion. */
    virtual bool            ShowTableWrapDialog();
    /** Derived classes may show a message box stating that the conversion is finished.
        @descr  Default here is no dialog. */
    virtual void            ShowFinishDialog();

private:
    /** Fills the edit engine from a document cell. */
    void                    FillFromCell( SCCOL nCol, SCROW nRow, SCTAB nTab );

protected:  // for usage in derived classes
    ScViewData&             mrViewData;
    ScDocShell&             mrDocShell;
    ScDocument&             mrDoc;

private:
    ScDocument*             mpUndoDoc;          /// Document stores all old cells for UNDO action.
    ScDocument*             mpRedoDoc;          /// Document stores all new cells for REDO action.
    ESelection*             mpEditSel;          /// Cell selection from edit mode or NULL.
    LanguageType            meCurrLang;         /// Current cell language.
    SCCOL                   mnStartCol;         /// Initial column index.
    SCROW                   mnStartRow;         /// Initial row index.
    SCTAB                   mnStartTab;         /// Initial sheet index.
    SCCOL                   mnCurrCol;          /// Current column index.
    SCROW                   mnCurrRow;          /// Current row index.
    bool                    mbCellSelect;       /// true = Cell selection; false = Entire sheet.
    bool                    mbIsAnyModified;    /// true = At least one cell has been changed.
    bool                    mbInitialState;     /// true = Not searched for a cell yet.
    bool                    mbWrappedInTable;   /// true = Already restarted at top of the sheet.
};

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

/** Edit engine for spell checking. */
class ScSpellingEngine : public ScConversionEngineBase
{
public:
    typedef ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XSpellChecker1 > XSpellCheckerRef;

    explicit                ScSpellingEngine(
                                SfxItemPool* pEnginePool,
                                ScViewData& rViewData,
                                ScDocument* pUndoDoc,
                                ScDocument* pRedoDoc,
                                ESelection* pEdSelection,
                                SCCOL nCol, SCROW nRow, SCTAB nTab,
                                bool bCellSelection,
                                XSpellCheckerRef xSpeller );

    /** Checks spelling of all cells in the selection or sheet. */
    virtual void            ConvertAll( EditView& rEditView );

protected:
    /** Callback from edit engine to check the next cell. */
    virtual BOOL            SpellNextDocument();

    /** Returns true, if the current text contains a spelling error. */
    virtual bool            NeedsConversion();

    /** Show a query box that asks whether to restart at top of the sheet.
        @return  true = Restart at top, false = Stop the conversion. */
    virtual bool            ShowTableWrapDialog();
    /** Show a message box stating that spell checking is finished. */
    virtual void            ShowFinishDialog();
};

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

/** Edit engine for text conversion. */
class ScTextConversionEngine : public ScConversionEngineBase
{
public:
    explicit                ScTextConversionEngine(
                                SfxItemPool* pEnginePool,
                                ScViewData& rViewData,
                                ScDocument* pUndoDoc,
                                ScDocument* pRedoDoc,
                                ESelection* pEdSelection,
                                SCCOL nCol, SCROW nRow, SCTAB nTab,
                                bool bCellSelection,
                                LanguageType eSourceLanguage,   // source language for conversion
                                LanguageType eTargetLanguage,   // target language for conversion
                                const Font *pTargetFont,        // target font to be used if language has to be changed
                                sal_Int32 nOptions,             // misc conversion flags
                                sal_Bool bIsInteractive         // textconversiob has (specific) dialog that may be raised
                            );

    /** Converts all cells in the selection or sheet according to set language. */
    virtual void            ConvertAll( EditView& rEditView );

protected:
    /** Callback from edit engine to convert the next cell. */
    virtual BOOL            ConvertNextDocument();

    /** Returns true, if the current text contains text to convert. */
    virtual bool            NeedsConversion();

private:
    LanguageType    meSourceLang;       // source language for conversion
    LanguageType    meTargetLang;       // target language for conversion
    const Font *    mpTargetFont;       // target font to be used if language has to be changed
    sal_Int32       mnOptions;          // misc conversion flags
    sal_Bool        mbIsInteractive;    // textconversiob has (specific) dialog that may be raised
};

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

#endif

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

#ifndef SC_SPELLENG_HXX
#define SC_SPELLENG_HXX

#include "editutil.hxx"

#ifndef SC_SELECTIONSTATE_HXX
#include "selectionstate.hxx"
#endif

class ScViewData;
class ScDocShell;
class ScDocument;
class SfxItemPool;

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

/** Base class for special type of edit engines, i.e. for spell checker and text conversion. */
class ScConversionEngineBase : public ScEditEngineDefaulter
{
public:
    explicit                ScConversionEngineBase(
                                SfxItemPool* pEnginePool, ScViewData& rViewData,
                                ScDocument* pUndoDoc, ScDocument* pRedoDoc );

    virtual                 ~ScConversionEngineBase();

    /** Derived classes implement to convert all cells in the selection or sheet. */
    virtual void            ConvertAll( EditView& rEditView ) = 0;

    /** Returns true, if at least one cell has been modified. */
    inline bool             IsAnyModified() const { return mbIsAnyModified; }
    /** Returns true, if the entire document/selection has been finished. */
    inline bool             IsFinished() const { return mbFinished; }

protected:
    /** Implementation of cell iteration. Finds a cell that needs conversion.
        @return  true = Current cell needs conversion (i.e. spelling error found). */
    bool                    FindNextConversionCell();

    /** Derived classes return, if the current text needs conversion (i.e. spelling error found).
        @return  true = Current edit text needs conversion. */
    virtual bool            NeedsConversion() = 0;

    /** Derived classes may show a query box that asks whether to restart at top of the sheet.
        @descr  Default here is no dialog and restart always.
        @return  true = Restart at top, false = Stop the conversion. */
    virtual bool            ShowTableWrapDialog();
    /** Derived classes may show a message box stating that the conversion is finished.
        @descr  Default here is no dialog. */
    virtual void            ShowFinishDialog();

private:
    /** Fills the edit engine from a document cell. */
    void                    FillFromCell( SCCOL nCol, SCROW nRow, SCTAB nTab );

protected:  // for usage in derived classes
    ScViewData&             mrViewData;
    ScDocShell&             mrDocShell;
    ScDocument&             mrDoc;

private:
    ScSelectionState        maSelState;         /// Selection data of the document.
    ScDocument*             mpUndoDoc;          /// Document stores all old cells for UNDO action.
    ScDocument*             mpRedoDoc;          /// Document stores all new cells for REDO action.
    LanguageType            meCurrLang;         /// Current cell language.
    SCCOL                   mnStartCol;         /// Initial column index.
    SCROW                   mnStartRow;         /// Initial row index.
    SCTAB                   mnStartTab;         /// Initial sheet index.
    SCCOL                   mnCurrCol;          /// Current column index.
    SCROW                   mnCurrRow;          /// Current row index.
    bool                    mbIsAnyModified;    /// true = At least one cell has been changed.
    bool                    mbInitialState;     /// true = Not searched for a cell yet.
    bool                    mbWrappedInTable;   /// true = Already restarted at top of the sheet.
    bool                    mbFinished;         /// true = Entire document/selection finished.
};

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

/** Edit engine for spell checking. */
class ScSpellingEngine : public ScConversionEngineBase
{
public:
    typedef ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XSpellChecker1 > XSpellCheckerRef;

    explicit                ScSpellingEngine(
                                SfxItemPool* pEnginePool,
                                ScViewData& rViewData,
                                ScDocument* pUndoDoc,
                                ScDocument* pRedoDoc,
                                XSpellCheckerRef xSpeller );

    /** Checks spelling of all cells in the selection or sheet. */
    virtual void            ConvertAll( EditView& rEditView );

protected:
    /** Callback from edit engine to check the next cell. */
    virtual BOOL            SpellNextDocument();

    /** Returns true, if the current text contains a spelling error. */
    virtual bool            NeedsConversion();

    /** Show a query box that asks whether to restart at top of the sheet.
        @return  true = Restart at top, false = Stop the conversion. */
    virtual bool            ShowTableWrapDialog();
    /** Show a message box stating that spell checking is finished. */
    virtual void            ShowFinishDialog();

private:
    /** Returns the spelling dialog if it is open. */
    Window*                 GetDialogParent();
};

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

/** Edit engine for text conversion. */
class ScTextConversionEngine : public ScConversionEngineBase
{
public:
    explicit                ScTextConversionEngine(
                                SfxItemPool* pEnginePool,
                                ScViewData& rViewData,
                                ScDocument* pUndoDoc,
                                ScDocument* pRedoDoc,
                                ESelection* pEdSelection,
                                SCCOL nCol, SCROW nRow, SCTAB nTab,
                                bool bCellSelection,
                                LanguageType eSourceLanguage,   // source language for conversion
                                LanguageType eTargetLanguage,   // target language for conversion
                                const Font *pTargetFont,        // target font to be used if language has to be changed
                                sal_Int32 nOptions,             // misc conversion flags
                                sal_Bool bIsInteractive         // textconversiob has (specific) dialog that may be raised
                                LanguageType eConvLanguage );

    /** Converts all cells in the selection or sheet according to set language. */
    virtual void            ConvertAll( EditView& rEditView );

protected:
    /** Callback from edit engine to convert the next cell. */
    virtual BOOL            ConvertNextDocument();

    /** Returns true, if the current text contains text to convert. */
    virtual bool            NeedsConversion();

private:
    LanguageType    meSourceLang;       // source language for conversion
    LanguageType    meTargetLang;       // target language for conversion
    const Font *    mpTargetFont;       // target font to be used if language has to be changed
    sal_Int32       mnOptions;          // misc conversion flags
    sal_Bool        mbIsInteractive;    // textconversiob has (specific) dialog that may be raised
};

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

#endif

<|endoftext|>


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

#ifndef SC_VIEWUTIL_HXX
#define SC_VIEWUTIL_HXX

#ifndef _SOLAR_H
#include <tools/solar.h>
#endif

class String;
class SfxItemSet;
class SvxFontItem;

class ScChangeAction;
class ScChangeViewSettings;
class ScDocument;
class ScAddress;

enum ScUpdateMode { SC_UPDATE_ALL, SC_UPDATE_CHANGED, SC_UPDATE_MARKS };

/** Specifiers for sheet conversion (functions iterating over the sheet and modifying cells). */
enum ScConversionType
{
    SC_CONVERSION_SPELLCHECK,       /// Spell checker.
    SC_CONVERSION_HANGULHANJA       /// Hangul-Hanja converter.
};

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

class ScViewUtil                                // static Methoden
{
public:
    static BOOL ExecuteCharMap( const SvxFontItem&  rOldFont,
                                SvxFontItem&        rNewFont,
                                String&             rString );

    static BOOL IsActionShown( const ScChangeAction& rAction,
                                const ScChangeViewSettings& rSettings,
                                ScDocument& rDocument );

    static void PutItemScript( SfxItemSet& rShellSet, const SfxItemSet& rCoreSet,
                                USHORT nWhichId, USHORT nScript );

    static USHORT GetEffLanguage( ScDocument* pDoc, const ScAddress& rPos );

    static sal_Int32 GetTransliterationType( USHORT nSlotID );
};

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

class ScUpdateRect
{
private:
    USHORT  nOldStartX;
    USHORT  nOldStartY;
    USHORT  nOldEndX;
    USHORT  nOldEndY;
    USHORT  nNewStartX;
    USHORT  nNewStartY;
    USHORT  nNewEndX;
    USHORT  nNewEndY;
    USHORT  nContX1;
    USHORT  nContY1;
    USHORT  nContX2;
    USHORT  nContY2;
public:
            ScUpdateRect( USHORT nX1, USHORT nY1, USHORT nX2, USHORT nY2 );
    void    SetNew( USHORT nX1, USHORT nY1, USHORT nX2, USHORT nY2 );
    BOOL    GetDiff( USHORT& rX1, USHORT& rY1, USHORT& rX2, USHORT& rY2 );
    BOOL    GetXorDiff( USHORT& rX1, USHORT& rY1, USHORT& rX2, USHORT& rY2, BOOL& rCont );
    void    GetContDiff( USHORT& rX1, USHORT& rY1, USHORT& rX2, USHORT& rY2 );
};

#endif

<commit_msg>INTEGRATION: CWS rowlimit (1.4.336); FILE MERGED 2004/01/16 17:42:52 er 1.4.336.3: #i1967# SCCOL,SCROW,SCTAB replace USHORT; SCsCOL,SCsROW,SCsTAB replace short 2004/01/13 20:04:53 er 1.4.336.2: #i1967# SCCOL,SCROW,SCTAB replace USHORT; SCsCOL,SCsROW,SCsTAB replace short 2003/11/28 19:48:04 er 1.4.336.1: #i1967# move ScAddress, ScRange from global.hxx to address.hxx<commit_after>/*************************************************************************
 *
 *  $RCSfile: viewutil.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: obo $ $Date: 2004-06-04 11:46:06 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef SC_VIEWUTIL_HXX
#define SC_VIEWUTIL_HXX

#ifndef SC_ADDRESS_HXX
#include "address.hxx"
#endif

#ifndef _SOLAR_H
#include <tools/solar.h>
#endif
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif

class String;
class SfxItemSet;
class SvxFontItem;

class ScChangeAction;
class ScChangeViewSettings;
class ScDocument;
class ScAddress;

enum ScUpdateMode { SC_UPDATE_ALL, SC_UPDATE_CHANGED, SC_UPDATE_MARKS };

/** Specifiers for sheet conversion (functions iterating over the sheet and modifying cells). */
enum ScConversionType
{
    SC_CONVERSION_SPELLCHECK,       /// Spell checker.
    SC_CONVERSION_HANGULHANJA       /// Hangul-Hanja converter.
};

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

class ScViewUtil                                // static Methoden
{
public:
    static BOOL ExecuteCharMap( const SvxFontItem&  rOldFont,
                                SvxFontItem&        rNewFont,
                                String&             rString );

    static BOOL IsActionShown( const ScChangeAction& rAction,
                                const ScChangeViewSettings& rSettings,
                                ScDocument& rDocument );

    static void PutItemScript( SfxItemSet& rShellSet, const SfxItemSet& rCoreSet,
                                USHORT nWhichId, USHORT nScript );

    static USHORT GetEffLanguage( ScDocument* pDoc, const ScAddress& rPos );

    static sal_Int32 GetTransliterationType( USHORT nSlotID );
};

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

class ScUpdateRect
{
private:
    SCCOL   nOldStartX;
    SCROW   nOldStartY;
    SCCOL   nOldEndX;
    SCROW   nOldEndY;
    SCCOL   nNewStartX;
    SCROW   nNewStartY;
    SCCOL   nNewEndX;
    SCROW   nNewEndY;
    SCCOL   nContX1;
    SCROW   nContY1;
    SCCOL   nContX2;
    SCROW   nContY2;
public:
            ScUpdateRect( SCCOL nX1, SCROW nY1, SCCOL nX2, SCROW nY2 );
    void    SetNew( SCCOL nX1, SCROW nY1, SCCOL nX2, SCROW nY2 );
    BOOL    GetDiff( SCCOL& rX1, SCROW& rY1, SCCOL& rX2, SCROW& rY2 );
    BOOL    GetXorDiff( SCCOL& rX1, SCROW& rY1, SCCOL& rX2, SCROW& rY2, BOOL& rCont );
    void    GetContDiff( SCCOL& rX1, SCROW& rY1, SCCOL& rX2, SCROW& rY2 );
};

#endif

<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// *       Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// *       Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// *       Neither the name of Industrial Light & Magic nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////

//-----------------------------------------------------------------------------
//
//	function blurImage() -- performs a hemispherical blur
//
//-----------------------------------------------------------------------------

#include <blurImage.h>

#include <resizeImage.h>
#include "Iex.h"
#include <iostream>
#include <algorithm>

using namespace std;
using namespace Imf;
using namespace Imath;

inline int
toInt (float x)
{
    return int (x + 0.5f);
}

inline double
cube (double x)
{
    return x * x * x;
}

void
blurImage (EnvmapImage &image1, bool verbose)
{
    //
    // Ideally we would blur the input image directly by convolving
    // it with a 180-degree wide blur kernel.  Unfortunately this
    // is prohibitively expensive when the input image is large.
    // In order to keep running times reasonable, we perform the
    // blur on a small proxy image that will later be re-sampled
    // to the desired output resolution.
    //
    // Here's how it works:
    //
    // * If the input image is in latitude-longitude format,
    //   convert it into a cube-face environment map.
    //
    // * Repeatedly resample the image, each time shrinking
    //   it to no less than half its current size, until the
    //   width of each cube face is MAX_IN_WIDTH pixels.
    //
    // * Multiply each pixel by a weight that is proportinal
    //   to the solid angle subtended by the pixel as seen
    //   from the center of the environment cube.
    //
    // * Create an output image in cube-face format.
    //   The cube faces of the output image are OUT_WIDTH
    //   pixels wide.
    //
    // * For each pixel of the output image:
    //
    //       Set the output pixel's color to black
    //
    //       Determine the direction, d2, from the center of the
    //       output environment cube to the center of the output
    //	     pixel.
    //
    //       For each pixel of the input image:
    //
    //           Determine the direction, d1, from the center of
    //           the input environment cube to the center of the
    //           input pixel.
    //
    //           Multiply the input pixel's color by max (0, d1.dot(d2))
    //           and add the result to the output pixel.
    //

    const int MAX_IN_WIDTH = 40;
    const int OUT_WIDTH = 100;

    if (verbose)
	cout << "blurring map image" << endl;

    EnvmapImage image2;
    EnvmapImage *iptr1 = &image1;
    EnvmapImage *iptr2 = &image2;

    int w = image1.dataWindow().max.x - image1.dataWindow().min.x + 1;
    int h = w * 6;

    if (iptr1->type() == ENVMAP_LATLONG)
    {
	//
	// Convert the input image from latitude-longitude
	// to cube-face format.
	//

	if (verbose)
	    cout << "    converting to cube-face format" << endl;

	w /= 4;
	h = w * 6;

	Box2i dw (V2i (0, 0), V2i (w - 1, h - 1));
	resizeCube (*iptr1, *iptr2, dw, 1, 7);

	swap (iptr1, iptr2);
    }

    while (w > MAX_IN_WIDTH)
    {
	//
	// Shrink the image.
	//

	if (w >= MAX_IN_WIDTH * 2)
	    w /= 2;
	else
	    w = MAX_IN_WIDTH;

	h = w * 6;

	if (verbose)
	{
	    cout << "    resizing cube faces "
		    "to " << w << " by " << w << " pixels" << endl;
	}

	Box2i dw (V2i (0, 0), V2i (w - 1, h - 1));
	resizeCube (*iptr1, *iptr2, dw, 1, 7);

	swap (iptr1, iptr2);
    }

    if (verbose)
	cout << "    computing pixel weights" << endl;

    {
	Box2i dw = iptr1->dataWindow();
	int sof = CubeMap::sizeOfFace (dw);

	Array2D<Rgba> &pixels = iptr1->pixels();

	double weightTotal = 0;

	for (int f = CUBEFACE_POS_X; f <= CUBEFACE_NEG_Z; ++f)
	{
	    if (verbose)
		cout << "        face " << f << endl;

	    CubeMapFace face = CubeMapFace (f);
	    V3f faceDir;

	    switch (face)
	    {
	      case CUBEFACE_POS_X:
		faceDir = V3f (1, 0, 0);
		break;

	      case CUBEFACE_NEG_X:
		faceDir = V3f (-1, 0, 0);
		break;

	      case CUBEFACE_POS_Y:
		faceDir = V3f (0, 1, 0);
		break;

	      case CUBEFACE_NEG_Y:
		faceDir = V3f (0, -1, 0);
		break;

	      case CUBEFACE_POS_Z:
		faceDir = V3f (0, 0, 1);
		break;

	      case CUBEFACE_NEG_Z:
		faceDir = V3f (0, 0, -1);
		break;
	    }

	    for (int y = 0; y < sof; ++y)
	    {
		bool yEdge = (y == 0 || y == sof - 1);

		for (int x = 0; x < sof; ++x)
		{
		    bool xEdge = (x == 0 || x == sof - 1);

		    V2f posInFace (x, y);

		    V3f dir =
			CubeMap::direction (face, dw, posInFace).normalized();

		    V2f pos =
			CubeMap::pixelPosition (face, dw, posInFace);

		    double weight = cube (dir ^ faceDir);

		    if (xEdge && yEdge)
			weight /= 3;
		    else if (xEdge || yEdge)
			weight /= 2;

		    Rgba &pixel = pixels[toInt (pos.y)][toInt (pos.x)];

		    pixel.r *= weight;
		    pixel.g *= weight;
		    pixel.b *= weight;
		    pixel.a *= weight;

		    weightTotal += weight;
		}
	    }
	}

	//
	// The weighting operation above has made the overall image darker.
	// Apply a correction to recover the image's original brightness.
	//

	int w = dw.max.x - dw.min.x + 1;
	int h = dw.max.y - dw.min.y + 1;
	size_t numPixels = w * h;
	double weight = numPixels / weightTotal;

	Rgba *p = &pixels[0][0];
	Rgba *end = p + numPixels;

	while (p < end)
	{
	    p->r *= weight;
	    p->g *= weight;
	    p->b *= weight;
	    p->a *= weight;

	    ++p;
	}
    }

    {
	if (verbose)
	    cout << "    generating blurred image" << endl;

	Box2i dw1 = iptr1->dataWindow();
	int sof1 = CubeMap::sizeOfFace (dw1);

	Box2i dw2 (V2i (0, 0), V2i (OUT_WIDTH - 1, OUT_WIDTH * 6 - 1));
	int sof2 = CubeMap::sizeOfFace (dw2);

	iptr2->resize (ENVMAP_CUBE, dw2);
	iptr2->clear ();

	Array2D<Rgba> &pixels1 = iptr1->pixels();
	Array2D<Rgba> &pixels2 = iptr2->pixels();

	for (int f2 = CUBEFACE_POS_X; f2 <= CUBEFACE_NEG_Z; ++f2)
	{
	    if (verbose)
		cout << "        face " << f2 << endl;

	    CubeMapFace face2 = CubeMapFace (f2);

	    for (int y2 = 0; y2 < sof2; ++y2)
	    {
		for (int x2 = 0; x2 < sof2; ++x2)
		{
		    V2f posInFace2 (x2, y2);

		    V3f dir2 = CubeMap::direction
			(face2, dw2, posInFace2);

		    V2f pos2 = CubeMap::pixelPosition
			(face2, dw2, posInFace2);

		    double weightTotal = 0;
		    double rTotal = 0;
		    double gTotal = 0;
		    double bTotal = 0;
		    double aTotal = 0;

		    Rgba &pixel2 =
			pixels2[toInt (pos2.y)][toInt (pos2.x)];

		    for (int f1 = CUBEFACE_POS_X; f1 <= CUBEFACE_NEG_Z; ++f1)
		    {
			CubeMapFace face1 = CubeMapFace (f1);

			for (int y1 = 0; y1 < sof1; ++y1)
			{
			    for (int x1 = 0; x1 < sof1; ++x1)
			    {
				V2f posInFace1 (x1, y1);

				V3f dir1 = CubeMap::direction
				    (face1, dw1, posInFace1);

				V2f pos1 = CubeMap::pixelPosition
				    (face1, dw1, posInFace1);

				double weight = dir1 ^ dir2;

				if (weight <= 0)
				    continue;

				Rgba &pixel1 =
				    pixels1[toInt (pos1.y)][toInt (pos1.x)];

				weightTotal += weight;
				rTotal += pixel1.r * weight;
				gTotal += pixel1.g * weight;
				bTotal += pixel1.b * weight;
				aTotal += pixel1.a * weight;
			    }
			}
		    }

		    pixel2.r = rTotal / weightTotal;
		    pixel2.g = gTotal / weightTotal;
		    pixel2.b = bTotal / weightTotal;
		    pixel2.a = aTotal / weightTotal;
		}
	    }
	}

	swap (iptr1, iptr2);
    }

    //
    // Depending on how many times we've re-sampled the image,
    // the result is now either in image1 or in image2.
    // If necessary, copy the result into image1.
    //

    if (iptr1 != &image1)
    {
	if (verbose)
	    cout << "    copying" << endl;

	Box2i dw = iptr1->dataWindow();
	image1.resize (ENVMAP_CUBE, dw);

	int w = dw.max.x - dw.min.x + 1;
	int h = dw.max.y - dw.min.y + 1;
	size_t size = w * h * sizeof (Rgba);

	memcpy (&image1.pixels()[0][0], &iptr1->pixels()[0][0], size);
    }
}
<commit_msg>Silence a bogus compiler warning.<commit_after>///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// *       Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// *       Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// *       Neither the name of Industrial Light & Magic nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////

//-----------------------------------------------------------------------------
//
//	function blurImage() -- performs a hemispherical blur
//
//-----------------------------------------------------------------------------

#include <blurImage.h>

#include <resizeImage.h>
#include "Iex.h"
#include <iostream>
#include <algorithm>

using namespace std;
using namespace Imf;
using namespace Imath;

inline int
toInt (float x)
{
    return int (x + 0.5f);
}

inline double
cube (double x)
{
    return x * x * x;
}

void
blurImage (EnvmapImage &image1, bool verbose)
{
    //
    // Ideally we would blur the input image directly by convolving
    // it with a 180-degree wide blur kernel.  Unfortunately this
    // is prohibitively expensive when the input image is large.
    // In order to keep running times reasonable, we perform the
    // blur on a small proxy image that will later be re-sampled
    // to the desired output resolution.
    //
    // Here's how it works:
    //
    // * If the input image is in latitude-longitude format,
    //   convert it into a cube-face environment map.
    //
    // * Repeatedly resample the image, each time shrinking
    //   it to no less than half its current size, until the
    //   width of each cube face is MAX_IN_WIDTH pixels.
    //
    // * Multiply each pixel by a weight that is proportinal
    //   to the solid angle subtended by the pixel as seen
    //   from the center of the environment cube.
    //
    // * Create an output image in cube-face format.
    //   The cube faces of the output image are OUT_WIDTH
    //   pixels wide.
    //
    // * For each pixel of the output image:
    //
    //       Set the output pixel's color to black
    //
    //       Determine the direction, d2, from the center of the
    //       output environment cube to the center of the output
    //	     pixel.
    //
    //       For each pixel of the input image:
    //
    //           Determine the direction, d1, from the center of
    //           the input environment cube to the center of the
    //           input pixel.
    //
    //           Multiply the input pixel's color by max (0, d1.dot(d2))
    //           and add the result to the output pixel.
    //

    const int MAX_IN_WIDTH = 40;
    const int OUT_WIDTH = 100;

    if (verbose)
	cout << "blurring map image" << endl;

    EnvmapImage image2;
    EnvmapImage *iptr1 = &image1;
    EnvmapImage *iptr2 = &image2;

    int w = image1.dataWindow().max.x - image1.dataWindow().min.x + 1;
    int h = w * 6;

    if (iptr1->type() == ENVMAP_LATLONG)
    {
	//
	// Convert the input image from latitude-longitude
	// to cube-face format.
	//

	if (verbose)
	    cout << "    converting to cube-face format" << endl;

	w /= 4;
	h = w * 6;

	Box2i dw (V2i (0, 0), V2i (w - 1, h - 1));
	resizeCube (*iptr1, *iptr2, dw, 1, 7);

	swap (iptr1, iptr2);
    }

    while (w > MAX_IN_WIDTH)
    {
	//
	// Shrink the image.
	//

	if (w >= MAX_IN_WIDTH * 2)
	    w /= 2;
	else
	    w = MAX_IN_WIDTH;

	h = w * 6;

	if (verbose)
	{
	    cout << "    resizing cube faces "
		    "to " << w << " by " << w << " pixels" << endl;
	}

	Box2i dw (V2i (0, 0), V2i (w - 1, h - 1));
	resizeCube (*iptr1, *iptr2, dw, 1, 7);

	swap (iptr1, iptr2);
    }

    if (verbose)
	cout << "    computing pixel weights" << endl;

    {
	Box2i dw = iptr1->dataWindow();
	int sof = CubeMap::sizeOfFace (dw);

	Array2D<Rgba> &pixels = iptr1->pixels();

	double weightTotal = 0;

	for (int f = CUBEFACE_POS_X; f <= CUBEFACE_NEG_Z; ++f)
	{
	    if (verbose)
		cout << "        face " << f << endl;

	    CubeMapFace face = CubeMapFace (f);
	    V3f faceDir (0, 0, 0);

	    switch (face)
	    {
	      case CUBEFACE_POS_X:
		faceDir = V3f (1, 0, 0);
		break;

	      case CUBEFACE_NEG_X:
		faceDir = V3f (-1, 0, 0);
		break;

	      case CUBEFACE_POS_Y:
		faceDir = V3f (0, 1, 0);
		break;

	      case CUBEFACE_NEG_Y:
		faceDir = V3f (0, -1, 0);
		break;

	      case CUBEFACE_POS_Z:
		faceDir = V3f (0, 0, 1);
		break;

	      case CUBEFACE_NEG_Z:
		faceDir = V3f (0, 0, -1);
		break;
	    }

	    for (int y = 0; y < sof; ++y)
	    {
		bool yEdge = (y == 0 || y == sof - 1);

		for (int x = 0; x < sof; ++x)
		{
		    bool xEdge = (x == 0 || x == sof - 1);

		    V2f posInFace (x, y);

		    V3f dir =
			CubeMap::direction (face, dw, posInFace).normalized();

		    V2f pos =
			CubeMap::pixelPosition (face, dw, posInFace);

		    double weight = cube (dir ^ faceDir);

		    if (xEdge && yEdge)
			weight /= 3;
		    else if (xEdge || yEdge)
			weight /= 2;

		    Rgba &pixel = pixels[toInt (pos.y)][toInt (pos.x)];

		    pixel.r *= weight;
		    pixel.g *= weight;
		    pixel.b *= weight;
		    pixel.a *= weight;

		    weightTotal += weight;
		}
	    }
	}

	//
	// The weighting operation above has made the overall image darker.
	// Apply a correction to recover the image's original brightness.
	//

	int w = dw.max.x - dw.min.x + 1;
	int h = dw.max.y - dw.min.y + 1;
	size_t numPixels = w * h;
	double weight = numPixels / weightTotal;

	Rgba *p = &pixels[0][0];
	Rgba *end = p + numPixels;

	while (p < end)
	{
	    p->r *= weight;
	    p->g *= weight;
	    p->b *= weight;
	    p->a *= weight;

	    ++p;
	}
    }

    {
	if (verbose)
	    cout << "    generating blurred image" << endl;

	Box2i dw1 = iptr1->dataWindow();
	int sof1 = CubeMap::sizeOfFace (dw1);

	Box2i dw2 (V2i (0, 0), V2i (OUT_WIDTH - 1, OUT_WIDTH * 6 - 1));
	int sof2 = CubeMap::sizeOfFace (dw2);

	iptr2->resize (ENVMAP_CUBE, dw2);
	iptr2->clear ();

	Array2D<Rgba> &pixels1 = iptr1->pixels();
	Array2D<Rgba> &pixels2 = iptr2->pixels();

	for (int f2 = CUBEFACE_POS_X; f2 <= CUBEFACE_NEG_Z; ++f2)
	{
	    if (verbose)
		cout << "        face " << f2 << endl;

	    CubeMapFace face2 = CubeMapFace (f2);

	    for (int y2 = 0; y2 < sof2; ++y2)
	    {
		for (int x2 = 0; x2 < sof2; ++x2)
		{
		    V2f posInFace2 (x2, y2);

		    V3f dir2 = CubeMap::direction
			(face2, dw2, posInFace2);

		    V2f pos2 = CubeMap::pixelPosition
			(face2, dw2, posInFace2);

		    double weightTotal = 0;
		    double rTotal = 0;
		    double gTotal = 0;
		    double bTotal = 0;
		    double aTotal = 0;

		    Rgba &pixel2 =
			pixels2[toInt (pos2.y)][toInt (pos2.x)];

		    for (int f1 = CUBEFACE_POS_X; f1 <= CUBEFACE_NEG_Z; ++f1)
		    {
			CubeMapFace face1 = CubeMapFace (f1);

			for (int y1 = 0; y1 < sof1; ++y1)
			{
			    for (int x1 = 0; x1 < sof1; ++x1)
			    {
				V2f posInFace1 (x1, y1);

				V3f dir1 = CubeMap::direction
				    (face1, dw1, posInFace1);

				V2f pos1 = CubeMap::pixelPosition
				    (face1, dw1, posInFace1);

				double weight = dir1 ^ dir2;

				if (weight <= 0)
				    continue;

				Rgba &pixel1 =
				    pixels1[toInt (pos1.y)][toInt (pos1.x)];

				weightTotal += weight;
				rTotal += pixel1.r * weight;
				gTotal += pixel1.g * weight;
				bTotal += pixel1.b * weight;
				aTotal += pixel1.a * weight;
			    }
			}
		    }

		    pixel2.r = rTotal / weightTotal;
		    pixel2.g = gTotal / weightTotal;
		    pixel2.b = bTotal / weightTotal;
		    pixel2.a = aTotal / weightTotal;
		}
	    }
	}

	swap (iptr1, iptr2);
    }

    //
    // Depending on how many times we've re-sampled the image,
    // the result is now either in image1 or in image2.
    // If necessary, copy the result into image1.
    //

    if (iptr1 != &image1)
    {
	if (verbose)
	    cout << "    copying" << endl;

	Box2i dw = iptr1->dataWindow();
	image1.resize (ENVMAP_CUBE, dw);

	int w = dw.max.x - dw.min.x + 1;
	int h = dw.max.y - dw.min.y + 1;
	size_t size = w * h * sizeof (Rgba);

	memcpy (&image1.pixels()[0][0], &iptr1->pixels()[0][0], size);
    }
}
<|endoftext|>


<commit_before>/*

This is a library for the BH1750FVI Digital Light Sensor
breakout board.

The board uses I2C for communication. 2 pins are required to
interface to the device.

Written by Christopher Laws, March, 2013.

*/

#include "BH1750.h"
//#include <util/delay.h>

BH1750::BH1750() {
}

void BH1750::begin(uint8_t mode) {

  Wire.begin();
  //write8(mode);
  configure(mode);
}

void BH1750::configure(uint8_t mode) {

    switch (mode) {
        case BH1750_CONTINUOUS_HIGH_RES_MODE:
        case BH1750_CONTINUOUS_HIGH_RES_MODE_2:
        case BH1750_CONTINUOUS_LOW_RES_MODE:
        case BH1750_ONE_TIME_HIGH_RES_MODE:
        case BH1750_ONE_TIME_HIGH_RES_MODE_2:
        case BH1750_ONE_TIME_LOW_RES_MODE:
            // apply a valid mode change
            write8(mode);
           // delayMicroseconds(10);
            break;
        default:
            // Invalid measurement mode
            #if BH1750_DEBUG == 1
            Serial.println("Invalid measurement mode");
            #endif
            break;
    }
}

uint16_t BH1750::readLightLevel(void) {

  uint16_t level;

  Wire.beginTransmission(BH1750_I2CADDR);
  Wire.requestFrom(BH1750_I2CADDR, 2);
#if (ARDUINO >= 100)
  level = Wire.read();
  level <<= 8;
  level |= Wire.read();
#else
  level = Wire.receive();
  level <<= 8;
  level |= Wire.receive();
#endif
  Wire.endTransmission();

#if BH1750_DEBUG == 1
  Serial.print("Raw light level: ");
  Serial.println(level);
#endif

  level = level/1.2; // convert to lux

#if BH1750_DEBUG == 1
  Serial.print("Light level: ");
  Serial.println(level);
#endif
  return level;
}

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

void BH1750::write8(uint8_t d) {
  Wire.beginTransmission(BH1750_I2CADDR);
#if (ARDUINO >= 100)
  Wire.write(d);
#else
  Wire.send(d);
#endif
  Wire.endTransmission();
}
<commit_msg>Update BH1750.cpp<commit_after>/*

This is a library for the BH1750FVI Digital Light Sensor
breakout board.

The board uses I2C for communication. 2 pins are required to
interface to the device.

Written by Christopher Laws, March, 2013.

*/

#include "BH1750.h"
//#include <util/delay.h>

BH1750::BH1750() {
}

void BH1750::begin(uint8_t mode) {

  Wire.begin();
  //write8(mode);
  configure(mode);
}

void BH1750::configure(uint8_t mode) {

    switch (mode) {
        case BH1750_CONTINUOUS_HIGH_RES_MODE:
        case BH1750_CONTINUOUS_HIGH_RES_MODE_2:
        case BH1750_CONTINUOUS_LOW_RES_MODE:
        case BH1750_ONE_TIME_HIGH_RES_MODE:
        case BH1750_ONE_TIME_HIGH_RES_MODE_2:
        case BH1750_ONE_TIME_LOW_RES_MODE:
            // apply a valid mode change
            Wire.beginTransmission(BH1750LIB_I2CADDR);
            Wire.write(mode);
            Wire.endTransmission();
            delayMicroseconds(10);
            break;
        default:
            // Invalid measurement mode
            #if BH1750_DEBUG == 1
            Serial.println("Invalid measurement mode");
            #endif
            break;
    }
}

uint16_t BH1750::readLightLevel(void) {

  uint16_t level;

  Wire.beginTransmission(BH1750_I2CADDR);
  Wire.requestFrom(BH1750_I2CADDR, 2);
#if (ARDUINO >= 100)
  level = Wire.read();
  level <<= 8;
  level |= Wire.read();
#endif
  Wire.endTransmission();

#if BH1750_DEBUG == 1
  Serial.print("Raw light level: ");
  Serial.println(level);
#endif

  level = level/1.2; // convert to lux

#if BH1750_DEBUG == 1
  Serial.print("Light level: ");
  Serial.println(level);
#endif
  return level;
}

<|endoftext|>


<commit_before>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile$
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "mitkVolumeDataVtkMapper3D.h"
#include "QmitkAbortEventFilter.h"
#include "QmitkRenderWindow.h"
#include "mitkRenderingManager.h"

#include <qapplication.h>
#include <qeventloop.h>

QmitkAbortEventFilter*
QmitkAbortEventFilter
::GetInstance()
{
  static QmitkAbortEventFilter instance;
  return &instance;
}

QmitkAbortEventFilter::QmitkAbortEventFilter()
{
}
QmitkAbortEventFilter::~QmitkAbortEventFilter()

{
}

bool QmitkAbortEventFilter::eventFilter( QObject *object, QEvent *event )
{
  if (mitk::RenderingManager::GetInstance()->IsRendering() )
  {
    switch ( event->type() )
    {

    case QEvent::MouseButtonPress:
    {
      m_ButtonPressed = true;
      //std::cout << "#BP ";

      mitk::RenderingManager::GetInstance()->AbortRendering( NULL );
      QMouseEvent* me = ( QMouseEvent* )( event );

      QMouseEvent* newEvent = new QMouseEvent(
        me->type(), me->pos(), me->globalPos(), me->button(), me->state()
      );
      m_EventQueue.push( ObjectEventPair(object, newEvent) );
      return true;
    }

    case QEvent::MouseButtonDblClick:
    {
      mitk::RenderingManager::GetInstance()->AbortRendering( NULL );
      QMouseEvent* me = ( QMouseEvent* )( event );

      QMouseEvent* newEvent = new QMouseEvent(
        me->type(), me->pos(), me->globalPos(), me->button(), me->state()
      );
      m_EventQueue.push( ObjectEventPair(object, newEvent) );
      return true;
    }

    case QEvent::MouseButtonRelease:
    {
      m_ButtonPressed = false;
      //std::cout << "#BR ";

      QMouseEvent* me = ( QMouseEvent* )( event );

      QMouseEvent* newEvent = new QMouseEvent(
        me->type(), me->pos(), me->globalPos(), me->button(), me->state()
      );
      m_EventQueue.push( ObjectEventPair(object, newEvent) );
      return true;
    }

    case QEvent::MouseMove:
    {
      if(m_ButtonPressed)
      {

        QMouseEvent* me = ( QMouseEvent* )( event );
        QMouseEvent* newEvent = new QMouseEvent(
          me->type(), me->pos(), me->globalPos(), me->button(), me->state()
        );
        m_EventQueue.push( ObjectEventPair(object, newEvent) );

  //std::cout << "#MM ";
        if(mitk::RenderingManager::GetInstance()->GetCurrentLOD()!=0)
        {
          mitk::RenderingManager::GetInstance()->SetCurrentLOD(0);
          mitk::RenderingManager::GetInstance()->AbortRendering( NULL );
        }
      }
      return true;
    }

    case QEvent::Resize:
      {
        //std::cout << "#R ";
        mitk::RenderingManager::GetInstance()->AbortRendering( NULL );

        QResizeEvent* re = ( QResizeEvent* )( event );

        QResizeEvent* newResizeEvent = new QResizeEvent( re->size(), re->oldSize() );
        m_EventQueue.push( ObjectEventPair(object, newResizeEvent) );
        return true;
      }

    case QEvent::Paint:
      {
        //std::cout << "#P ";
        QPaintEvent* pe = ( QPaintEvent* )( event );
        QPaintEvent* newPaintEvent = new QPaintEvent( pe->region() );
        m_EventQueue.push( ObjectEventPair(object, newPaintEvent) );
        return true;
      }

     case QEvent::ShowWindowRequest:
      {
        //std::cout << "#WR ";
        return false;
      }

      case QEvent::LayoutHint:
      {
        //std::cout << "#L ";
        return false;
      }
     case QEvent::ChildInserted: //change Layout (Big3D, 2D images up, etc.)
      {
        //std::cout << "#CI ";
        mitk::RenderingManager::GetInstance()->SetCurrentLOD(0);
        mitk::RenderingManager::GetInstance()->AbortRendering( NULL );
        return false;
      }

      case QEvent::KeyPress:
      {
        //std::cout << "#KP ";
        mitk::RenderingManager::GetInstance()->AbortRendering( NULL );
        QKeyEvent* ke = ( QKeyEvent* )( event );
        QKeyEvent* newEvent = new QKeyEvent(
          ke->type(), ke->key(), ke->ascii(), ke->state(), ke->text(), false, ke->count()
        );
        m_EventQueue.push( ObjectEventPair(object, newEvent) );
        return true;
      }

      //std::cout<<"Event Type: (Rendering)"<<event->type()<<std::endl;
      default:
      {
        return false;
      }
    }
  }
 else
  {
    if(event->type()==QEvent::MouseButtonPress)
    {
      m_ButtonPressed = true;
      //std::cout << "#BP2 ";
      return false;
    }

    if(event->type()==QEvent::MouseMove)
    {
      if(m_ButtonPressed){
        //std::cout << "#MM2 ";
        mitk::RenderingManager::GetInstance()->SetCurrentLOD(0);
      }
      return false;
    }

    if(event->type()==QEvent::MouseButtonRelease)
    {
      m_ButtonPressed = false;
      //std::cout << "#BR2 ";
      return false;
    }

    if(event->type()==QEvent::Resize)
    {
      //std::cout << "#R2 ";
      mitk::RenderingManager::GetInstance()->SetCurrentLOD(0);
      //mitk::RenderingManager::GetInstance()->RequestUpdateAll();
      return false;
    }

    if(event->type()==QEvent::ChildInserted)
    {
      //std::cout << "#CI2 ";
      mitk::RenderingManager::GetInstance()->SetCurrentLOD(0);
      return false;
    }

    //std::cout<<"Event Type: (Not Rendering)"<<event->type()<<std::endl;

  }
  return false;
}

void QmitkAbortEventFilter::ProcessEvents()
{
  //std::cout << "P";
  qApp->eventLoop()->processEvents( QEventLoop::AllEvents );
}

void QmitkAbortEventFilter::IssueQueuedEvents()
{
  while ( !m_EventQueue.empty() )
  {
    ObjectEventPair eventPair = m_EventQueue.front();
    QApplication::postEvent( eventPair.first, eventPair.second );
    m_EventQueue.pop();
  }

}
<commit_msg>ENH: Added handling of QEvent::Timer<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile$
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "mitkVolumeDataVtkMapper3D.h"
#include "QmitkAbortEventFilter.h"
#include "QmitkRenderWindow.h"
#include "mitkRenderingManager.h"

#include <qapplication.h>
#include <qeventloop.h>

QmitkAbortEventFilter*
QmitkAbortEventFilter
::GetInstance()
{
  static QmitkAbortEventFilter instance;
  return &instance;
}

QmitkAbortEventFilter::QmitkAbortEventFilter()
{
}
QmitkAbortEventFilter::~QmitkAbortEventFilter()

{
}

bool QmitkAbortEventFilter::eventFilter( QObject *object, QEvent *event )
{
  if (mitk::RenderingManager::GetInstance()->IsRendering() )
  {
    switch ( event->type() )
    {

    case QEvent::MouseButtonPress:
    {
      m_ButtonPressed = true;
      //std::cout << "#BP ";

      mitk::RenderingManager::GetInstance()->AbortRendering( NULL );
      QMouseEvent* me = ( QMouseEvent* )( event );

      QMouseEvent* newEvent = new QMouseEvent(
        me->type(), me->pos(), me->globalPos(), me->button(), me->state()
      );
      m_EventQueue.push( ObjectEventPair(object, newEvent) );
      return true;
    }

    case QEvent::MouseButtonDblClick:
    {
      mitk::RenderingManager::GetInstance()->AbortRendering( NULL );
      QMouseEvent* me = ( QMouseEvent* )( event );

      QMouseEvent* newEvent = new QMouseEvent(
        me->type(), me->pos(), me->globalPos(), me->button(), me->state()
      );
      m_EventQueue.push( ObjectEventPair(object, newEvent) );
      return true;
    }

    case QEvent::MouseButtonRelease:
    {
      m_ButtonPressed = false;
      //std::cout << "#BR ";

      QMouseEvent* me = ( QMouseEvent* )( event );

      QMouseEvent* newEvent = new QMouseEvent(
        me->type(), me->pos(), me->globalPos(), me->button(), me->state()
      );
      m_EventQueue.push( ObjectEventPair(object, newEvent) );
      return true;
    }

    case QEvent::MouseMove:
    {
      if(m_ButtonPressed && mitk::RenderingManager::GetInstance()->GetCurrentLOD()!=0)
      {
      //std::cout << "#MM ";
          mitk::RenderingManager::GetInstance()->SetCurrentLOD(0);
          mitk::RenderingManager::GetInstance()->AbortRendering( NULL );
      }
      return true;
    }

    case QEvent::Resize:
      {
        //std::cout << "#R ";
        mitk::RenderingManager::GetInstance()->AbortRendering( NULL );

        QResizeEvent* re = ( QResizeEvent* )( event );

        QResizeEvent* newResizeEvent = new QResizeEvent( re->size(), re->oldSize() );
        m_EventQueue.push( ObjectEventPair(object, newResizeEvent) );
        return true;
      }

    case QEvent::Paint:
      {
        //std::cout << "#P ";
        QPaintEvent* pe = ( QPaintEvent* )( event );
        QPaintEvent* newPaintEvent = new QPaintEvent( pe->region() );
        m_EventQueue.push( ObjectEventPair(object, newPaintEvent) );
        return true;
      }

     case QEvent::ShowWindowRequest:
      {
        //std::cout << "#WR ";
        return false;
      }

      case QEvent::LayoutHint:
      {
        //std::cout << "#L ";
        return false;
      }
     case QEvent::ChildInserted: //change Layout (Big3D, 2D images up, etc.)
      {
        //std::cout << "#CI ";
        mitk::RenderingManager::GetInstance()->SetCurrentLOD(0);
        mitk::RenderingManager::GetInstance()->AbortRendering( NULL );
        return false;
      }

      case QEvent::KeyPress:
      {
        //std::cout << "#KP ";
        mitk::RenderingManager::GetInstance()->AbortRendering( NULL );
        QKeyEvent* ke = ( QKeyEvent* )( event );
        QKeyEvent* newEvent = new QKeyEvent(
          ke->type(), ke->key(), ke->ascii(), ke->state(), ke->text(), false, ke->count()
        );
        m_EventQueue.push( ObjectEventPair(object, newEvent) );
        return true;
      }

      case QEvent::Timer:
      {
        //std::cout << "#T ";
        QTimerEvent* te = ( QTimerEvent* )( event );
        QTimerEvent* newEvent = new QTimerEvent(te->timerId());
        m_EventQueue.push( ObjectEventPair(object, newEvent) );
        return true;
      }

      default:
      {
        //std::cout<<"Event Type: (Rendering)"<<event->type()<<std::endl;
        return false;
      }
    }
  }
 else
  {
    if(event->type()==QEvent::MouseButtonPress)
    {
      m_ButtonPressed = true;
      //std::cout << "#BP2 ";
      return false;
    }

    if(event->type()==QEvent::MouseMove)
    {
      if(m_ButtonPressed){
        //std::cout << "#MM2 ";
        mitk::RenderingManager::GetInstance()->SetCurrentLOD(0);
      }
      return false;
    }

    if(event->type()==QEvent::MouseButtonRelease)
    {
      m_ButtonPressed = false;
      //std::cout << "#BR2 ";
      return false;
    }

    if(event->type()==QEvent::Resize)
    {
      //std::cout << "#R2 ";
      mitk::RenderingManager::GetInstance()->SetCurrentLOD(0);
      //mitk::RenderingManager::GetInstance()->RequestUpdateAll();
      return false;
    }

    if(event->type()==QEvent::ChildInserted)
    {
      //std::cout << "#CI2 ";
      mitk::RenderingManager::GetInstance()->SetCurrentLOD(0);
      return false;
    }

    //std::cout<<"Event Type: (Not Rendering)"<<event->type()<<std::endl;

  }
  return false;
}

void QmitkAbortEventFilter::ProcessEvents()
{
  //std::cout << "P";
  qApp->eventLoop()->processEvents( QEventLoop::AllEvents );
}

void QmitkAbortEventFilter::IssueQueuedEvents()
{
  while ( !m_EventQueue.empty() )
  {
    ObjectEventPair eventPair = m_EventQueue.front();
    QApplication::postEvent( eventPair.first, eventPair.second );
    m_EventQueue.pop();
  }

}
<|endoftext|>