<commit_before>#include "editorviewscene.h"
#include "editorviewmviface.h"
#include "editorview.h"

#include <QGraphicsTextItem>
#include <QtGui>

EditorViewScene::EditorViewScene(QObject * parent)
	:  QGraphicsScene(parent)
{
//	setSceneRect(-400, -300, 800, 600);
	setItemIndexMethod(NoIndex);
//	setBackgroundBrush(gradient);
}

void EditorViewScene::clearScene()
{
	QList < QGraphicsItem * >list = items();
	QList < QGraphicsItem * >::Iterator it = list.begin();
	for (; it != list.end(); ++it) {
		removeItem(*it);
	}
}

UML::Element * EditorViewScene::getElem(int uuid)
{
	// FIXME: SLOW!
	QList < QGraphicsItem * > list = items();
	for (QList < QGraphicsItem * >::Iterator it = list.begin(); it != list.end(); ++it) {
		if (UML::Element * elem = dynamic_cast < UML::Element * >(*it)) {
			if (elem->uuid() == uuid) {
				return elem;
			}
		}
	}
	return 0;
}

void EditorViewScene::dragEnterEvent ( QGraphicsSceneDragDropEvent * event )
{
	Q_UNUSED(event);
//	event->setAccepted();
}

void EditorViewScene::dragMoveEvent ( QGraphicsSceneDragDropEvent * event )
{
	Q_UNUSED(event);
}

void EditorViewScene::dragLeaveEvent ( QGraphicsSceneDragDropEvent * event )
{
	Q_UNUSED(event);
}

void EditorViewScene::dropEvent ( QGraphicsSceneDragDropEvent * event )
{
	// Transform mime data to include coordinates.
	const QMimeData *mimeData = event->mimeData();
	QByteArray itemData = mimeData->data("application/x-real-uml-data");

	QDataStream in_stream(&itemData, QIODevice::ReadOnly);

	int uuid, type_id;
	QString name;
	QPointF pos;

	in_stream >> uuid;
	in_stream >> type_id;
	in_stream >> name;
	in_stream >> pos;

	QByteArray newItemData;
	QDataStream stream(&newItemData, QIODevice::WriteOnly);

	stream << uuid;				// uuid
	stream << type_id;			// type
	stream << name;
	stream << event->scenePos();

	QMimeData *newMimeData = new QMimeData;
	newMimeData->setData("application/x-real-uml-data", newItemData);

	mv_iface->model()->dropMimeData( newMimeData, event->dropAction(),
			mv_iface->model()->rowCount(mv_iface->rootIndex()), 0, mv_iface->rootIndex() );
}

void EditorViewScene::keyPressEvent( QKeyEvent * event )
{
	if ( event->key() == Qt::Key_Delete ) {
		QList<QGraphicsItem *> list = selectedItems();
		foreach ( QGraphicsItem *item, list ) {
			if ( UML::Element *e = dynamic_cast<UML::Element *>(item) ) {

			}
		}
	}

	QGraphicsScene::keyPressEvent(event);
}
<commit_msg>Fix yet another memory leak.<commit_after>#include "editorviewscene.h"
#include "editorviewmviface.h"
#include "editorview.h"

#include <QGraphicsTextItem>
#include <QtGui>

EditorViewScene::EditorViewScene(QObject * parent)
	:  QGraphicsScene(parent)
{
//	setSceneRect(-400, -300, 800, 600);
	setItemIndexMethod(NoIndex);
//	setBackgroundBrush(gradient);
}

void EditorViewScene::clearScene()
{
	QList < QGraphicsItem * >list = items();
	QList < QGraphicsItem * >::Iterator it = list.begin();
	for (; it != list.end(); ++it) {
		removeItem(*it);
	}
}

UML::Element * EditorViewScene::getElem(int uuid)
{
	// FIXME: SLOW!
	QList < QGraphicsItem * > list = items();
	for (QList < QGraphicsItem * >::Iterator it = list.begin(); it != list.end(); ++it) {
		if (UML::Element * elem = dynamic_cast < UML::Element * >(*it)) {
			if (elem->uuid() == uuid) {
				return elem;
			}
		}
	}
	return 0;
}

void EditorViewScene::dragEnterEvent ( QGraphicsSceneDragDropEvent * event )
{
	Q_UNUSED(event);
//	event->setAccepted();
}

void EditorViewScene::dragMoveEvent ( QGraphicsSceneDragDropEvent * event )
{
	Q_UNUSED(event);
}

void EditorViewScene::dragLeaveEvent ( QGraphicsSceneDragDropEvent * event )
{
	Q_UNUSED(event);
}

void EditorViewScene::dropEvent ( QGraphicsSceneDragDropEvent * event )
{
	// Transform mime data to include coordinates.
	const QMimeData *mimeData = event->mimeData();
	QByteArray itemData = mimeData->data("application/x-real-uml-data");

	QDataStream in_stream(&itemData, QIODevice::ReadOnly);

	int uuid, type_id;
	QString name;
	QPointF pos;

	in_stream >> uuid;
	in_stream >> type_id;
	in_stream >> name;
	in_stream >> pos;

	QByteArray newItemData;
	QDataStream stream(&newItemData, QIODevice::WriteOnly);

	stream << uuid;				// uuid
	stream << type_id;			// type
	stream << name;
	stream << event->scenePos();

	QMimeData *newMimeData = new QMimeData;
	newMimeData->setData("application/x-real-uml-data", newItemData);

	mv_iface->model()->dropMimeData( newMimeData, event->dropAction(),
			mv_iface->model()->rowCount(mv_iface->rootIndex()), 0, mv_iface->rootIndex() );
	delete newMimeData;
}

void EditorViewScene::keyPressEvent( QKeyEvent * event )
{
	if ( event->key() == Qt::Key_Delete ) {
		QList<QGraphicsItem *> list = selectedItems();
		foreach ( QGraphicsItem *item, list ) {
			if ( UML::Element *e = dynamic_cast<UML::Element *>(item) ) {

			}
		}
	}

	QGraphicsScene::keyPressEvent(event);
}
<|endoftext|>


<commit_before>/** @file editorviewscene.cpp
 * 	@brief Сцена для отрисовки объектов
 * */
#include "editorviewscene.h"
#include "editorviewmviface.h"
#include "editorview.h"

#include <QGraphicsTextItem>
#include <QtGui>

EditorViewScene::EditorViewScene(QObject * parent)
	:  QGraphicsScene(parent)
{
//	setSceneRect(-400, -300, 800, 600);
	setItemIndexMethod(NoIndex);
//	setBackgroundBrush(gradient);
}

void EditorViewScene::clearScene()
{
	QList < QGraphicsItem * >list = items();
	QList < QGraphicsItem * >::Iterator it = list.begin();
	for (; it != list.end(); ++it) {
		removeItem(*it);
	}
}

UML::Element * EditorViewScene::getElem(int uuid)
{
	// FIXME: SLOW!
	QList < QGraphicsItem * > list = items();
	for (QList < QGraphicsItem * >::Iterator it = list.begin(); it != list.end(); ++it) {
		if (UML::Element * elem = dynamic_cast < UML::Element * >(*it)) {
			if (elem->uuid() == uuid) {
				return elem;
			}
		}
	}
	return 0;
}

UML::Element * EditorViewScene::getElemByModelIndex(const QModelIndex &ind)
{
	// FIXME: SLOW!
	QList < QGraphicsItem * > list = items();
	for (QList < QGraphicsItem * >::Iterator it = list.begin(); it != list.end(); ++it) {
		if (UML::Element * elem = dynamic_cast < UML::Element * >(*it)) {
			if (elem->index() == ind)
				return elem;
		}
	}
	return 0;
}

void EditorViewScene::dragEnterEvent ( QGraphicsSceneDragDropEvent * event )
{
	Q_UNUSED(event);
//	event->setAccepted();
}

void EditorViewScene::dragMoveEvent ( QGraphicsSceneDragDropEvent * event )
{
	Q_UNUSED(event);
}

void EditorViewScene::dragLeaveEvent ( QGraphicsSceneDragDropEvent * event )
{
	Q_UNUSED(event);
}

void EditorViewScene::dropEvent ( QGraphicsSceneDragDropEvent * event )
{
	// Transform mime data to include coordinates.
	const QMimeData *mimeData = event->mimeData();
	QByteArray itemData = mimeData->data("application/x-real-uml-data");

	QDataStream in_stream(&itemData, QIODevice::ReadOnly);

	int uuid, type_id, oldparent;
	QString name;
	QPointF pos;

	in_stream >> uuid;
	in_stream >> type_id;
	in_stream >> oldparent;
	in_stream >> name;
	in_stream >> pos;

	QByteArray newItemData;
	QDataStream stream(&newItemData, QIODevice::WriteOnly);

	stream << uuid;				// uuid
	stream << type_id;			// type
	stream << name;
	stream << event->scenePos();

	QMimeData *newMimeData = new QMimeData;
	newMimeData->setData("application/x-real-uml-data", newItemData);

	mv_iface->model()->dropMimeData( newMimeData, event->dropAction(),
			mv_iface->model()->rowCount(mv_iface->rootIndex()), 0, mv_iface->rootIndex() );
	delete newMimeData;
}

void EditorViewScene::keyPressEvent( QKeyEvent * event )
{
	QGraphicsScene::keyPressEvent(event);
}
<commit_msg>Креш при перетаскивании элемента на канву поправлен.<commit_after>/** @file editorviewscene.cpp
 * 	@brief Сцена для отрисовки объектов
 * */
#include "editorviewscene.h"
#include "editorviewmviface.h"
#include "editorview.h"

#include <QGraphicsTextItem>
#include <QtGui>

EditorViewScene::EditorViewScene(QObject * parent)
	:  QGraphicsScene(parent)
{
//	setSceneRect(-400, -300, 800, 600);
	setItemIndexMethod(NoIndex);
//	setBackgroundBrush(gradient);
}

void EditorViewScene::clearScene()
{
	QList < QGraphicsItem * >list = items();
	QList < QGraphicsItem * >::Iterator it = list.begin();
	for (; it != list.end(); ++it) {
		removeItem(*it);
	}
}

UML::Element * EditorViewScene::getElem(int uuid)
{
	// FIXME: SLOW!
	QList < QGraphicsItem * > list = items();
	for (QList < QGraphicsItem * >::Iterator it = list.begin(); it != list.end(); ++it) {
		if (UML::Element * elem = dynamic_cast < UML::Element * >(*it)) {
			if (elem->uuid() == uuid) {
				return elem;
			}
		}
	}
	return 0;
}

UML::Element * EditorViewScene::getElemByModelIndex(const QModelIndex &ind)
{
	// FIXME: SLOW!
	QList < QGraphicsItem * > list = items();
	for (QList < QGraphicsItem * >::Iterator it = list.begin(); it != list.end(); ++it) {
		if (UML::Element * elem = dynamic_cast < UML::Element * >(*it)) {
			if (elem->index() == ind)
				return elem;
		}
	}
	return 0;
}

void EditorViewScene::dragEnterEvent ( QGraphicsSceneDragDropEvent * event )
{
	Q_UNUSED(event);
//	event->setAccepted();
}

void EditorViewScene::dragMoveEvent ( QGraphicsSceneDragDropEvent * event )
{
	Q_UNUSED(event);
}

void EditorViewScene::dragLeaveEvent ( QGraphicsSceneDragDropEvent * event )
{
	Q_UNUSED(event);
}

void EditorViewScene::dropEvent ( QGraphicsSceneDragDropEvent * event )
{
	// Transform mime data to include coordinates.
	const QMimeData *mimeData = event->mimeData();
	QByteArray itemData = mimeData->data("application/x-real-uml-data");

	QDataStream in_stream(&itemData, QIODevice::ReadOnly);

	int uuid, type_id, oldparent;
	QString name;
	QPointF pos;

	in_stream >> uuid;
	in_stream >> type_id;
	in_stream >> oldparent;
	in_stream >> name;
	in_stream >> pos;

	QByteArray newItemData;
	QDataStream stream(&newItemData, QIODevice::WriteOnly);

	stream << uuid;				// uuid
	stream << type_id;			// type
	stream << oldparent;
	stream << name;
	stream << event->scenePos();

	QMimeData *newMimeData = new QMimeData;
	newMimeData->setData("application/x-real-uml-data", newItemData);

	mv_iface->model()->dropMimeData( newMimeData, event->dropAction(),
			mv_iface->model()->rowCount(mv_iface->rootIndex()), 0, mv_iface->rootIndex() );
	delete newMimeData;
}

void EditorViewScene::keyPressEvent( QKeyEvent * event )
{
	QGraphicsScene::keyPressEvent(event);
}
<|endoftext|>


<commit_before>#define _WIN32_WINNT 0x0400
#pragma comment( lib, "user32.lib" )

#include <iostream>
#include <windows.h>
#include <stdio.h>
#include <shellapi.h>
#include "resource.h"

#define WM_MYMESSAGE (WM_USER + 1)

#if _DEBUG
#define SHOW_WINDOW 1
#else
#define SHOW_WINDOW 0
#endif

HHOOK hKeyboardHook;

HWND GetConsoleWindow() {
	return FindWindow("ConsoleWindowClass", NULL);
}

__declspec(dllexport) LRESULT CALLBACK KeyboardEvent(int nCode, WPARAM wParam, LPARAM lParam)
{
	DWORD SHIFT_key = 0;
	DWORD CTRL_key = 0;
	DWORD ALT_key = 0;

	if ((nCode == HC_ACTION) && ((wParam == WM_SYSKEYDOWN) || (wParam == WM_KEYDOWN)))
	{
		KBDLLHOOKSTRUCT hooked_key = *((KBDLLHOOKSTRUCT*)lParam);
		DWORD dwMsg = 1;
		dwMsg += hooked_key.scanCode << 16;
		dwMsg += hooked_key.flags << 24;
		char lpszKeyName[1024] = { 0 };

		int i = GetKeyNameText(dwMsg, (lpszKeyName + 1), 0xFF) + 1;

		int key = hooked_key.vkCode;

		if (hooked_key.vkCode == VK_CAPITAL) {
			if ((GetKeyState(VK_CAPITAL) & 0x0001) == 0) {
				keybd_event(VK_CAPITAL, 0, KEYEVENTF_EXTENDEDKEY | 0, 0);
				keybd_event(VK_CAPITAL, 0, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
			}
		}

		SHIFT_key = GetAsyncKeyState(VK_SHIFT);
		CTRL_key = GetAsyncKeyState(VK_CONTROL);
		ALT_key = GetAsyncKeyState(VK_MENU);

		if (key >= 'A' && key <= 'Z')
		{

			if (GetAsyncKeyState(VK_SHIFT) >= 0) key += 32;

			// Lets you quit the program lmao
			if (CTRL_key != 0 && ALT_key != 0 && SHIFT_key != 0 && key == 'Q')
			{
				PostQuitMessage(0);
			}

			SHIFT_key = 0;
			CTRL_key = 0;
			ALT_key = 0;
		}

	}

	return CallNextHookEx(hKeyboardHook, nCode, wParam, lParam);
}

void MessageLoop()
{
	MSG message;
	while (GetMessage(&message, NULL, 0, 0))
	{
		TranslateMessage(&message);
		DispatchMessage(&message);
	}
}

DWORD WINAPI CapsLockKillerHook(LPVOID lpParm)
{
	HINSTANCE hInstance = GetModuleHandle(NULL);
	if (!hInstance) hInstance = LoadLibrary((LPCSTR)lpParm);
	if (!hInstance) return 1;

	hKeyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, (HOOKPROC)KeyboardEvent, hInstance, NULL);
	MessageLoop();
	UnhookWindowsHookEx(hKeyboardHook);
	return 0;
}

void TaskbarNotify() {
	HWND hWnd = GetConsoleWindow();

	NOTIFYICONDATA Tray;
	ShowWindow(hWnd, SHOW_WINDOW);
	Tray.cbSize = sizeof(Tray);
	Tray.hIcon = LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_ICON1));
	Tray.hWnd = hWnd;
	strcpy_s(Tray.szTip, "NoCapsLock - Running");
	Tray.uCallbackMessage = WM_MYMESSAGE;
	Tray.uFlags = NIF_ICON | NIF_TIP | NIF_MESSAGE;
	Tray.uID = 1;
	Shell_NotifyIcon(NIM_ADD, &Tray);
}

bool CheckOneInstance()
{

	HANDLE  m_hStartEvent = CreateEventW(NULL, FALSE, FALSE, L"Global\\CSAPP");

	if (m_hStartEvent == NULL)
	{
		CloseHandle(m_hStartEvent);
		return false;
	}

	if (GetLastError() == ERROR_ALREADY_EXISTS) {

		CloseHandle(m_hStartEvent);
		m_hStartEvent = NULL;
		return false;
	}

	return true;
}

int main(int argc, char** argv)
{
	if (CheckOneInstance()) {
		HANDLE hThread;
		DWORD dwThread;
		printf("Simple tool created by Toyz which allows you to kill capslock\n");
		printf("Source code at: https://github.com/Toyz/NoCapsLock\n");
		printf("LICENSED UNDER APACHE 2.0\n");

		hThread = CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)CapsLockKillerHook, (LPVOID)argv[0], NULL, &dwThread);

		TaskbarNotify();
		if (hThread) return WaitForSingleObject(hThread, INFINITE);
		else return 1;
	}
	else {
		ShowWindow(GetConsoleWindow(), 0);
		MessageBox(HWND_DESKTOP, "Only one instance can be running at a given time!", "ERROR", MB_ICONERROR | MB_OK);
		return 0;
	}
}
<commit_msg>Minor title fix for error<commit_after>#define _WIN32_WINNT 0x0400
#pragma comment( lib, "user32.lib" )

#include <iostream>
#include <windows.h>
#include <stdio.h>
#include <shellapi.h>
#include "resource.h"

#define WM_MYMESSAGE (WM_USER + 1)

#if _DEBUG
#define SHOW_WINDOW 1
#else
#define SHOW_WINDOW 0
#endif

HHOOK hKeyboardHook;

HWND GetConsoleWindow() {
	return FindWindow("ConsoleWindowClass", NULL);
}

__declspec(dllexport) LRESULT CALLBACK KeyboardEvent(int nCode, WPARAM wParam, LPARAM lParam)
{
	DWORD SHIFT_key = 0;
	DWORD CTRL_key = 0;
	DWORD ALT_key = 0;

	if ((nCode == HC_ACTION) && ((wParam == WM_SYSKEYDOWN) || (wParam == WM_KEYDOWN)))
	{
		KBDLLHOOKSTRUCT hooked_key = *((KBDLLHOOKSTRUCT*)lParam);
		DWORD dwMsg = 1;
		dwMsg += hooked_key.scanCode << 16;
		dwMsg += hooked_key.flags << 24;
		char lpszKeyName[1024] = { 0 };

		int i = GetKeyNameText(dwMsg, (lpszKeyName + 1), 0xFF) + 1;

		int key = hooked_key.vkCode;

		if (hooked_key.vkCode == VK_CAPITAL) {
			if ((GetKeyState(VK_CAPITAL) & 0x0001) == 0) {
				keybd_event(VK_CAPITAL, 0, KEYEVENTF_EXTENDEDKEY | 0, 0);
				keybd_event(VK_CAPITAL, 0, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
			}
		}

		SHIFT_key = GetAsyncKeyState(VK_SHIFT);
		CTRL_key = GetAsyncKeyState(VK_CONTROL);
		ALT_key = GetAsyncKeyState(VK_MENU);

		if (key >= 'A' && key <= 'Z')
		{

			if (GetAsyncKeyState(VK_SHIFT) >= 0) key += 32;

			// Lets you quit the program lmao
			if (CTRL_key != 0 && ALT_key != 0 && SHIFT_key != 0 && key == 'Q')
			{
				PostQuitMessage(0);
			}

			SHIFT_key = 0;
			CTRL_key = 0;
			ALT_key = 0;
		}

	}

	return CallNextHookEx(hKeyboardHook, nCode, wParam, lParam);
}

void MessageLoop()
{
	MSG message;
	while (GetMessage(&message, NULL, 0, 0))
	{
		TranslateMessage(&message);
		DispatchMessage(&message);
	}
}

DWORD WINAPI CapsLockKillerHook(LPVOID lpParm)
{
	HINSTANCE hInstance = GetModuleHandle(NULL);
	if (!hInstance) hInstance = LoadLibrary((LPCSTR)lpParm);
	if (!hInstance) return 1;

	hKeyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, (HOOKPROC)KeyboardEvent, hInstance, NULL);
	MessageLoop();
	UnhookWindowsHookEx(hKeyboardHook);
	return 0;
}

void TaskbarNotify() {
	HWND hWnd = GetConsoleWindow();

	NOTIFYICONDATA Tray;
	ShowWindow(hWnd, SHOW_WINDOW);
	Tray.cbSize = sizeof(Tray);
	Tray.hIcon = LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_ICON1));
	Tray.hWnd = hWnd;
	strcpy_s(Tray.szTip, "NoCapsLock - Running");
	Tray.uCallbackMessage = WM_MYMESSAGE;
	Tray.uFlags = NIF_ICON | NIF_TIP | NIF_MESSAGE;
	Tray.uID = 1;
	Shell_NotifyIcon(NIM_ADD, &Tray);
}

bool CheckOneInstance()
{

	HANDLE  m_hStartEvent = CreateEventW(NULL, FALSE, FALSE, L"Global\\CSAPP");

	if (m_hStartEvent == NULL)
	{
		CloseHandle(m_hStartEvent);
		return false;
	}

	if (GetLastError() == ERROR_ALREADY_EXISTS) {

		CloseHandle(m_hStartEvent);
		m_hStartEvent = NULL;
		return false;
	}

	return true;
}

int main(int argc, char** argv)
{
	if (CheckOneInstance()) {
		HANDLE hThread;
		DWORD dwThread;
		printf("Simple tool created by Toyz which allows you to kill capslock\n");
		printf("Source code at: https://github.com/Toyz/NoCapsLock\n");
		printf("LICENSED UNDER APACHE 2.0\n");

		hThread = CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)CapsLockKillerHook, (LPVOID)argv[0], NULL, &dwThread);

		TaskbarNotify();
		if (hThread) return WaitForSingleObject(hThread, INFINITE);
		else return 1;
	}
	else {
		ShowWindow(GetConsoleWindow(), 0);
		MessageBox(HWND_DESKTOP, "Only one instance can be running at a given time!", "ERROR - NoCapsLock", MB_ICONERROR | MB_OK);
		return 0;
	}
}
<|endoftext|>


<commit_before>/* Copyright (c) 2013 KrossX <krossx@live.com>
* License: http://www.opensource.org/licenses/mit-license.html  MIT License
*/

#include <Windows.h>
#include <iostream>
#include <fstream>
#include <vector>

#include "Advapi_Stuff.h"

enum
{
	MODE_AUTO,
	MODE_PATCH,
	MODE_UNPATCH
};

int setting_mode = MODE_AUTO;

static void find_all(char *buffer, char *str, size_t sizebuf, size_t size_str, std::vector<size_t> &pos)
{
	sizebuf -= size_str;

	for (size_t i = 0; i < sizebuf; i++)
	{
		if (!_strnicmp(&buffer[i], str, size_str))
			pos.push_back(i);
	}
}

static size_t find_single(char *buffer, char *str, size_t sizebuf, size_t size_str)
{
	sizebuf -= size_str;
	size_t pos = 0;

	for (size_t i = 0; i < sizebuf; i++)
	{
		if (!strncmp(&buffer[i], str, size_str))
		{
			pos = i;
			break;
		}
	}

	return pos;
}

static void CheapWide(char *str, wchar_t *out, size_t length)
{
	char *cbuf = (char*)out;

	memset(cbuf, 0, length * 2);

	size_t str_len = strlen(str);

	for(size_t i = 0; i < str_len; i++)
		cbuf[i*2] = str[i];
}

std::wstring parse_command_line(int count, wchar_t* lines[])
{
	std::vector<std::wstring> vlines;
	std::wstring out;

	for (int i = 1; i < count; i++)
		vlines.push_back(std::wstring(lines[i]));

	for (std::wstring &ws : vlines)
	{
		if (!_wcsicmp(ws.c_str(), L"-u") || !_wcsicmp(ws.c_str(), L"--unpatch"))
			setting_mode = MODE_UNPATCH;

		else if (!_wcsicmp(ws.c_str(), L"-p") || !_wcsicmp(ws.c_str(), L"--patch"))
			setting_mode = MODE_PATCH;
		else
			out = ws;
	}

	return out;
}

bool patch(std::fstream &file, char* buffer, size_t size)
{
	std::vector<size_t> advapi;
	find_all(buffer, "ADVAPI32", size, 8, advapi);

	std::vector<int> functionlist;

	bool fullcheck = false;
	bool supported = true;

	if (!advapi.empty())
	{
		if (fullcheck) for (int i = 0; i < 806; i++)
		{
			size_t func_len = strlen(Advapi_Function[i]);

			if (find_single(buffer, Advapi_Function[i], size, func_len))
			{
				functionlist.push_back(i);
				supported = supported && Advapi_Support[i];
			}
		};

		if (supported)
		{
			for (size_t pos : advapi)
			{
				file.seekg(pos, std::ios::beg);
				file.write("REGEMU32", 8);
			}
		}

		wprintf(L"ADVAPI32 found (%d) and patched. ", advapi.size());
	}
	else
	{
		wprintf(L"ADVAPI32 not found. ");
	}

	return !advapi.empty();
}

bool unpatch(std::fstream &file, char* buffer, size_t size)
{
	std::vector<size_t> regemu;
	find_all(buffer, "REGEMU32", size, 8, regemu);

	if (!regemu.empty())
	{
		for (size_t pos : regemu)
		{
			file.seekg(pos, std::ios::beg);
			file.write("ADVAPI32", 8);
		}

		wprintf(L"REGEMU32 found (%d) and unpatched. ", regemu.size());
	}
	else
	{
		wprintf(L"REGEMU32 not found. ");
	}

	return !regemu.empty();
}

int wmain(int argc, wchar_t* argv[])
{
	if (argc < 2)
	{
		wprintf(L"Regemu Patcher\n\n");
		wprintf(L"Usage: REGEMU32 file [option]\n\n");
		wprintf(L"  -p,  --patch             Replaces ADVAPI32 with REGEMU32 in FILE.\n");
		wprintf(L"  -u,  --unpatch           Replaces REGEMU32 with ADVAPI32 in FILE.\n");
		wprintf(L"\nDefault auto mode, unpatch is run if patch is unsuccessful.\n");

		return ERROR_SUCCESS;
	}

	std::wstring filename = parse_command_line(argc, argv);
	if (filename[0] == L'"') filename = filename.substr(1, filename.find_last_of(L'"') - 1);

	wprintf(L"%s (%d): ", filename.c_str(), setting_mode);

	std::fstream file(filename, std::ios::in | std::ios::out | std::ios::binary | std::ios::ate);

	if(file.is_open())
	{
		size_t size = static_cast<size_t>(file.tellg());
		char *buffer = new char[size];

		file.seekg(0, std::ios::beg);
		file.read(buffer, size);

		switch (setting_mode)
		{
		case MODE_AUTO: if (!patch(file, buffer, size)) unpatch(file, buffer, size); break;
		case MODE_PATCH: patch(file, buffer, size);  break;
		case MODE_UNPATCH: unpatch(file, buffer, size);  break;
		}

		wprintf(L"\n");

		//for each(int func in functionlist)
		//{
		//	wchar_t buff[64];
		//	CheapWide(Advapi_Function[func], buff, 64);
		//	message.append(buff).append(Advapi_Support[func] ? L"\t[o]" : L"\t[x]").append(L"\n");
		//}

		delete[] buffer;
		file.close();
	}
	else
	{
		wprintf(L"Could not open file.\n");
	}

	return EXIT_SUCCESS;
}
<commit_msg>Patcher now ignores itself<commit_after>/* Copyright (c) 2013 KrossX <krossx@live.com>
* License: http://www.opensource.org/licenses/mit-license.html  MIT License
*/

#include <Windows.h>
#include <Shlwapi.h>
#include <iostream>
#include <fstream>
#include <vector>

#include "Advapi_Stuff.h"

enum
{
	MODE_AUTO,
	MODE_PATCH,
	MODE_UNPATCH
};

int setting_mode = MODE_AUTO;

static void find_all(char *buffer, char *str, size_t sizebuf, size_t size_str, std::vector<size_t> &pos)
{
	sizebuf -= size_str;

	for (size_t i = 0; i < sizebuf; i++)
	{
		if (!_strnicmp(&buffer[i], str, size_str))
			pos.push_back(i);
	}
}

static size_t find_single(char *buffer, char *str, size_t sizebuf, size_t size_str)
{
	sizebuf -= size_str;
	size_t pos = 0;

	for (size_t i = 0; i < sizebuf; i++)
	{
		if (!strncmp(&buffer[i], str, size_str))
		{
			pos = i;
			break;
		}
	}

	return pos;
}

static void CheapWide(char *str, wchar_t *out, size_t length)
{
	char *cbuf = (char*)out;

	memset(cbuf, 0, length * 2);

	size_t str_len = strlen(str);

	for(size_t i = 0; i < str_len; i++)
		cbuf[i*2] = str[i];
}

std::wstring parse_command_line(int count, wchar_t* lines[])
{
	std::vector<std::wstring> vlines;
	std::wstring out;

	while (count--)
	{
		if (StrStrIW(lines[count], L"regemu32") == nullptr)
			vlines.push_back(std::wstring(lines[count]));
	}

	for (std::wstring &ws : vlines)
	{
		if (!_wcsicmp(ws.c_str(), L"-u") || !_wcsicmp(ws.c_str(), L"--unpatch"))
			setting_mode = MODE_UNPATCH;

		else if (!_wcsicmp(ws.c_str(), L"-p") || !_wcsicmp(ws.c_str(), L"--patch"))
			setting_mode = MODE_PATCH;
		else
			out = ws;
	}

	return out;
}

bool patch(std::fstream &file, char* buffer, size_t size)
{
	std::vector<size_t> advapi;
	find_all(buffer, "ADVAPI32", size, 8, advapi);

	std::vector<int> functionlist;

	bool fullcheck = false;
	bool supported = true;

	if (!advapi.empty())
	{
		if (fullcheck) for (int i = 0; i < 806; i++)
		{
			size_t func_len = strlen(Advapi_Function[i]);

			if (find_single(buffer, Advapi_Function[i], size, func_len))
			{
				functionlist.push_back(i);
				supported = supported && Advapi_Support[i];
			}
		};

		if (supported)
		{
			for (size_t pos : advapi)
			{
				file.seekg(pos, std::ios::beg);
				file.write("REGEMU32", 8);
			}
		}

		wprintf(L"ADVAPI32 found (%d) and patched. ", advapi.size());
	}
	else
	{
		wprintf(L"ADVAPI32 not found. ");
	}

	return !advapi.empty();
}

bool unpatch(std::fstream &file, char* buffer, size_t size)
{
	std::vector<size_t> regemu;
	find_all(buffer, "REGEMU32", size, 8, regemu);

	if (!regemu.empty())
	{
		for (size_t pos : regemu)
		{
			file.seekg(pos, std::ios::beg);
			file.write("ADVAPI32", 8);
		}

		wprintf(L"REGEMU32 found (%d) and unpatched. ", regemu.size());
	}
	else
	{
		wprintf(L"REGEMU32 not found. ");
	}

	return !regemu.empty();
}

int wmain(int argc, wchar_t* argv[])
{
	if (argc < 2)
	{
		wprintf(L"Regemu Patcher\n\n");
		wprintf(L"Usage: REGEMU32 file [option]\n\n");
		wprintf(L"  -p,  --patch             Replaces ADVAPI32 with REGEMU32 in FILE.\n");
		wprintf(L"  -u,  --unpatch           Replaces REGEMU32 with ADVAPI32 in FILE.\n");
		wprintf(L"\nDefault auto mode, unpatch is run if patch is unsuccessful.\n");

		return ERROR_SUCCESS;
	}

	std::wstring filename = parse_command_line(argc, argv);
	if (filename.empty()) return ERROR_SUCCESS;

	if (filename[0] == L'"') filename = filename.substr(1, filename.find_last_of(L'"') - 1);
	wprintf(L"%s (%d): ", filename.c_str(), setting_mode);

	std::fstream file(filename, std::ios::in | std::ios::out | std::ios::binary | std::ios::ate);

	if(file.is_open())
	{
		size_t size = static_cast<size_t>(file.tellg());
		char *buffer = new char[size];

		file.seekg(0, std::ios::beg);
		file.read(buffer, size);

		switch (setting_mode)
		{
		case MODE_AUTO: if (!patch(file, buffer, size)) unpatch(file, buffer, size); break;
		case MODE_PATCH: patch(file, buffer, size);  break;
		case MODE_UNPATCH: unpatch(file, buffer, size);  break;
		}

		wprintf(L"\n");

		//for each(int func in functionlist)
		//{
		//	wchar_t buff[64];
		//	CheapWide(Advapi_Function[func], buff, 64);
		//	message.append(buff).append(Advapi_Support[func] ? L"\t[o]" : L"\t[x]").append(L"\n");
		//}

		delete[] buffer;
		file.close();
	}
	else
	{
		wprintf(L"Could not open file.\n");
	}

	return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/* Copyright (c) 2017-2019 Hans-Kristian Arntzen
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include "lock_free_message_queue.hpp"
#include "util.hpp"
#include "aligned_alloc.hpp"
#include <stdlib.h>

namespace Util
{
void MessageQueuePayloadDeleter::operator()(void *ptr)
{
	memalign_free(ptr);
}

LockFreeMessageQueue::LockFreeMessageQueue()
{
	for (unsigned i = 0; i < 8; i++)
		payload_capacity[i] = 256u << i;
	for (unsigned i = 0; i < 8; i++)
		write_ring[i].reset((16u * 1024u) >> i);
	read_ring.reset(32 * 1024);

	// Pre-fill the rings.
	for (unsigned i = 0; i < 8; i++)
	{
		unsigned count = 512u >> i;
		for (unsigned j = 0; j < count; j++)
		{
			MessageQueuePayload payload;
			payload.set_payload_data(memalign_calloc(64, payload_capacity[i]), payload_capacity[i]);
			recycle_payload(std::move(payload));
		}
	}
}

size_t LockFreeMessageQueue::available_read_messages() const noexcept
{
	return read_ring.read_avail();
}

MessageQueuePayload LockFreeMessageQueue::read_message() noexcept
{
	MessageQueuePayload payload;
	read_ring.read_and_move(payload);
	return payload;
}

bool LockFreeMessageQueue::push_written_payload(MessageQueuePayload payload) noexcept
{
	return read_ring.write_and_move(std::move(payload));
}

void LockFreeMessageQueue::recycle_payload(MessageQueuePayload payload) noexcept
{
	for (unsigned i = 0; i < 8; i++)
	{
		if (payload.get_capacity() == payload_capacity[i])
		{
			if (!write_ring[i].write_and_move(std::move(payload)))
				LOGE("Failed to recycle write payload. Increase sizes!\n");
			return;
		}
	}
}

MessageQueuePayload LockFreeMessageQueue::allocate_write_payload(size_t size) noexcept
{
	MessageQueuePayload payload;
	for (unsigned i = 0; i < 8; i++)
	{
		if (size <= payload_capacity[i])
		{
			if (!write_ring[i].read_and_move(payload))
			{
				LOGE("Failed to allocate write payload. Have to allocate a new one on the fly. Increase sizes!\n");
				payload.set_payload_data(memalign_calloc(64, payload_capacity[i]), payload_capacity[i]);
			}
			return payload;
		}
	}

	LOGE("Failed to allocate any payload. Making a temporary one. Increase max payload size!\n");
	payload.set_payload_data(memalign_calloc(64, size), size);
	return payload;
}
}<commit_msg>Add a required include to lock_free_message_queue.<commit_after>/* Copyright (c) 2017-2019 Hans-Kristian Arntzen
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include "lock_free_message_queue.hpp"
#include "util.hpp"
#include "aligned_alloc.hpp"
#include <stdlib.h>
#include <algorithm>

namespace Util
{
void MessageQueuePayloadDeleter::operator()(void *ptr)
{
	memalign_free(ptr);
}

LockFreeMessageQueue::LockFreeMessageQueue()
{
	for (unsigned i = 0; i < 8; i++)
		payload_capacity[i] = 256u << i;
	for (unsigned i = 0; i < 8; i++)
		write_ring[i].reset((16u * 1024u) >> i);
	read_ring.reset(32 * 1024);

	// Pre-fill the rings.
	for (unsigned i = 0; i < 8; i++)
	{
		unsigned count = 512u >> i;
		for (unsigned j = 0; j < count; j++)
		{
			MessageQueuePayload payload;
			payload.set_payload_data(memalign_calloc(64, payload_capacity[i]), payload_capacity[i]);
			recycle_payload(std::move(payload));
		}
	}
}

size_t LockFreeMessageQueue::available_read_messages() const noexcept
{
	return read_ring.read_avail();
}

MessageQueuePayload LockFreeMessageQueue::read_message() noexcept
{
	MessageQueuePayload payload;
	read_ring.read_and_move(payload);
	return payload;
}

bool LockFreeMessageQueue::push_written_payload(MessageQueuePayload payload) noexcept
{
	return read_ring.write_and_move(std::move(payload));
}

void LockFreeMessageQueue::recycle_payload(MessageQueuePayload payload) noexcept
{
	for (unsigned i = 0; i < 8; i++)
	{
		if (payload.get_capacity() == payload_capacity[i])
		{
			if (!write_ring[i].write_and_move(std::move(payload)))
				LOGE("Failed to recycle write payload. Increase sizes!\n");
			return;
		}
	}
}

MessageQueuePayload LockFreeMessageQueue::allocate_write_payload(size_t size) noexcept
{
	MessageQueuePayload payload;
	for (unsigned i = 0; i < 8; i++)
	{
		if (size <= payload_capacity[i])
		{
			if (!write_ring[i].read_and_move(payload))
			{
				LOGE("Failed to allocate write payload. Have to allocate a new one on the fly. Increase sizes!\n");
				payload.set_payload_data(memalign_calloc(64, payload_capacity[i]), payload_capacity[i]);
			}
			return payload;
		}
	}

	LOGE("Failed to allocate any payload. Making a temporary one. Increase max payload size!\n");
	payload.set_payload_data(memalign_calloc(64, size), size);
	return payload;
}
}
<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <algothim>

namespace ML {
struct Elem {
	double p;
	double y;
};

bool LessThan(Elem a, Elem b)
{
	return a.p < b.p;
}

double auc(std::vector<Elem>& res)
{
	std::sort(res, LessThan);
	double auc = 0.0;
	int rank = res.size();
	for (int i=0; i<res.size(); ++i)
	{

	}
}

}

<commit_msg>update auc<commit_after>#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <fstream>
#include "gflags/gflags.h"
#include "Common/log.h"

DEFINE_string(res_file, "", "predict res");
DEFINE_int32(log_level, 2, "LogLevel :"
    "0 : TRACE "
    "1 : DEBUG "
    "2 : INFO "
    "3 : ERROR");

uint32_t log_level = 0;

namespace ML {
struct Elem {
	double p;
	double y;
};

bool LessThan(const Elem& a, const Elem& b) {
	return a.p < b.p;
}

bool Equal(const Elem& a, const Elem& b) {
	return fabs(a.p - b.p) < 1.e-10;
}

void check(const Elem& e, int& n, int& p) {
	if (e.y < 0.5) {
		n++;
	}
	else {
		p++;
	}
}

double auc(std::vector<Elem>& res) {
	if (res.size() <= 0)
	{
		return 0.5;
	}
	std::sort(res.begin(), res.end(), LessThan);
	int n = 0;
	int p = 0;
	int cur_n = 0;
	int cur_p = 0;
	double correct = 0;
	check(res[0], cur_n, cur_p);
	for (size_t i=1; i<res.size(); ++i)
	{
		if (Equal(res[i], res[i-1]))
		{
			check(res[i], cur_n, cur_p);
		}
		else
		{
			correct += cur_p*n + 0.5*cur_p*cur_n;
			p += cur_p;
			n += cur_n;
			cur_p = 0;
			cur_n = 0;
			check(res[i], cur_n, cur_p);
		}
	}
	correct += cur_p*n + 0.5*cur_p*cur_n;
	p += cur_p;
	n += cur_n;
	LOG_INFO("POSITIVE : %d , NEGATIVE : %d, CORRECT : %lf", p, n, correct);
	if (n == 0) return 1.0;
	if (p == 0) return 0.0;
	return correct*1.0/(p*n);
}

}

using namespace ML;
int main(int argc, char** argv)
{
    google::ParseCommandLineFlags(&argc, &argv, true);
    log_level = FLAGS_log_level;
    if (FLAGS_res_file.empty())
    {
        std::cout<< "res file is empty!" << std::endl;
        return 0;
    }
    std::ifstream infile(FLAGS_res_file.c_str());
    if (!infile)
    {
        LOG_ERROR("Load res file : %s failed!", FLAGS_res_file.c_str());
        return 0;
    }

    std::string line;
    std::vector<Elem> res;
    Elem e;
    e.p = 0.0;
    e.y = 1.0;
    getline(infile, line);
    while (!infile.eof())
    {
    	sscanf(line.c_str(), "%lf %lf", &(e.y), &(e.p));
    	LOG_TRACE("Elem p : %lf, y : %lf", e.p, e.y);
    	res.push_back(e);
    	getline(infile, line);
    }
    LOG_TRACE("Res size : %lu", res.size());
    printf("[%s]AUC = %lf\n", FLAGS_res_file.c_str(), auc(res));
    return 0;
}
<|endoftext|>


<commit_before>//---------------------------------------------------------------------------//
/*
  Copyright (c) 2012, Stuart R. Slattery
  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 the University of Wisconsin - Madison 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
  HOLDER 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.
*/
//---------------------------------------------------------------------------//
/*!
 * \brief DTK_POD_PointCloudEntitySet.cpp
 * \author Stuart R. Slattery
 * \brief POD point cloud entity set.
 */
//---------------------------------------------------------------------------//

#include <algorithm>

#include "DTK_POD_PointCloudEntitySet.hpp"
#include "DTK_POD_PointCloudEntity.hpp"
#include "DTK_POD_PointCloudEntityIterator.hpp"
#include "DTK_DBC.hpp"

#include <Teuchos_DefaultMpiComm.hpp>

namespace DataTransferKit
{
//---------------------------------------------------------------------------//
// Constructor.
POD_PointCloudEntitySet::POD_PointCloudEntitySet(
    const Teuchos::RCP<const Teuchos::Comm<int> >& comm,
    const double* cloud_coords,
    const EntityId* global_ids,
    const unsigned num_points,
    const int space_dim,
    const DataLayout layout )
    : d_comm( comm )
    , d_cloud_coords( cloud_coords )
    , d_global_ids( global_ids )
    , d_num_points( num_points )
    , d_space_dim( space_dim )
    , d_layout( layout )
{ /* ... */ }

//---------------------------------------------------------------------------//
// Get the parallel communicator for the entity set.
Teuchos::RCP<const Teuchos::Comm<int> >
POD_PointCloudEntitySet::communicator() const
{
    return d_comm;
}

//---------------------------------------------------------------------------//
// Return the largest physical dimension of the entities in the set.
int POD_PointCloudEntitySet::physicalDimension() const
{
    return d_space_dim;
}

//---------------------------------------------------------------------------//
// Given an EntityId, get the entity.
void POD_PointCloudEntitySet::getEntity( const EntityId entity_id,
                                         const int topological_dimension,
                                         Entity& entity ) const
{
    DTK_REQUIRE( 0 == topological_dimension );
    DTK_REQUIRE( 1 == std::count(&d_global_ids[0],
                                 &d_global_ids[0] + d_num_points,
                                 entity_id) );

    int local_id = std::distance( &d_global_ids[0],
                                  std::find(&d_global_ids[0],
                                            &d_global_ids[0] + d_num_points,
                                            entity_id) );

    entity = POD_PointCloudEntity( d_cloud_coords,
                                   d_num_points,
                                   d_space_dim,
                                   d_layout,
                                   entity_id,
                                   local_id,
                                   d_comm->getRank() );
}

//---------------------------------------------------------------------------//
// Get an iterator over a subset of the entity set that satisfies the given
// predicate.
EntityIterator POD_PointCloudEntitySet::entityIterator(
    const int topological_dimension,
    const PredicateFunction& predicate ) const
{
    DTK_REQUIRE( 0 == topological_dimension );

    return POD_PointCloudEntityIterator( d_cloud_coords,
                                         d_global_ids,
                                         d_num_points,
                                         d_space_dim,
                                         d_layout,
                                         d_comm->getRank(),
                                         predicate );
}

//---------------------------------------------------------------------------//
// Given an entity, get the entities of the given type that are adjacent to
// it.
void POD_PointCloudEntitySet::getAdjacentEntities(
    const Entity& entity,
    const int adjacent_dimension,
    Teuchos::Array<Entity>& adjacent_entities ) const
{
    // There is no adjacency information in a point cloud.
    DTK_INSIST( false );
}

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

} // end namespace DataTransferKit

//---------------------------------------------------------------------------//
// end DTK_POD_PointCloudEntitySet.cpp
//---------------------------------------------------------------------------//
<commit_msg>fixing bug in entity iterator for POD entity set<commit_after>//---------------------------------------------------------------------------//
/*
  Copyright (c) 2012, Stuart R. Slattery
  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 the University of Wisconsin - Madison 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
  HOLDER 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.
*/
//---------------------------------------------------------------------------//
/*!
 * \brief DTK_POD_PointCloudEntitySet.cpp
 * \author Stuart R. Slattery
 * \brief POD point cloud entity set.
 */
//---------------------------------------------------------------------------//

#include <algorithm>

#include "DTK_POD_PointCloudEntitySet.hpp"
#include "DTK_POD_PointCloudEntity.hpp"
#include "DTK_POD_PointCloudEntityIterator.hpp"
#include "DTK_DBC.hpp"

#include <Teuchos_DefaultMpiComm.hpp>

namespace DataTransferKit
{
//---------------------------------------------------------------------------//
// Constructor.
POD_PointCloudEntitySet::POD_PointCloudEntitySet(
    const Teuchos::RCP<const Teuchos::Comm<int> >& comm,
    const double* cloud_coords,
    const EntityId* global_ids,
    const unsigned num_points,
    const int space_dim,
    const DataLayout layout )
    : d_comm( comm )
    , d_cloud_coords( cloud_coords )
    , d_global_ids( global_ids )
    , d_num_points( num_points )
    , d_space_dim( space_dim )
    , d_layout( layout )
{ /* ... */ }

//---------------------------------------------------------------------------//
// Get the parallel communicator for the entity set.
Teuchos::RCP<const Teuchos::Comm<int> >
POD_PointCloudEntitySet::communicator() const
{
    return d_comm;
}

//---------------------------------------------------------------------------//
// Return the largest physical dimension of the entities in the set.
int POD_PointCloudEntitySet::physicalDimension() const
{
    return d_space_dim;
}

//---------------------------------------------------------------------------//
// Given an EntityId, get the entity.
void POD_PointCloudEntitySet::getEntity( const EntityId entity_id,
                                         const int topological_dimension,
                                         Entity& entity ) const
{
    DTK_REQUIRE( 0 == topological_dimension );
    DTK_REQUIRE( 1 == std::count(&d_global_ids[0],
                                 &d_global_ids[0] + d_num_points,
                                 entity_id) );

    int local_id = std::distance( &d_global_ids[0],
                                  std::find(&d_global_ids[0],
                                            &d_global_ids[0] + d_num_points,
                                            entity_id) );

    entity = POD_PointCloudEntity( d_cloud_coords,
                                   d_num_points,
                                   d_space_dim,
                                   d_layout,
                                   entity_id,
                                   local_id,
                                   d_comm->getRank() );
}

//---------------------------------------------------------------------------//
// Get an iterator over a subset of the entity set that satisfies the given
// predicate.
EntityIterator POD_PointCloudEntitySet::entityIterator(
    const int topological_dimension,
    const PredicateFunction& predicate ) const
{
    EntityIterator iterator;

    if ( 0 == topological_dimension )
    {
        iterator = POD_PointCloudEntityIterator( d_cloud_coords,
                                                 d_global_ids,
                                                 d_num_points,
                                                 d_space_dim,
                                                 d_layout,
                                                 d_comm->getRank(),
                                                 predicate );
    }

    return iterator;
}

//---------------------------------------------------------------------------//
// Given an entity, get the entities of the given type that are adjacent to
// it.
void POD_PointCloudEntitySet::getAdjacentEntities(
    const Entity& entity,
    const int adjacent_dimension,
    Teuchos::Array<Entity>& adjacent_entities ) const
{
    // There is no adjacency information in a point cloud.
    DTK_INSIST( false );
}

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

} // end namespace DataTransferKit

//---------------------------------------------------------------------------//
// end DTK_POD_PointCloudEntitySet.cpp
//---------------------------------------------------------------------------//
<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <omp.h>

#include "sort.h"

const int ser_n = 1<<9;

int round2(int n)   {
    int k = 1;
    while(k < n)
        k <<= 1;
    return k>>1;
}

void bMerge(bool up, dataType *data, int n)   {
    if(n <= 1)
        return;
    int i, m = round2(n);
    dataType tmp;
    for(i = 0; i < n-m; ++i)
    {
        if(((long long)data[i].key > (long long)data[i+m].key) == up) {
            tmp = data[i];
            data[i] = data[i+m];
            data[i+m] = tmp;
        }
    }
    bMerge(up, data, m);
    bMerge(up, data+m, n-m);
}

void bSort_helper(bool up, dataType *data, int n)    {
    if(n <= 1)
        return;

    int m = n>>1;
    #pragma omp task if(m > ser_n) untied
    bSort_helper(!up, data, m);
    #pragma omp task if(n-m > ser_n) untied
    bSort_helper(up, data+m, n-m);
    #pragma omp taskwait
    bMerge(up, data, n);
}

void bSort(dataType *data, int n)   {
    omp_set_num_threads(omp_get_num_procs() * 2);
    #pragma omp parallel firstprivate(data, n)
    {
        #pragma omp master
        {
            // printf("%d threads\n", omp_get_num_threads());
            bSort_helper(true, data, n);
        }
    }
}
<commit_msg>Added huge parallelism in bsort.<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <omp.h>

#include "sort.h"

const int ser_n = 1<<9;

int round2(int n)   {
    int k = 1;
    while(k < n)
        k <<= 1;
    return k>>1;
}

void bMerge(bool up, dataType *data, int n)   {
    if(n <= 1)
        return;
    int i, m = round2(n);
    dataType tmp;
    for(i = 0; i < n-m; ++i)
    {
        if(((long long)data[i].key > (long long)data[i+m].key) == up) {
            tmp = data[i];
            data[i] = data[i+m];
            data[i+m] = tmp;
        }
    }
    #pragma omp task if(m > ser_n) untied
    bMerge(up, data, m);
    #pragma omp task if(n-m > ser_n) untied
    bMerge(up, data+m, n-m);
    #pragma omp taskwait
}

void bSort_helper(bool up, dataType *data, int n)    {
    if(n <= 1)
        return;

    int m = n>>1;
    #pragma omp task if(m > ser_n) untied
    bSort_helper(!up, data, m);
    #pragma omp task if(n-m > ser_n) untied
    bSort_helper(up, data+m, n-m);
    #pragma omp taskwait
    bMerge(up, data, n);
}

void bSort(dataType *data, int n)   {
    omp_set_num_threads(omp_get_num_procs() * 2);
    #pragma omp parallel firstprivate(data, n)
    {
        #pragma omp master
        {
            // printf("%d threads\n", omp_get_num_threads());
            bSort_helper(true, data, n);
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>[AST] Correct bugs with DefaultVisitor and MethodVar<commit_after><|endoftext|>


<commit_before><commit_msg>Fixed furnace placement, wasn't being removed from the inventory<commit_after><|endoftext|>


<commit_before><commit_msg>remove empty conditions for color format export to excel<commit_after><|endoftext|>


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

#ifndef _SV_GCACHFTYP_HXX
#define _SV_GCACHFTYP_HXX

#include <glyphcache.hxx>
#include <rtl/textcvt.h>

#include <ft2build.h>
#include FT_FREETYPE_H
class FreetypeServerFont;
struct FT_GlyphRec_;

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

// FtFontFile has the responsibility that a font file is only mapped once.
// (#86621#) the old directly ft-managed solution caused it to be mapped
// in up to nTTC*nSizes*nOrientation*nSynthetic times
class FtFontFile
{
public:
    static FtFontFile*      FindFontFile( const ::rtl::OString& rNativeFileName );

    bool                    Map();
    void                    Unmap();

    const unsigned char*    GetBuffer() const { return mpFileMap; }
    int                     GetFileSize() const { return mnFileSize; }
    const ::rtl::OString*   GetFileName() const { return &maNativeFileName; }
    int                     GetLangBoost() const { return mnLangBoost; }

private:
                            FtFontFile( const ::rtl::OString& rNativeFileName );

    const ::rtl::OString    maNativeFileName;
    const unsigned char*    mpFileMap;
    int                     mnFileSize;
    int                     mnRefCount;
    int                     mnLangBoost;
};

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

// FtFontInfo corresponds to an unscaled font face
class FtFontInfo
{
public:
                           FtFontInfo( const ImplDevFontAttributes&,
                               const ::rtl::OString& rNativeFileName,
                               int nFaceNum, sal_IntPtr nFontId, int nSynthetic,
                                const ExtraKernInfo* );
                          ~FtFontInfo();

    const unsigned char*  GetTable( const char*, ULONG* pLength=0 ) const;

    FT_FaceRec_*          GetFaceFT();
    void                  ReleaseFaceFT( FT_FaceRec_* );

    const ::rtl::OString* GetFontFileName() const   { return mpFontFile->GetFileName(); }
    int                   GetFaceNum() const        { return mnFaceNum; }
    int                   GetSynthetic() const      { return mnSynthetic; }
    sal_IntPtr            GetFontId() const         { return mnFontId; }
    bool                  DontUseAntiAlias() const
        { return maDevFontAttributes.UseAntiAlias() == ANTIALIAS_FALSE; }
    bool                  DontUseEmbeddedBitmaps() const
        { return maDevFontAttributes.UseEmbeddedBitmap() == EMBEDDEDBITMAP_FALSE; }
    bool                  IsSymbolFont() const      { return maDevFontAttributes.IsSymbolFont(); }
    const ImplFontAttributes& GetFontAttributes() const { return maDevFontAttributes; }

    void                  AnnounceFont( ImplDevFontList* );

    int                   GetGlyphIndex( sal_UCS4 cChar ) const;
    void                  CacheGlyphIndex( sal_UCS4 cChar, int nGI ) const;

    bool                  HasExtraKerning() const;
    int                   GetExtraKernPairs( ImplKernPairData** ) const;
    int                   GetExtraGlyphKernValue( int nLeftGlyph, int nRightGlyph ) const;

private:
    FT_FaceRec_*    maFaceFT;
    FtFontFile*     mpFontFile;
    const int       mnFaceNum;
    int             mnRefCount;
    const int       mnSynthetic;

    sal_IntPtr      mnFontId;
    ImplDevFontAttributes maDevFontAttributes;

    // cache unicode->glyphid mapping because looking it up is expensive
    // TODO: change to hash_multimap when a use case requires a m:n mapping
    typedef ::std::hash_map<int,int> Int2IntMap;
    mutable Int2IntMap maChar2Glyph;
    mutable Int2IntMap maGlyph2Char;

    const ExtraKernInfo* mpExtraKernInfo;
};

// these two inlines are very important for performance

inline int FtFontInfo::GetGlyphIndex( sal_UCS4 cChar ) const
{
    Int2IntMap::const_iterator it = maChar2Glyph.find( cChar );
    if( it == maChar2Glyph.end() )
        return -1;
    return it->second;
}

inline void FtFontInfo::CacheGlyphIndex( sal_UCS4 cChar, int nIndex ) const
{
    maChar2Glyph[ cChar ] = nIndex;
    maGlyph2Char[ nIndex ] = cChar;
}

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

class FreetypeManager
{
public:
                        FreetypeManager();
                        ~FreetypeManager();

    long                AddFontDir( const String& rUrlName );
    void                AddFontFile( const rtl::OString& rNormalizedName,
                            int nFaceNum, sal_IntPtr nFontId, const ImplDevFontAttributes&,
                            const ExtraKernInfo* );
    void                AnnounceFonts( ImplDevFontList* ) const;
    void                ClearFontList();

    FreetypeServerFont* CreateFont( const ImplFontSelectData& );

private:
    typedef ::std::hash_map<sal_IntPtr,FtFontInfo*> FontList;
    FontList            maFontList;

    sal_IntPtr          mnMaxFontId;
    sal_IntPtr          mnNextFontId;
};

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

class FreetypeServerFont : public ServerFont
{
public:
                                FreetypeServerFont( const ImplFontSelectData&, FtFontInfo* );
    virtual                     ~FreetypeServerFont();

    virtual const ::rtl::OString* GetFontFileName() const { return mpFontInfo->GetFontFileName(); }
    virtual int                 GetFontFaceNum() const { return mpFontInfo->GetFaceNum(); }
    virtual bool                TestFont() const;

    virtual void                FetchFontMetric( ImplFontMetricData&, long& rFactor ) const;

    virtual int                 GetGlyphIndex( sal_UCS4 ) const;
    int                         GetRawGlyphIndex( sal_UCS4 ) const;
    int                         FixupGlyphIndex( int nGlyphIndex, sal_UCS4 ) const;

    virtual bool                GetAntialiasAdvice( void ) const;
    virtual bool                GetGlyphBitmap1( int nGlyphIndex, RawBitmap& ) const;
    virtual bool                GetGlyphBitmap8( int nGlyphIndex, RawBitmap& ) const;
    virtual bool                GetGlyphOutline( int nGlyphIndex, ::basegfx::B2DPolyPolygon& ) const;
    virtual int                 GetGlyphKernValue( int nLeftGlyph, int nRightGlyph ) const;
    virtual ULONG               GetKernPairs( ImplKernPairData** ) const;

    const unsigned char*        GetTable( const char* pName, ULONG* pLength )
                                { return mpFontInfo->GetTable( pName, pLength ); }
    int                         GetEmUnits() const;
    const FT_Size_Metrics&      GetMetricsFT() const { return maSizeFT->metrics; }

protected:
    friend class GlyphCache;

    int                         ApplyGlyphTransform( int nGlyphFlags, FT_GlyphRec_*, bool ) const;
    virtual void                InitGlyphData( int nGlyphIndex, GlyphData& ) const;
    virtual ULONG               GetFontCodeRanges( sal_uInt32* pCodes ) const;
    bool                        ApplyGSUB( const ImplFontSelectData& );
    virtual ServerFontLayoutEngine* GetLayoutEngine();

private:
    int                         mnWidth;
    int                         mnPrioEmbedded;
    int                         mnPrioAntiAlias;
    FtFontInfo*                 mpFontInfo;
    FT_Int                      mnLoadFlags;
    double                      mfStretch;
    FT_FaceRec_*                maFaceFT;
    FT_SizeRec_*                maSizeFT;

    bool            mbArtItalic;
    bool            mbArtBold;
    bool            mbUseGamma;

    typedef ::std::hash_map<int,int> GlyphSubstitution;
    GlyphSubstitution           maGlyphSubstitution;
    rtl_UnicodeToTextConverter  maRecodeConverter;

    ServerFontLayoutEngine*     mpLayoutEngine;
};

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

class ImplFTSFontData : public ImplFontData
{
private:
    FtFontInfo*             mpFtFontInfo;
    enum { IFTSFONT_MAGIC = 0x1F150A1C };

public:
                            ImplFTSFontData( FtFontInfo*, const ImplDevFontAttributes& );

    FtFontInfo*             GetFtFontInfo() const { return mpFtFontInfo; }

    virtual ImplFontEntry*  CreateFontInstance( ImplFontSelectData& ) const;
    virtual ImplFontData*   Clone() const   { return new ImplFTSFontData( *this ); }
    virtual sal_IntPtr      GetFontId() const { return mpFtFontInfo->GetFontId(); }

    static bool             CheckFontData( const ImplFontData& r ) { return r.CheckMagic( IFTSFONT_MAGIC ); }
};

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

#endif // _SV_GCACHFTYP_HXX
<commit_msg>INTEGRATION: CWS vcl70 (1.36.210); FILE MERGED 2006/11/28 14:44:30 hdu 1.36.210.1: #i68904# empty hash_tables are still too expensive<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: gcach_ftyp.hxx,v $
 *
 *  $Revision: 1.37 $
 *
 *  last change: $Author: ihi $ $Date: 2006-12-21 12:04:04 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _SV_GCACHFTYP_HXX
#define _SV_GCACHFTYP_HXX

#include <glyphcache.hxx>
#include <rtl/textcvt.h>

#include <ft2build.h>
#include FT_FREETYPE_H
class FreetypeServerFont;
struct FT_GlyphRec_;

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

// FtFontFile has the responsibility that a font file is only mapped once.
// (#86621#) the old directly ft-managed solution caused it to be mapped
// in up to nTTC*nSizes*nOrientation*nSynthetic times
class FtFontFile
{
public:
    static FtFontFile*      FindFontFile( const ::rtl::OString& rNativeFileName );

    bool                    Map();
    void                    Unmap();

    const unsigned char*    GetBuffer() const { return mpFileMap; }
    int                     GetFileSize() const { return mnFileSize; }
    const ::rtl::OString*   GetFileName() const { return &maNativeFileName; }
    int                     GetLangBoost() const { return mnLangBoost; }

private:
                            FtFontFile( const ::rtl::OString& rNativeFileName );

    const ::rtl::OString    maNativeFileName;
    const unsigned char*    mpFileMap;
    int                     mnFileSize;
    int                     mnRefCount;
    int                     mnLangBoost;
};

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

// FtFontInfo corresponds to an unscaled font face
class FtFontInfo
{
public:
                           FtFontInfo( const ImplDevFontAttributes&,
                               const ::rtl::OString& rNativeFileName,
                               int nFaceNum, sal_IntPtr nFontId, int nSynthetic,
                                const ExtraKernInfo* );
                          ~FtFontInfo();

    const unsigned char*  GetTable( const char*, ULONG* pLength=0 ) const;

    FT_FaceRec_*          GetFaceFT();
    void                  ReleaseFaceFT( FT_FaceRec_* );

    const ::rtl::OString* GetFontFileName() const   { return mpFontFile->GetFileName(); }
    int                   GetFaceNum() const        { return mnFaceNum; }
    int                   GetSynthetic() const      { return mnSynthetic; }
    sal_IntPtr            GetFontId() const         { return mnFontId; }
    bool                  DontUseAntiAlias() const
        { return maDevFontAttributes.UseAntiAlias() == ANTIALIAS_FALSE; }
    bool                  DontUseEmbeddedBitmaps() const
        { return maDevFontAttributes.UseEmbeddedBitmap() == EMBEDDEDBITMAP_FALSE; }
    bool                  IsSymbolFont() const      { return maDevFontAttributes.IsSymbolFont(); }
    const ImplFontAttributes& GetFontAttributes() const { return maDevFontAttributes; }

    void                  AnnounceFont( ImplDevFontList* );

    int                   GetGlyphIndex( sal_UCS4 cChar ) const;
    void                  CacheGlyphIndex( sal_UCS4 cChar, int nGI ) const;

    bool                  HasExtraKerning() const;
    int                   GetExtraKernPairs( ImplKernPairData** ) const;
    int                   GetExtraGlyphKernValue( int nLeftGlyph, int nRightGlyph ) const;

private:
    FT_FaceRec_*    maFaceFT;
    FtFontFile*     mpFontFile;
    const int       mnFaceNum;
    int             mnRefCount;
    const int       mnSynthetic;

    sal_IntPtr      mnFontId;
    ImplDevFontAttributes maDevFontAttributes;

    // cache unicode->glyphid mapping because looking it up is expensive
    // TODO: change to hash_multimap when a use case requires a m:n mapping
    typedef ::std::hash_map<int,int> Int2IntMap;
    mutable Int2IntMap* mpChar2Glyph;
    mutable Int2IntMap* mpGlyph2Char;
    void InitHashes() const;

    const ExtraKernInfo* mpExtraKernInfo;
};

// these two inlines are very important for performance

inline int FtFontInfo::GetGlyphIndex( sal_UCS4 cChar ) const
{
    if( !mpChar2Glyph )
        return -1;
    Int2IntMap::const_iterator it = mpChar2Glyph->find( cChar );
    if( it == mpChar2Glyph->end() )
        return -1;
    return it->second;
}

inline void FtFontInfo::CacheGlyphIndex( sal_UCS4 cChar, int nIndex ) const
{
    if( !mpChar2Glyph )
        InitHashes();
    (*mpChar2Glyph)[ cChar ] = nIndex;
    (*mpGlyph2Char)[ nIndex ] = cChar;
}

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

class FreetypeManager
{
public:
                        FreetypeManager();
                        ~FreetypeManager();

    long                AddFontDir( const String& rUrlName );
    void                AddFontFile( const rtl::OString& rNormalizedName,
                            int nFaceNum, sal_IntPtr nFontId, const ImplDevFontAttributes&,
                            const ExtraKernInfo* );
    void                AnnounceFonts( ImplDevFontList* ) const;
    void                ClearFontList();

    FreetypeServerFont* CreateFont( const ImplFontSelectData& );

private:
    typedef ::std::hash_map<sal_IntPtr,FtFontInfo*> FontList;
    FontList            maFontList;

    sal_IntPtr          mnMaxFontId;
    sal_IntPtr          mnNextFontId;
};

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

class FreetypeServerFont : public ServerFont
{
public:
                                FreetypeServerFont( const ImplFontSelectData&, FtFontInfo* );
    virtual                     ~FreetypeServerFont();

    virtual const ::rtl::OString* GetFontFileName() const { return mpFontInfo->GetFontFileName(); }
    virtual int                 GetFontFaceNum() const { return mpFontInfo->GetFaceNum(); }
    virtual bool                TestFont() const;

    virtual void                FetchFontMetric( ImplFontMetricData&, long& rFactor ) const;

    virtual int                 GetGlyphIndex( sal_UCS4 ) const;
    int                         GetRawGlyphIndex( sal_UCS4 ) const;
    int                         FixupGlyphIndex( int nGlyphIndex, sal_UCS4 ) const;

    virtual bool                GetAntialiasAdvice( void ) const;
    virtual bool                GetGlyphBitmap1( int nGlyphIndex, RawBitmap& ) const;
    virtual bool                GetGlyphBitmap8( int nGlyphIndex, RawBitmap& ) const;
    virtual bool                GetGlyphOutline( int nGlyphIndex, ::basegfx::B2DPolyPolygon& ) const;
    virtual int                 GetGlyphKernValue( int nLeftGlyph, int nRightGlyph ) const;
    virtual ULONG               GetKernPairs( ImplKernPairData** ) const;

    const unsigned char*        GetTable( const char* pName, ULONG* pLength )
                                { return mpFontInfo->GetTable( pName, pLength ); }
    int                         GetEmUnits() const;
    const FT_Size_Metrics&      GetMetricsFT() const { return maSizeFT->metrics; }

protected:
    friend class GlyphCache;

    int                         ApplyGlyphTransform( int nGlyphFlags, FT_GlyphRec_*, bool ) const;
    virtual void                InitGlyphData( int nGlyphIndex, GlyphData& ) const;
    virtual ULONG               GetFontCodeRanges( sal_uInt32* pCodes ) const;
    bool                        ApplyGSUB( const ImplFontSelectData& );
    virtual ServerFontLayoutEngine* GetLayoutEngine();

private:
    int                         mnWidth;
    int                         mnPrioEmbedded;
    int                         mnPrioAntiAlias;
    FtFontInfo*                 mpFontInfo;
    FT_Int                      mnLoadFlags;
    double                      mfStretch;
    FT_FaceRec_*                maFaceFT;
    FT_SizeRec_*                maSizeFT;

    bool            mbArtItalic;
    bool            mbArtBold;
    bool            mbUseGamma;

    typedef ::std::hash_map<int,int> GlyphSubstitution;
    GlyphSubstitution           maGlyphSubstitution;
    rtl_UnicodeToTextConverter  maRecodeConverter;

    ServerFontLayoutEngine*     mpLayoutEngine;
};

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

class ImplFTSFontData : public ImplFontData
{
private:
    FtFontInfo*             mpFtFontInfo;
    enum { IFTSFONT_MAGIC = 0x1F150A1C };

public:
                            ImplFTSFontData( FtFontInfo*, const ImplDevFontAttributes& );

    FtFontInfo*             GetFtFontInfo() const { return mpFtFontInfo; }

    virtual ImplFontEntry*  CreateFontInstance( ImplFontSelectData& ) const;
    virtual ImplFontData*   Clone() const   { return new ImplFTSFontData( *this ); }
    virtual sal_IntPtr      GetFontId() const { return mpFtFontInfo->GetFontId(); }

    static bool             CheckFontData( const ImplFontData& r ) { return r.CheckMagic( IFTSFONT_MAGIC ); }
};

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

#endif // _SV_GCACHFTYP_HXX
<|endoftext|>


<commit_before>#include <algorithm>
#include <utility>

#include "drawtypes/iconset.hpp"
#include "drawtypes/label.hpp"
#include "modules/xworkspaces.hpp"
#include "utils/factory.hpp"
#include "utils/math.hpp"
#include "x11/atoms.hpp"
#include "x11/connection.hpp"

#include "modules/meta/base.inl"

POLYBAR_NS

namespace {
  inline bool operator==(const position& a, const position& b) {
    return a.x + a.y == b.x + b.y;
  }
}

namespace modules {
  template class module<xworkspaces_module>;

  /**
   * Construct module
   */
  xworkspaces_module::xworkspaces_module(const bar_settings& bar, string name_)
      : static_module<xworkspaces_module>(bar, move(name_)), m_connection(connection::make()) {
    // Load config values
    m_pinworkspaces = m_conf.get(name(), "pin-workspaces", m_pinworkspaces);
    m_click = m_conf.get(name(), "enable-click", m_click);
    m_scroll = m_conf.get(name(), "enable-scroll", m_scroll);

    // Initialize ewmh atoms
    if ((m_ewmh = ewmh_util::initialize()) == nullptr) {
      throw module_error("Failed to initialize ewmh atoms");
    }

    // Check if the WM supports _NET_CURRENT_DESKTOP
    if (!ewmh_util::supports(m_ewmh->_NET_CURRENT_DESKTOP)) {
      throw module_error("The WM does not support _NET_CURRENT_DESKTOP, aborting...");
    }

    // Check if the WM supports _NET_DESKTOP_VIEWPORT
    if (!(m_monitorsupport = ewmh_util::supports(m_ewmh->_NET_DESKTOP_VIEWPORT)) && m_pinworkspaces) {
      throw module_error("The WM does not support _NET_DESKTOP_VIEWPORT (required when `pin-workspaces = true`)");
    }

    // Add formats and elements
    m_formatter->add(DEFAULT_FORMAT, TAG_LABEL_STATE, {TAG_LABEL_STATE, TAG_LABEL_MONITOR});

    if (m_formatter->has(TAG_LABEL_MONITOR)) {
      m_monitorlabel = load_optional_label(m_conf, name(), "label-monitor", DEFAULT_LABEL_MONITOR);
    }

    if (m_formatter->has(TAG_LABEL_STATE)) {
      // clang-format off
      m_labels.insert(make_pair(
          desktop_state::ACTIVE, load_optional_label(m_conf, name(), "label-active", DEFAULT_LABEL_STATE)));
      m_labels.insert(make_pair(
          desktop_state::OCCUPIED, load_optional_label(m_conf, name(), "label-occupied", DEFAULT_LABEL_STATE)));
      m_labels.insert(make_pair(
          desktop_state::URGENT, load_optional_label(m_conf, name(), "label-urgent", DEFAULT_LABEL_STATE)));
      m_labels.insert(make_pair(
          desktop_state::EMPTY, load_optional_label(m_conf, name(), "label-empty", DEFAULT_LABEL_STATE)));
      // clang-format on
    }

    m_icons = factory_util::shared<iconset>();
    m_icons->add(DEFAULT_ICON, factory_util::shared<label>(m_conf.get(name(), DEFAULT_ICON, ""s)));

    for (const auto& workspace : m_conf.get_list<string>(name(), "icon", {})) {
      auto vec = string_util::split(workspace, ';');
      if (vec.size() == 2) {
        m_icons->add(vec[0], factory_util::shared<label>(vec[1]));
      }
    }

    // Get list of monitors
    m_monitors = randr_util::get_monitors(m_connection, m_connection.root(), false);

    // Get desktop details
    m_desktop_names = ewmh_util::get_desktop_names();
    m_current_desktop = ewmh_util::get_current_desktop();

    rebuild_desktops();
    rebuild_desktop_states();

    // Get _NET_CLIENT_LIST
    rebuild_clientlist();
  }

  /**
   * Handler for XCB_PROPERTY_NOTIFY events
   */
  void xworkspaces_module::handle(const evt::property_notify& evt) {
    if (evt->atom == m_ewmh->_NET_CLIENT_LIST) {
      rebuild_clientlist();
    } else if (evt->atom == m_ewmh->_NET_DESKTOP_NAMES) {
      m_desktop_names = ewmh_util::get_desktop_names();
      rebuild_desktops();
      rebuild_desktop_states();
    } else if (evt->atom == m_ewmh->_NET_CURRENT_DESKTOP) {
      m_current_desktop = ewmh_util::get_current_desktop();
      rebuild_desktop_states();
    } else if (evt->atom == WM_HINTS) {
      if (icccm_util::get_wm_urgency(m_connection, evt->window)) {
        set_desktop_urgent(evt->window);
      }
    } else {
      return;
    }

    if (m_timer.allow(evt->time)) {
      broadcast();
    }
  }

  /**
   * Rebuild the list of managed clients
   */
  void xworkspaces_module::rebuild_clientlist() {
    vector<xcb_window_t> clients = ewmh_util::get_client_list();
    vector<xcb_window_t> diff;
    std::sort(clients.begin(), clients.end());
    std::sort(m_clientlist.begin(), m_clientlist.end());

    if (m_clientlist.size() > clients.size()) {
      std::set_difference(
          m_clientlist.begin(), m_clientlist.end(), clients.begin(), clients.end(), back_inserter(diff));
      for (auto&& win : diff) {
        // untrack window
        m_clientlist.erase(std::remove(m_clientlist.begin(), m_clientlist.end(), win), m_clientlist.end());
      }
    } else {
      std::set_difference(
          clients.begin(), clients.end(), m_clientlist.begin(), m_clientlist.end(), back_inserter(diff));
      for (auto&& win : diff) {
        // listen for wm_hint (urgency) changes
        m_connection.ensure_event_mask(win, XCB_EVENT_MASK_PROPERTY_CHANGE);
        // track window
        m_clientlist.emplace_back(win);
      }
    }
  }

  /**
   * Rebuild the desktop tree
   */
  void xworkspaces_module::rebuild_desktops() {
    m_viewports.clear();

    auto bounds = [&] {
      if (m_monitorsupport) {
        return ewmh_util::get_desktop_viewports();
      } else {
        vector<position> b;
        std::fill_n(std::back_inserter(b), m_desktop_names.size(), position{m_bar.monitor->x, m_bar.monitor->y});
        return b;
      }
    }();

    bounds.erase(std::unique(bounds.begin(), bounds.end(), [](auto& a, auto& b) { return a == b; }), bounds.end());

    unsigned int step = m_desktop_names.size() / bounds.size();
    unsigned int offset = 0;
    for (unsigned int i = 0; i < bounds.size(); i++) {
      if (!m_pinworkspaces || m_bar.monitor->match(bounds[i])) {
        auto viewport = make_unique<struct viewport>();
        viewport->state = viewport_state::UNFOCUSED;
        viewport->pos = bounds[i];

        for (auto&& m : m_monitors) {
          if (m->match(viewport->pos)) {
            viewport->name = m->name;
            viewport->state = viewport_state::FOCUSED;
          }
        }

        viewport->label = [&] {
          label_t label;
          if (m_monitorlabel) {
            label = m_monitorlabel->clone();
            label->reset_tokens();
            label->replace_token("%name%", viewport->name);
          }
          return label;
        }();

        for (unsigned int index = offset; index < offset + step; index++) {
          viewport->desktops.emplace_back(make_unique<struct desktop>(index, offset, desktop_state::EMPTY, label_t{}));
        }

        m_viewports.emplace_back(move(viewport));
      }
      offset += step;
    }
  }

  /**
   * Update active state of current desktops
   */
  void xworkspaces_module::rebuild_desktop_states() {
    for (auto&& v : m_viewports) {
      for (auto&& d : v->desktops) {
        if (d->index == m_current_desktop) {
          d->state = desktop_state::ACTIVE;
        } else {
          d->state = desktop_state::EMPTY;
        }

        d->label = m_labels.at(d->state)->clone();
        d->label->reset_tokens();
        d->label->replace_token("%index%", to_string(d->index - d->offset + 1));
        d->label->replace_token("%name%", m_desktop_names[d->index]);
        d->label->replace_token("%icon%", m_icons->get(m_desktop_names[d->index], DEFAULT_ICON)->get());
      }
    }
  }

  /**
   * Find window and set corresponding desktop to urgent
   */
  void xworkspaces_module::set_desktop_urgent(xcb_window_t window) {
    auto desk = ewmh_util::get_desktop_from_window(window);
    if(desk == m_current_desktop)
      // ignore if current desktop is urgent
      return;
    for (auto&& v : m_viewports) {
      for (auto&& d : v->desktops) {
        if (d->index == desk && d->state != desktop_state::URGENT) {
          d->state = desktop_state::URGENT;

          d->label = m_labels.at(d->state)->clone();
          d->label->reset_tokens();
          d->label->replace_token("%index%", to_string(d->index - d->offset + 1));
          d->label->replace_token("%name%", m_desktop_names[d->index]);
          d->label->replace_token("%icon%", m_icons->get(m_desktop_names[d->index], DEFAULT_ICON)->get());
          return;
        }
      }
    }

  }

  /**
   * Fetch and parse data
   */
  void xworkspaces_module::update() {}

  /**
   * Generate module output
   */
  string xworkspaces_module::get_output() {
    // Get the module output early so that
    // the format prefix/suffix also gets wrapped
    // with the cmd handlers
    string output;
    for (m_index = 0; m_index < m_viewports.size(); m_index++) {
      if (m_index > 0) {
        m_builder->space(m_formatter->get(DEFAULT_FORMAT)->spacing);
      }
      output += module::get_output();
    }

    if (m_scroll) {
      m_builder->cmd(mousebtn::SCROLL_DOWN, string{EVENT_PREFIX} + string{EVENT_SCROLL_DOWN});
      m_builder->cmd(mousebtn::SCROLL_UP, string{EVENT_PREFIX} + string{EVENT_SCROLL_UP});
    }

    m_builder->append(output);

    m_builder->cmd_close();
    m_builder->cmd_close();

    return m_builder->flush();
  }

  /**
   * Output content as defined in the config
   */
  bool xworkspaces_module::build(builder* builder, const string& tag) const {
    if (tag == TAG_LABEL_MONITOR) {
      if (m_viewports[m_index]->state != viewport_state::NONE) {
        builder->node(m_viewports[m_index]->label);
        return true;
      } else {
        return false;
      }
    } else if (tag == TAG_LABEL_STATE) {
      unsigned int added_states = 0;
      for (auto&& desktop : m_viewports[m_index]->desktops) {
        if (desktop->label.get()) {
          if (m_click && desktop->state != desktop_state::ACTIVE) {
            builder->cmd(mousebtn::LEFT, string{EVENT_PREFIX} + string{EVENT_CLICK} + to_string(desktop->index));
            builder->node(desktop->label);
            builder->cmd_close();
          } else {
            builder->node(desktop->label);
          }
          added_states++;
        }
      }
      return added_states > 0;
    } else {
      return false;
    }
  }

  /**
   * Handle user input event
   */
  bool xworkspaces_module::input(string&& cmd) {
    size_t len{strlen(EVENT_PREFIX)};
    if (cmd.compare(0, len, EVENT_PREFIX) != 0) {
      return false;
    }
    cmd.erase(0, len);

    vector<unsigned int> indexes;
    for (auto&& viewport : m_viewports) {
      for (auto&& desktop : viewport->desktops) {
        indexes.emplace_back(desktop->index);
      }
    }

    std::sort(indexes.begin(), indexes.end());

    unsigned int new_desktop{0};
    unsigned int current_desktop{ewmh_util::get_current_desktop()};

    if ((len = strlen(EVENT_CLICK)) && cmd.compare(0, len, EVENT_CLICK) == 0) {
      new_desktop = std::strtoul(cmd.substr(len).c_str(), nullptr, 10);
    } else if ((len = strlen(EVENT_SCROLL_UP)) && cmd.compare(0, len, EVENT_SCROLL_UP) == 0) {
      new_desktop = math_util::min<unsigned int>(indexes.back(), current_desktop + 1);
      new_desktop = new_desktop == current_desktop ? indexes.front() : new_desktop;
    } else if ((len = strlen(EVENT_SCROLL_DOWN)) && cmd.compare(0, len, EVENT_SCROLL_DOWN) == 0) {
      new_desktop = math_util::max<unsigned int>(indexes.front(), current_desktop - 1);
      new_desktop = new_desktop == current_desktop ? indexes.back() : new_desktop;
    }

    if (new_desktop != current_desktop) {
      m_log.info("%s: Requesting change to desktop #%u", name(), new_desktop);
      ewmh_util::change_current_desktop(new_desktop);
    } else {
      m_log.info("%s: Ignoring change to current desktop", name());
    }

    return true;
  }
}

POLYBAR_NS_END
<commit_msg>fix(xworkspaces): FPE when no _NET_DESKTOP_NAMES (#1576)<commit_after>#include <algorithm>
#include <utility>

#include "drawtypes/iconset.hpp"
#include "drawtypes/label.hpp"
#include "modules/xworkspaces.hpp"
#include "utils/factory.hpp"
#include "utils/math.hpp"
#include "x11/atoms.hpp"
#include "x11/connection.hpp"

#include "modules/meta/base.inl"

POLYBAR_NS

namespace {
  inline bool operator==(const position& a, const position& b) {
    return a.x + a.y == b.x + b.y;
  }
}

namespace modules {
  template class module<xworkspaces_module>;

  /**
   * Construct module
   */
  xworkspaces_module::xworkspaces_module(const bar_settings& bar, string name_)
      : static_module<xworkspaces_module>(bar, move(name_)), m_connection(connection::make()) {
    // Load config values
    m_pinworkspaces = m_conf.get(name(), "pin-workspaces", m_pinworkspaces);
    m_click = m_conf.get(name(), "enable-click", m_click);
    m_scroll = m_conf.get(name(), "enable-scroll", m_scroll);

    // Initialize ewmh atoms
    if ((m_ewmh = ewmh_util::initialize()) == nullptr) {
      throw module_error("Failed to initialize ewmh atoms");
    }

    // Check if the WM supports _NET_CURRENT_DESKTOP
    if (!ewmh_util::supports(m_ewmh->_NET_CURRENT_DESKTOP)) {
      throw module_error("The WM does not support _NET_CURRENT_DESKTOP, aborting...");
    }

    // Check if the WM supports _NET_DESKTOP_VIEWPORT
    if (!(m_monitorsupport = ewmh_util::supports(m_ewmh->_NET_DESKTOP_VIEWPORT)) && m_pinworkspaces) {
      throw module_error("The WM does not support _NET_DESKTOP_VIEWPORT (required when `pin-workspaces = true`)");
    }

    // Add formats and elements
    m_formatter->add(DEFAULT_FORMAT, TAG_LABEL_STATE, {TAG_LABEL_STATE, TAG_LABEL_MONITOR});

    if (m_formatter->has(TAG_LABEL_MONITOR)) {
      m_monitorlabel = load_optional_label(m_conf, name(), "label-monitor", DEFAULT_LABEL_MONITOR);
    }

    if (m_formatter->has(TAG_LABEL_STATE)) {
      // clang-format off
      m_labels.insert(make_pair(
          desktop_state::ACTIVE, load_optional_label(m_conf, name(), "label-active", DEFAULT_LABEL_STATE)));
      m_labels.insert(make_pair(
          desktop_state::OCCUPIED, load_optional_label(m_conf, name(), "label-occupied", DEFAULT_LABEL_STATE)));
      m_labels.insert(make_pair(
          desktop_state::URGENT, load_optional_label(m_conf, name(), "label-urgent", DEFAULT_LABEL_STATE)));
      m_labels.insert(make_pair(
          desktop_state::EMPTY, load_optional_label(m_conf, name(), "label-empty", DEFAULT_LABEL_STATE)));
      // clang-format on
    }

    m_icons = factory_util::shared<iconset>();
    m_icons->add(DEFAULT_ICON, factory_util::shared<label>(m_conf.get(name(), DEFAULT_ICON, ""s)));

    for (const auto& workspace : m_conf.get_list<string>(name(), "icon", {})) {
      auto vec = string_util::split(workspace, ';');
      if (vec.size() == 2) {
        m_icons->add(vec[0], factory_util::shared<label>(vec[1]));
      }
    }

    // Get list of monitors
    m_monitors = randr_util::get_monitors(m_connection, m_connection.root(), false);

    // Get desktop details
    m_desktop_names = ewmh_util::get_desktop_names();
    m_current_desktop = ewmh_util::get_current_desktop();

    rebuild_desktops();
    rebuild_desktop_states();

    // Get _NET_CLIENT_LIST
    rebuild_clientlist();
  }

  /**
   * Handler for XCB_PROPERTY_NOTIFY events
   */
  void xworkspaces_module::handle(const evt::property_notify& evt) {
    if (evt->atom == m_ewmh->_NET_CLIENT_LIST) {
      rebuild_clientlist();
    } else if (evt->atom == m_ewmh->_NET_DESKTOP_NAMES) {
      m_desktop_names = ewmh_util::get_desktop_names();
      rebuild_desktops();
      rebuild_desktop_states();
    } else if (evt->atom == m_ewmh->_NET_CURRENT_DESKTOP) {
      m_current_desktop = ewmh_util::get_current_desktop();
      rebuild_desktop_states();
    } else if (evt->atom == WM_HINTS) {
      if (icccm_util::get_wm_urgency(m_connection, evt->window)) {
        set_desktop_urgent(evt->window);
      }
    } else {
      return;
    }

    if (m_timer.allow(evt->time)) {
      broadcast();
    }
  }

  /**
   * Rebuild the list of managed clients
   */
  void xworkspaces_module::rebuild_clientlist() {
    vector<xcb_window_t> clients = ewmh_util::get_client_list();
    vector<xcb_window_t> diff;
    std::sort(clients.begin(), clients.end());
    std::sort(m_clientlist.begin(), m_clientlist.end());

    if (m_clientlist.size() > clients.size()) {
      std::set_difference(
          m_clientlist.begin(), m_clientlist.end(), clients.begin(), clients.end(), back_inserter(diff));
      for (auto&& win : diff) {
        // untrack window
        m_clientlist.erase(std::remove(m_clientlist.begin(), m_clientlist.end(), win), m_clientlist.end());
      }
    } else {
      std::set_difference(
          clients.begin(), clients.end(), m_clientlist.begin(), m_clientlist.end(), back_inserter(diff));
      for (auto&& win : diff) {
        // listen for wm_hint (urgency) changes
        m_connection.ensure_event_mask(win, XCB_EVENT_MASK_PROPERTY_CHANGE);
        // track window
        m_clientlist.emplace_back(win);
      }
    }
  }

  /**
   * Rebuild the desktop tree
   */
  void xworkspaces_module::rebuild_desktops() {
    m_viewports.clear();

    auto bounds = [&] {
      if (m_monitorsupport) {
        return ewmh_util::get_desktop_viewports();
      } else {
        vector<position> b;
        std::fill_n(std::back_inserter(b), m_desktop_names.size(), position{m_bar.monitor->x, m_bar.monitor->y});
        return b;
      }
    }();

    bounds.erase(std::unique(bounds.begin(), bounds.end(), [](auto& a, auto& b) { return a == b; }), bounds.end());

    unsigned int step;
    if (bounds.size() > 0) {
      step = m_desktop_names.size() / bounds.size();
    } else {
      step = 1;
    }
    unsigned int offset = 0;
    for (unsigned int i = 0; i < bounds.size(); i++) {
      if (!m_pinworkspaces || m_bar.monitor->match(bounds[i])) {
        auto viewport = make_unique<struct viewport>();
        viewport->state = viewport_state::UNFOCUSED;
        viewport->pos = bounds[i];

        for (auto&& m : m_monitors) {
          if (m->match(viewport->pos)) {
            viewport->name = m->name;
            viewport->state = viewport_state::FOCUSED;
          }
        }

        viewport->label = [&] {
          label_t label;
          if (m_monitorlabel) {
            label = m_monitorlabel->clone();
            label->reset_tokens();
            label->replace_token("%name%", viewport->name);
          }
          return label;
        }();

        for (unsigned int index = offset; index < offset + step; index++) {
          viewport->desktops.emplace_back(make_unique<struct desktop>(index, offset, desktop_state::EMPTY, label_t{}));
        }

        m_viewports.emplace_back(move(viewport));
      }
      offset += step;
    }
  }

  /**
   * Update active state of current desktops
   */
  void xworkspaces_module::rebuild_desktop_states() {
    for (auto&& v : m_viewports) {
      for (auto&& d : v->desktops) {
        if (d->index == m_current_desktop) {
          d->state = desktop_state::ACTIVE;
        } else {
          d->state = desktop_state::EMPTY;
        }

        d->label = m_labels.at(d->state)->clone();
        d->label->reset_tokens();
        d->label->replace_token("%index%", to_string(d->index - d->offset + 1));
        d->label->replace_token("%name%", m_desktop_names[d->index]);
        d->label->replace_token("%icon%", m_icons->get(m_desktop_names[d->index], DEFAULT_ICON)->get());
      }
    }
  }

  /**
   * Find window and set corresponding desktop to urgent
   */
  void xworkspaces_module::set_desktop_urgent(xcb_window_t window) {
    auto desk = ewmh_util::get_desktop_from_window(window);
    if(desk == m_current_desktop)
      // ignore if current desktop is urgent
      return;
    for (auto&& v : m_viewports) {
      for (auto&& d : v->desktops) {
        if (d->index == desk && d->state != desktop_state::URGENT) {
          d->state = desktop_state::URGENT;

          d->label = m_labels.at(d->state)->clone();
          d->label->reset_tokens();
          d->label->replace_token("%index%", to_string(d->index - d->offset + 1));
          d->label->replace_token("%name%", m_desktop_names[d->index]);
          d->label->replace_token("%icon%", m_icons->get(m_desktop_names[d->index], DEFAULT_ICON)->get());
          return;
        }
      }
    }

  }

  /**
   * Fetch and parse data
   */
  void xworkspaces_module::update() {}

  /**
   * Generate module output
   */
  string xworkspaces_module::get_output() {
    // Get the module output early so that
    // the format prefix/suffix also gets wrapped
    // with the cmd handlers
    string output;
    for (m_index = 0; m_index < m_viewports.size(); m_index++) {
      if (m_index > 0) {
        m_builder->space(m_formatter->get(DEFAULT_FORMAT)->spacing);
      }
      output += module::get_output();
    }

    if (m_scroll) {
      m_builder->cmd(mousebtn::SCROLL_DOWN, string{EVENT_PREFIX} + string{EVENT_SCROLL_DOWN});
      m_builder->cmd(mousebtn::SCROLL_UP, string{EVENT_PREFIX} + string{EVENT_SCROLL_UP});
    }

    m_builder->append(output);

    m_builder->cmd_close();
    m_builder->cmd_close();

    return m_builder->flush();
  }

  /**
   * Output content as defined in the config
   */
  bool xworkspaces_module::build(builder* builder, const string& tag) const {
    if (tag == TAG_LABEL_MONITOR) {
      if (m_viewports[m_index]->state != viewport_state::NONE) {
        builder->node(m_viewports[m_index]->label);
        return true;
      } else {
        return false;
      }
    } else if (tag == TAG_LABEL_STATE) {
      unsigned int added_states = 0;
      for (auto&& desktop : m_viewports[m_index]->desktops) {
        if (desktop->label.get()) {
          if (m_click && desktop->state != desktop_state::ACTIVE) {
            builder->cmd(mousebtn::LEFT, string{EVENT_PREFIX} + string{EVENT_CLICK} + to_string(desktop->index));
            builder->node(desktop->label);
            builder->cmd_close();
          } else {
            builder->node(desktop->label);
          }
          added_states++;
        }
      }
      return added_states > 0;
    } else {
      return false;
    }
  }

  /**
   * Handle user input event
   */
  bool xworkspaces_module::input(string&& cmd) {
    size_t len{strlen(EVENT_PREFIX)};
    if (cmd.compare(0, len, EVENT_PREFIX) != 0) {
      return false;
    }
    cmd.erase(0, len);

    vector<unsigned int> indexes;
    for (auto&& viewport : m_viewports) {
      for (auto&& desktop : viewport->desktops) {
        indexes.emplace_back(desktop->index);
      }
    }

    std::sort(indexes.begin(), indexes.end());

    unsigned int new_desktop{0};
    unsigned int current_desktop{ewmh_util::get_current_desktop()};

    if ((len = strlen(EVENT_CLICK)) && cmd.compare(0, len, EVENT_CLICK) == 0) {
      new_desktop = std::strtoul(cmd.substr(len).c_str(), nullptr, 10);
    } else if ((len = strlen(EVENT_SCROLL_UP)) && cmd.compare(0, len, EVENT_SCROLL_UP) == 0) {
      new_desktop = math_util::min<unsigned int>(indexes.back(), current_desktop + 1);
      new_desktop = new_desktop == current_desktop ? indexes.front() : new_desktop;
    } else if ((len = strlen(EVENT_SCROLL_DOWN)) && cmd.compare(0, len, EVENT_SCROLL_DOWN) == 0) {
      new_desktop = math_util::max<unsigned int>(indexes.front(), current_desktop - 1);
      new_desktop = new_desktop == current_desktop ? indexes.back() : new_desktop;
    }

    if (new_desktop != current_desktop) {
      m_log.info("%s: Requesting change to desktop #%u", name(), new_desktop);
      ewmh_util::change_current_desktop(new_desktop);
    } else {
      m_log.info("%s: Ignoring change to current desktop", name());
    }

    return true;
  }
}

POLYBAR_NS_END
<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
// File: minterface.hpp
//
// Desc: Interface for Data Mining.
//
// Copyright (c) 2014-2018. veyesys.com All rights reserved.
//------------------------------------------------------------------------------
#ifndef __M_INTERFACE_HPP__
#define __M_INTERFACE_HPP__
#include "utility.hpp"
#include "videotype.hpp"
#include "miningtype.hpp"

using namespace std;

typedef enum __MiningRetType
{
	MINING_RET_MOT = 1,
	MINING_RET_OBJS,
	MINING_RET_LAST
}MiningRetType;

typedef enum __MModuleFlag
{
	MM_MOT = 1,
	MM_TRACK = 2,
	MM_PEOPLE_CNT = 4,
	MM_ALPR = 8,
	MM_LAST
}MModuleFlag;

typedef enum __MMReqStream
{
	MM_STREAM_MAIN = 1,
	MM_STREAM_SUB = 2,
	MM_STREAM_MAIN_RAW = 1,
	MM_STREAM_SUB_RAW = 2,
	MM_STREAM_LAST
}MMReqStream;

typedef struct __MiningRet
{
	MiningRetType ret;
	union {
		VeObjGroup objs;
		VeMotionBox mot;
	} data;
}MiningRet;

#ifdef WIN32
typedef void (__cdecl * MiningCallbackFunctionPtr)(s32 id, MiningRet& ret, void * pParam);
#else
typedef void ( * MiningCallbackFunctionPtr)(s32 id, MiningRet& ret, void * pParam);
#endif

class MiningInterface
{
public:
	MiningInterface() {}
	virtual ~MiningInterface() {}

public:
	/* Channel manage */
	virtual BOOL AddChannel(s32 id) = 0;
	virtual BOOL DelChannel(s32 id) = 0;

	/* Process decoded or compressed data */
	virtual BOOL Process(s32 id, VideoFrame& frame) = 0;
	virtual BOOL ProcessRaw(s32 id, RawFrame& frame) = 0;

	/* Get the stream type of this module */
	virtual BOOL GetReqStream(MMReqStream& type) = 0;

	virtual BOOL RegRetCallback(MiningCallbackFunctionPtr pCallback, void * pParam);
	virtual BOOL UnRegDataCallback(void * pParam);
	virtual u32 GetFlags();
	virtual astring GetVersion();
};

/* Create MiningInterface from the module  */
typedef MiningInterface * (*MiningCreateObject)();

#endif /* __M_INTERFACE_HPP__ */
<commit_msg>debug mining<commit_after>//------------------------------------------------------------------------------
// File: minterface.hpp
//
// Desc: Interface for Data Mining.
//
// Copyright (c) 2014-2018. veyesys.com All rights reserved.
//------------------------------------------------------------------------------
#ifndef __M_INTERFACE_HPP__
#define __M_INTERFACE_HPP__
#include "utility.hpp"
#include "videotype.hpp"
#include "miningtype.hpp"

using namespace std;

typedef enum __MiningRetType
{
	MINING_RET_MOT = 1,
	MINING_RET_OBJS,
	MINING_RET_LAST
}MiningRetType;

typedef enum __MModuleFlag
{
	MM_MOT = 1,
	MM_TRACK = 2,
	MM_PEOPLE_CNT = 4,
	MM_ALPR = 8,
	MM_LAST
}MModuleFlag;

typedef enum __MMReqStream
{
	MM_STREAM_MAIN = 1,
	MM_STREAM_SUB = 2,
	MM_STREAM_MAIN_RAW = 1,
	MM_STREAM_SUB_RAW = 2,
	MM_STREAM_LAST
}MMReqStream;

typedef struct __MiningRet
{
	MiningRetType ret;
	union {
		VeObjGroup objs;
		VeMotionBox mot;
	} data;
}MiningRet;

#ifdef WIN32
typedef void (__cdecl * MiningCallbackFunctionPtr)(s32 id, MiningRet& ret, void * pParam);
#else
typedef void ( * MiningCallbackFunctionPtr)(s32 id, MiningRet& ret, void * pParam);
#endif

class MiningInterface
{
public:
	MiningInterface() {}
	virtual ~MiningInterface() {}

public:
	/* Channel manage */
	virtual BOOL AddChannel(s32 id) = 0;
	virtual BOOL DelChannel(s32 id) = 0;

	/* Process decoded or compressed data */
	virtual BOOL Process(s32 id, VideoFrame& frame) = 0;
	virtual BOOL ProcessRaw(s32 id, RawFrame& frame) = 0;

	/* Get the stream type of this module */
	virtual BOOL GetReqStream(MMReqStream& type) = 0;

	virtual BOOL RegRetCallback(MiningCallbackFunctionPtr pCallback, void * pParam) = 0;
	virtual BOOL UnRegDataCallback(void * pParam) = 0;
	virtual u32 GetFlags() = 0;
	virtual astring GetVersion() = 0;
};

/* Create MiningInterface from the module MiningCreateObject function  */
typedef MiningInterface * (*MiningCreateObjectFunc)();

#ifdef __cplusplus
extern "C" {
#endif
VE_LIBRARY_API MiningInterface * MiningCreateObject();
#ifdef __cplusplus
}
#endif

#endif /* __M_INTERFACE_HPP__ */
<|endoftext|>