<commit_before>#include <string.h>
#include <windows.h>
#include <shellapi.h>
#include "../ClientContext.h"
#include "../Config.h"
#include "../NetDb.h"
#include "../RouterContext.h"
#include "../Transports.h"
#include "../Tunnel.h"
#include "../version.h"
#include "resource.h"
#include "Win32App.h"
#include <stdio.h>

#if defined(_MSC_VER) && _MSC_VER < 1900
#define snprintf _snprintf
#endif

#define ID_ABOUT 2000
#define ID_EXIT 2001
#define ID_CONSOLE 2002
#define ID_APP 2003
#define ID_GRACEFUL_SHUTDOWN 2004

#define ID_TRAY_ICON 2050
#define WM_TRAYICON (WM_USER + 1)

#define IDT_GRACEFUL_SHUTDOWN_TIMER 2100
#define FRAME_UPDATE_TIMER 2101

namespace i2p
{
namespace win32
{
	static void ShowPopupMenu (HWND hWnd, POINT *curpos, int wDefaultItem)
	{
		HMENU hPopup = CreatePopupMenu();
		InsertMenu (hPopup, -1, MF_BYPOSITION | MF_STRING, ID_CONSOLE, "Open &console");
		InsertMenu (hPopup, -1, MF_BYPOSITION | MF_STRING, ID_APP, "Show app");
		InsertMenu (hPopup, -1, MF_BYPOSITION | MF_STRING, ID_ABOUT, "&About...");
		InsertMenu (hPopup, -1, MF_BYPOSITION | MF_SEPARATOR, NULL, NULL);
		InsertMenu (hPopup, -1, MF_BYPOSITION | MF_STRING, ID_GRACEFUL_SHUTDOWN, "&Graceful shutdown");
		InsertMenu (hPopup, -1, MF_BYPOSITION | MF_STRING, ID_EXIT, "E&xit");
		SetMenuDefaultItem (hPopup, ID_CONSOLE, FALSE);
		SendMessage (hWnd, WM_INITMENUPOPUP, (WPARAM)hPopup, 0);

		POINT p;
		if (!curpos)
		{
			GetCursorPos (&p);
			curpos = &p;
		}

		WORD cmd = TrackPopupMenu (hPopup, TPM_LEFTALIGN | TPM_RIGHTBUTTON | TPM_RETURNCMD | TPM_NONOTIFY, curpos->x, curpos->y, 0, hWnd, NULL);
		SendMessage (hWnd, WM_COMMAND, cmd, 0);

		DestroyMenu(hPopup);
	}

	static void AddTrayIcon (HWND hWnd)
	{
		NOTIFYICONDATA nid;
		memset(&nid, 0, sizeof(nid));
		nid.cbSize = sizeof(nid);
		nid.hWnd = hWnd;
		nid.uID = ID_TRAY_ICON;
		nid.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP | NIF_INFO;
		nid.uCallbackMessage = WM_TRAYICON;
		nid.hIcon = LoadIcon (GetModuleHandle(NULL), MAKEINTRESOURCE (MAINICON));
		strcpy (nid.szTip, "i2pd");
		strcpy (nid.szInfo, "i2pd is running");
		Shell_NotifyIcon(NIM_ADD, &nid );
	}

	static void RemoveTrayIcon (HWND hWnd)
	{
		NOTIFYICONDATA nid;
		nid.hWnd = hWnd;
		nid.uID = ID_TRAY_ICON;
		Shell_NotifyIcon (NIM_DELETE, &nid);
	}

	static void ShowUptime (std::stringstream& s, int seconds)
	{
		int num;

		if ((num = seconds / 86400) > 0) {
			s << num << " days, ";
			seconds -= num * 86400;
		}
		if ((num = seconds / 3600) > 0) {
			s << num << " hours, ";
			seconds -= num * 3600;
		}
		if ((num = seconds / 60) > 0) {
			s << num << " min, ";
			seconds -= num * 60;
		}
		s << seconds << " seconds\n";
	}

	static void ShowTransfered (std::stringstream& s, int transfer)
	{
		auto bytes = transfer & 0x03ff;
		transfer >>= 10;
		auto kbytes = transfer & 0x03ff;
		transfer >>= 10;
		auto mbytes = transfer & 0x03ff;
		transfer >>= 10;
		auto gbytes = transfer & 0x03ff;

		if (gbytes)
			s << gbytes << " GB, ";
		if (mbytes)
			s << mbytes << " MB, ";
		if (kbytes)
			s << kbytes << " KB, ";
		s << bytes << " Bytes\n";
	}

	static void PrintMainWindowText (std::stringstream& s)
	{
		s << "Status: ";
		switch (i2p::context.GetStatus())
		{
			case eRouterStatusOK: s << "OK"; break;
			case eRouterStatusTesting: s << "Testing"; break;
			case eRouterStatusFirewalled: s << "Firewalled"; break;
			case eRouterStatusError:
			{
				switch (i2p::context.GetError())
				{
					case eRouterErrorClockSkew: s << "Clock skew"; break;
					default: s << "Error";
				}
				break;
			}
			default: s << "Unknown";
		}
		s << "; ";
		s << "Success Rate: " << i2p::tunnel::tunnels.GetTunnelCreationSuccessRate() << "%\n";
		s << "Uptime: "; ShowUptime(s, i2p::context.GetUptime ());
		s << "\n";
		s << "Inbound: " << i2p::transport::transports.GetInBandwidth() / 1024 << " KiB/s; ";
		s << "Outbound: " << i2p::transport::transports.GetOutBandwidth() / 1024 << " KiB/s\n";
		s << "Recvieved: "; ShowTransfered (s, i2p::transport::transports.GetTotalReceivedBytes());
		s << "Sent: "; ShowTransfered (s, i2p::transport::transports.GetTotalSentBytes());
		s << "\n";
		s << "Routers: " << i2p::data::netdb.GetNumRouters () << "; ";
		s << "Floodfills: " << i2p::data::netdb.GetNumFloodfills () << "; ";
		s << "LeaseSets: " << i2p::data::netdb.GetNumLeaseSets () << "\n";
		s << "Tunnels: ";
		s << "In: " << i2p::tunnel::tunnels.CountInboundTunnels() << "; ";
		s << "Out: " << i2p::tunnel::tunnels.CountOutboundTunnels() << "; ";
		s << "Transit: " << i2p::tunnel::tunnels.CountTransitTunnels() << "\n";
	}

	static LRESULT CALLBACK WndProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
	{
		switch (uMsg)
		{
			case WM_CREATE:
			{
				AddTrayIcon (hWnd);
				break;
			}
			case WM_CLOSE:
			{
				RemoveTrayIcon (hWnd);
				KillTimer (hWnd, FRAME_UPDATE_TIMER);
				KillTimer (hWnd, IDT_GRACEFUL_SHUTDOWN_TIMER);
				PostQuitMessage (0);
				break;
			}
			case WM_COMMAND:
			{
				switch (LOWORD(wParam))
				{
					case ID_ABOUT:
					{
						std::stringstream text;
						text << "Version: " << I2PD_VERSION << " " << CODENAME;
						MessageBox( hWnd, TEXT(text.str ().c_str ()), TEXT("i2pd"), MB_ICONINFORMATION | MB_OK );
						return 0;
					}
					case ID_EXIT:
					{
						PostMessage (hWnd, WM_CLOSE, 0, 0);
						return 0;
					}
					case ID_GRACEFUL_SHUTDOWN:
					{
						i2p::context.SetAcceptsTunnels (false);
						SetTimer (hWnd, IDT_GRACEFUL_SHUTDOWN_TIMER, 10*60*1000, nullptr); // 10 minutes
						return 0;
					}
					case ID_CONSOLE:
					{
						char buf[30];
						std::string httpAddr; i2p::config::GetOption("http.address", httpAddr);
						uint16_t	httpPort; i2p::config::GetOption("http.port", httpPort);
						snprintf(buf, 30, "http://%s:%d", httpAddr.c_str(), httpPort);
						ShellExecute(NULL, "open", buf, NULL, NULL, SW_SHOWNORMAL);
						return 0;
					}
					case ID_APP:
					{
						ShowWindow(hWnd, SW_SHOW);
						SetTimer(hWnd, FRAME_UPDATE_TIMER, 3000, NULL);
						return 0;
					}
				}
				break;
			}
			case WM_SYSCOMMAND:
			{
				switch (wParam)
				{
					case SC_MINIMIZE:
					{
						ShowWindow(hWnd, SW_HIDE);
						KillTimer (hWnd, FRAME_UPDATE_TIMER);
						return 0;
					}
					case SC_CLOSE:
					{
						std::string close; i2p::config::GetOption("close", close);
						if (0 == close.compare("ask"))
						switch(::MessageBox(hWnd, "Would you like to minimize instead of exiting?"
						" You can add 'close' configuration option. Valid values are: ask, minimize, exit.",
						"Minimize instead of exiting?", MB_ICONQUESTION | MB_YESNOCANCEL | MB_DEFBUTTON1))
						{
							case IDYES: close = "minimize"; break;
							case IDNO: close = "exit"; break;
							default: return 0;
						}
						if (0 == close.compare("minimize"))
						{
							ShowWindow(hWnd, SW_HIDE);
							KillTimer (hWnd, FRAME_UPDATE_TIMER);
							return 0;
						}
						if (0 != close.compare("exit"))
						{
							::MessageBox(hWnd, close.c_str(), "Unknown close action in config", MB_OK | MB_ICONWARNING);
							return 0;
						}
					}
				}
			}
			case WM_TRAYICON:
			{
				switch (lParam)
				{
					case WM_LBUTTONUP:
					case WM_RBUTTONUP:
					{
						SetForegroundWindow (hWnd);
						ShowPopupMenu(hWnd, NULL, -1);
						PostMessage (hWnd, WM_APP + 1, 0, 0);
						break;
					}
				}
				break;
			}
			case WM_TIMER:
			{
				if (wParam == IDT_GRACEFUL_SHUTDOWN_TIMER)
				{
					PostMessage (hWnd, WM_CLOSE, 0, 0); // exit
					return 0;
				}
				if (wParam == FRAME_UPDATE_TIMER)
				{
					InvalidateRect(hWnd, NULL, TRUE);
				}
				break;
			}
			case WM_PAINT:
			{
				HDC hDC;
				PAINTSTRUCT ps;
				RECT rp;
				HFONT hFont;
				std::stringstream s; PrintMainWindowText (s);
				hDC = BeginPaint (hWnd, &ps);
				GetClientRect(hWnd, &rp);
				SetTextColor(hDC, 0x00D43B69);
				hFont = CreateFont(18,0,0,0,0,0,0,0,DEFAULT_CHARSET,0,0,0,0,TEXT("Times New Roman"));
				SelectObject(hDC,hFont);
				DrawText(hDC, TEXT(s.str().c_str()), s.str().length(), &rp, DT_CENTER|DT_VCENTER);
				EndPaint(hWnd, &ps);
				break;
			}
		}
		return DefWindowProc( hWnd, uMsg, wParam, lParam);
	}

	bool StartWin32App ()
	{
		if (FindWindow (I2PD_WIN32_CLASSNAME, TEXT("i2pd")))
		{
			MessageBox(NULL, TEXT("I2Pd is running already"), TEXT("Warning"), MB_OK);
			return false;
		}
		// register main window
		auto hInst = GetModuleHandle(NULL);
		WNDCLASSEX wclx;
		memset (&wclx, 0, sizeof(wclx));
		wclx.cbSize = sizeof(wclx);
		wclx.style = 0;
		wclx.lpfnWndProc = WndProc;
		wclx.cbClsExtra = 0;
		wclx.cbWndExtra = 0;
		wclx.hInstance = hInst;
		wclx.hIcon = LoadIcon (hInst, MAKEINTRESOURCE(MAINICON));
		wclx.hCursor = LoadCursor (NULL, IDC_ARROW);
		wclx.hbrBackground = (HBRUSH)(COLOR_BTNFACE + 1);
		wclx.lpszMenuName = NULL;
		wclx.lpszClassName = I2PD_WIN32_CLASSNAME;
		RegisterClassEx (&wclx);
		// create new window
		if (!CreateWindow(I2PD_WIN32_CLASSNAME, TEXT("i2pd"), WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX, 100, 100, 350, 180, NULL, NULL, hInst, NULL))
		{
			MessageBox(NULL, "Failed to create main window", TEXT("Warning!"), MB_ICONERROR | MB_OK | MB_TOPMOST);
			return false;
		}
		return true;
	}

	int RunWin32App ()
	{
		MSG msg;
		while (GetMessage (&msg, NULL, 0, 0 ))
		{
			TranslateMessage (&msg);
			DispatchMessage (&msg);
		}
		return msg.wParam;
	}

	void StopWin32App ()
	{
		UnregisterClass (I2PD_WIN32_CLASSNAME, GetModuleHandle(NULL));
	}

	bool GracefulShutdown ()
	{
		HWND hWnd = FindWindow (I2PD_WIN32_CLASSNAME, TEXT("i2pd"));
		if (hWnd)
		PostMessage (hWnd, WM_COMMAND, MAKEWPARAM(ID_GRACEFUL_SHUTDOWN, 0), 0);
		return hWnd;
	}
}
}
<commit_msg>winapi - fix style, delete hFont object after drawing (fixes overflow)<commit_after>#include <string.h>
#include <windows.h>
#include <shellapi.h>
#include "../ClientContext.h"
#include "../Config.h"
#include "../NetDb.h"
#include "../RouterContext.h"
#include "../Transports.h"
#include "../Tunnel.h"
#include "../version.h"
#include "resource.h"
#include "Win32App.h"
#include <stdio.h>

#if defined(_MSC_VER) && _MSC_VER < 1900
#define snprintf _snprintf
#endif

#define ID_ABOUT 2000
#define ID_EXIT 2001
#define ID_CONSOLE 2002
#define ID_APP 2003
#define ID_GRACEFUL_SHUTDOWN 2004

#define ID_TRAY_ICON 2050
#define WM_TRAYICON (WM_USER + 1)

#define IDT_GRACEFUL_SHUTDOWN_TIMER 2100
#define FRAME_UPDATE_TIMER 2101

namespace i2p
{
namespace win32
{
	static void ShowPopupMenu (HWND hWnd, POINT *curpos, int wDefaultItem)
	{
		HMENU hPopup = CreatePopupMenu();
		InsertMenu (hPopup, -1, MF_BYPOSITION | MF_STRING, ID_CONSOLE, "Open &console");
		InsertMenu (hPopup, -1, MF_BYPOSITION | MF_STRING, ID_APP, "Show app");
		InsertMenu (hPopup, -1, MF_BYPOSITION | MF_STRING, ID_ABOUT, "&About...");
		InsertMenu (hPopup, -1, MF_BYPOSITION | MF_SEPARATOR, NULL, NULL);
		InsertMenu (hPopup, -1, MF_BYPOSITION | MF_STRING, ID_GRACEFUL_SHUTDOWN, "&Graceful shutdown");
		InsertMenu (hPopup, -1, MF_BYPOSITION | MF_STRING, ID_EXIT, "E&xit");
		SetMenuDefaultItem (hPopup, ID_CONSOLE, FALSE);
		SendMessage (hWnd, WM_INITMENUPOPUP, (WPARAM)hPopup, 0);

		POINT p;
		if (!curpos)
		{
			GetCursorPos (&p);
			curpos = &p;
		}

		WORD cmd = TrackPopupMenu (hPopup, TPM_LEFTALIGN | TPM_RIGHTBUTTON | TPM_RETURNCMD | TPM_NONOTIFY, curpos->x, curpos->y, 0, hWnd, NULL);
		SendMessage (hWnd, WM_COMMAND, cmd, 0);

		DestroyMenu(hPopup);
	}

	static void AddTrayIcon (HWND hWnd)
	{
		NOTIFYICONDATA nid;
		memset(&nid, 0, sizeof(nid));
		nid.cbSize = sizeof(nid);
		nid.hWnd = hWnd;
		nid.uID = ID_TRAY_ICON;
		nid.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP | NIF_INFO;
		nid.uCallbackMessage = WM_TRAYICON;
		nid.hIcon = LoadIcon (GetModuleHandle(NULL), MAKEINTRESOURCE (MAINICON));
		strcpy (nid.szTip, "i2pd");
		strcpy (nid.szInfo, "i2pd is running");
		Shell_NotifyIcon(NIM_ADD, &nid );
	}

	static void RemoveTrayIcon (HWND hWnd)
	{
		NOTIFYICONDATA nid;
		nid.hWnd = hWnd;
		nid.uID = ID_TRAY_ICON;
		Shell_NotifyIcon (NIM_DELETE, &nid);
	}

	static void ShowUptime (std::stringstream& s, int seconds)
	{
		int num;

		if ((num = seconds / 86400) > 0) {
			s << num << " days, ";
			seconds -= num * 86400;
		}
		if ((num = seconds / 3600) > 0) {
			s << num << " hours, ";
			seconds -= num * 3600;
		}
		if ((num = seconds / 60) > 0) {
			s << num << " min, ";
			seconds -= num * 60;
		}
		s << seconds << " seconds\n";
	}

	static void ShowTransfered (std::stringstream& s, int transfer)
	{
		auto bytes = transfer & 0x03ff;
		transfer >>= 10;
		auto kbytes = transfer & 0x03ff;
		transfer >>= 10;
		auto mbytes = transfer & 0x03ff;
		transfer >>= 10;
		auto gbytes = transfer & 0x03ff;

		if (gbytes)
			s << gbytes << " GB, ";
		if (mbytes)
			s << mbytes << " MB, ";
		if (kbytes)
			s << kbytes << " KB, ";
		s << bytes << " Bytes\n";
	}

	static void PrintMainWindowText (std::stringstream& s)
	{
		s << "Status: ";
		switch (i2p::context.GetStatus())
		{
			case eRouterStatusOK: s << "OK"; break;
			case eRouterStatusTesting: s << "Testing"; break;
			case eRouterStatusFirewalled: s << "Firewalled"; break;
			case eRouterStatusError:
			{
				switch (i2p::context.GetError())
				{
					case eRouterErrorClockSkew: s << "Clock skew"; break;
					default: s << "Error";
				}
				break;
			}
			default: s << "Unknown";
		}
		s << "; ";
		s << "Success Rate: " << i2p::tunnel::tunnels.GetTunnelCreationSuccessRate() << "%\n";
		s << "Uptime: "; ShowUptime(s, i2p::context.GetUptime ());
		s << "\n";
		s << "Inbound: " << i2p::transport::transports.GetInBandwidth() / 1024 << " KiB/s; ";
		s << "Outbound: " << i2p::transport::transports.GetOutBandwidth() / 1024 << " KiB/s\n";
		s << "Recvieved: "; ShowTransfered (s, i2p::transport::transports.GetTotalReceivedBytes());
		s << "Sent: "; ShowTransfered (s, i2p::transport::transports.GetTotalSentBytes());
		s << "\n";
		s << "Routers: " << i2p::data::netdb.GetNumRouters () << "; ";
		s << "Floodfills: " << i2p::data::netdb.GetNumFloodfills () << "; ";
		s << "LeaseSets: " << i2p::data::netdb.GetNumLeaseSets () << "\n";
		s << "Tunnels: ";
		s << "In: " << i2p::tunnel::tunnels.CountInboundTunnels() << "; ";
		s << "Out: " << i2p::tunnel::tunnels.CountOutboundTunnels() << "; ";
		s << "Transit: " << i2p::tunnel::tunnels.CountTransitTunnels() << "\n";
	}

	static LRESULT CALLBACK WndProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
	{
		switch (uMsg)
		{
			case WM_CREATE:
			{
				AddTrayIcon (hWnd);
				break;
			}
			case WM_CLOSE:
			{
				RemoveTrayIcon (hWnd);
				KillTimer (hWnd, FRAME_UPDATE_TIMER);
				KillTimer (hWnd, IDT_GRACEFUL_SHUTDOWN_TIMER);
				PostQuitMessage (0);
				break;
			}
			case WM_COMMAND:
			{
				switch (LOWORD(wParam))
				{
					case ID_ABOUT:
					{
						std::stringstream text;
						text << "Version: " << I2PD_VERSION << " " << CODENAME;
						MessageBox( hWnd, TEXT(text.str ().c_str ()), TEXT("i2pd"), MB_ICONINFORMATION | MB_OK );
						return 0;
					}
					case ID_EXIT:
					{
						PostMessage (hWnd, WM_CLOSE, 0, 0);
						return 0;
					}
					case ID_GRACEFUL_SHUTDOWN:
					{
						i2p::context.SetAcceptsTunnels (false);
						SetTimer (hWnd, IDT_GRACEFUL_SHUTDOWN_TIMER, 10*60*1000, nullptr); // 10 minutes
						return 0;
					}
					case ID_CONSOLE:
					{
						char buf[30];
						std::string httpAddr; i2p::config::GetOption("http.address", httpAddr);
						uint16_t	httpPort; i2p::config::GetOption("http.port", httpPort);
						snprintf(buf, 30, "http://%s:%d", httpAddr.c_str(), httpPort);
						ShellExecute(NULL, "open", buf, NULL, NULL, SW_SHOWNORMAL);
						return 0;
					}
					case ID_APP:
					{
						ShowWindow(hWnd, SW_SHOW);
						SetTimer(hWnd, FRAME_UPDATE_TIMER, 3000, NULL);
						return 0;
					}
				}
				break;
			}
			case WM_SYSCOMMAND:
			{
				switch (wParam)
				{
					case SC_MINIMIZE:
					{
						ShowWindow(hWnd, SW_HIDE);
						KillTimer (hWnd, FRAME_UPDATE_TIMER);
						return 0;
					}
					case SC_CLOSE:
					{
						std::string close; i2p::config::GetOption("close", close);
						if (0 == close.compare("ask"))
						switch(::MessageBox(hWnd, "Would you like to minimize instead of exiting?"
						" You can add 'close' configuration option. Valid values are: ask, minimize, exit.",
						"Minimize instead of exiting?", MB_ICONQUESTION | MB_YESNOCANCEL | MB_DEFBUTTON1))
						{
							case IDYES: close = "minimize"; break;
							case IDNO: close = "exit"; break;
							default: return 0;
						}
						if (0 == close.compare("minimize"))
						{
							ShowWindow(hWnd, SW_HIDE);
							KillTimer (hWnd, FRAME_UPDATE_TIMER);
							return 0;
						}
						if (0 != close.compare("exit"))
						{
							::MessageBox(hWnd, close.c_str(), "Unknown close action in config", MB_OK | MB_ICONWARNING);
							return 0;
						}
					}
				}
			}
			case WM_TRAYICON:
			{
				switch (lParam)
				{
					case WM_LBUTTONUP:
					case WM_RBUTTONUP:
					{
						SetForegroundWindow (hWnd);
						ShowPopupMenu(hWnd, NULL, -1);
						PostMessage (hWnd, WM_APP + 1, 0, 0);
						break;
					}
				}
				break;
			}
			case WM_TIMER:
			{
				if (wParam == IDT_GRACEFUL_SHUTDOWN_TIMER)
				{
					PostMessage (hWnd, WM_CLOSE, 0, 0); // exit
					return 0;
				}
				if (wParam == FRAME_UPDATE_TIMER)
				{
					InvalidateRect(hWnd, NULL, TRUE);
				}
				break;
			}
			case WM_PAINT:
			{
				HDC hDC;
				PAINTSTRUCT ps;
				RECT rp;
				HFONT hFont;
				std::stringstream s; PrintMainWindowText (s);
				hDC = BeginPaint (hWnd, &ps);
				GetClientRect(hWnd, &rp);
				SetTextColor(hDC, 0x00D43B69);
				hFont = CreateFont(18,0,0,0,0,0,0,0,DEFAULT_CHARSET,0,0,0,0,TEXT("Times New Roman"));
				SelectObject(hDC,hFont);
				DrawText(hDC, TEXT(s.str().c_str()), s.str().length(), &rp, DT_CENTER|DT_VCENTER);
				DeleteObject(hFont);
				EndPaint(hWnd, &ps);
				break;
			}
		}
		return DefWindowProc( hWnd, uMsg, wParam, lParam);
	}

	bool StartWin32App ()
	{
		if (FindWindow (I2PD_WIN32_CLASSNAME, TEXT("i2pd")))
		{
			MessageBox(NULL, TEXT("I2Pd is running already"), TEXT("Warning"), MB_OK);
			return false;
		}
		// register main window
		auto hInst = GetModuleHandle(NULL);
		WNDCLASSEX wclx;
		memset (&wclx, 0, sizeof(wclx));
		wclx.cbSize = sizeof(wclx);
		wclx.style = 0;
		wclx.lpfnWndProc = WndProc;
		//wclx.cbClsExtra = 0;
		//wclx.cbWndExtra = 0;
		wclx.hInstance = hInst;
		wclx.hIcon = LoadIcon (hInst, MAKEINTRESOURCE(MAINICON));
		wclx.hCursor = LoadCursor (NULL, IDC_ARROW);
		//wclx.hbrBackground = (HBRUSH)(COLOR_BTNFACE + 1);
		wclx.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
		wclx.lpszMenuName = NULL;
		wclx.lpszClassName = I2PD_WIN32_CLASSNAME;
		RegisterClassEx (&wclx);
		// create new window
		if (!CreateWindow(I2PD_WIN32_CLASSNAME, TEXT("i2pd"), WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX, 100, 100, 350, 180, NULL, NULL, hInst, NULL))
		{
			MessageBox(NULL, "Failed to create main window", TEXT("Warning!"), MB_ICONERROR | MB_OK | MB_TOPMOST);
			return false;
		}
		return true;
	}

	int RunWin32App ()
	{
		MSG msg;
		while (GetMessage (&msg, NULL, 0, 0 ))
		{
			TranslateMessage (&msg);
			DispatchMessage (&msg);
		}
		return msg.wParam;
	}

	void StopWin32App ()
	{
		UnregisterClass (I2PD_WIN32_CLASSNAME, GetModuleHandle(NULL));
	}

	bool GracefulShutdown ()
	{
		HWND hWnd = FindWindow (I2PD_WIN32_CLASSNAME, TEXT("i2pd"));
		if (hWnd)
		PostMessage (hWnd, WM_COMMAND, MAKEWPARAM(ID_GRACEFUL_SHUTDOWN, 0), 0);
		return hWnd;
	}
}
}
<|endoftext|>


<commit_before>#ifndef RECURSE_HPP
#define RECURSE_HPP

#include <QCoreApplication>
#include <QObject>
#include <QTcpServer>
#include <QTcpSocket>
#include <QHostAddress>
#include <QHash>
#include <QStringBuilder>
#include <QVector>
#include "request.hpp"
#include "response.hpp"

#include <functional>
using std::function;
using std::bind;
using std::ref;

typedef function<void(Request &request, Response &response, function<void()> next)> next_f;

//!
//! \brief The Recurse class
//! main class of the app
//!
class Recurse : public QObject
{
public:

    Recurse(int & argc, char ** argv, QObject *parent = NULL);
    ~Recurse();

    bool listen(quint64 port, QHostAddress address = QHostAddress::Any);
    void use(next_f next);

private:
    QCoreApplication app;
    QTcpServer m_tcp_server;
    quint64 m_port;
    QVector<next_f> m_middleware;
    int current_middleware = 0;
    void m_next(Request &request, Response &response);
    void http_parse(Request &request);
    QString http_build_header(const Response &response);
};

Recurse::Recurse(int & argc, char ** argv, QObject *parent) : app(argc, argv)
{
    Q_UNUSED(parent);
};

Recurse::~Recurse()
{

};

//!
//! \brief Recurse::listen
//! listen for tcp requests
//!
//! \param port tcp server port
//! \param address tcp server listening address
//!
//! \return true on success
//!
bool Recurse::listen(quint64 port, QHostAddress address)
{
    m_port = port;
    int bound = m_tcp_server.listen(address, port);
    if (!bound)
        return false;

    connect(&m_tcp_server, &QTcpServer::newConnection, [this] {
        qDebug() << "client connected";
        QTcpSocket *client = m_tcp_server.nextPendingConnection();

        connect(client, &QTcpSocket::readyRead, [this, client] {
            Request request;
            Response response;

            request.data = client->readAll();
            QRegExp httpRx("^(?=[A-Z]).* \\/.* HTTP\\/[0-9]\\.[0-9]\\r\\n");
            bool isHttp = request.data.contains(httpRx);

            if (isHttp)
                http_parse(request);

            qDebug() << "client request: " << request.data;

            if (m_middleware.count() > 0)
                m_middleware[current_middleware](request, response, bind(&Recurse::m_next, this, ref(request), ref(response)));

            current_middleware = 0;
            QString header;

            if (isHttp) {
                response.method = request.method;
                response.proto = request.proto;

                if (response.status == 0)
                    response.status = 200;

                header = http_build_header(response);
            }

            QString response_data = header + response.body;

            // send response to the client
            qint64 check = client->write(response_data.toStdString().c_str(), response_data.size());

            qDebug() << "socket write debug:" << check;
            client->close();
        });
    });

    return app.exec();
};

//!
//! \brief Recurse::m_next
//! call next middleware
//!
void Recurse::m_next(Request &request, Response &response)
{
    qDebug() << "calling next:" << current_middleware << " num:" << m_middleware.size();

    if (++current_middleware >= m_middleware.size()) {
        return;
    };

    m_middleware[current_middleware](request, response, bind(&Recurse::m_next, this, ref(request), ref(response)));

};

//!
//! \brief Recurse::use
//! add new middleware
//!
//! \param f middleware function that will be called later
//!
void Recurse::use(next_f f)
{
    m_middleware.push_back(f);
};

//!
//! \brief Recurse::http_parse
//! parse http data
//!
//! \param data reference to data received from the tcp connection
//!
void Recurse::http_parse(Request &request)
{
    QStringList data_list = request.data.split("\r\n");
    bool is_body = false;

    for (int i = 0; i < data_list.size(); ++i) {
        if (is_body) {
            request.body.append(data_list.at(i));
            continue;
        }

        QStringList entity_item = data_list.at(i).split(":");

        if (entity_item.length() < 2 && entity_item.at(0).size() < 1 && !is_body) {
            is_body = true;
            continue;
        }
        else if (i == 0 && entity_item.length() < 2) {
            QStringList first_line = entity_item.at(0).split(" ");
            request.method = first_line.at(0);
            request.url = first_line.at(1).trimmed();
            request.proto = first_line.at(2).trimmed();
            continue;
        }

        request.header[entity_item.at(0).toLower()] = entity_item.at(1).trimmed();
    }

    qDebug() << "request object populated: " << request.method << request.url << request.header << request.proto << request.body;
};

//!
//! \brief Recurse::http_build_header
//! build http header for response
//!
//! \param response reference to the Response instance
//!
QString Recurse::http_build_header(const Response &response)
{
    QString header = response.proto % " " % QString::number(response.status) % " "
        % response.http_codes[response.status] % "\r\n";

    // set default header fields
    QHash<QString, QString>::const_iterator i;

    for (i = response.default_headers.constBegin(); i != response.default_headers.constEnd(); ++i) {
        if (response.header[i.key()] == "")
            header += i.key() % ": " % i.value() % "\r\n";
    }

    // set user-defined header fields
    QHash<QString, QString>::const_iterator j;

    for (j = response.header.constBegin(); j != response.header.constEnd(); ++j) {
        header += j.key() % ": " % j.value() % "\r\n";
    }

    qDebug() << "response header" << header;

    return header + "\r\n";
}

#endif // RECURSE_HPP
<commit_msg>fill content-length<commit_after>#ifndef RECURSE_HPP
#define RECURSE_HPP

#include <QCoreApplication>
#include <QObject>
#include <QTcpServer>
#include <QTcpSocket>
#include <QHostAddress>
#include <QHash>
#include <QStringBuilder>
#include <QVector>
#include "request.hpp"
#include "response.hpp"

#include <functional>
using std::function;
using std::bind;
using std::ref;

typedef function<void(Request &request, Response &response, function<void()> next)> next_f;

//!
//! \brief The Recurse class
//! main class of the app
//!
class Recurse : public QObject
{
public:

    Recurse(int & argc, char ** argv, QObject *parent = NULL);
    ~Recurse();

    bool listen(quint64 port, QHostAddress address = QHostAddress::Any);
    void use(next_f next);

private:
    QCoreApplication app;
    QTcpServer m_tcp_server;
    quint64 m_port;
    QVector<next_f> m_middleware;
    int current_middleware = 0;
    void m_next(Request &request, Response &response);
    void http_parse(Request &request);
    QString http_build_header(const Response &response);
};

Recurse::Recurse(int & argc, char ** argv, QObject *parent) : app(argc, argv)
{
    Q_UNUSED(parent);
};

Recurse::~Recurse()
{

};

//!
//! \brief Recurse::listen
//! listen for tcp requests
//!
//! \param port tcp server port
//! \param address tcp server listening address
//!
//! \return true on success
//!
bool Recurse::listen(quint64 port, QHostAddress address)
{
    m_port = port;
    int bound = m_tcp_server.listen(address, port);
    if (!bound)
        return false;

    connect(&m_tcp_server, &QTcpServer::newConnection, [this] {
        qDebug() << "client connected";
        QTcpSocket *client = m_tcp_server.nextPendingConnection();

        connect(client, &QTcpSocket::readyRead, [this, client] {
            Request request;
            Response response;

            request.data = client->readAll();
            QRegExp httpRx("^(?=[A-Z]).* \\/.* HTTP\\/[0-9]\\.[0-9]\\r\\n");
            bool isHttp = request.data.contains(httpRx);

            if (isHttp)
                http_parse(request);

            qDebug() << "client request: " << request.data;

            if (m_middleware.count() > 0)
                m_middleware[current_middleware](request, response, bind(&Recurse::m_next, this, ref(request), ref(response)));

            current_middleware = 0;
            QString header;

            if (isHttp) {
                response.method = request.method;
                response.proto = request.proto;

                if (response.status == 0)
                    response.status = 200;

                header = http_build_header(response);
            }

            QString response_data = header + response.body;

            // send response to the client
            qint64 check = client->write(response_data.toStdString().c_str(), response_data.size());

            qDebug() << "socket write debug:" << check;
            client->close();
        });
    });

    return app.exec();
};

//!
//! \brief Recurse::m_next
//! call next middleware
//!
void Recurse::m_next(Request &request, Response &response)
{
    qDebug() << "calling next:" << current_middleware << " num:" << m_middleware.size();

    if (++current_middleware >= m_middleware.size()) {
        return;
    };

    m_middleware[current_middleware](request, response, bind(&Recurse::m_next, this, ref(request), ref(response)));

};

//!
//! \brief Recurse::use
//! add new middleware
//!
//! \param f middleware function that will be called later
//!
void Recurse::use(next_f f)
{
    m_middleware.push_back(f);
};

//!
//! \brief Recurse::http_parse
//! parse http data
//!
//! \param data reference to data received from the tcp connection
//!
void Recurse::http_parse(Request &request)
{
    QStringList data_list = request.data.split("\r\n");
    bool is_body = false;

    for (int i = 0; i < data_list.size(); ++i) {
        if (is_body) {
            request.body.append(data_list.at(i));
            continue;
        }

        QStringList entity_item = data_list.at(i).split(":");

        if (entity_item.length() < 2 && entity_item.at(0).size() < 1 && !is_body) {
            is_body = true;
            continue;
        }
        else if (i == 0 && entity_item.length() < 2) {
            QStringList first_line = entity_item.at(0).split(" ");
            request.method = first_line.at(0);
            request.url = first_line.at(1).trimmed();
            request.proto = first_line.at(2).trimmed();
            continue;
        }

        request.header[entity_item.at(0).toLower()] = entity_item.at(1).trimmed();
    }

    qDebug() << "request object populated: " << request.method << request.url << request.header << request.proto << request.body;
};

//!
//! \brief Recurse::http_build_header
//! build http header for response
//!
//! \param response reference to the Response instance
//!
QString Recurse::http_build_header(const Response &response)
{
    QString header = response.proto % " " % QString::number(response.status) % " "
        % response.http_codes[response.status] % "\r\n";

    // set default header fields
    QHash<QString, QString>::const_iterator i;

    for (i = response.default_headers.constBegin(); i != response.default_headers.constEnd(); ++i) {
        if (i.key() == "content-length" && response.header[i.key()] == "")
            header += i.key() % ": " % QString::number(response.body.size()) % "\r\n";
        else if (response.header[i.key()] == "")
            header += i.key() % ": " % i.value() % "\r\n";
    }

    // set user-defined header fields
    QHash<QString, QString>::const_iterator j;

    for (j = response.header.constBegin(); j != response.header.constEnd(); ++j) {
        header += j.key() % ": " % j.value() % "\r\n";
    }

    qDebug() << "response header" << header;

    return header + "\r\n";
}

#endif // RECURSE_HPP
<|endoftext|>


<commit_before>/**
  @file  sparse_adjacency_matrices.cc
  @brief Tool for calculating persistent homology of sparse adjacency matrices

  This is a tool shipped by 'Aleph - A Library for Exploring Persistent
  Homology'. It calculates the persistent homology of sparse adjacency
  matrices, i.e. data sets containing *multiple* graphs, using either
  a degree filtration or a filtration based on the *sum* of degrees.

  Original author: Bastian Rieck
*/

#include <aleph/geometry/RipsExpander.hh>

#include <aleph/math/KahanSummation.hh>

#include <aleph/persistentHomology/Calculation.hh>

#include <aleph/topology/FloydWarshall.hh>
#include <aleph/topology/Simplex.hh>
#include <aleph/topology/SimplicialComplex.hh>

#include <aleph/topology/filtrations/Data.hh>
#include <aleph/topology/filtrations/Degree.hh>

#include <aleph/topology/io/GML.hh>
#include <aleph/topology/io/SparseAdjacencyMatrix.hh>

#include <aleph/utilities/Format.hh>
#include <aleph/utilities/String.hh>

#include <getopt.h>

#include <algorithm>
#include <fstream>
#include <iostream>
#include <limits>
#include <stdexcept>
#include <string>
#include <vector>

#include <cmath>

using DataType          = float;
using VertexType        = std::size_t;
using Simplex           = aleph::topology::Simplex<DataType, VertexType>;
using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>;

std::vector<DataType> closenessCentrality( const SimplicialComplex& K )
{
  auto M = aleph::topology::floydWarshall( K, 1 );
  auto n = M.numRows();

  std::vector<DataType> result;
  result.reserve( n );

  for( decltype(n) i = 0; i < n; i++ )
  {
    aleph::math::KahanSummation<DataType> sum = DataType();

    for( decltype(n) j = 0; j < n; j++ )
      if( std::isfinite( M(i,j) ) )
        sum += M(i,j);

    result.push_back( DataType(n) / sum );
  }

  return result;
}

void usage()
{
  std::cerr << "Usage: sparse_adjacency_matrices FILE\n"
            << "\n"
            << "Loads a set of sparse adjacency matrices from FILE and performs\n"
            << "several operations with them. By default, the tool will extract\n"
            << "all graphs from the file, use a degree-based filtration, and do\n"
            << "a conversion to GML. Furthermore, persistence diagrams of every\n"
            << "graph will be calculated.\n"
            << "\n"
            << "Optional arguments:\n"
            << "\n"
            << " --dimension D: Expand simplicial complexes up to dimension D\n"
            << " --infinity I:  Use factor I for unpaired points in a diagram\n"
            << "\n"
            << "Flags:\n"
            << "\n"
            << " --closeness-centrality: Calculates closeness centrality filtration\n"
            << " --graphs:               Stores converted graphs in GML format\n"
            << " --sum:                  Calculates degree sum filtration\n"
            << "\n"
            << "\n";
}

int main( int argc, char** argv )
{
  static option commandLineOptions[] =
  {
    { "dimension"           , required_argument, nullptr, 'd' },
    { "infinity"            , required_argument, nullptr, 'f' },
    { "output"              , required_argument, nullptr, 'o' },
    { "closeness-centrality", no_argument      , nullptr, 'c' },
    { "graphs"              , no_argument      , nullptr, 'g' },
    { "sum"                 , no_argument      , nullptr, 's' },
    { nullptr               , 0                , nullptr,  0  }
  };

  unsigned dimension                = 0;
  bool calculateClosenessCentrality = false;
  bool storeGraphs                  = false;
  bool useSumOfDegrees              = false;
  DataType infinity                 = DataType(2);
  std::string output                = "/tmp";

  {
    int option = 0;
    while( ( option = getopt_long( argc, argv, "d:f:o:cgs", commandLineOptions, nullptr ) ) != -1 )
    {
      switch( option )
      {
      case 'd':
        dimension = static_cast<unsigned>( std::stoul( optarg  ) );
        break;
      case 'f':
        infinity = aleph::utilities::convert<DataType>( optarg );
        break;
      case 'o':
        output = optarg;
        break;
      case 'c':
        calculateClosenessCentrality = true;
        break;
      case 'g':
        storeGraphs = true;
        break;
      case 's':
        useSumOfDegrees = true;
        break;
      default:
        throw std::runtime_error( "Unknown command-line arugment" );
      }
    }
  }

  if( ( argc - optind ) < 1 )
  {
    usage();
    return -1;
  }

  // Check that the output parameter at least *looks* like a directory
  if( output.back() != '/' )
    output.push_back( '/' );

  std::string filename = argv[optind++];

  std::vector<SimplicialComplex> simplicialComplexes;
  std::vector<std::string> labels;

  aleph::topology::io::SparseAdjacencyMatrixReader reader;
  reader.setReadGraphLabels();
  reader.setReadNodeLabels();

  std::vector<std::string> nodeLabels;

  std::cerr << "* Reading '" << filename << "'...";

  reader( filename, simplicialComplexes );

  // Get node labels for further processing because we must not drop
  // this valuable information.
  reader.nodeLabels(
    std::back_inserter( nodeLabels )
  );

  std::cerr << "finished\n"
            << "* Read " << simplicialComplexes.size() << " simplicial complexes\n";

  // Calculate closeness centrality ------------------------------------

  if( calculateClosenessCentrality )
  {
    std::size_t index = 0;

    for( auto&& K : simplicialComplexes )
    {
      K.sort();
      auto cc         = closenessCentrality( K );
      auto outputPath = output
                      + aleph::utilities::format( index, simplicialComplexes.size() )
                      + "_closeness_centrality.txt";

      std::cerr << "* Storing closeness centrality values in '" << outputPath << "'\n";

      std::ofstream out( outputPath );
      for( auto&& value : cc )
        out << value << "\n";

      ++index;
    }
  }

  // Expand simplicial complexes ---------------------------------------

  aleph::geometry::RipsExpander<SimplicialComplex> expander;

  if( dimension != 0 )
  {
    std::cerr << "* Expanding simplicial complexes to dimension " << dimension << "...";

    for( auto&& K : simplicialComplexes )
      expander( K, dimension );

    std::cerr << "finished\n";
  }

  // Calculate degrees -------------------------------------------------

  DataType maxDegree = 0;

  std::cerr << "* Calculating degree-based filtration...";

  for( auto&& K : simplicialComplexes )
  {
    std::vector<unsigned> degrees_;
    aleph::topology::filtrations::degrees( K, std::back_inserter( degrees_ ) );

    std::vector<DataType> degrees( degrees_.begin(), degrees_.end() );

    if( !degrees.empty() )
    {
      maxDegree
        = std::max( maxDegree,
                    *std::max_element( degrees.begin(), degrees.end() ) );
    }

    if( useSumOfDegrees )
      K = expander.assignData( K, degrees.begin(), degrees.end(), DataType(0), [] ( DataType a, DataType b ) { return a+b; } );
    else
      K = expander.assignMaximumData( K, degrees.begin(), degrees.end() );

    K.sort( aleph::topology::filtrations::Data<Simplex>() );
  }

  std::cerr << "finished\n"
            << "* Identified maximum degree as D=" << maxDegree << "\n";

  // Store graphs ------------------------------------------------------

  if( storeGraphs )
  {
    aleph::topology::io::GMLWriter writer;
    writer.setNodeLabels( nodeLabels.begin(), nodeLabels.end() );

    for( std::size_t i = 0; i < simplicialComplexes.size(); i++ )
    {
      auto filename = output
                      + aleph::utilities::format( i, simplicialComplexes.size() )
                      + ".gml";

      std::cerr << "* Storing graph in '" << filename << "'...";

      writer( filename, simplicialComplexes[i] );

      std::cerr << "finished\n";
    }
  }

  // Calculate persistent homology -------------------------------------

  {
    std::size_t index = 0;

    for( auto&& K : simplicialComplexes )
    {
      bool dualize                    = true;
      bool includeAllUnpairedCreators = true;

      auto diagrams
        = aleph::calculatePersistenceDiagrams( K,
                                               dualize,
                                               includeAllUnpairedCreators );

      for( auto&& diagram : diagrams )
      {
        diagram.removeDiagonal();

        auto outputPath = output
                        + aleph::utilities::format( index, simplicialComplexes.size() )
                        + "_d"
                        + std::to_string( diagram.dimension() )
                        + ".txt";

        std::ofstream out( outputPath );

        for( auto&& point : diagram )
        {
          if( point.isUnpaired() )
            out << point.x() << "\t" << infinity * maxDegree << "\n";
          else
            out << point.x() << "\t" << point.y() << "\n";
        }
      }

      ++index;
    }
  }

  // Store labels ------------------------------------------------------

  {
    std::vector<std::string> labels;
    reader.graphLabels( std::back_inserter( labels ) );

    auto outputPath = output
                    + "Labels.txt";

    std::cerr << "* Storing labels in '" << outputPath << "'\n";

    std::ofstream out( outputPath );
    for( auto&& label : labels )
      out << label << "\n";
  }
}
<commit_msg>Made node label reading optional for sparse adjacency matrix analysis tool<commit_after>/**
  @file  sparse_adjacency_matrices.cc
  @brief Tool for calculating persistent homology of sparse adjacency matrices

  This is a tool shipped by 'Aleph - A Library for Exploring Persistent
  Homology'. It calculates the persistent homology of sparse adjacency
  matrices, i.e. data sets containing *multiple* graphs, using either
  a degree filtration or a filtration based on the *sum* of degrees.

  Original author: Bastian Rieck
*/

#include <aleph/geometry/RipsExpander.hh>

#include <aleph/math/KahanSummation.hh>

#include <aleph/persistentHomology/Calculation.hh>

#include <aleph/topology/FloydWarshall.hh>
#include <aleph/topology/Simplex.hh>
#include <aleph/topology/SimplicialComplex.hh>

#include <aleph/topology/filtrations/Data.hh>
#include <aleph/topology/filtrations/Degree.hh>

#include <aleph/topology/io/GML.hh>
#include <aleph/topology/io/SparseAdjacencyMatrix.hh>

#include <aleph/utilities/Format.hh>
#include <aleph/utilities/String.hh>

#include <getopt.h>

#include <algorithm>
#include <fstream>
#include <iostream>
#include <limits>
#include <stdexcept>
#include <string>
#include <vector>

#include <cmath>

using DataType          = float;
using VertexType        = std::size_t;
using Simplex           = aleph::topology::Simplex<DataType, VertexType>;
using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>;

std::vector<DataType> closenessCentrality( const SimplicialComplex& K )
{
  auto M = aleph::topology::floydWarshall( K, 1 );
  auto n = M.numRows();

  std::vector<DataType> result;
  result.reserve( n );

  for( decltype(n) i = 0; i < n; i++ )
  {
    aleph::math::KahanSummation<DataType> sum = DataType();

    for( decltype(n) j = 0; j < n; j++ )
      if( std::isfinite( M(i,j) ) )
        sum += M(i,j);

    result.push_back( DataType(n) / sum );
  }

  return result;
}

void usage()
{
  std::cerr << "Usage: sparse_adjacency_matrices FILE\n"
            << "\n"
            << "Loads a set of sparse adjacency matrices from FILE and performs\n"
            << "several operations with them. By default, the tool will extract\n"
            << "all graphs from the file, use a degree-based filtration, and do\n"
            << "a conversion to GML. Furthermore, persistence diagrams of every\n"
            << "graph will be calculated.\n"
            << "\n"
            << "Optional arguments:\n"
            << "\n"
            << " --dimension D: Expand simplicial complexes up to dimension D\n"
            << " --infinity I:  Use factor I for unpaired points in a diagram\n"
            << "\n"
            << "Flags:\n"
            << "\n"
            << " --closeness-centrality: Calculates closeness centrality filtration\n"
            << " --graphs:               Stores converted graphs in GML format\n"
            << " --sum:                  Calculates degree sum filtration\n"
            << "\n"
            << "\n";
}

int main( int argc, char** argv )
{
  static option commandLineOptions[] =
  {
    { "dimension"           , required_argument, nullptr, 'd' },
    { "infinity"            , required_argument, nullptr, 'f' },
    { "output"              , required_argument, nullptr, 'o' },
    { "closeness-centrality", no_argument      , nullptr, 'c' },
    { "graphs"              , no_argument      , nullptr, 'g' },
    { "sum"                 , no_argument      , nullptr, 's' },
    { "node-labels"         , no_argument      , nullptr, 'n' },
    { nullptr               , 0                , nullptr,  0  }
  };

  unsigned dimension                = 0;
  bool calculateClosenessCentrality = false;
  bool storeGraphs                  = false;
  bool useSumOfDegrees              = false;
  bool readNodeLabels               = false;
  DataType infinity                 = DataType(2);
  std::string output                = "/tmp";

  {
    int option = 0;
    while( ( option = getopt_long( argc, argv, "d:f:o:cgs", commandLineOptions, nullptr ) ) != -1 )
    {
      switch( option )
      {
      case 'd':
        dimension = static_cast<unsigned>( std::stoul( optarg  ) );
        break;
      case 'f':
        infinity = aleph::utilities::convert<DataType>( optarg );
        break;
      case 'o':
        output = optarg;
        break;
      case 'c':
        calculateClosenessCentrality = true;
        break;
      case 'g':
        storeGraphs = true;
        break;
      case 'n':
        readNodeLabels = true;
        break;
      case 's':
        useSumOfDegrees = true;
        break;
      default:
        throw std::runtime_error( "Unknown command-line arugment" );
      }
    }
  }

  if( ( argc - optind ) < 1 )
  {
    usage();
    return -1;
  }

  // Check that the output parameter at least *looks* like a directory
  if( output.back() != '/' )
    output.push_back( '/' );

  std::string filename = argv[optind++];

  std::vector<SimplicialComplex> simplicialComplexes;
  std::vector<std::string> labels;

  aleph::topology::io::SparseAdjacencyMatrixReader reader;
  reader.setReadGraphLabels();

  if( readNodeLabels )
    reader.setReadNodeLabels();

  std::vector<std::string> nodeLabels;

  std::cerr << "* Reading '" << filename << "'...";

  reader( filename, simplicialComplexes );

  if( readNodeLabels )
  {
    // Get node labels for further processing because we must not drop
    // this valuable information.
    reader.nodeLabels(
      std::back_inserter( nodeLabels )
    );
  }

  std::cerr << "finished\n"
            << "* Read " << simplicialComplexes.size() << " simplicial complexes\n";

  // Calculate closeness centrality ------------------------------------

  if( calculateClosenessCentrality )
  {
    std::size_t index = 0;

    for( auto&& K : simplicialComplexes )
    {
      K.sort();
      auto cc         = closenessCentrality( K );
      auto outputPath = output
                      + aleph::utilities::format( index, simplicialComplexes.size() )
                      + "_closeness_centrality.txt";

      std::cerr << "* Storing closeness centrality values in '" << outputPath << "'\n";

      std::ofstream out( outputPath );
      for( auto&& value : cc )
        out << value << "\n";

      ++index;
    }
  }

  // Expand simplicial complexes ---------------------------------------

  aleph::geometry::RipsExpander<SimplicialComplex> expander;

  if( dimension != 0 )
  {
    std::cerr << "* Expanding simplicial complexes to dimension " << dimension << "...";

    for( auto&& K : simplicialComplexes )
      expander( K, dimension );

    std::cerr << "finished\n";
  }

  // Calculate degrees -------------------------------------------------

  DataType maxDegree = 0;

  std::cerr << "* Calculating degree-based filtration...";

  for( auto&& K : simplicialComplexes )
  {
    std::vector<unsigned> degrees_;
    aleph::topology::filtrations::degrees( K, std::back_inserter( degrees_ ) );

    std::vector<DataType> degrees( degrees_.begin(), degrees_.end() );

    if( !degrees.empty() )
    {
      maxDegree
        = std::max( maxDegree,
                    *std::max_element( degrees.begin(), degrees.end() ) );
    }

    if( useSumOfDegrees )
      K = expander.assignData( K, degrees.begin(), degrees.end(), DataType(0), [] ( DataType a, DataType b ) { return a+b; } );
    else
      K = expander.assignMaximumData( K, degrees.begin(), degrees.end() );

    K.sort( aleph::topology::filtrations::Data<Simplex>() );
  }

  std::cerr << "finished\n"
            << "* Identified maximum degree as D=" << maxDegree << "\n";

  // Store graphs ------------------------------------------------------

  if( storeGraphs )
  {
    aleph::topology::io::GMLWriter writer;
    writer.setNodeLabels( nodeLabels.begin(), nodeLabels.end() );

    for( std::size_t i = 0; i < simplicialComplexes.size(); i++ )
    {
      auto filename = output
                      + aleph::utilities::format( i, simplicialComplexes.size() )
                      + ".gml";

      std::cerr << "* Storing graph in '" << filename << "'...";

      writer( filename, simplicialComplexes[i] );

      std::cerr << "finished\n";
    }
  }

  // Calculate persistent homology -------------------------------------

  {
    std::size_t index = 0;

    for( auto&& K : simplicialComplexes )
    {
      bool dualize                    = true;
      bool includeAllUnpairedCreators = true;

      auto diagrams
        = aleph::calculatePersistenceDiagrams( K,
                                               dualize,
                                               includeAllUnpairedCreators );

      for( auto&& diagram : diagrams )
      {
        diagram.removeDiagonal();

        auto outputPath = output
                        + aleph::utilities::format( index, simplicialComplexes.size() )
                        + "_d"
                        + std::to_string( diagram.dimension() )
                        + ".txt";

        std::ofstream out( outputPath );

        for( auto&& point : diagram )
        {
          if( point.isUnpaired() )
            out << point.x() << "\t" << infinity * maxDegree << "\n";
          else
            out << point.x() << "\t" << point.y() << "\n";
        }
      }

      ++index;
    }
  }

  // Store labels ------------------------------------------------------

  {
    std::vector<std::string> labels;
    reader.graphLabels( std::back_inserter( labels ) );

    auto outputPath = output
                    + "Labels.txt";

    std::cerr << "* Storing labels in '" << outputPath << "'\n";

    std::ofstream out( outputPath );
    for( auto&& label : labels )
      out << label << "\n";
  }
}
<|endoftext|>


<commit_before>/**
  @file  sparse_adjacency_matrices.cc
  @brief Tool for calculating persistent homology of sparse adjacency matrices

  This is a tool shipped by 'Aleph - A Library for Exploring Persistent
  Homology'. It calculates the persistent homology of sparse adjacency
  matrices, i.e. data sets containing *multiple* graphs, using either
  a degree filtration or a filtration based on the *sum* of degrees.

  Original author: Bastian Rieck
*/

#include <aleph/geometry/RipsExpander.hh>

#include <aleph/math/KahanSummation.hh>

#include <aleph/persistentHomology/Calculation.hh>

#include <aleph/topology/FloydWarshall.hh>
#include <aleph/topology/Simplex.hh>
#include <aleph/topology/SimplicialComplex.hh>

#include <aleph/topology/filtrations/Data.hh>
#include <aleph/topology/filtrations/Degree.hh>

#include <aleph/topology/io/GML.hh>
#include <aleph/topology/io/SparseAdjacencyMatrix.hh>

#include <aleph/utilities/Format.hh>
#include <aleph/utilities/String.hh>

#include <getopt.h>

#include <algorithm>
#include <fstream>
#include <iostream>
#include <limits>
#include <stdexcept>
#include <string>
#include <vector>

#include <cmath>

using DataType          = float;
using VertexType        = std::size_t;
using Simplex           = aleph::topology::Simplex<DataType, VertexType>;
using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>;

std::vector<DataType> closenessCentrality( const SimplicialComplex& K )
{
  auto M = aleph::topology::floydWarshall( K, 1 );
  auto n = M.numRows();

  std::vector<DataType> result;
  result.reserve( n );

  for( decltype(n) i = 0; i < n; i++ )
  {
    aleph::math::KahanSummation<DataType> sum = DataType();

    for( decltype(n) j = 0; j < n; j++ )
      if( std::isfinite( M(i,j) ) )
        sum += M(i,j);

    result.push_back( DataType(n) / sum );
  }

  return result;
}

void usage()
{
  std::cerr << "Usage: sparse_adjacency_matrices FILE\n"
            << "\n"
            << "Loads a set of sparse adjacency matrices from FILE and performs\n"
            << "several operations with them. By default, the tool will extract\n"
            << "all graphs from the file, use a degree-based filtration, and do\n"
            << "a conversion to GML. Furthermore, persistence diagrams of every\n"
            << "graph will be calculated.\n"
            << "\n"
            << "Optional arguments:\n"
            << "\n"
            << " --dimension D: Expand simplicial complexes up to dimension D\n"
            << " --infinity I:  Use factor I for unpaired points in a diagram\n"
            << "\n"
            << "Flags:\n"
            << "\n"
            << " --closeness-centrality: Calculates closeness centrality filtration\n"
            << " --graphs:               Stores converted graphs in GML format\n"
            << " --sum:                  Calculates degree sum filtration\n"
            << "\n"
            << "\n";
}

int main( int argc, char** argv )
{
  static option commandLineOptions[] =
  {
    { "dimension"           , required_argument, nullptr, 'd' },
    { "infinity"            , required_argument, nullptr, 'f' },
    { "output"              , required_argument, nullptr, 'o' },
    { "closeness-centrality", no_argument      , nullptr, 'c' },
    { "graphs"              , no_argument      , nullptr, 'g' },
    { "sum"                 , no_argument      , nullptr, 's' },
    { nullptr               , 0                , nullptr,  0  }
  };

  unsigned dimension                = 0;
  bool calculateClosenessCentrality = false;
  bool storeGraphs                  = false;
  bool useSumOfDegrees              = false;
  DataType infinity                 = DataType(2);
  std::string output                = "/tmp";

  {
    int option = 0;
    while( ( option = getopt_long( argc, argv, "d:f:o:cgs", commandLineOptions, nullptr ) ) != -1 )
    {
      switch( option )
      {
      case 'd':
        dimension = static_cast<unsigned>( std::stoul( optarg  ) );
        break;
      case 'f':
        infinity = aleph::utilities::convert<DataType>( optarg );
        break;
      case 'o':
        output = optarg;
        break;
      case 'c':
        calculateClosenessCentrality = true;
        break;
      case 'g':
        storeGraphs = true;
        break;
      case 's':
        useSumOfDegrees = true;
        break;
      default:
        throw std::runtime_error( "Unknown command-line arugment" );
      }
    }
  }

  if( ( argc - optind ) < 1 )
  {
    usage();
    return -1;
  }

  // Check that the output parameter at least *looks* like a directory
  if( output.back() != '/' )
    output.push_back( '/' );

  std::string filename = argv[optind++];

  std::vector<SimplicialComplex> simplicialComplexes;
  std::vector<std::string> labels;

  aleph::topology::io::SparseAdjacencyMatrixReader reader;
  reader.setReadGraphLabels();

  std::cerr << "* Reading '" << filename << "'...";

  reader( filename, simplicialComplexes );

  std::cerr << "finished\n"
            << "* Read " << simplicialComplexes.size() << " simplicial complexes\n";

  // Calculate closeness centrality ------------------------------------

  if( calculateClosenessCentrality )
  {
    std::size_t index = 0;

    for( auto&& K : simplicialComplexes )
    {
      K.sort();
      auto cc         = closenessCentrality( K );
      auto outputPath = output
                      + aleph::utilities::format( index, simplicialComplexes.size() )
                      + "_closeness_centrality.txt";

      std::cerr << "* Storing closeness centrality values in '" << outputPath << "'\n";

      std::ofstream out( outputPath );
      for( auto&& value : cc )
        out << value << "\n";

      ++index;
    }
  }

  // Expand simplicial complexes ---------------------------------------

  aleph::geometry::RipsExpander<SimplicialComplex> expander;

  if( dimension != 0 )
  {
    std::cerr << "* Expanding simplicial complexes to dimension " << dimension << "...";

    for( auto&& K : simplicialComplexes )
      expander( K, dimension );

    std::cerr << "finished\n";
  }

  // Calculate degrees -------------------------------------------------

  DataType maxDegree = 0;

  std::cerr << "* Calculating degree-based filtration...";

  for( auto&& K : simplicialComplexes )
  {
    std::vector<unsigned> degrees_;
    aleph::topology::filtrations::degrees( K, std::back_inserter( degrees_ ) );

    std::vector<DataType> degrees( degrees_.begin(), degrees_.end() );

    if( !degrees.empty() )
    {
      maxDegree
        = std::max( maxDegree,
                    *std::max_element( degrees.begin(), degrees.end() ) );
    }

    if( useSumOfDegrees )
      K = expander.assignData( K, degrees.begin(), degrees.end(), DataType(0), [] ( DataType a, DataType b ) { return a+b; } );
    else
      K = expander.assignMaximumData( K, degrees.begin(), degrees.end() );

    K.sort( aleph::topology::filtrations::Data<Simplex>() );
  }

  std::cerr << "finished\n"
            << "* Identified maximum degree as D=" << maxDegree << "\n";

  // Store graphs ------------------------------------------------------

  if( storeGraphs )
  {
    aleph::topology::io::GMLWriter writer;

    for( std::size_t i = 0; i < simplicialComplexes.size(); i++ )
    {
      auto filename = output
                      + aleph::utilities::format( i, simplicialComplexes.size() )
                      + ".gml";

      std::cerr << "* Storing graph in '" << filename << "'...";

      writer( filename, simplicialComplexes[i] );

      std::cerr << "finished\n";
    }
  }

  // Calculate persistent homology -------------------------------------

  {
    std::size_t index = 0;

    for( auto&& K : simplicialComplexes )
    {
      bool dualize                    = true;
      bool includeAllUnpairedCreators = true;

      auto diagrams
        = aleph::calculatePersistenceDiagrams( K,
                                               dualize,
                                               includeAllUnpairedCreators );

      for( auto&& diagram : diagrams )
      {
        diagram.removeDiagonal();

        auto outputPath = output
                        + aleph::utilities::format( index, simplicialComplexes.size() )
                        + "_d"
                        + std::to_string( diagram.dimension() )
                        + ".txt";

        std::ofstream out( outputPath );

        for( auto&& point : diagram )
        {
          if( point.isUnpaired() )
            out << point.x() << "\t" << infinity * maxDegree << "\n";
          else
            out << point.x() << "\t" << point.y() << "\n";
        }
      }

      ++index;
    }
  }

  // Store labels ------------------------------------------------------

  {
    std::vector<std::string> labels;
    reader.graphLabels( std::back_inserter( labels ) );

    auto outputPath = output
                    + "Labels.txt";

    std::cerr << "* Storing labels in '" << outputPath << "'\n";

    std::ofstream out( outputPath );
    for( auto&& label : labels )
      out << label << "\n";
  }
}
<commit_msg>Reading and displaying node labels for sparse adjacency matrix loading<commit_after>/**
  @file  sparse_adjacency_matrices.cc
  @brief Tool for calculating persistent homology of sparse adjacency matrices

  This is a tool shipped by 'Aleph - A Library for Exploring Persistent
  Homology'. It calculates the persistent homology of sparse adjacency
  matrices, i.e. data sets containing *multiple* graphs, using either
  a degree filtration or a filtration based on the *sum* of degrees.

  Original author: Bastian Rieck
*/

#include <aleph/geometry/RipsExpander.hh>

#include <aleph/math/KahanSummation.hh>

#include <aleph/persistentHomology/Calculation.hh>

#include <aleph/topology/FloydWarshall.hh>
#include <aleph/topology/Simplex.hh>
#include <aleph/topology/SimplicialComplex.hh>

#include <aleph/topology/filtrations/Data.hh>
#include <aleph/topology/filtrations/Degree.hh>

#include <aleph/topology/io/GML.hh>
#include <aleph/topology/io/SparseAdjacencyMatrix.hh>

#include <aleph/utilities/Format.hh>
#include <aleph/utilities/String.hh>

#include <getopt.h>

#include <algorithm>
#include <fstream>
#include <iostream>
#include <limits>
#include <stdexcept>
#include <string>
#include <vector>

#include <cmath>

using DataType          = float;
using VertexType        = std::size_t;
using Simplex           = aleph::topology::Simplex<DataType, VertexType>;
using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>;

std::vector<DataType> closenessCentrality( const SimplicialComplex& K )
{
  auto M = aleph::topology::floydWarshall( K, 1 );
  auto n = M.numRows();

  std::vector<DataType> result;
  result.reserve( n );

  for( decltype(n) i = 0; i < n; i++ )
  {
    aleph::math::KahanSummation<DataType> sum = DataType();

    for( decltype(n) j = 0; j < n; j++ )
      if( std::isfinite( M(i,j) ) )
        sum += M(i,j);

    result.push_back( DataType(n) / sum );
  }

  return result;
}

void usage()
{
  std::cerr << "Usage: sparse_adjacency_matrices FILE\n"
            << "\n"
            << "Loads a set of sparse adjacency matrices from FILE and performs\n"
            << "several operations with them. By default, the tool will extract\n"
            << "all graphs from the file, use a degree-based filtration, and do\n"
            << "a conversion to GML. Furthermore, persistence diagrams of every\n"
            << "graph will be calculated.\n"
            << "\n"
            << "Optional arguments:\n"
            << "\n"
            << " --dimension D: Expand simplicial complexes up to dimension D\n"
            << " --infinity I:  Use factor I for unpaired points in a diagram\n"
            << "\n"
            << "Flags:\n"
            << "\n"
            << " --closeness-centrality: Calculates closeness centrality filtration\n"
            << " --graphs:               Stores converted graphs in GML format\n"
            << " --sum:                  Calculates degree sum filtration\n"
            << "\n"
            << "\n";
}

int main( int argc, char** argv )
{
  static option commandLineOptions[] =
  {
    { "dimension"           , required_argument, nullptr, 'd' },
    { "infinity"            , required_argument, nullptr, 'f' },
    { "output"              , required_argument, nullptr, 'o' },
    { "closeness-centrality", no_argument      , nullptr, 'c' },
    { "graphs"              , no_argument      , nullptr, 'g' },
    { "sum"                 , no_argument      , nullptr, 's' },
    { nullptr               , 0                , nullptr,  0  }
  };

  unsigned dimension                = 0;
  bool calculateClosenessCentrality = false;
  bool storeGraphs                  = false;
  bool useSumOfDegrees              = false;
  DataType infinity                 = DataType(2);
  std::string output                = "/tmp";

  {
    int option = 0;
    while( ( option = getopt_long( argc, argv, "d:f:o:cgs", commandLineOptions, nullptr ) ) != -1 )
    {
      switch( option )
      {
      case 'd':
        dimension = static_cast<unsigned>( std::stoul( optarg  ) );
        break;
      case 'f':
        infinity = aleph::utilities::convert<DataType>( optarg );
        break;
      case 'o':
        output = optarg;
        break;
      case 'c':
        calculateClosenessCentrality = true;
        break;
      case 'g':
        storeGraphs = true;
        break;
      case 's':
        useSumOfDegrees = true;
        break;
      default:
        throw std::runtime_error( "Unknown command-line arugment" );
      }
    }
  }

  if( ( argc - optind ) < 1 )
  {
    usage();
    return -1;
  }

  // Check that the output parameter at least *looks* like a directory
  if( output.back() != '/' )
    output.push_back( '/' );

  std::string filename = argv[optind++];

  std::vector<SimplicialComplex> simplicialComplexes;
  std::vector<std::string> labels;

  aleph::topology::io::SparseAdjacencyMatrixReader reader;
  reader.setReadGraphLabels();
  reader.setReadNodeLabels();

  std::vector<std::string> nodeLabels;

  std::cerr << "* Reading '" << filename << "'...";

  reader( filename, simplicialComplexes );

  // Get node labels for further processing because we must not drop
  // this valuable information.
  reader.nodeLabels(
    std::back_inserter( nodeLabels )
  );

  for( auto&& label : nodeLabels )
    std::cerr << label << "\n";

  std::cerr << "finished\n"
            << "* Read " << simplicialComplexes.size() << " simplicial complexes\n";

  // Calculate closeness centrality ------------------------------------

  if( calculateClosenessCentrality )
  {
    std::size_t index = 0;

    for( auto&& K : simplicialComplexes )
    {
      K.sort();
      auto cc         = closenessCentrality( K );
      auto outputPath = output
                      + aleph::utilities::format( index, simplicialComplexes.size() )
                      + "_closeness_centrality.txt";

      std::cerr << "* Storing closeness centrality values in '" << outputPath << "'\n";

      std::ofstream out( outputPath );
      for( auto&& value : cc )
        out << value << "\n";

      ++index;
    }
  }

  // Expand simplicial complexes ---------------------------------------

  aleph::geometry::RipsExpander<SimplicialComplex> expander;

  if( dimension != 0 )
  {
    std::cerr << "* Expanding simplicial complexes to dimension " << dimension << "...";

    for( auto&& K : simplicialComplexes )
      expander( K, dimension );

    std::cerr << "finished\n";
  }

  // Calculate degrees -------------------------------------------------

  DataType maxDegree = 0;

  std::cerr << "* Calculating degree-based filtration...";

  for( auto&& K : simplicialComplexes )
  {
    std::vector<unsigned> degrees_;
    aleph::topology::filtrations::degrees( K, std::back_inserter( degrees_ ) );

    std::vector<DataType> degrees( degrees_.begin(), degrees_.end() );

    if( !degrees.empty() )
    {
      maxDegree
        = std::max( maxDegree,
                    *std::max_element( degrees.begin(), degrees.end() ) );
    }

    if( useSumOfDegrees )
      K = expander.assignData( K, degrees.begin(), degrees.end(), DataType(0), [] ( DataType a, DataType b ) { return a+b; } );
    else
      K = expander.assignMaximumData( K, degrees.begin(), degrees.end() );

    K.sort( aleph::topology::filtrations::Data<Simplex>() );
  }

  std::cerr << "finished\n"
            << "* Identified maximum degree as D=" << maxDegree << "\n";

  // Store graphs ------------------------------------------------------

  if( storeGraphs )
  {
    aleph::topology::io::GMLWriter writer;

    for( std::size_t i = 0; i < simplicialComplexes.size(); i++ )
    {
      auto filename = output
                      + aleph::utilities::format( i, simplicialComplexes.size() )
                      + ".gml";

      std::cerr << "* Storing graph in '" << filename << "'...";

      writer( filename, simplicialComplexes[i] );

      std::cerr << "finished\n";
    }
  }

  // Calculate persistent homology -------------------------------------

  {
    std::size_t index = 0;

    for( auto&& K : simplicialComplexes )
    {
      bool dualize                    = true;
      bool includeAllUnpairedCreators = true;

      auto diagrams
        = aleph::calculatePersistenceDiagrams( K,
                                               dualize,
                                               includeAllUnpairedCreators );

      for( auto&& diagram : diagrams )
      {
        diagram.removeDiagonal();

        auto outputPath = output
                        + aleph::utilities::format( index, simplicialComplexes.size() )
                        + "_d"
                        + std::to_string( diagram.dimension() )
                        + ".txt";

        std::ofstream out( outputPath );

        for( auto&& point : diagram )
        {
          if( point.isUnpaired() )
            out << point.x() << "\t" << infinity * maxDegree << "\n";
          else
            out << point.x() << "\t" << point.y() << "\n";
        }
      }

      ++index;
    }
  }

  // Store labels ------------------------------------------------------

  {
    std::vector<std::string> labels;
    reader.graphLabels( std::back_inserter( labels ) );

    auto outputPath = output
                    + "Labels.txt";

    std::cerr << "* Storing labels in '" << outputPath << "'\n";

    std::ofstream out( outputPath );
    for( auto&& label : labels )
      out << label << "\n";
  }
}
<|endoftext|>


<commit_before>#include <QCoreApplication>
#include <QFile>
#include <QHostAddress>
#include <QObject>
#include <QSslCertificate>
#include <QSslConfiguration>
#include <QSslKey>
#include <QSslSocket>
#include <QStringBuilder>
#include <QTcpServer>
#include <QTcpSocket>
#include <QVector>
#include <functional>

#include "request.hpp"
#include "response.hpp"
#include "context.hpp"

//!
//! \brief The SslTcpServer class
//! Recurse ssl server implementation used for Recurse::HttpsServer
//!
class SslTcpServer : public QTcpServer
{
    Q_OBJECT
    Q_DISABLE_COPY(SslTcpServer)

public:
    SslTcpServer(QObject *parent = NULL);
    ~SslTcpServer();

    QSslSocket *nextPendingConnection();
    void setSslConfiguration(const QSslConfiguration &sslConfiguration);

Q_SIGNALS:
    void connectionEncrypted();

protected:
    //!
    //! brief overridden incomingConnection from QTcpServer
    //!
    virtual void incomingConnection(qintptr socket_descriptor)
    {
        QSslSocket *socket = new QSslSocket();

        socket->setSslConfiguration(m_ssl_configuration);
        socket->setSocketDescriptor(socket_descriptor);

        connect(socket, &QSslSocket::encrypted, this, &SslTcpServer::connectionEncrypted);

        addPendingConnection(socket);
        socket->startServerEncryption();
    };

private:
    QSslConfiguration m_ssl_configuration;
};

inline SslTcpServer::SslTcpServer(QObject *parent)
{
    Q_UNUSED(parent);
};

inline SslTcpServer::~SslTcpServer()
{

};

inline void SslTcpServer::setSslConfiguration(const QSslConfiguration &sslConfiguration)
{
    m_ssl_configuration = sslConfiguration;
};

inline QSslSocket *SslTcpServer::nextPendingConnection()
{
    return static_cast<QSslSocket *>(QTcpServer::nextPendingConnection());
};

//!
//! \brief The HttpServer class
//! Http (unsecure) server class
//!
class HttpServer : public QObject
{
    Q_OBJECT

public:
    HttpServer(QObject *parent = NULL);
    ~HttpServer();

    bool compose(quint16 port, QHostAddress address = QHostAddress::Any);

private:
    QTcpServer m_tcp_server;
    quint16 m_port;
    QHostAddress m_address;
    QObject *m_parent;

signals:
    void socketReady(QTcpSocket *socket);
};

inline HttpServer::HttpServer(QObject *parent)
{
    m_parent = parent;
};

inline HttpServer::~HttpServer()
{

};

inline bool HttpServer::compose(quint16 port, QHostAddress address)
{
    m_port = port;
    m_address = address;

    if (!m_tcp_server.listen(address, port)) {
        qDebug() << "failed to start listening";
        return false;
    }

    connect(&m_tcp_server, &QTcpServer::newConnection, [this] {
        qDebug() << "client connected";
        QTcpSocket *socket = m_tcp_server.nextPendingConnection();

        if (socket == 0) {
            qDebug() << "no connection?";
            delete socket;
            return;
        }

        emit socketReady(socket);
    });

    return true;
};

//!
//! \brief The HttpsServer class
//! Https (secure) server class
//!
class HttpsServer : public QObject
{
    Q_OBJECT

public:
    HttpsServer(QObject *parent = NULL);
    ~HttpsServer();

    bool compose(quint16 port, QHostAddress address = QHostAddress::Any);
    bool compose(const QHash<QString, QVariant> &options);
    // TODO: create port, address, options overload

private:
    SslTcpServer m_tcp_server;
    quint16 m_port;
    QHostAddress m_address;
    QObject *m_parent;

signals:
    void socketReady(QTcpSocket *socket);
};

inline HttpsServer::HttpsServer(QObject *parent)
{
    m_parent = parent;
};

inline HttpsServer::~HttpsServer()
{

};

// TODO: do we need this method? (port, address)
inline bool HttpsServer::compose(quint16 port, QHostAddress address)
{
    m_port = port;
    m_address = address;

    if (!m_tcp_server.listen(address, port)) {
        qDebug() << "failed to start listening";
        return false;
    }

    connect(&m_tcp_server, &SslTcpServer::connectionEncrypted, [this] {
        qDebug() << "secured connection ready";

        // FIXME: check this out
        QTcpSocket *socket = m_tcp_server.nextPendingConnection();

        if (socket == 0) {
            qDebug() << "no connection?";
            delete socket;
            return;
        }

        emit socketReady(socket);
    });

    return true;
};

inline bool HttpsServer::compose(const QHash<QString, QVariant> &options)
{
    QByteArray priv_key;
    QFile priv_key_file(options["private_key"].toString());

    if (priv_key_file.open(QIODevice::ReadOnly)) {
        priv_key = priv_key_file.readAll();
        priv_key_file.close();
    }

    QSslKey ssl_key(priv_key, QSsl::Rsa);

    QByteArray cert_key;
    QFile cert_key_file(options["certificate"].toString());

    if (cert_key_file.open(QIODevice::ReadOnly)) {
        cert_key = cert_key_file.readAll();
        cert_key_file.close();
    }

    QSslCertificate ssl_cert(cert_key);

    QSslConfiguration ssl_configuration;
    ssl_configuration.setPrivateKey(ssl_key);
    ssl_configuration.setLocalCertificate(ssl_cert);

    m_tcp_server.setSslConfiguration(ssl_configuration);

    // TODO: run server and set slots

    if (!options.contains("port")) {
        // FIXME: return something else?
        return false;
    }

    return compose(options["port"].toUInt(), QHostAddress::LocalHost);
};

//!
//! \brief The Recurse class
//! main class of the app
//!
class Recurse : public QObject
{
    Q_OBJECT

    using void_f = std::function<void()>;
    using void_ff = std::function<void(void_f prev)>;
    using next_prev_f = std::function<void(Context &ctx, void_ff next, void_f prev)>;
    using next_f = std::function<void(Context &ctx, void_f next)>;
    using final_f =  std::function<void(Context &ctx)>;

public:
    Recurse(int & argc, char ** argv, QObject *parent = NULL);
    ~Recurse();

    bool listen(quint16 port, QHostAddress address = QHostAddress::Any);
    bool listen(HttpServer *server);
    bool listen(HttpsServer *server);

    void use(next_f next);
    void use(next_prev_f next);

    void use(QVector<next_f> nexts);
    void use(QVector<next_prev_f> nexts);

    void use(final_f next);

public slots:
    bool handleConnection(QTcpSocket *socket);

private:
    QCoreApplication app;
    HttpServer *http;
    HttpsServer *https;

    QVector<next_prev_f> m_middleware_next;

    void m_end(QVector<void_f> *middleware_prev);
    void m_send(Context *ctx);
    void m_next(void_f prev, Context *ctx, int current_middleware, QVector<void_f> *middleware_prev);
    bool startEventLoop();
};

inline Recurse::Recurse(int & argc, char ** argv, QObject *parent) : app(argc, argv)
{
    Q_UNUSED(parent);
};

inline Recurse::~Recurse()
{
    delete http;
    delete https;
};

//!
//! \brief Recurse::startEventLoop
//! starts a Qt build-in event loop
//!
//! \return true on success
//!
inline bool Recurse::startEventLoop()
{
    return app.exec();
};

//!
//! \brief Recurse::handleConnection
//! creates new recurse context for a tcp session
//!
//! \return true on success
//!
inline bool Recurse::handleConnection(QTcpSocket *socket)
{
    qDebug() << "handling new connection";

    auto middleware_prev = new QVector<void_f>;
    auto ctx = new Context;
    ctx->request.socket = socket;

    connect(socket, &QTcpSocket::readyRead, [this, ctx, middleware_prev] {
        QString data(ctx->request.socket->readAll());

        ctx->request.parse(data);

        if (ctx->request.length < ctx->request.get("content-length").toLongLong()) {
            return;
        }

        qDebug() << ctx->request.body;

        /*
        if (m_middleware_next.count() > 0) {
            ctx->response.end = std::bind(&Recurse::m_end, this, middleware_prev);

            m_middleware_next[0](
                *ctx,
                std::bind(&Recurse::m_next, this, std::placeholders::_1, ctx, 0, middleware_prev),
                std::bind(&Recurse::m_send, this, ctx));
        }
        */

    });

    return true;
};

//!
//! \brief Recurse::listen
//! listen for tcp requests
//!
//! \param port tcp server port
//! \param address tcp server listening address
//!
//! \return true on success
//!
inline bool Recurse::listen(quint16 port, QHostAddress address)
{
    // set HttpServer instance, send reference to this object and prepare http connection
    http = new HttpServer(this);
    http->compose(port, address);

    // connect HttpServer signal 'socketReady' to this class' 'handleConnection' slot
    connect(http, &HttpServer::socketReady, this, &Recurse::handleConnection);
    return startEventLoop();
};

//!
//! \brief Recurse::listen
//! listen for tcp requests
//!
//! overloaded function
//!
//! \param server pointer to the HttpServer instance
//!
//! \return true on success
//!
inline bool Recurse::listen(HttpServer *server)
{
    http = server;

    // connect HttpServer signal 'socketReady' to this class' 'handleConnection' slot
    connect(http, &HttpServer::socketReady, this, &Recurse::handleConnection);
    return startEventLoop();
};

//!
//! \brief Recurse::listen
//! listen for tcp requests
//!
//! overloaded function
//!
//! \param server pointer to the HttpsServer instance
//!
//! \return true on success
//!
inline bool Recurse::listen(HttpsServer *server)
{
    https = server;

    // connect HttpServer signal 'socketReady' to this class' 'handleConnection' slot
    // connect(http, &HttpServer::socketReady, this, &Recurse::handleConnection);
    return startEventLoop();
};

<commit_msg>handle HttpsServer::socketReady<commit_after>#include <QCoreApplication>
#include <QFile>
#include <QHostAddress>
#include <QObject>
#include <QSslCertificate>
#include <QSslConfiguration>
#include <QSslKey>
#include <QSslSocket>
#include <QStringBuilder>
#include <QTcpServer>
#include <QTcpSocket>
#include <QVector>
#include <functional>

#include "request.hpp"
#include "response.hpp"
#include "context.hpp"

//!
//! \brief The SslTcpServer class
//! Recurse ssl server implementation used for Recurse::HttpsServer
//!
class SslTcpServer : public QTcpServer
{
    Q_OBJECT
    Q_DISABLE_COPY(SslTcpServer)

public:
    SslTcpServer(QObject *parent = NULL);
    ~SslTcpServer();

    QSslSocket *nextPendingConnection();
    void setSslConfiguration(const QSslConfiguration &sslConfiguration);

Q_SIGNALS:
    void connectionEncrypted();

protected:
    //!
    //! brief overridden incomingConnection from QTcpServer
    //!
    virtual void incomingConnection(qintptr socket_descriptor)
    {
        QSslSocket *socket = new QSslSocket();

        socket->setSslConfiguration(m_ssl_configuration);
        socket->setSocketDescriptor(socket_descriptor);

        connect(socket, &QSslSocket::encrypted, this, &SslTcpServer::connectionEncrypted);

        addPendingConnection(socket);
        socket->startServerEncryption();
    };

private:
    QSslConfiguration m_ssl_configuration;
};

inline SslTcpServer::SslTcpServer(QObject *parent)
{
    Q_UNUSED(parent);
};

inline SslTcpServer::~SslTcpServer()
{

};

inline void SslTcpServer::setSslConfiguration(const QSslConfiguration &sslConfiguration)
{
    m_ssl_configuration = sslConfiguration;
};

inline QSslSocket *SslTcpServer::nextPendingConnection()
{
    return static_cast<QSslSocket *>(QTcpServer::nextPendingConnection());
};

//!
//! \brief The HttpServer class
//! Http (unsecure) server class
//!
class HttpServer : public QObject
{
    Q_OBJECT

public:
    HttpServer(QObject *parent = NULL);
    ~HttpServer();

    bool compose(quint16 port, QHostAddress address = QHostAddress::Any);

private:
    QTcpServer m_tcp_server;
    quint16 m_port;
    QHostAddress m_address;
    QObject *m_parent;

signals:
    void socketReady(QTcpSocket *socket);
};

inline HttpServer::HttpServer(QObject *parent)
{
    m_parent = parent;
};

inline HttpServer::~HttpServer()
{

};

inline bool HttpServer::compose(quint16 port, QHostAddress address)
{
    m_port = port;
    m_address = address;

    if (!m_tcp_server.listen(address, port)) {
        qDebug() << "failed to start listening";
        return false;
    }

    connect(&m_tcp_server, &QTcpServer::newConnection, [this] {
        qDebug() << "client connected";
        QTcpSocket *socket = m_tcp_server.nextPendingConnection();

        if (socket == 0) {
            qDebug() << "no connection?";
            delete socket;
            return;
        }

        emit socketReady(socket);
    });

    return true;
};

//!
//! \brief The HttpsServer class
//! Https (secure) server class
//!
class HttpsServer : public QObject
{
    Q_OBJECT

public:
    HttpsServer(QObject *parent = NULL);
    ~HttpsServer();

    bool compose(quint16 port, QHostAddress address = QHostAddress::Any);
    bool compose(const QHash<QString, QVariant> &options);
    // TODO: create port, address, options overload

private:
    SslTcpServer m_tcp_server;
    quint16 m_port;
    QHostAddress m_address;
    QObject *m_parent;

signals:
    void socketReady(QTcpSocket *socket);
};

inline HttpsServer::HttpsServer(QObject *parent)
{
    m_parent = parent;
};

inline HttpsServer::~HttpsServer()
{

};

// TODO: do we need this method? (port, address)
inline bool HttpsServer::compose(quint16 port, QHostAddress address)
{
    m_port = port;
    m_address = address;

    if (!m_tcp_server.listen(address, port)) {
        qDebug() << "failed to start listening";
        return false;
    }

    connect(&m_tcp_server, &SslTcpServer::connectionEncrypted, [this] {
        qDebug() << "secured connection ready";

        // FIXME: check this out
        QTcpSocket *socket = m_tcp_server.nextPendingConnection();

        if (socket == 0) {
            qDebug() << "no connection?";
            delete socket;
            return;
        }

        emit socketReady(socket);
    });

    return true;
};

inline bool HttpsServer::compose(const QHash<QString, QVariant> &options)
{
    QByteArray priv_key;
    QFile priv_key_file(options["private_key"].toString());

    if (priv_key_file.open(QIODevice::ReadOnly)) {
        priv_key = priv_key_file.readAll();
        priv_key_file.close();
    }

    QSslKey ssl_key(priv_key, QSsl::Rsa);

    QByteArray cert_key;
    QFile cert_key_file(options["certificate"].toString());

    if (cert_key_file.open(QIODevice::ReadOnly)) {
        cert_key = cert_key_file.readAll();
        cert_key_file.close();
    }

    QSslCertificate ssl_cert(cert_key);

    QSslConfiguration ssl_configuration;
    ssl_configuration.setPrivateKey(ssl_key);
    ssl_configuration.setLocalCertificate(ssl_cert);

    m_tcp_server.setSslConfiguration(ssl_configuration);

    // TODO: run server and set slots

    if (!options.contains("port")) {
        // FIXME: return something else?
        return false;
    }

    return compose(options["port"].toUInt(), QHostAddress::LocalHost);
};

//!
//! \brief The Recurse class
//! main class of the app
//!
class Recurse : public QObject
{
    Q_OBJECT

    using void_f = std::function<void()>;
    using void_ff = std::function<void(void_f prev)>;
    using next_prev_f = std::function<void(Context &ctx, void_ff next, void_f prev)>;
    using next_f = std::function<void(Context &ctx, void_f next)>;
    using final_f =  std::function<void(Context &ctx)>;

public:
    Recurse(int & argc, char ** argv, QObject *parent = NULL);
    ~Recurse();

    bool listen(quint16 port, QHostAddress address = QHostAddress::Any);
    bool listen(HttpServer *server);
    bool listen(HttpsServer *server);

    void use(next_f next);
    void use(next_prev_f next);

    void use(QVector<next_f> nexts);
    void use(QVector<next_prev_f> nexts);

    void use(final_f next);

public slots:
    bool handleConnection(QTcpSocket *socket);

private:
    QCoreApplication app;
    HttpServer *http;
    HttpsServer *https;

    QVector<next_prev_f> m_middleware_next;

    void m_end(QVector<void_f> *middleware_prev);
    void m_send(Context *ctx);
    void m_next(void_f prev, Context *ctx, int current_middleware, QVector<void_f> *middleware_prev);
    bool startEventLoop();
};

inline Recurse::Recurse(int & argc, char ** argv, QObject *parent) : app(argc, argv)
{
    Q_UNUSED(parent);
};

inline Recurse::~Recurse()
{
    delete http;
    delete https;
};

//!
//! \brief Recurse::startEventLoop
//! starts a Qt build-in event loop
//!
//! \return true on success
//!
inline bool Recurse::startEventLoop()
{
    return app.exec();
};

//!
//! \brief Recurse::handleConnection
//! creates new recurse context for a tcp session
//!
//! \return true on success
//!
inline bool Recurse::handleConnection(QTcpSocket *socket)
{
    qDebug() << "handling new connection";

    auto middleware_prev = new QVector<void_f>;
    auto ctx = new Context;
    ctx->request.socket = socket;

    connect(socket, &QTcpSocket::readyRead, [this, ctx, middleware_prev] {
        QString data(ctx->request.socket->readAll());

        ctx->request.parse(data);

        if (ctx->request.length < ctx->request.get("content-length").toLongLong()) {
            return;
        }

        qDebug() << ctx->request.body;

        /*
        if (m_middleware_next.count() > 0) {
            ctx->response.end = std::bind(&Recurse::m_end, this, middleware_prev);

            m_middleware_next[0](
                *ctx,
                std::bind(&Recurse::m_next, this, std::placeholders::_1, ctx, 0, middleware_prev),
                std::bind(&Recurse::m_send, this, ctx));
        }
        */

    });

    return true;
};

//!
//! \brief Recurse::listen
//! listen for tcp requests
//!
//! \param port tcp server port
//! \param address tcp server listening address
//!
//! \return true on success
//!
inline bool Recurse::listen(quint16 port, QHostAddress address)
{
    // set HttpServer instance, send reference to this object and prepare http connection
    http = new HttpServer(this);
    http->compose(port, address);

    // connect HttpServer signal 'socketReady' to this class' 'handleConnection' slot
    connect(http, &HttpServer::socketReady, this, &Recurse::handleConnection);
    return startEventLoop();
};

//!
//! \brief Recurse::listen
//! listen for tcp requests
//!
//! overloaded function
//!
//! \param server pointer to the HttpServer instance
//!
//! \return true on success
//!
inline bool Recurse::listen(HttpServer *server)
{
    http = server;

    // connect HttpServer signal 'socketReady' to this class' 'handleConnection' slot
    connect(http, &HttpServer::socketReady, this, &Recurse::handleConnection);
    return startEventLoop();
};

//!
//! \brief Recurse::listen
//! listen for tcp requests
//!
//! overloaded function
//!
//! \param server pointer to the HttpsServer instance
//!
//! \return true on success
//!
inline bool Recurse::listen(HttpsServer *server)
{
    https = server;

    // connect HttpServer signal 'socketReady' to this class' 'handleConnection' slot
    connect(https, &HttpsServer::socketReady, this, &Recurse::handleConnection);
    return startEventLoop();
};

<|endoftext|>